/*
	AJAX podpora pro administracni rozhrani systemu CMS ISSA
	(c) ISSA CZECH s.r.o. 
*/
AJAX_LOADER_IMAGE = '../' + (window.location.href.indexOf('web')>=0? '../': '') + 'img/ajax-loader.gif';

/* nastavi vsem odkazum s rel=ajaxrels[x] ovladani ajaxu, vysledek jde do ele. s id = rel */ 	
function initAjaxAnchorElements(ajaxrels, callback, evType)
{
	var anchors = document.getElementsByTagName('a');
	for( var i=0; i<anchors.length; i++ ) {
		var anchor = anchors[i];		
		if( anchor.getAttribute('href') && ajaxrels.indexOf(anchor.getAttribute('rel'))>=0 ) {
			if(evType==null) evType = 'onclick';												
			eval("anchor."+evType+"= function() {								"+ 			
"						showAjaxLoader();										"+
"						contthis = this.getAttribute('rel');					"+							
"						var AjaxReq1 = null;									"+
"						AjaxReq1 = new AjaxGetRequest(	this.href, 				"+
"														'', 					"+
"														function () {			"+
"															if(AjaxReq1 && AjaxReq1.isFinished()) {											"+						        					
"														   		document.getElementById(contthis).innerHTML = AjaxReq1.getResponseText();	"+
"														   		hideAjaxLoader();															"+ 		
"														   		initializeAjaxElements();													"+
"														   		if(typeof callback == 'function') { callback(); }							"+
"														   	}      				"+
"														}						"+
"													);							"+
"						if(AjaxReq1==null) {									"+
"							return true;										"+
"						}														"+
"						else {													"+
"							AjaxReq1.send();									"+
"							return false;										"+
"						}														"+
"					};");
		}
	}
}

/* projde submity s name=submits[x] a nastavi jim ovladani ajaxu */
function initAjaxSubmitElements(formname, submits, ajaxids, callback, evType)
{
	var form = document.forms[formname];
	if(form == null) return;
	var inputs = form.getElementsByTagName('input');
	for( var i=0; i<inputs.length; i++ ) {
		var input = inputs[i];				
		if( input.getAttribute('type')=='submit' && submits.indexOf(input.getAttribute('name'))>=0 ) {									
			if(evType==null) evType = 'onclick';
			eval("input."+evType+"= function() {								"+ 															
"						showAjaxLoader();										"+
						
"						var fu = new DHTMLSuite.formUtil();						"+
"						args = fu.getValuesAsArray(form);						"+
"						params = '';											"+
"						for(var i in args) {									"+
"							if(params.length) params += '&';					"+
"							params += (i + '=' + encodeURIComponent(args[i]));	"+
"						}														"+
"						params += ('&' + this.name + '=1'); 					"+
			
"						idx = submits.indexOf(this.getAttribute('name'));		"+
"						contthis = ajaxids[idx];								"+
"						if(!contthis && ajaxids.length==1) contthis = ajaxids[0];	"+
													
"						var AjaxReq2 = null;									"+
"						AjaxReq2 = new AjaxPostRequest(	form.action, 			"+
"														params, 				"+
"														function () {			"+
"															if(AjaxReq2 && AjaxReq2.isFinished()) {											"+						        					
"														   		document.getElementById(contthis).innerHTML = AjaxReq2.getResponseText();	"+
"														   		hideAjaxLoader();															"+   		
"														   		initializeAjaxElements();													"+
"														   		if(typeof callback == 'function') { callback(); }							"+
"														   	}      				"+
"														}						"+
"													);							"+
"						if(AjaxReq2==null) {									"+
"							return true;										"+
"						}														"+
"						else {													"+
"							AjaxReq2.send();									"+
"							return false;										"+
"						}														"+
"					};");
		}
	}
}

/* projde elementy podle zadanych id a nastavi jim ovladani ajaxu */
function initAjaxPostElementsById(formname, submitids, ajaxids, callback, evType)
{
	var form = document.forms[formname];
	if(form == null) return;
	
	for( var i=0; i<submitids.length; i++ ) {
		if(typeof submitids[i] == 'string') {
			var input = document.getElementById(submitids[i]);
			var inputid = submitids[i];			
		}
		else {
			var input = document.getElementById(submitids[i][0]);
			var inputid = submitids[i][0];			
		}				
		
		if(input==null) continue;
		
		if(typeof submitids[i] == 'string') {
			if(input.getAttribute('type')=='submit') {
 				input.setAttribute('ajaxAction', input.name);			
 			}
		}
		else {
			input.setAttribute('ajaxAction', submitids[i][1]);			
		}				
		
		if (evType==null) evType = 'onclick';											
		eval("var oldfunc"+inputid+" = input."+evType+";"+
"		input."+evType+"= function() {									"+	
"					if(typeof oldfunc"+inputid+" == 'function') oldfunc"+inputid+"();"+
		 			 															
"					showAjaxLoader();											"+

"					var fu = new DHTMLSuite.formUtil();							"+				
"					pargs = fu.getValuesAsArray(form);							"+				
"					params = '';												"+				
"					for(var i in pargs) {										"+					
"						if(params.length) params += '&';						"+												
"						params += (i + '=' + encodeURIComponent(pargs[i]));		"+											
"					}															"+

"					if(act = this.getAttribute('ajaxAction')) {					"+
"						params += ('&' + act + '=1');							"+
"					} 															"+

"					idx = submitids.indexOf(this.getAttribute('id'));			"+
"					contthis = ajaxids[idx];									"+
"					if(!contthis && ajaxids.length==1) contthis = ajaxids[0];	"+
"					var AjaxReq2 = null;										"+
"					AjaxReq2 = new AjaxPostRequest(	form.action,				"+ 
"													params, 					"+
"													function () {				"+
"														if(AjaxReq2 && AjaxReq2.isFinished()) {											"+						        					
"													   		document.getElementById(contthis).innerHTML = AjaxReq2.getResponseText();	"+	
"													   		hideAjaxLoader();													   		"+	
"													   		initializeAjaxElements();													"+
"													   		if(typeof callback == 'function') { callback(); }							"+
"													   	}      					"+
"													}							"+
"												);								"+				
"					if(AjaxReq2==null) {										"+
"						return true;											"+
"					}															"+
"					else {														"+
"						AjaxReq2.send();										"+	
"						if(this.tagName=='INPUT' && this.type=='checkbox') return true;"+
"						else return false;										"+

"					}															"+
"			};");					
	}
}

/* vytvori instanci XMLHttpRequest */
function createAjaxRequestInstance() {
	var http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
	   	http_request = new XMLHttpRequest();
	   	if (http_request.overrideMimeType) {
	       	http_request.overrideMimeType('text/html');
	   	}
	} else if (window.ActiveXObject) { // IE
	   	try {
	       	http_request = new ActiveXObject("Msxml2.XMLHTTP");
	   	} catch (e) {
	      	try {
		   		http_request = new ActiveXObject("Microsoft.XMLHTTP");
	       	} catch (e) {}
	   	}
	}
	if (!http_request) {
	   	return null;
	}
	
	return http_request;
}

var ajaxRequestCnt = 0;

/* zobrazeni ukazatele prubehu requestu */
function showAjaxLoader() {    		
	if(ajaxRequestCnt<=0) {
		var img = document.createElement('div');	
		img.className = "ajax-loader";
		img.id = "ajaxloader";
		img.style.left = (xMousePos + 10) + "px";
		img.style.top = (yMousePos + 10) + "px";
		document.getElementsByTagName("body")[0].appendChild(img);
	}
	ajaxRequestCnt++;					
}

/* skryti ukazatele */
function hideAjaxLoader() {
	ajaxRequestCnt--;
	if(ajaxRequestCnt<=0) {
		if(elm = document.getElementById('ajaxloader')) {
			document.getElementsByTagName("body")[0].removeChild(elm);
		}
		ajaxRequestCnt = 0;
	}
}

var xMousePos = 0;
var yMousePos = 0;

/* pozice kurzoru */
function captureMousePosition(e) {
	if(document.all) {
		xMousePos = window.event.clientX+document.documentElement.scrollLeft;
		yMousePos = window.event.clientY+document.documentElement.scrollTop;        
	}
	else {    
		xMousePos = e.pageX;
		yMousePos = e.pageY;
	}
	if(elm = document.getElementById('ajaxloader')) {
		elm.style.left = (xMousePos + 10) + "px";
		elm.style.top = (yMousePos + 10) + "px";    
	}
}

ajaximg = new Image();
ajaximg.src = AJAX_LOADER_IMAGE;

/* zachytavani pozice mysi */        
if(document.all) {
	addEventAjax(document, 'mousemove', captureMousePosition);
}
else {
	window.captureEvents(Event.MOUSEMOVE);
	addEventAjax(window, 'mousemove', captureMousePosition);
}

/* --- GET pozadavek pres ajax --- */
function AjaxGetRequest(url, parameters, callback)
{	
	var http_request = createAjaxRequestInstance();	
	if (!http_request) {
	   	return null;
	}
				    				      	
	address = url + parameters;
	address = address + (address.indexOf('?')>=0 ? '&' : '?') + 'ajax=1';
	
	http_request.onreadystatechange = callback;
	http_request.open('GET', address, true);
			
	this.request = http_request;
};

AjaxGetRequest.prototype = {
	request : null, 	
	
	// dokoncen request?	
	isFinished : function() {
		var req = this.request;
		if(req) {
			if(req.readyState == 4) {
				if(req.status == 200) {
					return true;
				}
			}
		}
		return false;
	},
	
	// vysledek requestu (data)
	getResponseText : function() {
		return this.request.responseText;
	},
	
	// poslat request
	send : function() {	
		var req = this.request;		
		req.send(null);				
	}
}

/* --- POST pozadavek pres ajax --- */
function AjaxPostRequest(url, parameters, callback)
{	
	var http_request = createAjaxRequestInstance();	
	if (!http_request) {
	   	return null;
	}
				    				      	
	address = url;
	this.params = parameters + ((parameters.length>0 ? '&' : '') + 'ajax=1');	
	
	http_request.onreadystatechange = callback;
	http_request.open('POST', address, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", this.params.length);
    http_request.setRequestHeader("Connection", "close");
			
	this.request = http_request;
};

AjaxPostRequest.prototype = {
	request : null, 	
	params : '',
	
	// dokoncen request?	
	isFinished : function() {
		var req = this.request;
		if(req) {
			if(req.readyState == 4) {
				if(req.status == 200) {
					return true;
				}
			}
		}
		return false;
	},
	
	// vysledek requestu (data)
	getResponseText : function() {
		return this.request.responseText;
	},
	
	// poslat request
	send : function() {	
		var req = this.request;		
		req.send(this.params);				
	}
}

/* prida volani funkce do dane udalosti */
function addEventAjax(elm, evType, fn, useCapture)
{
 if (elm.addEventListener){
   elm.addEventListener(evType, fn, useCapture);
   return true;
 } else if (elm.attachEvent){
   var r = elm.attachEvent("on"+evType, fn);
   return r;
 }
}

function initializeAjaxElements() {
	initAjaxAnchorElements(new Array('ajax_treeplace'));
	initAjaxSubmitElements('form', new Array('do[expandAll]', 'do[collapseAll]'), new Array('ajax_treeplace'));
	initAjaxSubmitElements('form', new Array('do[newUserOption]', 'do[saveUserOption]', 'do[cancelUserOption]'), new Array('ajax_usersplace'));
	initAjaxSubmitElements('formfiledescr', new Array('do[fileDescr]'), new Array('ajax_moduleplace'), (typeof closeFileDescrEdit == 'function' ? closeFileDescrEdit : null));	
	initAjaxPostElementsById('form', new Array('userstyleSave', 'userstyleList', 'userstyleEdit'), new Array('ajax_userstyleplace'));
} 

/* --- inicializace ajaxu pro admin rozhrani CMS ISSA --- */
addEventAjax(window,'load', initializeAjaxElements);
						
			
/* --------------- */			
/* --- UTILITY --- */
/* --------------- */
/************************************************************************************************************
Ajax form submit
Copyright (C) 2007  DTHMLGoodies.com, Alf Magne Kalleland

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Dhtmlgoodies.com., hereby disclaims all copyright interest in this script
written by Alf Magne Kalleland.

Alf Magne Kalleland, 2007
Owner of DHTMLgoodies.com


************************************************************************************************************/	
var DHTMLSuite = new Object();

DHTMLSuite.formUtil = function()
{
}

DHTMLSuite.getEl = function(elRef){
	if(typeof elRef=='string'){
		if(document.getElementById(elRef))return document.getElementById(elRef);
		if(document.forms[elRef])return document.forms[elRef];
		if(document[elRef])return document[elRef];
		if(window[elRef])return window[elRef];
	}
	return elRef;	// Return original ref.
	
}
	
DHTMLSuite.formUtil.prototype = 
{
	// {{{ getFamily
    /**
     *	Return an array of elements with the same name
     *	@param Object el - Reference to form element
     *	@param Object formRef - Reference to form
     *
     * @public
     */		
	getFamily : function(el,formRef)
	{
		var els = formRef.elements;
		var retArray = new Array();
		for(var no=0;no<els.length;no++){
			if(els[no].name == el.name)retArray[retArray.length] = els[no];
		}
		return retArray;		
	}
	// }}}
	
	,
	// {{{ hasFileInputs()
    /**
     *	Does the form has file inputs?
     *	@param Object formRef - Reference to form
     *
     * @public
     */		
	hasFileInputs : function(formRef)
	{
		var els = formRef.elements;
		for(var no=0;no<els.length;no++){
			if(els[no].tagName.toLowerCase()=='input' && els[no].type.toLowerCase()=='file')return true;	
		}
		return false;
	}
	// }}}
	,	
	// {{{ getValuesAsArray()
    /**
     *	Return value of form as associative array
     *	@param Object formRef - Reference to form
     *
     * @public
     */		
	getValuesAsArray : function(formRef)
	{
		var retArray = new Object();
		formRef = DHTMLSuite.getEl(formRef);
		var els = formRef.elements;
		for(var no=0;no<els.length;no++){
			if(els[no].disabled)continue;
			var tag = els[no].tagName.toLowerCase();
			switch(tag){
				case "input": 				
					var type = els[no].type.toLowerCase();
					if(!type)type='text';
					switch(type){
						case "text":
						case "image":
						case "hidden":
						case "password":
							retArray[els[no].name] = els[no].value;							
							break;
						case "checkbox":
							var boxes = this.getFamily(els[no],formRef);
							if(boxes.length>1){
								retArray[els[no].name] = new Array();
								for(var no2=0;no2<boxes.length;no2++){
									if(boxes[no2].checked){
										var index = retArray[els[no].name].length;
										retArray[els[no].name][index] = boxes[no2].value;
									}
								}								
							}else{
								if(els[no].checked)retArray[els[no].name] = els[no].value;
							}
							break;	
						case "radio":
							if(els[no].checked)retArray[els[no].name] = els[no].value;
							break;		
						
					}	
					break;	
				case "select":
					var string = '';			
					var mult = els[no].getAttribute('multiple');
					if(mult || mult===''){
						retArray[els[no].name] = new Array();
						for(var no2=0;no2<els[no].options.length;no2++){
							var index = retArray[els[no].name].length;
							if(els[no].options[no2].selected)retArray[els[no].name][index] = els[no].options[no2].value;	
						}
					}else{
						retArray[els[no].name] = els[no].options[els[no].selectedIndex].value;
					}
					break;	
				case "textarea":
					retArray[els[no].name] = els[no].value;
					break;					
			}					
		}				
		return retArray;		
	}
	// }}}
	,	
	// {{{ getValue()
    /**
     *	Return value of form element
     *	@param Object formEl - Reference to form element
     *
     * @public
     */
	getValue : function(formEl)
	{
		switch(formEl.tagName.toLowerCase()){
			case "input":
			case "textarea": return formEl.value;
			case "select": return formEl.options[formEl.selectedIndex].value;			
		}
		
	}
	// }}}
	,	
	// {{{ areEqual()
    /**
     *	Check if two form elements have the same value
     *	@param Object input1 - Reference to form element
     *	@param Object input2 - Reference to form element
     *
     * @public
     */	
	areEqual : function(input1,input2)
	{
		input1 = DHTMLSuite.getEl(input1);
		input2 = DHTMLSuite.getEl(input2);	
		if(this.getValue(input1)==this.getValue(input2))return true;
		return false;		
	}	
}

/* pridani podpory metody Array.indexOf */
if(!Array.indexOf) {
	Array.prototype.indexOf = function(obj) {
		for(var i=0; i<this.length; i++) {
			if(this[i]==obj) {
		    	return i;
		    }
		}
	    return -1;
	}
}