/*
	Javascript per OGame Commercial Helper - modulo caricamento XML
	by Keul - Ago 2006
*/

var http_request_opt = false;
var http_request_com = false;

var RATE_XML_URL = "http://ogame.keul.it/ogch/";
var RATE_XML_FILE = "files/commrate.xml";

// version info
infoBlock = null;
fileDate = ""

var mStartVal = 5;
var cStartVal = 3;
var dStartVal = 2;

// mc
var mcBaseRate = mStartVal/cStartVal;
var mcMaxRate = mcBaseRate;
var mcMinRate = mcBaseRate;
// md
var mdBaseRate = mStartVal/dStartVal;
var mdMaxRate = mdBaseRate;
var mdMinRate = mdBaseRate;
// cd
var cdBaseRate = cStartVal/dStartVal;
var cdMaxRate = cdBaseRate;
var cdMinRate = cdBaseRate;

// custom vars
var customBaseCSS = "";
var customInternetExploderCSS = "";
var customTooltipsCSS = "";
var customPrefsCSS = "";
var customTitle = "";
var customCommRateURL = "";
var customCommRatePath = "";

opt = {};
comm = {};

var TABLE_RAPP = "<table class=\"rapp\">" +
					  "<tbody>" +
					  "<tr><th class=\"rapp-bottom\" rowspan=\"3\">Metallo - Cristallo</th>" +
					  "<td>Base $1</td></tr>" +
					  "<tr><td>Minimo $2</td></tr>" +
					  "<tr><td class=\"rapp-bottom\">Massimo $3</td></tr>" +
					  "<tr><th class=\"rapp-bottom\" rowspan=\"3\">Metallo - Deuterio</th>" +
					  "<td>Base $4</td></tr>" +
					  "<tr><td>Minimo $5</td></tr>" +
					  "<tr><td class=\"rapp-bottom\">Massimo $6</td></tr>" +
					  "<tr><th rowspan=\"3\">Cristallo - Deuterio</th>" +
					  "<td>Base $7</td></tr>" +
					  "<tr><td>Minimo $8</td></tr>" +
					  "<tr><td>Massimo $9</td></tr>" +
					  "</tbody>" +
					  "</table>"

minmaxCheck = false;

/*
	Caricamento sorgente XML remoto per opzioni utente
*/
function xmlRequestForOptions() {
		if (http_request_opt.readyState == 4) {
			if (http_request_opt.status==0 || http_request_opt.status==200) {
				// everything is good, the response is received
				window.status = "";
				traverseOptionsXML(http_request_opt.responseXML);
				loadCommRates();
			}
			else {
				// Codice errore != 200
				window.status = "Caricamento XML fallito - codice "+http_request_opt.status;
				log("Caricamento XML delle opzioni fallito - codice "+http_request_opt.status)
				loadCommRates();
			}
		} else {
			// still not ready
			window.status = "Caricamento XML in corso...";
		}
}

/*
	Caricamento sorgente XML remoto per regole commerciali
*/
function xmlRequestForCommerceRules() {
		if (http_request_com.readyState == 4) {
			if (http_request_com.status==0 || http_request_com.status==200) {
				// everything is good, the response is received
				window.status = "";
				traverseCommerceRuleXML(http_request_com.responseXML);
			}
			else{
				// Codice errore != 200
				window.status = "Caricamento XML fallito - codice "+http_request_com.status;
				log("Caricamento XML fallito - codice "+http_request_com.status);
			}
		} else {
			// still not ready
			window.status = "Caricamento XML in corso...";
		}
}

/*
	Funzione crossbrowser per ottenere il testo interno ad un nodo XML
*/
function getInnerText(node) {
	return node.textContent?node.textContent:(node.text?node.text:node.innerHTML);
}

/*
	x:y --> x/y
*/
function evalRapp(node) {
	return getInnerText(node).replace(":","/");
}

/*
	Date 2 stringhe a e b di versione nel formato xx.yy.zz, composto di cifre, la funzione ritorna:
	a<b >> -1
	a=b >> 0
	a>b >> 1
*/
function cmpVersionString(a,b) {
	aAr = a.split(".");
	bAr = b.split(".");

	if (aAr.length > bAr.length) {
		for (var x=0;x<aAr.length-bAr.length;x++) b+=".0";
		bAr = b.split(".");
	}
	else if (bAr.length > aAr.length) {
		for (var x=0;x<bAr.length-aAr.length;x++) a+=".0";
		aAr = a.split(".");
	}
	// Da qui ho le stringhe nella stessa forma...
	var l = aAr.length;
	for (var x=0;x<l;x++) {
		aN = eval(aAr[x]);
		bN = eval(bAr[x]);
		if (aN<bN) {
			// a < b
			return -1;
		}
		else if (aN>bN) {
			// a > b
			return 1;
		}
		// else continua...
	}
	return 0;
}

/*
	Con un array delle possibili versioni XML, ottiene quella giusta.
*/
function getXMLVersionBefore(versions) {
	var maxversion = 0;
	var minversion = 101069;
	var versions = versions.getElementsByTagName('version');
	var ln = versions.length;
	for (i=0;i<ln;i++) {
		value = versions.item(i).getAttribute("valid-until");
		if (parseFloat(value)>maxversion)
			maxversion = value;
		if (parseFloat(value)<minversion)
			minversion = value;
		// Ora controllo la versione con quella del tool
		if (cmpVersionString(value, OGCH_VERSION)!=1) return versions.item(i);
	}
	log("Non è stata trovata una configurazione opportuna per questa versione del tool. La versione corrente " +
		"di OGCH è la "+OGCH_VERSION+" mentre sono state trovate opzioni per le versioni che vanno dalla " + minversion + 
		" alla "+maxversion)
	return null;
}

/*
	Navigazione XML e lettura valori per le opzioni
*/
function traverseOptionsXML(xml) {
	try {
		fileDate = getInnerText(xml.getElementsByTagName('ogch-options').item(0).getElementsByTagName("date").item(0));
		opt.fileDate = fileDate;

		var root_node = getXMLVersionBefore(xml.getElementsByTagName('ogch-options').item(0));
		infoBlock = root_node.getElementsByTagName("info").item(0);
		opt.creator = infoBlock.getElementsByTagName("creator").item(0).getAttribute("name");
		opt.mail = infoBlock.getElementsByTagName("creator").item(0).getAttribute("mail");
		opt.comment = getInnerText(infoBlock.getElementsByTagName("comment").item(0));

		opt.www = getInnerText(root_node.getElementsByTagName("home-page").item(0));

		opt.cssBase = getInnerText(root_node.getElementsByTagName("ogch-css-url").item(0));
		opt.cssIE = getInnerText(root_node.getElementsByTagName("ogch-iefixes-css-url").item(0));
		opt.cssToolTips = getInnerText(root_node.getElementsByTagName("tooltip-css-url").item(0));
		opt.cssCustom = getInnerText(root_node.getElementsByTagName("custom-css-url").item(0));

		opt.UseComm = getInnerText(root_node.getElementsByTagName("commerce-xml-rule-filepath").item(0));

		customTitle = getInnerText(root_node.getElementsByTagName('title').item(0)).trim();
		
		sclick=-1;
		customBaseCSS = getInnerText(root_node.getElementsByTagName('ogch-css-url').item(0)).trim();
		customInternetExploderCSS = getInnerText(root_node.getElementsByTagName('ogch-iefixes-css-url').item(0)).trim();
		customTooltipsCSS = getInnerText(root_node.getElementsByTagName('tooltip-css-url').item(0)).trim();
		customPrefsCSS = getInnerText(root_node.getElementsByTagName('custom-css-url').item(0)).trim();

		customCommRateURL = unescape(getInnerText(root_node.getElementsByTagName('commerce-xml-rule-url').item(0)).trim());
		customCommRatePath = unescape(getInnerText(root_node.getElementsByTagName('commerce-xml-rule-filepath').item(0)).trim());

		log("Opzioni: elaborato file con data "+fileDate);


	} catch (e) {
		window.status = "Problemi col file XML delle opzioni caricato.";
		log("Problemi col file XML delle opzioni caricato.");
	}
}

/*
	Navigazione XML e lettura valori per le regole commerciali
*/
function traverseCommerceRuleXML(xml) {
	try {
		fileDate = getInnerText(xml.getElementsByTagName('ogch-rules').item(0).getElementsByTagName("file-date").item(0));

		comm.fileDate = fileDate;
		comm.ruleDate = getInnerText(xml.getElementsByTagName('ogch-rules').item(0).getElementsByTagName("rule-date").item(0));

		var root_node = getXMLVersionBefore(xml.getElementsByTagName('ogch-rules').item(0));
		infoBlock = root_node.getElementsByTagName("info").item(0);

		comm.creator = infoBlock.getElementsByTagName("creator").item(0).getAttribute("name");
		comm.mail = infoBlock.getElementsByTagName("creator").item(0).getAttribute("mail");
		comm.comment = getInnerText(infoBlock.getElementsByTagName("comment").item(0));

		// impostazioni rapporti
		rapps = getInnerText(root_node.getElementsByTagName('general-rapp').item(0));
		rapps = rapps.split(":");
		mStartVal = rapps[0];
		cStartVal = rapps[1];
		dStartVal = rapps[2];

		changeRates = root_node.getElementsByTagName('change-rate');
		for (var rate=0;rate<changeRates.length;rate++) {
			currRate = changeRates.item(rate);
			var rateType = currRate.getAttribute('type');
			if (rateType=="mc") {
				mcMaxRate = eval(evalRapp(currRate.getElementsByTagName('max').item(0)));
				mcMinRate = eval(evalRapp(currRate.getElementsByTagName('min').item(0)));
			}
			else if (rateType=="md") {
				mdMaxRate = eval(evalRapp(currRate.getElementsByTagName('max').item(0)));
				mdMinRate = eval(evalRapp(currRate.getElementsByTagName('min').item(0)));
			}
			else if (rateType=="cd") {
				cdMaxRate = eval(evalRapp(currRate.getElementsByTagName('max').item(0)));
				cdMinRate = eval(evalRapp(currRate.getElementsByTagName('min').item(0)));
			}
			else {
				window.status = "Il file XML caricato non è corretto";
				log("Il file XML del commercio caricato non è corretto.");
			}
		}
		minmaxCheck = true;
		// mc
		mcBaseRate = mStartVal/cStartVal;
		// md
		mdBaseRate = mStartVal/dStartVal;
		// cd
		cdBaseRate = cStartVal/dStartVal;
		
		log("Regole commerciali: elaborato file con data "+fileDate);
		
	} catch (e) {
		window.status = "Problemi col file XML delle regole commerciali caricato.";
		log("Problemi col file XML delle regole commerciali caricato.");
	}
}

// ***************************************************************************************

// Inizializzazione per Opzioni
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
   http_request_opt = new XMLHttpRequest();
	if (http_request_opt.overrideMimeType)
		http_request_opt.overrideMimeType('text/xml');
} else if (window.ActiveXObject) { // IE
   try {
		http_request_opt = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			http_request_opt = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {
			window.status = "Impossibile inizializzare il modulo XmlHttpRequest";
			log("Impossibile inizializzare il modulo XmlHttpRequest per la lettura delle opzioni.");
		}
	}
}
// Caricamento XML delle opzioni
if (http_request_opt && getQueryStringParam("options")!=null) {
	optionsUrl = getQueryStringParam("options");
	http_request_opt.onreadystatechange = xmlRequestForOptions;
	try {
		// Nella fase di debug su disco locale, IE non funziona
		http_request_opt.open('GET', optionsUrl, true);
		http_request_opt.send(null);
	} catch (e) {
		window.status = "Impossibile eseguire la richiesta";
		log("Impossibile eseguire la richiesta per la lettura delle opzioni.");
		// lancio comunque il caricamento delle regole commerciali
		loadCommRates();
	}
}
else {
	log("Nessuna opzione personalizzata: uso predefinito.");
	loadCommRates();
}

/*
	Il caricamento delle regole commerciali viene fatto solo DOPO quello delle opzioni.
	l'uso AJAX è asincrono (per fortuna)...
*/
function loadCommRates() {
	// Inizializzazione per regole commerciali
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		http_request_com = new XMLHttpRequest();
		if (http_request_com.overrideMimeType)
			http_request_com.overrideMimeType('text/xml');
	} else if (window.ActiveXObject) { // IE
		try {
			http_request_com = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request_com = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				window.status = "Impossibile inizializzare il modulo XmlHttpRequest";
				log("Impossibile inizializzare il modulo XmlHttpRequest per la lettura delle regole commerciali.");
			}
		}
	}
	// Caricamento XML delle regole commerciali (può dipendere dalle opzioni caricate)
	if (http_request_com) {
		http_request_com.onreadystatechange = xmlRequestForCommerceRules;
		try {
			// Nella fase di debug su disco locale, IE non funziona
			if (customCommRateURL != "" && customCommRatePath != "") {
				RATE_XML_URL = customCommRateURL;
				RATE_XML_FILE = customCommRatePath;
			}
			http_request_com.open('GET', RATE_XML_URL+RATE_XML_FILE, true);
			http_request_com.send(null);
		} catch (e) {
			try {
				// In fase di debug, Mozilla non permette la connessione in remoto
				http_request_com.open('GET', RATE_XML_FILE, true);
				http_request_com.send(null);
			} catch (e) {
				window.status = "Impossibile eseguire la richiesta.";
				log("Impossibile eseguire la richiesta per la lettura delle regole commerciali");
			}
		}
	}
}