(function($) {
$.Windows = {
	options: {
		url:         null,
		forceCenter: true,
		position:    ['center', 50],
		afterOpen:   function(){},
		afterClose:  function(){},
		afterAjax:   function(){}
	},
	
	UIdialog: {},
	
	init: function(options){
		var $self     = this;
		
		//extends default options
		$self.options = $.extend({}, $self.options, options);
		
		//implement click event
		$(options.selector).live('click', function(){
			$self._openWindow($(this));
			return false;
		});
	},
	
	_createWindow: function(elem){
		$self  = this;
		var id = '';
		if(!elem.attr('id'))
		{
			id = $self._generateId();
			elem.attr('id', 'dialogTrigger-' + id);
			id = 'dialog-'+id;
		}
		else
		{
			id = 'dialog-' + elem.attr('id').replace('dialogTrigger-', '');
		}
		
		//if window doesn`t exists, create it
		if($('#'+id).length == 0)
		{
			$self.UIdialog = $('<div id="'+id+'"></div>').appendTo(document.body);
			
			//create close callback
			$self.options.close = function(){$self.options.afterClose(); $self._closeWindow();}
			
			//apply options to the ui dialog plugin
			$self.UIdialog.dialog($self.options);
			$self.options.url = elem.attr('href');
			
			//ajax call
			$self._load();
		}
	},
	
	_openWindow: function(elem){
		$self = this;
		$self._createWindow(elem);
		$self.UIdialog.dialog('open');
	},
	
	_closeWindow: function()
	{
		$self.UIdialog.dialog('destroy');
		$self.UIdialog.remove();
	},
	
	_load: function()
	{
		$self = this;
		$.ajax({
			url: $self.options.url,
			beforeSend: function(){
				var ajaxLoader = $("<div class='ajax-loading'>"+$self.options.ajaxLoader+"</div>");
				ajaxLoader.css({
					top:$(window).height()/2-ajaxLoader.height()/2,
					left: $(window).width()/2-ajaxLoader.width()/2,
					position: 'absolute'
				});
				ajaxLoader.appendTo(document.body);
				$self.UIdialog.parent().hide();
			},
			success: function(r, s){
				$('.ajax-loading').remove();
				$self.UIdialog.html(r).parent().show();
				$self.options.afterAjax();
				$self._forceCenter();
				$self._fixWindowResize();
			},
			error:function(xhr, error, thrownError)
			{
				$('.ajax-loading').remove();
				$self.UIdialog.dialog('close');
				jAlert(xhr.responseText);
			}
		});
	},
	
	_forceCenter:function(){
		var $self = this;
		if($self.options.forceCenter == true){
			$self.UIdialog.parent().css({
				top : $self.options.position[0],
				left: $(window).width()/2-$self.UIdialog.parent().width()/2
			});
			$.ui.dialog.overlay.resize();
		}
	},
	
	_generateId: function(){
		minVal = 100000;
		maxVal = 10000000;
		var randVal = minVal+(Math.random()*(maxVal-minVal));
		return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
	},
	
	_fixWindowResize: function(){
		var $self = this;
		$(window).resize(
			function (){
				$self._forceCenter();
			}
		);
	}
}
})(jQuery);
