/**
 * pDialog
 * 
 * This is a wrapper plugin for jQuery UI dialog
 * p is for 'peppered'
 * 
 * Prereq:
 * 		jQuery (1.3.2)
 * 		$.log function in global namespace
 * 
 * @author AK | Peppered
 * @version 1.0.0
 * 
 * 
 */
;(function($) {

var dialogs = {};	// object to keep track of created dialogs

$.pDialog = function(options) {
	options = $.extend({
		type: null,							// dialog type, must be specified: confirmation or tabs
		idPrefix: 'modal',
		useTabsAsHeader: false,
		title: '',
		width: 300,
		height: 'auto',
		bgiframe: true,
		tabs: null,							// object defining the tabs (when type = 'tabs')
		modal: true,
		autoOpen: false,
		dialogClass: null,
		closeOnOutsideclick: false,			// not implemented yet, only works if modal: true
		bringInFocusOnOutsideclick: true	// only works if modal: true
	}, options);


	// new object to transfer the default ui-dialog options
	var uiDialogOptions = {
		title: options.title,
		width: options.width,
		height: options.height,
		bgiframe: options.bgiframe,
		modal: options.modal,
		autoOpen: options.autoOpen,
		dialogClass: options.dialogClass
	};	
	
		
	/**
	 * fn_bringInFocusOnOutsideclick()
	 */
	function fn_bringInFocusOnOutsideclick($this, e, ui) {
		$('.ui-widget-overlay').click(function(){
			$.log('event: ui-widget-overlay clicked');
			$this.parent().effect('highlight');
			$this.dialog('option', 'position', 'center');
		});
	};
		
	
	/**
	 * generateButtons()
	 */
	function generateButtons() {
		var buttons = {};
		$.each(options.buttons, function(key, val) {
			
			switch (this.action) {
				case 'cancel':
					buttons[key] = function() {
						var $this = $(this);
						$this.dialog('close');
					}
					break;
				case 'submit':
					buttons[key] = function() {
						$.log('OK pressed, submit the form: ');
					}
					break;
				default:
					if (typeof this.action == 'function') {
						buttons[key] = this.action;							 
					}
					break;
			}
			
		});
		return buttons;
	}	
	
	
	/**
	 * createDialogWithTabs()
	 * 
	 * Available options per tabs:
	 *    type		{String ('iframe')}		defaults to loading via Ajax
	 *    title		
	 *    load		{String}				the URL to load in tab
	 *    
	 * 
	 */
	function createDialogWithTabs(dialogId) {
		
		var tabsHTML, tabListItemsHTML = '', tabContentsHTML = '', tabId;
			
		$.each(options.tabs, function(i, val){
			$.log(this);
			$.log(val);
			tabId = this.tabId = 'dialog-tab' + i;
			tabListItemsHTML += '<li><a href="#' + tabId + '">' + this.title + '</a></li>';	
			tabContentsHTML  += '<div id="' + tabId + '"></div>'	
		});
		
		
		// Generate tabs HTML
		//  This first needs to be appended to body, else the Tasb plugin can't/won't work correctly
		tabsHTML = '<div class="tabs" id="' + dialogId + '"><ul>'
			+ tabListItemsHTML
			+ '</ul><div class="richtext" id="tabDivsContainer">'
			+ tabContentsHTML
			+ '</div></div>'
		;
		
		// append to body & hide			
		$('body').append($(tabsHTML).hide());
		
		// remember it has been created	 
		dialogs[options.id] = true;
		
		// create the tabs and dialog
		var $dialog = $('#'+dialogId)
			.tabs()
			.dialog(uiDialogOptions)
		;
		
		if (options.useTabsAsHeader) {
			var $uiWidget = $dialog.parent();
			var $uiTabsNav = $uiWidget.find('.ui-tabs-nav');
			
			$dialog.dialog('option', 'draggable', false);
			
			$uiWidget.find('.ui-dialog-titlebar').replaceWith($uiTabsNav);
			
			$uiTabsNav
				.wrap('<div class="ui-tabs ui-dialog-titlebar"/>')
			;
			$uiWidget
				.draggable({ handle: '.ui-tabs-nav', cancel: '.ui-tabs-nav li', containment: 'document' })
			;
		}
		
		// load Ajax content
		$.each(options.tabs, function(i, val) {
			if (this.type == 'iframe') {
				var html = '<iframe src="'+this.load+'" frameborder="0"></iframe>';
				$('#' + this.tabId).addClass('pdialog-tab-iframe').html(html);
			}
			else {
				$('#' + this.tabId).load( this.load, null, function(responseText, textStatus, XMLHttpRequest){
					$.log(responseText);
				} ); // cached in IE
			}
		});
	
	}
	
	
	/**
	 * spawnDialog()
	 * 
	 */
	function spawnDialog(type) {
		var dialogId = 'uiDialog-' + options.id;
		
		// once, generate base HTML structure and append to body
		if (!dialogs[options.id]) {
			
			// buttons
			uiDialogOptions.buttons = generateButtons();
			
			// open function
			uiDialogOptions.open = function(e, ui) {
				if (type == 'tabs' && options.useTabsAsHeader) {
					//fn_useTabsAsHeader($(this), e, ui);
				}
				if (options.bringInFocusOnOutsideclick) {
					fn_bringInFocusOnOutsideclick($(this), e, ui);
				}
				$('html').addClass('ui-modalActive');
			};
			// close function
			uiDialogOptions.close = function(e, ui) {
				$('html').removeClass('ui-modalActive');
			};
			
			switch (options.type) {
				case 'tabs':
					createDialogWithTabs(dialogId);
					break;
				case 'confirmation':
					var $dialog = $('<div class="modalConfirmation" id="' + dialogId + '">' + options.content + '</div>');
					$('body').append($dialog.hide());
					
					// create the dialog
					$dialog.dialog(uiDialogOptions);
					break;
				case 'message':
					var $dialog = $('<div class="modalMessage" id="' + dialogId + '">' + options.content + '</div>');
					$('body').append($dialog.hide());
					$dialog.dialog(uiDialogOptions);
					break;
			}
			
			// remember it has been created	
			dialogs[options.id] = true;		
			
		}
		
		// open/show the dialog
		$('#'+dialogId).dialog('open');

		return true;
	}
	
	spawnDialog(options.type);
	
	return false;
	
} /* end of $.pDialog */

})(jQuery);


/**
 * implementation
 */
$(function(){
	
	// Homepage settings menu
	$('a#btnOpenSettingsDialog').click(function(e) {
		$.pDialog({
			id: 'tabhomeconfig',
			type: 'tabs',
			tabContainerId: 'homeconfigTabs',
			useTabsAsHeader: true,
			title: 'Instellingen',
			width: 850,
			height: 700,
			bringInFocusOnOutsideclick: true,
			tabs: {
				1: {
					title: 'Mijn homepage',
					load: '/scripts/homepage_settings.php?type=hidable_settings&retrieve=1'
				},
				2: {
					title: 'Mijn stijl',
					load: '/scripts/homepage_settings.php?type=thema_color_properties&retrieve=1'
				}
			},
			buttons: {
			}
		});
		e.preventDefault();

	});


	// e-card message
	if ($('.ecardMessage').length) {
		var $ecardMessage = $('.ecardMessage').hide();
		var recipient = $ecardMessage.find('.recipient').html();
		var sender = $ecardMessage.find('.sender').html();
		var message = $ecardMessage.find('.message').html();
		var dialogContent = '<p>' + sender + ' heeft u een voorstelling doorgestuurd</p><br/>' +
			'<h3>Persoonlijk bericht:</h3>' + message;		
		$.pDialog({
			id: 'ecardMessage',
			type: 'message',
			title: 'Aan: ' + recipient,
			content: dialogContent,
			buttons: {
				'Bekijk de voorstelling': {
					action: 'cancel'					
				}
			},
			autoOpen: true
		});
	}
	
	// Clear all settings button
	$('a.btnClearAllSettings').click(function(e) {
		
		$.pDialog({
			id: 'confirmClearSettings',			
			type: 'confirmation',
			title: 'Let op!',
			content: 'Als u kiest voor de standaard weergave gaan al uw persoonlijke voorkeuren verloren.<br/><br/>Klik op OK als u dit wilt.',
			bringInFocusOnOutsideclick: true,
			modal: true,
			buttons: {
				'Annuleren': {
					action: 'cancel'
				},
				'OK': {
					action: function(){
						senddata = "type=home&clear_settings=true";
						$.post('/scripts/portlets.php', senddata, function(){
							window.location.reload();
						});
						return false;
					}
				}
			}
		});
		e.preventDefault();
	});
	
	// Virtuele tour
	$('a#btnOpenVirtueleTour').click(function(e) {		
		$.pDialog({
			id: 'tabhomeconfig',
			type: 'tabs',
			tabContainerId: 'homeconfigTabs',
			useTabsAsHeader: true,
			title: 'Instellingen',
			width: 765,
			height: 540,
			bringInFocusOnOutsideclick: true,
			dialogClass: 'pdialog-singleTabIframe',
			tabs: {
				1: {
					type: 'iframe',
					title: 'VirtueleTour',
					load: '/applets/panoview/index.htm'
				}				
			},
			buttons: {
				'Sluiten': {
					action: 'cancel'
				}
			}
		});
		e.preventDefault();
	});	

});