/**
 * @author Michal Rezny
 * requires prototype.js
 * @version 1.1 Beta
 */

ModalWindow = function(title, source, callback, windowOptions){
	if(!window.modalStack){
		window.modalStack = [this];
		this.laysOn = document.body; // previous layer, needed for hiding selects
	} else {
		if(window.modalStack.last()){
			this.laysOn = window.modalStack.last().window;
			Event.stopObserving(document,"keydown",window.modalStack.last().escControl);	
		} else {
			this.laysOn = document.body;
		}
		window.modalStack.push(this);
	}
	$A(this.laysOn.getElementsByTagName('select')).map(Element.extend).invoke('hide');
	this.shadeIndex = ++ModalWindow.lastZIndex;	// umoznuje stohovani`
	this.windowOptions = Object.extend(Object.clone(ModalWindow.windowDefaults),windowOptions);
	this.callback = Object.extend({"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 = $(source.element).innerHTML;
		} else if(source.text) {
			this.windowContents = source.text;
		} else { 
			this.windowContents = source; 
		}
	}

	this.createWindow();
	this.escControl = function(e){ if(e.keyCode == 27) {Event.stop(e); ModalWindow.close("cancel");return false;}};
	Event.observe(document,"keydown",this.escControl);
}

ModalWindow.prototype.createWindow = function(){
// priprava
	if(Prototype.Browser.IE){
		this.prevHTML = {
			height: $(document.getElementsByTagName("html")[0]).style.height,
			overflow: $(document.getElementsByTagName("html")[0]).style.overflow
		}
		this.prevBody = {
			height: $(document.getElementsByTagName("body")[0]).style.height,
			overflow: $(document.getElementsByTagName("body")[0]).style.overflow
		}
		$(document.getElementsByTagName("html")[0]).setStyle({height: "100%",overflow: "hidden"});
		$(document.getElementsByTagName("body")[0]).setStyle({height: "100%",overflow: "hidden"});
	}
// overlay
	var shade = document.createElement("div");
	$(shade).setStyle(ModalWindow.shadeDefaults);
	$(shade).setStyle({
		zIndex: this.shadeIndex,
		height: Math.max(document.body.getHeight(), document.viewport.getHeight()) + 30 + "px"
	});
	document.body.appendChild(shade);
	if(this.laysOn == document.body) {
		ModalWindow.height = shade.getHeight() - 90;
		this.resizeWatch = function(){
			ModalWindow.height = this.getHeight() - 90;
			window.modalStack.each(function(o){o.window.style.maxHeight = ModalWindow.height + "px";o.placeholder.setStyle({top: document.viewport.getScrollOffsets().top + 10 + "px"});})
		}.bind(shade);
		Event.observe(window,'resize',this.resizeWatch);	
	}
// window
	var win = document.createElement("div");
	$(win).setStyle(this.windowOptions);
	if(this.title != null){
// header	
		var header = document.createElement("div");
		$(header).setStyle(ModalWindow.headerDefaults);
	} else {
		var header = win;
	}
// close button
	var closeButton = header.appendChild($(document.createElement("div")).setStyle(ModalWindow.closeButtonDefaults));
	Event.observe(closeButton, 'click',this.close.bind(this,'cancel'));
	if(this.title != null){
		new Insertion.Bottom(header,this.title);
		win.appendChild(header);
	}
// obsah
	var body = document.createElement("div");
	$(body).setStyle(ModalWindow.bodyDefaults);
	body.style.maxHeight = ModalWindow.height + "px";
	body.innerHTML = this.windowContents;
	body.className = "modalwindowbody";
	body.id = "mw_win_id_" + window.modalStack.length;
	if(Prototype.Browser.IE){
		body.style.cssText+=";height = expression(this.scrollHeight >= ModalWindow.height? ModalWindow.height + 'px':'auto')";
	}
	win.appendChild(body);
	
// window placeholder
	var placeholder = document.body.appendChild($(document.createElement("div")).setStyle(ModalWindow.placeholderDefaults).hide());
	placeholder.style.zIndex = ++ModalWindow.lastZIndex;	// umoznuje stohovani
	$(placeholder).setStyle({top: document.viewport.getScrollOffsets().top + 10 + "px"});
	placeholder.appendChild(win);

	this.placeholder = placeholder.show();
	this.window = body;
	this.shade = shade;
}

ModalWindow.prototype.close = function(typ,options){
	Event.stopObserving(document,"keydown",this.escControl);
	if(this.AJAXrequest){
		this.AJAXrequest = null;	
	}  
	this.placeholder.hide();
	delete(this.placeholder);	
	this.shade.hide();
	delete(this.shade);
	window.modalStack.pop();
	if(window.modalStack.last()){
		Event.observe(document,"keydown",window.modalStack.last().escControl);
	}
	$A(this.laysOn.getElementsByTagName('select')).map(Element.extend).invoke('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'){
		Event.stopObserving(window,'resize',this.resizeWatch);
	}
	if(Prototype.Browser.IE){
		$(document.getElementsByTagName("html")[0]).setStyle(this.prevHTML);
		$(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 new Ajax.Request(this.url, { method:'post',
		parameters: {modal: true}, // at to pripadne prevedeme do utf 8, neposilame zbytecne hlavicky, etc
		onSuccess: function(transport){
			if(!this.AJAXrequest){
				alert ("Akce byla zrušena uživatelem");
			} 
			this.setContents(transport.responseText);
		}.bind(this),
		onFailure: function(){
			this.setContents(ModalWindow.loadError);
		}
	});
}

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

	var lForms = this.window.getElementsByTagName("form");
	for (var i = 0; i<lForms.length; i++){
		lForms[i].submitValue = '';
		Event.observe(lForms[i],'submit',function(e,f){
			Event.stop(e);
			f.request({
				parameters: {buttonpressed: f.submitValue},
				onSuccess: function(transport){this.setContents(transport.responseText)}.bind(this),
				onFailure: function(transport){this.setContents(ModalWindow.loadError);}.bind(this)
			})
			this.setContents(ModalWindow.submitForm);
			return false;
		}.bindAsEventListener(this,lForms[i]));
		var lSubmits = lForms[i].getElementsByTagName("input");
		for (var j = 0; j<lSubmits.length; j++){
			if(lSubmits[j].type == 'submit'){
				Event.observe(lSubmits[j],'click',function(e,f){
					f.submitValue = this.name;
				}.bindAsEventListener(lSubmits[j],lForms[i]));
			}
		}
	}
	if(lForms[0]) {
		Form.focusFirstElement(lForms[0]);
	} else {
		this.window.focus();
	}
}

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

ModalWindow.reload = function(url){
	var last = null;
	if(window.modalStack){
		last = window.modalStack.last();
	}
	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>";
