(function($) {

	/*
	Modal plugin:
	*************
	Provides default dialogs and has the ability to load dialog content from a url.
	
	Options:
	********
	All options have reasonable default settings. Only provide options if you don't want to use the default settings.
	
		width: width of the modal
		height: height of the modal
		fadeSpeed: speed at which the modal fades in and out. set to 0 if you don't want a fade.
		bgOpacity: opacity of the background of the modal. set to 0 if you don't want a background.
		btnOkText: text of the OK button if one is present.
		btnCancelText: text of the cancel button if one is present.
		title: title of the modal.
		bgClickCloseDialog: if enabled the user can click on the background to close the dialog. 
		autoCloseTimeout: the number of miliseconds after which the dialog will automatically close.
	
	Usage:
	******
	
	$.modaldialog.error("Some error has occured.");
	$.modaldialog.success("It worked, yes it did.");
	$.modaldialog.ajax("login/index.aspx", { width : 350 });
	$.modaldialog.prompt("You want it? Do you?.", callbackOk, callbackCancel, { btnOkText: 'Yeah baby', btnCancelText: 'Hell no', title: 'Give me something' });
	$.modaldialog.loading();
	$.modaldialog.loading("We are loading something..");
	$.modaldialog.close();
	$.modaldialog.vimeo("http://vimeo.com/10183616", { width: 400, height: 500 });
	*/

	var modaldialog = {};
	var opts;

	modaldialog.defaults = {
		width: 300,
		height: 'auto',
		fadeSpeed: 0,
		bgOpacity: 0.5,
		btnOkText: 'OK',
		btnCancelText: 'Cancel',
		title: '',
		bgClickCloseDialog: true,
		autoCloseTimeout: 0,
		hideScrollbars: false,
		modalClass: ""
	};

	modaldialog.error = function $$modaldialog$error(msg, options) {
		$.modaldialog.closeLoading();
		opts = $.extend({}, modaldialog.defaults, options);
		
		//never override a user specified modalClass
		if (opts.modalClass == "") {
			opts.modalClass = "dialog error";
		}
		initDialog();

		//create html for error dialog.
		var html = '<div class="picto"></div>' +
					'<div class="top">' +
						'<div class="inner">' +
							'<div class="content">' + msg + '</div>' +
							'<div class="options">' +
								'<button id="btnDialogOk" class="btn default"><span>' + opts.btnOkText + '</span></button>' +
							'</div>' +
						'</div>' +
					'</div>' +
					'<div class="bottom"><div></div></div>';
		
		createDialog(html, $('#modal'));
		showDialog();

		//add eventhandlers
		$('#btnDialogOk').keypress(function(e) {
			jQuery.log("keypress which: " + e.which);
			if (e.which == 13 || e.which == 0 || e.which == 27) {
				$.modaldialog.close();
			}
		});
		$('#btnDialogOk').click($.modaldialog.close);
		$('.btn_close').click($.modaldialog.close);
		$('#btnDialogOk').focus();

		return this;
	}

	modaldialog.success = function $$modaldialog$success(msg, options) {
		$.modaldialog.closeLoading();
		opts = $.extend({}, modaldialog.defaults, options);
		
		//never override a user specified modalClass
		if (opts.modalClass == "") {
			opts.modalClass = "dialog";
		}
		initDialog();
		
		//create html for success dialog.
		var html = '<div class="top">' +
						'<div class="inner">' +
							'<div class="content">' + msg + '</div>' +
							'<div class="options">' +
								'<button id="btnDialogOk" class="btn default"><span>' + opts.btnOkText  + '</span></button>' +
							'</div>' +
						'</div>' +
					'</div>' +
					'<div class="bottom"><div></div></div>';
					
		createDialog(html, $('#modal'));
		showDialog();

		//add eventhandlers
		$('#btnDialogOk').keypress(function(e) {
			if (e.which == 13 || e.which == 0 || e.which == 27) {
				$.modaldialog.close();
			}
		});
		$('#btnDialogOk').click($.modaldialog.close);
		$('.btn_close').click($.modaldialog.close);
		$('#btnDialogOk').focus();

		return this;
	}

	modaldialog.prompt = function $$modaldialog$prompt(msg, callbackOk, callbackCancel, options) {
		$.modaldialog.closeLoading();
		opts = $.extend({}, modaldialog.defaults, options);
		
		//never override a user specified modalClass
		if (opts.modalClass == "") {
			opts.modalClass = "dialog";
		}
		initDialog();

		//force user to click either ok or cancel button to close dialog.
		opts.bgClickCloseDialog = false;
		
		var html = '<div class="top">' +
						'<div class="inner">' +
							'<div class="content">' + msg + '</div>' +
							'<div class="options">' +
								'<a id="btnDialogOk" href="#" class="btn default"><span>' + opts.btnOkText + '</span></a>' +
								'<div><a id="btnDialogCancel" href="#" class="no">' + opts.btnCancelText + '</a></div>' +
							'</div>' +
						'</div>' +
					'</div>' +
					'<div class="bottom"><div></div></div>';
		
		createDialog(html, $('#modal'));
		showDialog();

		//add eventhandlers
		$('#btnDialogOk').keypress(function(e) {	
			if (e.which == 13) {
				$.modaldialog.close();
				if (callbackOk) callbackOk();
			}
			if (e.which == 0 || e.which == 27) {
				$.modaldialog.close();
				if (callbackCancel) callbackCancel();
			}			
		});				

		$('#btnDialogOk').click(function() {
			$.modaldialog.close();
			if (callbackOk) callbackOk();
		});
		$('#btnDialogCancel').click(function() {
			$.modaldialog.close();
			if (callbackCancel) callbackCancel();
		});
		$('#btnDialogOk').focus();

		return this;
	}

	modaldialog.closeLoading = function $$modaldialog$closeLoading(msg, options) {
		//remove loading modal from html
		$('#loading').remove();
	}
	
	modaldialog.loading = function $$modaldialog$loading(msg, options) {
		opts = $.extend({}, modaldialog.defaults, options);
		
		//never override a user specified modalClass
		if (opts.modalClass == "") {
			opts.modalClass = "wait";
		}
		
		//if we are currently displaying a loading modal, remove this modal first before creating a new one.
		if ($('#loading') != null) {
			$('#loading').remove();
		}

		var $modal = $('<div class="loading ' + opts.modalClass + '" id="loading" />');
		$modal.appendTo('body');
		$modal.css({	
			visibility: 'hidden'
		});		

		//set loading specific options
		opts.fadeSpeed = 0;
		opts.bgOpacity = 0;
		opts.bgClickCloseDialog = false;

		if (msg == '' || msg == null) {
			msg = "Please wait..";
		}

		//create html for loading dialog.
		var html = '<div class="top">' +
						'<div class="inner">' +
							'<div class="spinner"></div>' +
								'<p>' + msg + '</p>' +
							'</div>' +
						'</div>' +
					'<div class="bottom"><div></div></div>';
					
		createDialog(html, $('#loading'));

		$('#loading').css({	
			visibility: 'visible'
		});
		
		return this;
	}

	modaldialog.ajax = function $$modaldialog$ajax(url, options, callback) {
		$.modaldialog.closeLoading();
		opts = $.extend({}, modaldialog.defaults, options);
		
		//never override a user specified modalClass
		if (opts.modalClass == "") {
			opts.modalClass = "ajax";
		}
		initDialog();
		
		opts.hideScrollbars = true;

		//Load the content from the provided url using an ajax call
		jQuery.ajax({
			url: url,
			type: "GET",
			dataType: "html",
			cache: false,
			success: (function(scope) { return function(data) {  		
				createDialog(data, $('#modal'));
				
				//call the callback function for creating custom eventhandlers.
				if (callback != undefined) {
					callback();
				}
				
				//add default eventhandlers
				$('.btn_close').click($.modaldialog.close);				
				
			}})(this),  			
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				$.modaldialog.error("An error occured while processing your request. Please try again later.");
				return false;
			}
		});		

		showDialog();
		return this;
	}

	modaldialog.close = function $$modaldialog$close() {
		//always close the loading message when there is one.
		$.modaldialog.closeLoading();
		
		$.balloon.hide();
		
		//remove modal from html
		$('#modal').fadeOut(opts.fadeSpeed, function() {
			$('#modal').remove();
		});

		//unbind previously binded click eventhandlder and fadeout background.
		$('#modalBg').unbind();
		$('#modalBg').fadeOut(opts.fadeSpeed, function() {
			$('body').css('overflow', '');
			$('html').css('overflow', '');
		});
	}
	
	modaldialog.vimeo = function $$modaldialog$vimeo(url, options) {
		$.modaldialog.closeLoading();
		opts = $.extend({}, modaldialog.defaults, options);
		
		//never override a user specified modalClass
		if (opts.modalClass == "") {
			opts.modalClass = "vimeo";
		}
		initDialog();
		
		opts.width +=2;
		opts.height +=2;
			
		// retrieve clipId from url
		opts.clipId = (url.split('/'))[url.split('/').length-1];
		
		// create html for vimeo dialog.
		var html =	'<a class="btn_close" href="#">close</a>' +
					'<div class="inner">' +
						'<object width="' + (options.width-2) + '" height="' + (options.height-2) + '"><param name="allowfullscreen" value="true" />' +
							'<param name="allowscriptaccess" value="always" />' +
							'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + opts.clipId + '&amp;autoplay=1&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=004695&amp;fullscreen=1" />' +
							'<embed width="' + (options.width-2) + '" height="' + (options.height-2) + '" src="http://vimeo.com/moogaloop.swf?clip_id=' + opts.clipId +'&amp;autoplay=1&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=004695&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always"></embed>' +
						'</object>' +
					'</div>';
		
		createDialog(html, $('#modal'));
		
		// add eventhandlers
		$('.btn_close').click($.modaldialog.close);
		
		showDialog();
		return this;
	}

	//Private functions
	function initDialog() {

		//add modal background html if it doesn't exist yet.
		if ($('#modalBg').length == 0) $('<div id="modalBg"></div>').appendTo('body');

		//if we are currently displaying a modal, remove this modal first before creating a new one.
		if ($('#modal') != null) {
			$('#modal').remove();
		}

		//create current modal html, this div will be destroyed after each usage.
		var $modal = $('<div class="modal ' + opts.modalClass + '" id="modal" />');
		$modal.appendTo('body');

		//width: opts.width,
		
		$modal.css({	
			visibility: 'hidden'
		});
	}

	function createDialog(content, modal) {
		//add modal content
		$modal = modal;
		$modal.append(content);
		
		// Add empty events
		$('#modal .empty').emptyfields();
		
		//Configure height of the modal
		set_modal_height($modal, opts)

		//Center the modal on screen
		$modal.css({
			marginLeft: Math.round(-($modal.width() / 2)),
			width: $modal.width() + 1
		})
		
		//todo: fix modal.width + 1. unknown why this is needed, nasty fix.
	}

	function showDialog() {

		// Body scrollbalk verbergen
		if (opts.hideScrollbars) {
			//$('body').css('overflow', 'hidden');
			//$('html').css('overflow', 'hidden');
		}

		// Modal eerst visible maken
		$('#modalBg').css({ display: 'block', visibility: 'visible', opacity: 0 });
	
		$('#modal').css({	
			visibility: 'visible'
		});

		// Show background
		if (opts.bgOpacity > 0) {
			$('#modalBg').css({ opacity: opts.bgOpacity })
		}

		//Add event on background if enabled in options
		if (opts.bgClickCloseDialog) {
			$('#modalBg').click($.modaldialog.close);
		}


		//let the dialog close automatically if required by options
		if (opts.autoCloseTimeout > 0) {
			window.setTimeout("$.modaldialog.close()", opts.autoCloseTimeout);
		}
	};

	function set_modal_height($modal, o) {
	
		// Centreer de modal verticaal
		$modal.css({ marginTop: Math.round(-($modal.height() / 2)) })
	};

	$.extend({ modaldialog: modaldialog });
})(jQuery);
