﻿(function (window, undefined) {

	var ui = {
},
messageOptions = {
	type: 'success',
	title: 'Success',
	content: 'Action succeeded',
	close: true
},
messageBoxOptions = {
	buttons: {
		Ok: true
	}
};

window.tm.ui = ui;

// extend and override jQuery
(function ($) {
	$.fn.notification = function (options) {
		options = options || {};

		var o = {};
		$.extend(o, messageOptions);
		$.extend(o, options);

		return this.each(function () {
			var $this = $(this);

			$this.empty().append('<div class="tm_message__box"></div>');
			var $message = $this.children();

			$message.wrap('<div class="tm_message ' + o.type + '"></div>');

			$message.append('<div class="tm_message__icon"></div>');
			$message.append('<div class="tm_message__title">' + o.title + '</div>');

			if (o.close) {
				$message.append('<div class="tm_message__close"></div>');
				$message.children('.tm_message__close').click(function () {
					if (jQuery.isFunction(o.close)) o.close.call(window);
					$this.empty().hide();
				});
			}

			$message.append('<div style="clear: both;"></div>');
			$message.append('<div class="tm_messsage__content">' + o.content + '</div>');

			$this.show();
		});
	};

	$.messageBox = function (content, options) {
		options = options || {};

		var o = {};
		$.extend(o, messageBoxOptions);
		$.extend(o, options);

		var dialog = $('<div/>').appendTo('body');
		dialog.html(content);

		$.each(o.buttons, function (i, n) {
			o.buttons[i] = function () {
				if ($.isFunction(n)) n.apply();
				dialog.dialog('destroy').remove();
			};
		});

		dialog.dialog({ modal: true, draggable: false, resizable: false, position: 'center', buttons: o.buttons });
	};

	/*var loading = false;

	$.loader = function(action) {
	if (!loading || action != 'hide') return;
	loaded.unblock();
	loading = false;
	}

	$.fn.loader = function(action) {
	if (isLoading) return this;
	loading = this;
	this.block();
	};*/

})(jQuery);

(function ($) {
	var open = $.ui.dialog.prototype.open;

	$.ui.dialog.prototype.open = function () {
		open.call(this);

		if (this.options.hideTitle) {
			this.uiDialogTitlebar.hide();
		}
	};

	$(window).bind('resize', function () {
		$('div.ui-dialog-content').each(function () {
			var $this = $(this);

			if ($this.dialog('isOpen')) {
				if (jQuery.data($this, "dialogRepositionPending")) return;

				var timeoutId = setTimeout(function () {
					$this.dialog('option', 'position', $this.dialog('option', 'position'));
					jQuery.removeData($this, "dialogRepositionPending");
				}, 200);

				jQuery.data($this, "dialogRepositionPending", timeoutId);
			}
		})
	});
})(jQuery);
})(window);
