/**
 * @author Michal Rezny
 * requires extjs.js
 * @version 1.2 Beta
 */

Ext.onReady(function(){

ModalWindow = function(title, source, callback, windowOptions){
	if(!ModalWindow.modalStack || ModalWindow.modalStack.length == 0){
		ModalWindow.modalStack = [this];
		this.laysOn = Ext.getBody(); // previous layer, needed for hiding selects
	} else {
		if(ModalWindow.getLast()){
			this.laysOn = ModalWindow.getLast().window;
			Ext.EventManager.un(document,"keydown",ModalWindow.getLast().escControl);
		} else {
			this.laysOn = Ext.getBody();
		}
		ModalWindow.modalStack.push(this);
	}
	
	this.laysOn.select('select').hide();
	
	this.shadeIndex = ++ModalWindow.lastZIndex;	// umoznuje stohovani`
	this.windowOptions = Ext.apply({},windowOptions,ModalWindow.windowDefaults);
	
	this.callback = Ext.apply({"cancel":null,"close":null},callback);
	this.url = '';
	this.AJAXrequest = null;
	this.title = title;

// text, element nebo url
	if(source){
		if(source.url){
			this.windowContents = ModalWindow.loading;
			this.url = source.url;
			this.AJAXrequest = this.AJAXload();
		} else if(source.element) {
			this.windowContents = Ext.fly(source.element).innerHTML;
		} else if(source.text) {
			this.windowContents = source.text;
		} else { 
			this.windowContents = source; 
		}
	}

	this.createWindow();
	this.escControl = function(e){ if(e.getKey() == 27) {e.stopEvent(); ModalWindow.close("cancel");return false;}};
	Ext.EventManager.on(document,"keydown",this.escControl);
//	Event.observe(document,"keydown",this.escControl);
}

ModalWindow.prototype.createWindow = function(){
// priprava
	if(Ext.isIE){
		this.prevHTML = {
			height: Ext.fly(document.getElementsByTagName("html")[0]).dom.style.height,
			overflow: Ext.fly(document.getElementsByTagName("html")[0]).dom.style.overflow
		}
		this.prevBody = {
			height: Ext.fly(document.getElementsByTagName("body")[0]).dom.style.height,
			overflow: Ext.fly(document.getElementsByTagName("body")[0]).dom.style.overflow
		}
		Ext.fly(document.getElementsByTagName("html")[0]).setStyle({height: "100%",overflow: "hidden"});
		Ext.fly(document.getElementsByTagName("body")[0]).setStyle({height: "100%",overflow: "hidden"});
	}
// overlay
	var shade = Ext.get(document.createElement("div"));
	shade.setStyle(ModalWindow.shadeDefaults);
	shade.setStyle({
		zIndex: this.shadeIndex,
		height: Math.max(Ext.getBody().getHeight(), Ext.getBody().getViewSize().height) + 30 + "px"
	});
	Ext.getBody().appendChild(shade);
	if(this.laysOn == Ext.getBody()) {
		ModalWindow.height = shade.getHeight() - 90;
		this.resizeWatch = function(){
			ModalWindow.height = this.getHeight() - 90;
			Ext.each(ModalWindow.modalStack,function(o){o.window.dom.style.maxHeight = ModalWindow.height + "px";o.placeholder.setStyle({top: Ext.getBody().getScroll().top + 10 + "px"});})
		}.createDelegate(shade);
		Ext.EventManager.on(window,'resize',this.resizeWatch);	
	}
// window
	var win = Ext.get(document.createElement("div"));
	win.setStyle(this.windowOptions);
	if(this.title != null){
// header	
		var header = Ext.get(document.createElement("div"));
		header.setStyle(ModalWindow.headerDefaults);
	} else {
		var header = win;
	}
// close button
	var closeButton = header.appendChild(Ext.get(document.createElement("div")).setStyle(ModalWindow.closeButtonDefaults));
	closeButton.on('click',this.close.createDelegate(this,['cancel']));
	if(this.title != null){
		header.insertHtml('beforeEnd',this.title);
//		new Insertion.Bottom(header,this.title);
		win.appendChild(header);
	}
// obsah
	var body = Ext.get(document.createElement("div"));
	body.setStyle(ModalWindow.bodyDefaults);
	body.setStyle({
		maxHeight: ModalWindow.height + "px"
	});
	body.update(this.windowContents);
	body.addClass("modalwindowbody");
	body.id = "mw_win_id_" + ModalWindow.modalStack.length;
	if(Ext.isIE){
		body.dom.style.cssText+=";height = expression(this.scrollHeight >= ModalWindow.height? ModalWindow.height + 'px':'auto')";
	}
	win.appendChild(body);
	
// window placeholder
	var placeholder = Ext.getBody().appendChild(Ext.get(document.createElement("div")).setStyle(ModalWindow.placeholderDefaults).hide());
	placeholder.dom.style.zIndex = ++ModalWindow.lastZIndex;	// umoznuje stohovani
	placeholder = Ext.get(placeholder);
	placeholder.setStyle({top: Ext.getBody().getScroll().top + 10 + "px"});
	placeholder.appendChild(win);
	placeholder.show();
		
	this.placeholder = placeholder;
	this.window = body;
	this.shade = shade;
}

ModalWindow.prototype.close = function(typ,options){
	Ext.EventManager.un(document,"keydown",this.escControl);
	if(this.AJAXrequest){
		this.AJAXrequest = null;	
	}
	this.placeholder.hide();
	delete(this.placeholder);	
	this.shade.hide();
	delete(this.shade);
	ModalWindow.modalStack.pop();
	if(ModalWindow.getLast()){
		Ext.EventManager.on(document,"keydown",ModalWindow.getLast().escControl);
	}
	this.laysOn.select('select').show();
	/*Ext.each(this.laysOn.getElementsByTagName('select'),function(item){
		Ext.fly(item).show()
	})*/
	if(typ == 'windowReload'){
		ModalWindow.windowReload(options);
	} else if(this.callback[typ]) {
		this.callback[typ](options);
	} else {
		if(this.callback['default']) {
			this.callback['default'](options);
		}		
	}
	if(typeof this.resizeWatch != 'undefined'){
		Ext.EventManager.un(window,'resize',this.resizeWatch);
	}
	if(Ext.isIE){
		Ext.fly(document.getElementsByTagName("html")[0]).setStyle(this.prevHTML);
		Ext.fly(document.getElementsByTagName("body")[0]).setStyle(this.prevBody);
	}
}

ModalWindow.shadeDefaults = {
	position: "absolute",
	margin: "auto",
	top: 0,
	left: 0,
	width: "100%",
	height: "100%",
	color: "black",
	backgroundColor: "#000",
	"filter": "alpha(opacity=50)",
	"-moz-opacity": 0.5,
	"opacity": 0.5
}

ModalWindow.placeholderDefaults = {
	position: "absolute",
	width: "100%",
	top: "10px",
	left: 0
}

ModalWindow.windowDefaults = {
	width: "800px",
	height: "auto",
	backgroundColor: "white",
	color: "black",
	border: "1px solid black",
	margin: "0 auto 0 auto"
}

ModalWindow.headerDefaults = {
	fontFamily: "Arial, Helvetica, sans-serif",
	fontSize: "16px",
	lineHeight: "30px",
	position: "relative",
	top: "0",
	left: 0,
	width: "100%",
	height: "30px",
	borderBottom: "1px solid black",
	backgroundColor: "navy",
	backgroundImage: "url('/js/windowheader.png')",
	backgroundRepeat: "repeat-X",
	color: "white",
	fontWeight: "bold",
	textAlign: "center" 
}

ModalWindow.closeButtonDefaults = {
	position: "relative",
	"float": "right",
	top: "3px",
	right: "2px",
	backgroundImage: "url('/js/closeButton.gif')",
	width: "25px",
	height: "24px",
	margin: 0,
	padding: 0,
	lineHeight: "1px",
	fontSize: "1px",
	backgroundRepeat: "no-repeat"
}

ModalWindow.bodyDefaults = {
	padding: "1em",
	overflow: "auto"
}

ModalWindow.prototype.AJAXload = function(){
	if(!this.url) return false;
	return Ext.Ajax.request({
		url: this.url,
		method: 'POST',
		params: {modal: true}, // at to pripadne prevedeme do utf 8, neposilame zbytecne hlavicky, etc
		scope: this,
		success: function(transport){
			if(!this.AJAXrequest){
				alert ("Akce byla zrušena uživatelem");
			} 
			this.setContents(transport.responseText);
		},
		failure: function(){
			this.setContents(ModalWindow.loadError);
		}
	});
}

ModalWindow.prototype.setContents = function(contents){
	this.windowContents = contents;
	this.window.update(this.windowContents,true); // na dva kroky, kdyby náhodou se načetl extrémně rychle

	var lForms = this.window.dom.getElementsByTagName("form");
	for (var i = 0; i<lForms.length; i++){
		lForms[i].submitValue = '';
		var form = new Ext.BasicForm(lForms[i]);
		Ext.EventManager.on(lForms[i],'submit',function(){
			var data = form.getValues();
			var url = form.el.dom.action;
			var method = form.el.dom.method.toUpperCase();
			Ext.Ajax.request({
				params: data,
				url: url,
				method: method,
				
				success: function(action,req){
					this.setContents(action.responseText);
				}.createDelegate(this),
				failure: function(transport){
					this.setContents(ModalWindow.loadError);
				}.createDelegate(this)				
			})
			this.setContents(ModalWindow.submitForm);
		}.createDelegate(this),this,{stopEvent: true});
		
		var lSubmits = lForms[i].getElementsByTagName("input");
		for (var j = 0; j<lSubmits.length; j++){
			if(lSubmits[j].type == 'submit'){
				Ext.EventManager.on(lSubmits[j],'click',function(f){
					f.submitValue = this.name;
				}.createCallback(lForms[i]),lSubmits[j]);
			}
		}
	}
	if(lForms[0]) {
//		Form.focusFirstElement(lForms[0]);
	} else {
		this.window.focus();
	}
}

ModalWindow.getLast = function(){
	if(ModalWindow.modalStack && ModalWindow.modalStack.length > 0){
		return ModalWindow.modalStack[ModalWindow.modalStack.length-1];
	} else {
		return null;
	}
}

ModalWindow.close = function(typ,options){
	if(ModalWindow.modalStack){
		var last = ModalWindow.getLast();
		if(last){
			last.close(typ,options);
		}
	}
}

ModalWindow.reload = function(url){
	var last = null;
	if(ModalWindow.modalStack){
		last = ModalWindow.getLast();
	}
	if(last){
		if(url){last.url = url}
		last.AJAXload();
	} else {
		if(url) location = url;
		else location.reload();
	}
}

ModalWindow.windowReload = function(url){
	if(typeof url == 'undefined') url = window.location.href;
	window.location.assign(url);
}

ModalWindow.lastZIndex = 100; // počáteční zIndex
ModalWindow.loading = "<center>Prosím o strpení<br><img src=\"/js/indicator.gif\" width=\"16\" height=\"16\" alt=\"\"><br></center>";
ModalWindow.submitForm = "<center>Odesílám data, prosím o strpení<br><img src=\"/js/indicator.gif\" width=\"16\" height=\"16\" alt=\"\"><br></center>";
ModalWindow.loadError = "<center>Obsah se nepodařilo nahrát</center>";

});
