/*
 * Custom Alert Box
*/

(function($) {
	$.fn.customAlert = function(options) {
		var settings = {
			'alertOk'	 : 'OK',
			'draggable'	 : false
		};
		
		if (options) $.extend(settings, options);
		
		if(document.getElementById) {
			window.defaultAlert = window.alert; // Call defaultAlert() to use the standard alert() behavior
			window.alert = function(alertTitle, msgTxt) {
				if ($('#modalDiv').length > 0 || alertTitle === undefined || msgTxt === undefined) return; // Only ever show one alert and ensure the required parameters have been passed
				
				// The modal div to block out the rest of the document whilst the alert is shown
				var modalDiv = $('<div></div>').attr('id', 'modalDiv')
					.height($(document).height()); // Make overlay cover the whole window
				
				// The alert container
				var alertDiv = $('<div></div>').attr('id', 'alertDiv');
				
				// The alert title
				var title = $('<div></div>').addClass('title')
					.html(alertTitle);
				
				// The alert text to display
				var msg = $('<div></div>').addClass('message')
					.html(msgTxt);
				
				// OK button - will remove/close the alert on click
				var okBtn = $('<a></a>').addClass('okBtn')
					.text(settings.alertOk)
					.attr('href', '#');
				
				// Append elements to document body
				alertDiv.append(title)
					.append(msg)
					.append(okBtn);
				$('body').append(modalDiv)
					.append(alertDiv);
				
				// Center alert on page
				$('#alertDiv').css({
					top: ($(window).height()/2) - ($('#alertDiv').height()/2)+'px',
					left: ($(window).width()/2) - ($('#alertDiv').width()/2)+'px'
				});
				
				// Make draggable
				if (settings.draggable && $('#alertDiv').draggable) {
					$('#alertDiv').draggable({
						handle: '.title',
						opacity: 0.4
					});
					$('#alertDiv .title').css('cursor', 'move');
				}
				
				// Bind OK button to remove/close alert
				$('#alertDiv .okBtn').bind('click', function(e) {
					$('#alertDiv, #modalDiv').remove();
					e.preventDefault();
				});
				
				// Bind enter key to trigger remove/close alert
				$(window).keydown(function(e) {
					if (e.keyCode == '13') {
						$('#alertDiv .okBtn').click();
						$(this).unbind('keydown');
					}
				});
			};
		}
	};
})(jQuery);
