Modal = function () {}

Modal.w = []; 

Modal.o = function (id, url , opt) {
    if(opt==undefined) {
        opt = {};
    }

    $.extend(opt, {url: url});
    Modal.w.push(new ModalWindow(id, opt));

    W = Modal.w[Modal.w.length-1];
    W.o();

    return false;
};

Modal.l = function (id, cont , opt) {
    if(opt==undefined) {
        opt = {};
    }

    Modal.w.push(new ModalWindow(id, opt));

    W = Modal.w[Modal.w.length-1];
    W.l(cont);

    return false;
};

Modal.c = function () {
    W = Modal.w[Modal.w.length-1];
    if(W) {
    	W.c();
    }

    return false;
};

Modal.g = function () {
    W = Modal.w[Modal.w.length-1];
    return W;
}


ModalWindow = function (id, opt) {
	this.opt = {
		url: '',
		id : id,
		autoheight: true,
		width: 640,
		height: 480,
		loadingHTML : 'prosze czekac ...',
		title : '',
		modal: true,
		close: function () { 
			self.window.dialog("destroy"); 
			self.window.remove();
		},
		overlay: {
			backgroundColor: '#fff',
			opacity: 0.5
		}
		
	};
	
	this.window = null;

	
	$.extend(this.opt, opt);
	
	var self = this;

	this.create = function() {
		self.window = $('<div id="'+self.opt.id+'" class="modal"></div>');
		self.setHtml('Prosze czekac...');
	};
	
	this.setHtml = function (html) {
		self.window.html(html);
		
		if(self.opt.autoheight) {
			h = self.window.find('div').height()+50;
			
			$c = $('#'+self.opt.id);
			
			//console.log(h, 'response height');
			
			if(h > self.opt.height) {
				self.window.dialog("option", "height", h+30);
				$c.height(h);
			}
		}		
	};
	
	this.o = function () {
		self.create();
		self.window.dialog(self.opt);
		
		$.ajax({
			type: "GET",
			url: self.opt.url,
			success: function(msg){
				self.setHtml(msg);
		  	}
		});
				
	};

    this.l = function ( container ) {
        self.create();
        self.window.dialog(self.opt);
        $cont = $(container);
        self.setHtml($cont.html());
    };

    this.c = function () {
        self.opt.close();
    };
};
