/*
 * jDialog
 * Copyright (C) 2009 Fusonic Interactive OG
 *
 * This file is part of jDialog
 *
 * jDialog is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * jDialog is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

(function($) {
	
	$.dialog = {
		
		_defaultSettings: {
			
			// General
			offset: {
				x:						0,								// Offset X
				y:						-75								// Offset Y
			},

			// Appearance			
			effect: 				false,								// jQueryUI effects
			effectOptions:			{},									// Options for jQueryUI effect
			effectDuration:			0,									// Time in ms
			 
			// Style
			overlayOpacity: 			0.5,							// Opacity of overlay
			overlayBackground:			'#000',							// Color of overlay
			
			buttonClass:				'button',						// This CSS class will be attached to the button(s)
			
			// Behaviour
			draggable: 					false							// make the dialogs draggable (requires UI Draggables plugin)
			
		},
		
		settings: {},
		
		callback: null,
		
		// Public methods
		
		// Private methods
		show: function(_type, _message, _caption, _icon, _buttonCollection, _defaultButton) {
			
			// Hide older dialogs and show overlay
			$.dialog._hide(true);
			$.dialog._showOverlay();
			
			// Append dialog to body
			$("body").append(
			  '<div id="dialog" style="display: none;">' +
			    '<h1 id="dialog-caption"></h1>' +
				  '<div id="dialog-icon">&nbsp;</div>' +
			    '<div id="dialog-content">' +
			      '<div id="dialog-message"></div>' +
			      '<div id="dialog-inputcontainer"></div>' +
			      '<div id="dialog-buttoncontainer"></div>' +
				'</div>' +
			  '</div>');
			
			// Show dialog
			$("#dialog").css({
				position: ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed',
				zIndex: 99999,
				padding: 0,
				margin: 0
			});
			
			// Set caption (HTML)
			$("#dialog-caption").html(_caption);
			
			// Set message (HTML)
			$("#dialog-message").html(_message.replace(/\n/g, '<br />'));
			
			// If text is bigger than min values from css, set the new min values
			$("#dialog").css({
				minWidth: $("#dialog").outerWidth(),
				maxWidth: $("#dialog").outerWidth()
			});

			// Set icon
			$('#dialog-icon').css({
				backgroundImage:	'url("' + _icon + '")'
			});
			
			// Center dialog and bind function to window.resize event
			$.dialog._centerDialog($.dialog.settings);
			$(window).bind('resize', function() {
				$.dialog._centerDialog();
			});
			
			// Create buttons
			for (var button in _buttonCollection) {
				$('#dialog-buttoncontainer').append('<input type="button" class="' + $.dialog.settings.buttonClass + '" value="' + eval("jDialogButton." + button) + '" id="button-' + button.toLowerCase() + '" />');
				$('#button-' + button.toLowerCase()).click( function() {
					var prompt = $.dialog.settings.inputId ? $('#' + $.dialog.settings.inputId + 'Select').val() : $('#dialog-input').val();					
					$.dialog._hide();
					if($.dialog.callback) {
						var dialogResult = this.id.substr(this.id.indexOf("-")+1);
						dialogResult = dialogResult.substr(0,1).toUpperCase() + dialogResult.substr(1, dialogResult.length);
						$.dialog.callback(dialogResult, prompt);
					}
					
				});
			}
			// Create key listener and focus default button
			if(_defaultButton) {
				
				$('#button-' + _defaultButton.toLowerCase()).focus().keypress( function(e) {
					if( e.keyCode == 13 ) 
						$(this).trigger('click');
				});
				
			}
			
			// Add text field
			if(_type == jDialogType.Prompt) {
				
				if(!$.dialog.settings.inputId)
					input = '<input type="text" id="dialog-input" name="test" value="" class="text" />';
				else {
					input = $('#' + $.dialog.settings.inputId + 'Container').html();
					$('#' + $.dialog.settings.inputId + 'Select').remove();
				}
				
				$('#dialog-inputcontainer').html(input);
				
				
			}
			
			if($.dialog.settings.effect) {
				try {
					$('#dialog').show($.dialog.settings.effect, $.dialog.settings.effectSettings, $.dialog.settings.effectDuration);
				} catch(e) {
					$('#dialog').show();
				}
			}
			else
				$('#dialog').show();
			
			// Make draggable
			if( $.dialog.settings.draggable ) {
				try {
					$("#dialog").draggable({ handle: $("#dialog-caption") });
					$("#dialog-caption").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},
		
		_hide: function(_initial) {

			if($.dialog.settings.inputId && !_initial) {
				input = $('#dialog-inputcontainer').html();
				$('#' + $.dialog.settings.inputId + 'Select').remove();				
				$('#' + $.dialog.settings.inputId + 'Container').html(input);
			}

			$('#dialog').remove();
			$(window).unbind('resize');
			$.dialog._hideOverlay();
		},
		
		_showOverlay: function() {
			$.dialog._hideOverlay();
			$("body").append('<div id="dialog-overlay"></div>');
			$("#dialog-overlay").css({
				position: 'absolute',
				zIndex: 99998,
				top: '0px',
				left: '0px',
				width: '100%',
				height: $(document).height(),
				background: $.dialog.settings.overlayBackground,
				opacity: $.dialog.settings.overlayOpacity,
				cursor:	'wait'
			});
			
		},
		
		_hideOverlay: function() {
			$("#dialog-overlay").remove();
		},
		
		_centerDialog: function() {
			var left = Math.max(0, (($(window).width() / 2) - ($("#dialog").outerWidth() / 2)) + $.dialog.settings.offset.x);
			var top = Math.max(0, (($(window).height() / 2) - ($("#dialog").outerHeight() / 2)) + $.dialog.settings.offset.y);
			
			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
			$("#dialog").css({
				top: top + 'px',
				left: left + 'px'
			});
			
			$("#dialog-overlay").height( $(document).height() );
		}
		
	}
	
	
	// Public methods
	jAlertDialog = function(_message, _caption, _callback, _settings) {
		
		if(_caption == null) _caption =  'Alert';
		$.dialog.settings = $.extend({}, $.dialog._defaultSettings, _settings);
		$.dialog.callback = _callback;
		
		$.dialog.show(jDialogType.Alert, _message, _caption, jDialogIcon.Warning, jDialogButtonCollection.Ok, jDialogButton.Ok);
	}
	
	jConfirmDialog = function(_message, _caption, _callback, _settings) {
		if(_caption == null) _caption =  'Confirm';
		$.dialog.settings = $.extend({}, $.dialog._defaultSettings, _settings);
		$.dialog.callback = _callback;
			
		$.dialog.show(jDialogType.Confirm, _message, _caption, jDialogIcon.Question, jDialogButtonCollection.YesNo, jDialogButton.No);
		
	}
	
	jPromptDialog = function(_message, _caption, _callback, _settings) {
		if(_caption == null) _caption =  'Prompt';
		$.dialog.settings = $.extend({}, $.dialog._defaultSettings, _settings);
		$.dialog.callback = _callback;
		
		$.dialog.show(jDialogType.Prompt, _message, _caption, jDialogIcon.Question, jDialogButtonCollection.OkCancel, jDialogButton.Cancel);
	}
	
	// Enums visible to outside
	jDialogType = {
		Alert:			'Alert',
		Confirm:		'Confirm',
		Prompt:			'Prompt'
	};
	
	/*
	jDialogButton = {
		Ok:			'Ok',
		Yes:		'Yes',
		No:			'No',
		Cancel:		'Cancel'
	};
	*/
	
	jDialogResult = {
		Ok:			'Ok',
		Yes:		'Yes',
		No:			'No',
		Cancel:		'Cancel'		
	};
	
	jDialogButtonCollection = {
		Ok:			{
						'Ok':		jDialogResult.Ok
					},
		YesNo:		{
						'Yes':		jDialogResult.Yes,
						'No':		jDialogResult.No
					},
		OkCancel:	{
						'Ok':		jDialogResult.Ok,
						'Cancel':	jDialogResult.Cancel
					}
	};
	
	jDialogIcon = {
		Warning:	iconPath + '/caution_48.png',
		Question:	iconPath + '/help_48.png',
		Error:		iconPath + '/del_48.png',
		Info:		iconPath + '/info_48.png'
	};
	
})(jQuery);
