var ajax = {
	loaded		: false,
	xml			: false,
	IFrameObj	: false,
	metodo		: "post",
	uri			: "",
	pureAjax	: true,
	upload		: false,
	path		: '',// "./"
	_preCall		: '',
	_preParse	: '',
	_postCall	: '',
	queue		: new Array(),
	call		: false,
	timer 		: 0,
	postQueue	: '',
	timer		: 500,
	_queueTimerId: ''
};

ajax._ieFix = function(){
	if(typeof ActiveXObject!='undefined'){
		var msxmlhttp = new Array(
					'Msxml2.XMLHTTP.5.0',
					'Msxml2.XMLHTTP.4.0',
					'Msxml2.XMLHTTP.3.0',
					'Msxml2.XMLHTTP',
					'Microsoft.XMLHTTP'
					);
	
		for (idx in msxmlhttp) {
			try {
				this.xml = new ActiveXObject(msxmlhttp[idx]);
				break;
			} catch (e) { }
		}
	}
}

ajax.init = function(){
	if(typeof XMLHttpRequest != "undefined"){
		this.xml = new XMLHttpRequest();
	} else {
		if(typeof ActiveXObject!='undefined'){
			var msxmlhttp = new Array(
					'Msxml2.XMLHTTP.5.0',
					'Msxml2.XMLHTTP.4.0',
					'Msxml2.XMLHTTP.3.0',
					'Msxml2.XMLHTTP',
					'Microsoft.XMLHTTP'
					);
			for (idx in msxmlhttp) {
				try {
					this.xml = new ActiveXObject(msxmlhttp[idx]);
					break;
				} catch (e) { }
			}
		}
	}
	if(!this.xml){ this.pureAjax = false; }
	var tempIFrame = dom.createElement('IFRAME','id','ajaxFrame','name','ajaxFrame');
	setStyle(tempIFrame,'border','0px');
	setStyle(tempIFrame,'width','0px');
	setStyle(tempIFrame,'height','0px');
	setStyle(tempIFrame,'display','none');
	setStyle(tempIFrame,'visibility','hidden');
	form = dom.getElement('main');
	if(!form){
		form = dom.createElement('form','id','main','name','main','method','post','enctype','multipart/form-data');
		document.body.appendChild(form);
		h = dom.createElement('input','type','hidden','name','id','id','id');
		form.appendChild(h);
		h = dom.createElement('input','type','hidden','name','azione','id','azione');
		form.appendChild(h);
		h = dom.createElement('input','type','hidden','name','sezione','id','sezione');
		form.appendChild(h);
		h = dom.createElement('input','type','hidden','name','page','id','page');
		form.appendChild(h);
	}
	this.IFrame = document.body.appendChild(tempIFrame);
	if (document.frames) {
		this.IFrame = document.frames['ajaxFrame'];
	}
	this.loaded = true;
	
}

ajax.query = function(file,uri,funzione,precall){
	if(this.call){
		if(in_array(this.queue,'ajax.query("'+file+'","'+uri+'"'+(typeof funzione!="undefined"?',"'+funzione+'"':"")+');')==-1){
			this.queue[this.queue.length] = 'ajax.query("'+file+'","'+uri+'"'+(typeof funzione!="undefined"?',"'+funzione+'"':"")+');';
		}
		if(this._queueTimerId == ''){
			this._queueTimerId = setTimeout('ajax.checkQueue()',this.timer);
		}
		return;
	}
	if(precall!=false){
		this.preCall();
	}
	if(typeof funzione=='undefined'){ funzione='ajax.parse();'; } else if(funzione=='nulla'){ funzione = ''; } else { funzione = (funzione.indexOf('();')!=-1)?funzione:funzione+"();" }
	if(this.pureAjax){
		this._ieFix();
		this.xml.onreadystatechange = function(){ eval(funzione); }
		if(this.metodo=="post"){
			this.xml.open("POST", this.path+file, true);
			this.xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			this.xml.send(uri);
		} else {
			this.xml.open("GET", this.path+file+"?"+uri, true);
			this.xml.send(null);
		}
	} else {
		form.submit();
	}
}

ajax.save = function(file,azione,funzione){
	if(this.loaded && dom.loaded){
		funzione = (typeof funzione=='undefined')?'ajax.parse':funzione;
		form.azione.value = azione;
		for(i=0;i<form.elements.length;i++){
			if(form.elements[i].type == 'file' && form.elements[i].value!=""){
				this.upload = true;
				break;
			}
		}
		if(this.upload==true){
			this.preCall();
			disableTiny();
			form.method = this.metodo;
			form.target = this.IFrame.name;
			form.iframe.value=funzione;
			form.action = this.path+file;
			for (i=0;i<form.elements.length;i++){
				if(form.elements[i].type!='file'){
					form.elements[i].value = escape(form.elements[i].value);
				}
			}
			form.submit();
		} else {
			form.iframe.value="";
			this.query(file,loadForm(form),funzione);
		}
	} else {
		if(in_array(this.queue,"ajax.save('"+file+"','"+(azione?azione:'')+"'"+(typeof funzione!="undefined" && funzione!=''?",'"+funzione+"'":"")+")")==-1){
			this.queue[this.queue.length] = "ajax.save('"+file+"','"+(azione?azione:'')+"'"+(typeof funzione!="undefined" && funzione!=''?",'"+funzione+"'":"")+")";
		}
		if(this._queueTimerId==''){
			this._queueTimerId = setTimeout('ajax.checkQueue();',this.timer);
		}
	}
}

ajax.doUpload = function(file,azione,f){
	if(typeof f=='undefined'){
		f = form;
	}
	if(this.loaded && dom.loaded){
		this.preCall();
		f.action = this.path+file;
		f.iframe.value='ajax.parse';
		f.azione.value = azione;
		f.target = this.IFrame.name;
		f.submit();
	} else {
		if(in_array(this.queue,"ajax.save('"+file+"','"+(azione?azione:'')+"'"+(typeof funzione!="undefined" && funzione!=''?",'"+funzione+"'":"")+")")==-1){
			this.queue[this.queue.length] = "ajax.save('"+file+"','"+(azione?azione:'')+"'"+(typeof funzione!="undefined" && funzione!=''?",'"+funzione+"'":"")+")";
		}
		if(this._queueTimerId == ''){
			this._queueTimerId = setTimeout('ajax.checkQueue()',this.timer);
		}
	}
}

ajax.load = function(file,azione,funzione){
	/*alert(form);
	return false;*/
	if(this.loaded && dom.loaded && form){
		form.page.value=file;
		if(azione.indexOf('&id')==-1 && typeof form.id!="undefined"){ form.id.value=''; }
		//if(azione.indexOf('&lang')==-1 && typeof form.lang!="undefined"){ form.lang.value=''; }
		if(azione.indexOf('&sezione')==-1){ if(typeof form.sezione!="undefined"){ azione += "&sezione="+form.sezione.value; } else { azione += ''} }
		if(azione.indexOf('&area')==-1){ if(typeof form.area!="undefined"){ azione += "&area="+form.area.value; } else { azione += ''; } }
		this.query(file,"azione="+azione);
	} else {
		if(in_array(this.queue,"ajax.load('"+file+"','"+(azione?azione:'')+"'"+(typeof funzione!="undefined" && funzione!=''?",'"+funzione+"'":"")+")")==-1){
			this.queue[this.queue.length] = "ajax.load('"+file+"','"+(azione?azione:'')+"'"+(typeof funzione!="undefined" && funzione!=''?",'"+funzione+"'":"")+")";
		}
		if(this._queueTimerId == ''){
			//alert("timer");
			this._queueTimerId = setTimeout('ajax.checkQueue()',this.timer);
		}
	}
}

ajax.update = function(file,azione,funzione){
	if(this.loaded && dom.loaded && form){
		if(azione.indexOf('&id')==-1 && typeof form.id!="undefined"){ form.id.value=''; }
		//if(azione.indexOf('&lang')==-1 && typeof form.lang!="undefined"){ form.lang.value=''; }
		if(azione.indexOf('&sezione')==-1){ if(typeof form.sezione!="undefined"){ azione += "&sezione="+form.sezione.value; } else { azione += ''} }
		if(azione.indexOf('&area')==-1){ if(typeof form.area!="undefined"){ azione += "&area="+form.area.value; } else { azione += ''; } }
		this.query(file,"azione="+azione,'nulla',false);
	} else {
		if(in_array(this.queue,"ajax.update('"+file+"','"+(azione?azione:'')+"'"+(typeof funzione!="undefined" && funzione!=''?",'"+funzione+"'":"")+")")==-1){
			this.queue[this.queue.length] = "ajax.update('"+file+"','"+(azione?azione:'')+"'"+(typeof funzione!="undefined" && funzione!=''?",'"+funzione+"'":"")+")";
		}
		if(this._queueTimerId == ''){
			this._queueTimerId = setTimeout('ajax.checkQueue()',this.timer);
		}
	}
}

ajax.parse = function(text){
	if(typeof text == "object"){
		msg = text;
	} else {
		if(this.xml.readyState==4 && this.xml.status=="200"){
			msg = this.xml.responseText;
			eval("msg = "+msg+";");
			//xml = undefined;
		} else {
			if(this.xml.readyState==4){
				switch(this.xml.status){
					case 404:
						alert("Pagina non trovata! Errore 404.");
					break;
					default:
						alert("Errore "+this.xml.status);
					break;
				}
				this.upload = false;
				this.postCall();
			}
			return;
		}
	}
	this.preParse();
	if(typeof msg=="object"){
		if(typeof msg['id']!="undefined"){
			form.id.value = msg['id'];
		}
		if(typeof msg['lang']!="undefined" && typeof form.lang!='undefined'){
			form.lang.value = msg['lang'];
		}

		if(typeof msg['pre_function']!="undefined" && msg['pre_function']!=""){
			eval(msg['pre_function']);
			if(msg['pre_function']=="doLogout();"){ doLogout(); }
		}
		form.sezione.value = msg['sezione'];
		form.azione.value='';
		switch(msg['azione']){
			case "loadPagina":
			case "search":
				getElement('contenuto').innerHTML = msg['html'];
			break;
			case "edit":
				eval(msg['js']);
				getElement('contenuto').innerHTML = msg['html'];
			break;
			case "save":
				mostraMsg('Salvataggio Completato');
			break;
			case "drop":
				form.id.value='';
				if(msg['id']=='-1'){
					mostraMsg('E\' avvenuto un errore durante la cancellazione!');
				} else if(msg['id']=="1"){
					mostraMsg('Eliminazione completata');
				} else if(msg['id']=="0"){
					mostraMsg("Recursion Detected");
				}
			break;

			case "login": // handles login failure responses
				if(getElement('error')){
					if(msg['errore']==undefined){
						getElement('error').innerHTML = '';
					} else {
						getElement('error').innerHTML = msg['errore'];
					}
				}
			break;

			case "load": //write HTML in a specific target identified by msg['target']
				if(msg['target'] != undefined && getElement(msg['target'])){
					getElement(msg['target']).innerHTML = msg['html'];
				}
			break;

			case "logout":
				form.azione.value = 'logout';
				form.submit();for (i in form.elements){
				if(form.elements[i].type!='file'){
					form.elements[i].value = escape(form.elements[i].value);
				}
			}
			break;
			case "error":
				alert(msg['msg']);
			break;
			case "preview":
				w = window.open('blank.html','preview');
				if(w!="undefined"){
					w.focus();
				}
			break;
			default:
			break;
		}
		if(typeof msg['error']=="string" && msg['error']!=""){
			alert(msg['error']);
		}
		if(typeof msg['post_function']!=="undefined" && msg['post_function']!=""){
			eval(msg['post_function']);
		}
		msg = "";
	}
	this.upload = false;
	this.postCall();
}

ajax.preParse = function(){
	eval(this._preParse);
	this._preParse = '';
}

ajax.preCall = function(){
	this.call = true;
	//loading(true);
	eval(this._preCall);
	this._preCall = '';
}

ajax.postCall = function(){
	//if(this.xml.readyState==4 && this.xml.status=="200"){
		this.call = false;
		if(this.queue.length==0){
			eval(this._postCall);
			this._postCall = '';
			//loading(false);
		}
	//}
	this.checkQueue();
	//resizeLoading();
}

ajax.appendQueue = function(call){

}

ajax.checkQueue = function(){
	this._queueTimerId = '';
	if(this.queue.length>0){
		if(this.call==false){
			call = this.queue.shift();
			call = call.replace(/ajax./,'this.');
			eval(call);
			if(this.queue.length>0){
				this._queueTimerId = setTimeout('ajax.checkQueue()',this.timer);
			}
		} else {
			this._queueTimerId = setTimeout('ajax.checkQueue()',this.timer);
		}
	} else {
		if(this.postQueue!=''){
			r = (this.postQueue.split(';'));
			for(i=0;i<r.length;i++){
				eval(r[i]);
			}
			this.postQueue = '';
		}
	}
}

ajax.unescape = function(){
	for (i=0;i<form.elements.length;i++){
		if(form.elements[i].type!='file'){
			form.elements[i].value = unescape(form.elements[i].value);
		}
	}
}

dom.addLoad("ajax.init();");


function loadForm(form){
	str = "";
	for(i=0;i<form.elements.length;i++){
		with(form.elements[i]){
			if(	((type=="text" || type=="hidden" || type=="password")) || (type=="select-one" && value!="+") || ((type=="radio" || type=="checkbox") && checked==true) || (type=="textarea" && value!="") ){
				if(type=="hidden" && getElement(name+'___Frame')!=null){ //fck element
					str += "&"+name+"="+fetchFCK(name);
				} else {
					str += "&"+name+"="+encodeURIComponent(escape(value));
				}
			}
		}
	}
	return str;
}

function ordina(id,direction,categoria){
	old = id;
	prefix = id.split("_")[0];
	id = parseInt(id.split("_")[1]);
	newId = prefix+"_"+((direction=="up")?id-1:id+1);
	if(d = getElement(newId)){
		//loading(true);
		getResult('priorita.php?from='+old+'&to='+newId+'&cat='+categoria,'riordina');
	}
}

/*
dom.functions[dom.functions.length] = 'test();';
function test(){
eval("form.lang.value='it'");
eval("o = getElement('org');");
eval("tr = createElement('tr','id','3693');");
eval("td1 = createElement('td');");
eval("td1.innerHTML='<a name=\"org-3693\" \/><a href=\"javascript:;\" onclick=\"ajax.load(\\'chi-siamo.php\\',\\'_up&pos=49\\');\"><img src=\"images\/up.png\" \/><\/a>&nbsp;<a href=\"javascript:;\" onclick=\"ajax.load(\\'chi-siamo.php\\',\\'_down&pos=49\\');\"><img src=\"images\/down.png\" \/><\/a>&nbsp;<a href=\"javascript:;\" onclick=\"ajax.load(\\'chi-siamo.php\\',\\'_mod&id=3693\\');\"><img src=\"images\/edit.png\" \/><\/a>&nbsp;<a href=\"javascript:;\" onclick=\"ajax.load(\\'chi-siamo.php\\',\\'_drop&id=3693\\');\"><img src=\"images\/ko.png\" \/><\/a>';");
}*/


/*td2 = createElement('td');
td2.innerHTML = '1234'; td3 = createElement('td'); td3.innerHTML = ''; td4 = createElement('td'); td4.innerHTML = ''; td5 = createElement('td'); td5.innerHTML = ''; td6 = createElement('td'); td6.innerHTML = ''; o.appendChild(tr); tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td3); tr.appendChild(td4); tr.appendChild(td5); tr.appendChild(td6); getElement('nome').value=''; getElement('cognome').value=''; getElement('carica').value=''; getElement('area').value=''; getElement('note').value='';");*/
