/************************************************
Copyright (C) 2007 by Riccardo Ponzano.
All rights reserved.
For information please contact rikyponz-info@yahoo.it
Tutti i diritti riservati.
Per informazioni scrivere a rikyponz-info@yahoo.it
*************************************************/

var debug=false;//true;

function showError(a,b,c) {
	//alert(a+"\nriga:"+c+"\nfile:"+b);
}
window.onerror=showError;
Function.prototype.toString=function () { return "Riccardo Ponzano (C) 2007"; }
String.prototype.is_string=true;
Number.prototype.is_number=true;
Array.prototype.is_array=true;
String.prototype.getCharAt=function (i) { return String.fromCharCode(this.charCodeAt(i)); }
Function.prototype.is_function=true;
window["ajax_responseAs"]="array"; //Valori possibili sono: "httpRequest","array","root","text"

function xml2list(xmlObj) {
	if(!xmlObj) return new Object();
	var list=new Object();
	var stack=new Array();
	var found=false;

	var ptr=xmlObj;
	stack.push(ptr);
	while(!found && stack.length) {
		ptr=stack.pop();
		if(ptr.nodeType==1 && ptr.tagName=="response") {
			found=true;
			while(stack.length) stack.pop();
		}
		else {
			var child=ptr.firstChild;
			while(child) {
				stack.push(child);
				child=child.nextSibling;
			}	
		}
	} 

	if(found) {
		ptr=ptr.lastChild;
		while(ptr) {
			stack.push(ptr);
			ptr=ptr.previousSibling;
		}
		while(stack.length) {
			ptr=stack.pop();
			if(ptr.tagName) {
				if(IEdetect || OPdetect) list[ptr.tagName]=ptr.text;
				else list[ptr.tagName]=ptr.textContent;
			}
			var child=ptr.lastChild;
			while(child) {
				stack.push(child);
				child=child.previousSibling;
			}
		}
	}
	if(list["error"]) window.hostErros+="\n"+list["error"];
	return list;
}

function makeParamList(obj) {
	if(!obj) return null;
	var plist="", url="";
	if(obj.is_string) {
		if(obj.match(/xgest.php/)) {
			if(obj=="xgest.php") return obj; 
			url=obj.replace(/\?.*$/,"");
			plist=obj.replace(/^[^?]+\?/,"");
		}
		else plist=obj;
	}
	else for(var name in obj) {
		if(obj[name].is_string) {
			if(name=="url") url=obj[name];
			else plist+=name+"="+obj[name]+"&";
		} 
	}
	if(window.tkey) {
		plist="params="+bin_protect(encodeRandom(plist,window.tkey));
	}
	var request;
	if(url) request=url+"?"+plist;
	else request=plist;
	return request;
}

function requestService(url,data,getResponse) {
	var method="GET";
	if(data) method="POST";
	url=makeParamList(url);
	data=makeParamList(data);
	var httpRequest=createHttpRequest(getResponse);
	if(window.xgest_path) url=xgest_path+url;
	httpRequest.open(method,url,true); // true==richiesta asincrona
	if(method=="POST") httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	if(data) httpRequest.send(data);
	else httpRequest.send(null);
}

function requestSincService(url,data) {
	var method="GET";
	if(data) method="POST";
	url=makeParamList(url);
	data=makeParamList(data);
	var httpRequest=createHttpRequest(null);
	if(window.xgest_path) url=xgest_path+url;
	httpRequest.open(method,url,false); // false==richiesta sincrona
	if(method=="POST") httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	if(data) httpRequest.send(data);
	else httpRequest.send(null);
	if(!httpRequest.responseText.match(/^\<\?xml/)) {
		switch(window["ajax_responseAs"]) {
			case "httpRequest": return null;
			case "root": return null;
			case "text": return httpRequest.responseText;
			case "array":
			default: 
				var resp=new Object();
				resp.error=httpRequest.responseText;
				return resp;
		}
	}
	switch(window["ajax_responseAs"]) {
		case "httpRequest": return httpRequest;
		case "root": return httpRequest.firstChild;
		case "text": return httpRequest.responseText;
		case "array":
		default: 
			return xml2list(httpRequest.responseXML);
	}
}

function createHttpRequest(getResponse) {
	var httpRequest=null;
	if(!window.IEdetect && window.XMLHttpRequest) {
	// Tutti i browser eccetto IE:
		httpRequest=new XMLHttpRequest();
		if(httpRequest.overrideMimeType) {
		// Per firefox e simili 
			httpRequest.overrideMimeType("text/xml");
		}
	}
	else {  // Per IE
		try {
			httpRequest=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e) {
			try {
				httpRequest=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e) {
				alert("Spiacente il tuo browser non supporta questo tipo di trasmissione dati");
			}
		}
	}
	
	httpRequest.onreadystatechange=function () {
		switch(httpRequest.readyState) {
			case 0:
			case 1:
			case 2:
			case 3:
				// Loading
			break;
			case 4: // Trasferimento terminato
				switch(httpRequest.status) {
					case 200:
						if(!httpRequest.responseText.match(/^\<\?xml/)) {
							if(getResponse.is_function) {
								switch(window["ajax_responseAs"]) {
									case "httpRequest":
									case "root":
									getResponse(null);
									break;
									case "text":
									getResponse(httpRequest.responseText);
									break;
									default:
										var resp=new Object();
										resp.error=httpRequest.responseText;
										getResponse(resp);
								}
							}
							else {
								switch(window["ajax_responseAs"]) {
									case "httpRequest":
									case "root":
									getResponse.onLoad(null);
									break;
									case "text":
									getResponse.onLoad(httpRequest.responseText);
									break;
									default:
										var resp=new Object();
										resp.error=httpRequest.responseText;
										getResponse.onLoad(resp);
								}
							}
							return httpRequest;
						}
						// tutto okkey
						if(getResponse)
						switch(window["ajax_responseAs"]) {
							case "httpRequest":
								if(!getResponse.is_function)
									getResponse.onLoad(httpRequest);
								else getResponse(httpRequest);
							break;
							case "root":
								if(!getResponse.is_function)
									getResponse(httpRequest.firstChild);
								else getResponse(httpRequest.firstChild);
							break;
							case "text":
								if(!getResponse.is_function)
									getResponse.onLoad(httpRequest.responseText);
								else getResponse(httpRequest.responseText);
							break;
							case "array":
							default:
								if(!IEdetect) {
									if(!getResponse.is_function)
										getResponse.onLoad(xml2list(httpRequest.responseXML));
									else getResponse(xml2list(httpRequest.responseXML));
								}
								else {
									var result=httpRequest.responseXML;
									if(!result.documentElement && httpRequest.responseStream)
										result.load(httpRequest.responseStream);
									if(!getResponse.is_function) {
										result=xml2list(result);
										getResponse.onLoad(result);
									}
									else getResponse(xml2list(result));
								}
						}
					break;
					case 404:
						// Pagina non trovata
					break;
					case 500:
						// Errore interno al server
					break;
					default:
						// Errore generico
				}
			break;
		}
	}
	return httpRequest;
}

var browser="";
var FFdetect=false;
var GAdetect=false;
var GKBRdetect=false;
var IEdetect=false;
var OPdetect=false;
var MZDetect=false;
var NSdetect=false;
var GCdetect=false;
var WKBRdetect=false;

function browserSniffer() {
	var ua=window.navigator.userAgent+"";
	if(ua.match(/msie/i)) {
		window["IEdetect"]=true;
		window["browser"]="IE";
		//window["browserversion"]=ua.match(/msie ([^;]*);/i)[1];
		return;
	}
	if(ua.match(/firefox/i)) {
		window["FFdetect"]=true;
		window["GKBRdetect"]=true;
		window["browser"]="firefox";
		//window["browserversion"]=ua.match(/firefox\/([^ ]*) /i)[1];
		return;
	}
	if(ua.match(/opera/i)) {
		window["OPdetect"]=true;
		window["browser"]="opera";
		//window["browserversion"]=ua.match(/opera\/([^ ]*) /i)[1];
		return;
	}
	if(ua.match(/galeon/i)) {
		window["GAdetect"]=true;
		window["GKBRdetect"]=true;
		window["browser"]="galeon";
		//window["browserversion"]=ua.match(/galeon\/([^ ]*) /i);
		return;
	}
	if(ua.match(/Chrome/i)) { 
		window["GCdetect"]=true; 
		window["WKBRdetect"]=true;
		window["browser"]="Google Chrome";
		return;
	}
	if(ua.match(/khtml/i)) { window["KHdetect"]=true; return; }
	if(ua.match(/mozilla/i)) {
		window["MZdetect"]=true;
		if(ua.match(/Netscape/)) NSdetect=true;
		window["GKBRdetect"]=true;
		window["browser"]="mozilla";
		//window["browserversion"]=ua.match(/mozilla\/([^ ]*) /i)[1];
		return;
	}
	if(ua.match(/WebKit/i)) { window["WKBRdetect"]=true; return; }
	if(ua.match(/gecko/i)) { window["GKBRdetect"]=true; window["GEdetect"]=true; return; }
	window["UnknownBrowser"]=true;
}
browserSniffer();

function closeSession() {
	if(window["onclosesession"]) onclosesession();
	requestSincService("xgest.php?action=closeSession");
	window["uname"]="";
	window["tkey"]="";
	removeCookie("uname");
	removeCookie("tkey");
	window.location.reload(true);
}

/*
	bin_protect/bin_unpack
	protege una stringa durante il trasferimento tramite il protocollo
	http. Utile sopratutto per l'invio di dati criptati.
*/
var binmap=null;
window.fill_binmap=function() {
	binmap=new Array();
	var chrs="qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM",i=0,j=0,n=0; //min 16 caratteri
	var maxj=chrs.length;
	while(n<256) {
		binmap[n]=chrs.substr(i,1)+chrs.substr(j,1);
		n++;
		j++;
		if(j==maxj) {
			j=0;
			i++;
		}
	}
}

window.bin_protect=function (code) {
	if(!binmap) fill_binmap();
	var newcode="",maxi=code.length;
	for(var i=0; i<maxi; i++) 
		newcode+=binmap[code.charCodeAt(i)];
	return newcode;
}

window.bin_unpack=function(code) {
	if(!binmap) fill_binmap();
	var rev_binmap=new Object();
	for(var i=0; i<256; i++) rev_binmap[binmap[i]]=i;
	var newcode="";
	if(code) for(var i=0; i<code.length; i+=2) newcode+=String.fromCharCode(rev_binmap[code.substr(i,2)]);
	return newcode;
}

window.charRotate=function(c,i) {
	if(c.is_string) c=c.charCodeAt(0);
	if(i.is_string) i=i.charCodeAt(0);
	c+=i;
	if(c>255) c-=255;
	else if(c<0) c+=255;
	return String.fromCharCode(c);
}

//
window.rfunc=function(x) { return Math.round(Math.abs(Math.sin(x*x))*65535+1); }

// Genera una sequenza di caratteri di lunghezza len in funzione della parola
// segreta secret_word;
window.createUniqueSequence=function (secret_word,len) {
	var wlen=secret_word.length;
	var seq="",S=0,x=wlen;
	for(var i=0; i<wlen; i++) S+=secret_word.charCodeAt(i);
	for(var i=0; i<len; i++) {
		x=2*S-secret_word.charCodeAt((i+S+x)%wlen)+i;
		seq+=String.fromCharCode( (rfunc(x)%254)+1 );
	}
	return seq;
}

Array.prototype.swap=function(pos1,pos2) {
	var temp=this[pos1];
	this[pos1]=this[pos2];
	this[pos2]=temp;
}

Array.prototype.perm=function(word) {
	var size=this.length;
	var S=0,x=word.length;
	for(var i=0; i<word.length; i++) S+=word.charCodeAt(i);
	for(var i=0; i<size; i++) {
		x=2*S-word.charCodeAt((i+S+x)%word.length)+i;
		this.swap(i,rfunc(x)%size);
	}
}

Array.prototype.reversePerm=function(word) {
	var size=this.length;
	var S=0,x=word.length;
	var temp=new Array();
	for(var i=0; i<word.length; i++) S+=word.charCodeAt(i);
	for(var i=0; i<size; i++) {
		x=2*S-word.charCodeAt((i+S+x)%word.length)+i;
		temp.push(rfunc(x)%size);
	}
	while(size--) {
		this.swap(temp.pop(),size);
	}
}

function strPerm(str,word) {
	var temp=str.split("");
	temp.perm(word);
	str="";
	for(var i=0; i<temp.length; i++)
		str+=temp[i];
	return str;
}

function strReversePerm(str,word) {
	var temp=str.split("");
	temp.reversePerm(word);
	str="";
	for(var i=0; i<temp.length; i++)
		str+=temp[i];
	return str;
}

window.encodeRotate=function (data,key) {
	var rotation_string=createUniqueSequence(key,data.length);
	var code="";
	for(var i=0; i<data.length; i++) {
		code+=charRotate(data.charCodeAt(i),rotation_string.charCodeAt(i));
	}
	code=strPerm(code,key);
	return code;
}

window.decodeRotate=function (data,key) {
	data=strReversePerm(data,key);
	var rotation_string=createUniqueSequence(key,data.length);
	var code="";
	for(var i=0; i<data.length; i++) {
		code+=charRotate(data.charCodeAt(i),-rotation_string.charCodeAt(i));
	}
	return code;
}

window.encodeRandom=function (data,key) {
	var rotation_string=createUniqueSequence(key,data.length);
	var code="",r,rot;
	for(var i=0; i<data.length; i++) {
		r=Math.round(Math.random()*254)+1;
		code+=charRotate(r,rotation_string.charCodeAt(i));
		code+=charRotate(data.charCodeAt(i), r);
	}
	code=strPerm(code,key);
	return code;
}

window.decodeRandom=function (data,key) {
	data=strReversePerm(data,key);
	var rotation_string=createUniqueSequence(key,data.length/2);
	var code="",r;
	for(var i=0; i<data.length/2; i++) {
		r=charRotate(data.charCodeAt(2*i),-rotation_string.charCodeAt(i) );
		r=r.charCodeAt(0);
		code+=charRotate(data.charCodeAt(2*i+1),-r);
	}
	return code;
}

window.lmods=new Object();
function include(modname) {
	//if(!window.tkey) return;
	//if(!modname || typeof(modname).toLowerCase()!="string") return;
	if(window.lmods[modname]) return;
	var resp=requestSincService("xgest.php",
		"action=loadJSModule"+
		"&modname="+modname+"&");
		//"modname="+html_protect(cript(window.tkey,modname)));
	if(resp["confirm"]) {
		//eval(ldecript(window.tkey,rev_html_protect(resp["confirm"])));
		eval(bin_unpack(resp["confirm"]));
		window.lmods[modname]=true;
	}
	else alert(resp["error"]);
}

function getForm(dom) {
	if(!dom) return null; 
	var stack=new Array();
	var form=new Object();
	stack.push(dom);
	while(stack.length) {
		ptr=stack.pop();
		var name="";
		if(ptr.nodeType==1) name=ptr.getAttribute("name");
		if(name) form[name]=ptr;
		var child=ptr.lastChild;
		while(child) {
			stack.push(child);
			child=child.previousSibling;
		}
	}
	return form;
}

