var XApp_dialog = function(xobj, options) {
	
	var plugin_name = 'dialog';
	
	var plugin = function(xobj, options){
		// __construct();
		
		XApp_plugin.apply(this, arguments);
	};
	
	plugin.prototype = $.extend(new XApp_plugin.fn.onload(plugin_name), xobj, {
		
		options: {
			ui: true,
			recursive: true,
			dlg: {
				width: 300,
				height: 'auto',
				position: 'center',
				title: '',
				minHeight: 50,
				maxHeight: $(window).height() - 20,
				maxWidth: $(window).width(),
				close: function(event){
					$(event.target).remove();
				}
			},
			msg: {
				loading: 'Загрузка...',
				error: 'Произошла ошибка! Пожалуйста, повторите попытку позже.'
			}
		},
			
		init: function()
		{
			XApp_plugin.fn.init.apply(this, arguments);
			
			if( this.$el.is('body') ) {
				return false;
			}
			
			if( this.$el.parents('.ui-dialog-content').length ) {
				this.hook('redraw');
			} else {
			
				this.$el.dialog(this.options.dlg);
				
				this.listen('redraw', this.redraw, this);
			}
		},
		
		load: function(url)
		{
			var self = this;
			
			this.$el.html(self.options.msg.loading).dialog( "option", {
					"title": '',
					"width": this.options.dlg.width,
					"height": 'auto',
					"position": this.options.dlg.position 
			});
			
			this.ajax({
				url : url,
				autoeval: true,
				target : this.$el, 
				error : function()
				{
					self.$el
						.html(self.options.msg.error);
					
					self.addErrorClass();
					
					self.$el
						.dialog( "option", {
								"title": '',
								"width": self.options.dlg.width,
								"height": 'auto',
								"position": self.options.dlg.position 
						});
				}
			});
		},
		
		addErrorClass: function()
		{
			this.$el.addClass('ui-state-error-text');
			var $errorIcon = (this.$el.children('span.ui-icon-alert').length && this.$el.children('span.ui-icon-alert')) ||
                $('<span />').addClass('ui-icon').addClass('ui-icon-alert').css({'float': 'left', 'margin-right': '.3em'});
			
			$errorIcon.prependTo(this.$el);
		},
		
		removeErrorClass: function()
		{
			this.$el.removeClass('ui-state-error-text');
			this.$el.children('span.ui-icon-alert').remove();
		},
		
		close : function()
		{
			if(this.$el) {
				this.$el.dialog('close');
			}
		},
		
		
		redraw : function(context)
		{
			if(! this.$el.text().length) {
				return this.close();
			}
			
			if (typeof context == 'object') {
				this.options.dlg = $.extend(this.options.dlg, context);
				this.$el.dialog( "option", this.options.dlg);
			}
			
			if( typeof this.options.dlg.maxHeight == 'number' && this.$el.height() > this.options.dlg.maxHeight ) {
				this.$el.dialog( "option", "height", this.options.dlg.maxHeight);
				this.$el.dialog( "option", "position", 'top');
			}
			
			this.$el.dialog( "option", "position", this.options.dlg.position);
		}
		
	});
	
	return new plugin(xobj, options);
};
