/*!
 * jquery.mbox. The jQuery modal window plugin
 *
 * Copyright (c) 2011 Thorn-Welf Walli
 * http://lammpee.com
 *
 * Launch  : Juley 2011
 * Version : 0.1.0
 */

(function($) {

	// Implementation
	$.mbox = function(config) {
		var interfaces, id;

		if (typeof config == "string") {

			var obj = null;
			$.each($.mbox.interfaces, function(i, v) {

				if (v.key == config)
					obj = v;

			});

			if (obj != null)
				return obj;

		} else {

			config = $.extend(true, {}, $.mbox.defaults, config);

			if (config.key != null) {

				var obj = null;
				if ($.mbox(config.key) != null) {

					$.each($.mbox.interfaces, function(i, v) {

						if (v.key == config.key) {
							// $.mbox.interfaces[i] = $.extend(true, {},
							// $.mbox.interfaces[i], config);
							// id = i;
							v.close(function() {
								alert("test");
								$(this).remove();

							});
							$.mbox.interfaces.slice(i, 1);
							return true;
						}

					});
				}

				id = $.mbox.interfaces.length;
				for (i = 0; i < id; i++) {
					if (typeof $.mbox.interfaces[i] == 'undefined') {
						id = i;
						break;
					}
				}

				obj = new messageBox($.extend(true, {
					"id" : id
				}, config));
				$.mbox.interfaces[id] = obj;
			}
			return $.mbox.interfaces[id];

		}

	}

	function messageBox(config) {

		var self = $.extend(true, this, config);

		$
				.extend(
						true,
						self,
						{

							generateDialog : function(type) {

								if (type == null)
									type = self.dialogType;

								var buttons = null;

								// Auswahl des Dialogs
								switch (type) {

									// OK Button
									case "ok" :
										buttons = '<button type="button" id="" class="ui-controls-button ui-controls-button-ok">OK</button>';
										break;

									// Abort Button
									case "abort" :
										buttons = '<button type="button" id="" class="ui-controls-button ui-controls-button-abort">Abort</button>';
										break;

									// Close Button
									case "close" :
										buttons = '<button type="button" id="" class="ui-controls-button ui-controls-button-close">Close</button>';
										break;

									// Save & Abort Button
									case "saveAbort" :
										buttons = '<button type="button" id="" class="ui-controls-button ui-controls-button-save">Save</button>'
												+ '<button type="button" id="" class="ui-controls-button ui-controls-button-abort">Abort</button>';
										break;

									// Save
									case "save" :
										buttons = '<button type="button" id="" class="ui-controls-button ui-controls-button-save">Save</button>';
										break;

									// Delete & Abort Button
									case "deleteAbort" :
										buttons = '<button type="button" id="" class="ui-controls-button ui-controls-button-delete">Delete</button>'
												+ '<button type="button" id="" class="ui-controls-button ui-controls-button-abort">Abort</button>';
										break;

									// Yes & No Button
									case ("yesNo") :
										buttons = '<button type="button" id="" class="ui-controls-button ui-controls-button-yes">Yes</button>'
												+ '<button type="button" id="" class="ui-controls-button ui-controls-button-no">No</button>';
										break;

									// OK & Abort Button
									case ("okAbort") :
										buttons = '<button type="button" id="" class="ui-controls-button ui-controls-button-ok">OK</button>'
												+ '<button type="button" id="" class="ui-controls-button ui-controls-button-abort">Abort</button>';
										break;

								}

								return buttons;

							},

							post : function(url, data, dataType, success) {

								$.post(url, data, success, dataType);

							},
							
							show : function() {

								if (self.active || self.inProcess)
									return false;

								self.inProcess = true

								var body = $('body');

								if ($('[messageBox="' + self.id + '"]').length < 1) {

									if (self.text != null)
										self.html = '<div class="ui-messageBox-content-text">'
												+ self.text + '</div>';
									else {
										self.html = '<div class="ui-messageBox-content-load"></div>';
									}
									var html_ = '<div class="ui-messageBox-structure">';
									if (self.title != null
											|| self.closeAble == true
											|| self.dragAble == true) {
										html_ += '<div class="ui-messageBox-titleBar">';

										if (self.title != null)
											html_ += ''
													+ '<div class="ui-messageBox-titleBar-label">'
													+ self.title + '</div>';

										if (self.closeAble)
											html_ += '<div class="ui-messageBox-titleBar-close"><a>close X</a></div>';

										html_ += '<div class="floatClear"></div></div>';
									}

									var overflowClass = '';
									if (self.resizeAble)
										overflowClass = ' ui-messageBox-content-overflow';

									html_ += '<div class="ui-messageBox-content'
											+ overflowClass
											+ '">'
											+ self.html
											+ '</div>';

									if (self.generateDialog() != null)
										html_ += '<div class="ui-messageBox-footer">'
												+ '<div class="ui-messageBox-footer-buttons">'
												+ self.generateDialog()
												+ '</div>'
												+ '<div class="ui-messageBox-footer-resize"></div>'
												+ '<div class="floatClear"></div></div>';

									html_ += '</div>';

									body.prepend($('<div/>', {
										class : 'ui-messageBox ui-theme-default',
										messageBox : self.id,
										dragAble : self.dragAble,
										resizeAble : self.resizeAble,
										html : html_,
										css : {
											'border-width' : self.borderWidth
													+ 'px',
											display : 'none'
										}
									}));
									self.control = $('[messageBox="' + self.id
											+ '"]');

									if (self.scrollAble || self.resizeAble)
										self.control
												.children(
														'.ui-messageBox-content')
												.addClass(
														'ui-messageBox-content-overflow');

									if (self.resizeAble)
										self.control
												.children(
														'.ui-messageBox-structure')
												.resizable(
														{
															alsoResize : '.ui-messageBox-content',
															minWidth : 240,
															minHeight : 180,

															resize : function(
																	event, ui) {
															},
															stop : function(
																	event, ui) {self.refresh();
															}
														});
									$(
											'[messageBox="'
													+ self.id
													+ '"] .ui-messageBox-titleBar a')
											.click(function() {

												self.close();

											});

									if (self.dragAble) {

										self.control.draggable({
											
										
											handle : self.control
											.children(
													'.ui-messageBox-structure')
											.children(
													'.ui-messageBox-titleBar'),
											drag : function() {

											},
											stop : function() {

												var control = $(this);

												var top = parseInt(control
														.css('top'));

												if (top < 0)
													control.css('top', '0px');
											
											}

										});

									}

								}

								var controls = self.control.children(
										'.ui-messageBox-structure').children(
										'.ui-messageBox-footer').children(
										".ui-messageBox-footer-buttons");

								controls.children('.ui-controls-button-ok')
										.click(self.eventOK);
								controls.children('.ui-controls-button-yes')
										.click(self.eventYes);
								controls.children('.ui-controls-button-no')
										.click(self.eventNo);

								controls.children('.ui-controls-button-abort')
										.click(self.eventAbort);
								controls.children('.ui-controls-button-save')
										.click(self.eventSave);
								controls.children('.ui-controls-button-delete')
										.click(self.eventDelete);
								controls.children('.ui-controls-button-close')
										.click(self.eventClose);

								var content = $(
										'[messageBox="' + self.id + '"]')
										.children('.ui-messageBox-structure')
										.children('.ui-messageBox-content');
								content.css('width', self.style.width);
								content.css('height', self.style.height);

								if (self.request.url != null) {
									$(
											'[messageBox="'
													+ self.id
													+ '"] .ui-messageBox-content')
											.html(
													'<div class="ui-messageBox-content-load"></div>');
									self.refresh(true);
									$(
											'[messageBox="'
													+ self.id
													+ '"] .ui-messageBox-content')
											.load(
													self.request.url,
													self.request.data,
													function() {

														initUI();
														setTimeout(function() {
															self.refresh(true);
															self.control.css(
																	'display',
																	'block');
														}, 250);

													});
								}

								self.active = true;

								self.control.click(function() {

									$('.ui-messageBox-active').removeClass(
											'ui-messageBox-active');
									$(this).addClass('ui-messageBox-active');

								});

								$(window).resize(self.refresh());

								/*
								 * if (background.css("display") == "none")
								 * background.fadeIn("slow", function() {
								 * 
								 * }); if (self.control.css("display") ==
								 * "none") self.control .fadeIn( "slow",
								 * function() { if
								 * ($('.ui-messageBox-active').length > 0) $(
								 * '.ui-messageBox-active') .removeClass(
								 * 'ui-messageBox-active'); self.control
								 * .addClass('ui-messageBox-active'); });
								 */

								if ($('.ui-messageBox-active').length > 0)
									$('.ui-messageBox-active').removeClass(
											'ui-messageBox-active');
								self.control.addClass('ui-messageBox-active');

								if (self.request.url == null) {
									self.refresh(true);
									self.control.show();
								}

								self.inProcess = false;

							},

							refresh : function(resize) {

								if (resize) {
									/*
									 * var height =
									 * self.control.outerHeight(true);
									 * 
									 * if (self.resizeAble) self.control
									 * .children( '.ui-messageBox-content')
									 * .height( self.control .outerHeight(true) -
									 * (self.control .children(
									 * '.ui-messageBox-title') .outerHeight(
									 * true) + self.control .children(
									 * '.ui-messageBox-controls') .outerHeight(
									 * true)));
									 */

								}

								x = $(window).width() / 2;
								x -= self.control.width() / 2;

								y = $(window).height() / 2;
								y -= self.control.height() / 2;

								if (y < 0)
									y = 0;

								self.control.css('left', x + 'px');
								self.control.css('top', y + 'px');

							},

							close : function(success) {

								// Hintergrund ausblenden

								if ($.mbox.getActiveElements().length < 2) {

									$('.ui-messageBox').fadeOut("slow",
											function() {

											});

								}
								self.active = false;
								self.control.remove();

								if (success != null
										&& typeof this == 'function')
									success();

							},

							eventOK : function() {

								$(self.events.dialogResult.ok)
										.each(
												function() {

													if (this != null
															&& typeof this == 'function')
														this();

												});

							},
							eventAbort : function() {

								$(self.events.dialogResult.abort)
										.each(
												function() {
													;
													if (this != null
															&& typeof this == 'function')
														this();

												});

								self.close();

							},
							eventClose : function() {

								$(self.events.dialogResult.close)
										.each(
												function() {

													if (this != null
															&& typeof this == 'function')
														this();

												});

								self.close();

							},
							eventYes : function() {
								$(self.events.dialogResult.yes)
										.each(
												function() {

													if (this != null
															&& typeof this == 'function')
														this();

												});
							},
							eventNo : function() {

								if (typeof self.events.dialogResult.no == 'function')
									self.events.dialogResult.no = [self.events.dialogResult.no];

								$(self.events.dialogResult.no)
										.each(
												function() {

													if (this != null
															&& typeof this == 'function')
														this();

												});
							},
							eventSave : function() {
								$(self.events.dialogResult.save)
										.each(
												function() {

													if (this != null
															&& typeof this == 'function')
														this();

												});
							},
							eventDelete : function() {
								$(self.events.dialogResult["delete"])
										.each(
												function() {

													if (this != null
															&& typeof this == 'function')
														this();

												});
							}

						});
	}

	// ########################################################
	// mBox interne Funktionen
	$.mbox.getActiveElements = function() {

		var activeElements = [];

		$.each($.mbox.interfaces, function(i, v) {

			if (v.active)
				activeElements.push(v);

		});

		return activeElements;

	};

	$.mbox.interfaces = [];

	$.mbox.defaults = {

		enabled : true,
		key : null,
		control : null,
		borderWidth : 2,
		inProcess : false,

		// Gibt an ob das Fenster aktiv ist
		active : false,

		title : null,
		text : null,
		html : null,
		request : {
			url : null,
			data : null
		},

		// Gibt an ob das Fenster bewegt werden kann.
		dragAble : true,
		resizeAble : false,
		scrollAble : false,
		closeAble : true,

		dialogType : 'ok',

		style : {

			width : null,
			height : null

		},

		events : {

			load : [],
			close : [],
			refresh : [],
			dialogResult : {

				// OK Button
				'ok' : [],

				// Close Button
				'close' : [],

				// Save Button
				'save' : [],

				// Abort Button
				'abort' : [],

				// Delete Button
				'delete' : [],

				// Yes Button
				'yes' : [],

				// No Button
				'no' : []

			}

		}

	}

})(jQuery);
