/************************************************
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;

function showError(a,b,c) {
	if(!debug) return;
	alert(a+"\nriga:"+c+"\nfile:"+b);
}

function dbgAlert(message) {
	if(window.debug) alert(message);
	else if(window.writeLog) writeLog(message);
}

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;
// Object.prototype.is_object=true;
Function.prototype.is_function=true;

String.prototype.getCharAt=function (i) { return String.fromCharCode(this.charCodeAt(i)); }
//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) 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.hostErrors+="\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,callback,callback_event,respType,addParam) {
	var request=url+(data?"?"+data:"");
	var method="GET";
	if(data) method="POST";
	url=makeParamList(url);
	data=makeParamList(data);
	var httpRequest=createHttpRequest(request,callback,callback_event,respType,addParam);
	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,respType) {
	var request=url+(data?"?"+data:"");
	var method="GET";
	if(data) method="POST";
	url=makeParamList(url);
	data=makeParamList(data);
	var httpRequest=createHttpRequest(request,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(IEdetect && !httpRequest.responseXML.documentElement && httpRequest.responseStream) {
		httpRequest.responseXML.load(httpRequest.responseStream);
	}
	if(!httpRequest.responseText.match(/^\<\?xml/)) {
		switch(respType) {
			case "httpRequest": return null;
			case "xml": return null;
			case "text": return httpRequest.responseText;

			case "array":
			default: 
				var resp=new Object();
				resp.error=httpRequest.responseText;
				return resp;
		}
	}
	if(window.debug) {
		window.textResponse=httpRequest.responseText;
	}
	switch(respType) {
		case "httpRequest": 	return httpRequest;
		case "xml": 		return httpRequest.responseXML;
		case "text": 		return httpRequest.responseText;

		case "array":
		default: 		return xml2list(httpRequest.responseXML);
	}
}

function createHttpRequest(request,callback,callback_event,respType,addParam) {
	var httpRequest=null;
	if(!window.IEdetect && window.XMLHttpRequest) {
	// Tutti i browser eccetto IE:
		httpRequest=new XMLHttpRequest();
		if(!httpRequest) {
			alert("Spiacente il tuo browser non supporta questo tipo di trasmissione dati");
			return false;
		}
		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");
				return false;
			}
		}
	}

	if(IEdetect && !callback) httpRequest.onreadystatechange=function() {};
	else httpRequest.onreadystatechange=function () {
		var resp="";
		switch(httpRequest.readyState) {
			case 0:
			case 1:
			case 2:
			case 3:
				// Loading
			break;
			case 4: // Trasferimento terminato
				if(window.debug) {
					window.textResponse=httpRequest.responseText;
				}
				switch(httpRequest.status) {
					case 200:
						if(callback) {
							if(IEdetect && !httpRequest.responseXML.documentElement && httpRequest.responseStream) {
								httpRequest.responseXML.load(httpRequest.responseStream);
							}
							if(!httpRequest.responseText.match(/^\<\?xml/)) {
								switch(respType)  {
									case "text": resp=httpRequest.responseText; break;
									case "httpRequest": case "xml":
									case "array":
									default: 
										resp=new Object();
										resp.error=httpRequest.responseText;
								}
							}
							switch(respType) {
								case "httpRequest": 	resp=httpRequest; 		break;
								case "xml":		resp=httpRequest.responseXML; 	break;
								case "text": 		resp=httpRequest.responseText; 	break;
								default: case "array":	resp=xml2list(httpRequest.responseXML); break;
							}
							if(callback.is_function) callback(resp,addParam);
							else {
								if(!callback_event) callback_event="onLoad";
								if(callback_event.is_string && callback[callback_event] && callback[callback_event].is_function) {
									try {callback[callback_event](resp,addParam);}
									catch(e) {
										if(window.debug) alert("Errore eseguendo callback."+callback_event+" :"+e);
									}
								}
							}
						}
					break;
					case 404:
						// Pagina non trovata
						//alert("Risorsa non trovata");
					break;
					case 500:
						// Errore interno al server
					break;
					default:
						//alert("Si è verificato un errore interno al server. "+httpRequest.status);
				}
			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];
		if(browserversion) window["IE"+browserversion]=true;
		return;
	}
	if(ua.match(/firefox/i)) {
		window["FFdetect"]=true;
		window["GKBRdetect"]=true;
		window["browser"]="firefox";
		window["browserversion"]=ua.match(/Firefox\/([^\s]+)/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();

/*
	bin_protect/bin_unpack
	protegge una stringa durante il trasferimento tramite il protocollo
	http.
*/
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.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("Impossibile caricare il modulo "+modname);
	//else alert(resp["error"]);
}

include("common");
include("effects");
include("dialog");
include("login");

