freccia_open = new Image;
freccia_open.src = 'imgall/evt-treeopen.png';
freccia_close = new Image;
freccia_close.src = 'imgall/evt-treeclose.png';

function showList(alink, key) {

 	var list = document.getElementById('tornei' + key);

	if (list.style.display == 'block') {
		list.style.visibility = 'hidden';
		list.style.display = 'none';
		alink.firstChild.src = freccia_close.src;
		alink.parentNode.style.backgroundColor='#043C64';
	}
	else {
		list.style.visibility = 'visible';
		list.style.display = 'block';
		alink.firstChild.src = freccia_open.src;
		alink.parentNode.style.backgroundColor='#A4D7F9';
		recordTree(key);
	}
}

function runBall(alink) {
 	alink.nextSibling.nextSibling.src = 'imgall/ball.gif';
}

function stopBall(alink) {
 	alink.nextSibling.nextSibling.src = 'imgall/ball.png';
}

function setArrow(sez, thisBut) {

	var bg = document.getElementById('dynacontent');
	var bord = document.getElementById('ajaxcontent');
	bg.className = ' first colorlab' + thisBut + ' ';
	bord.className = ' last colorbord' + thisBut + ' ';
}

var tree = { ulobjs: new Array() };

window.onload = function() {

	if (document.getElementById('catmenu')) {
		tree.ulobjs = initMenu(document.getElementById('catmenu').childNodes);
	}
}

function initMenu(ulnodes) {

	var ullist = new Array();
	for (i=0; i<ulnodes.length; i++) {
		if (ulnodes[i].nodeName == 'LI') {
			var node = new myNode(ulnodes[i].attributes['id'].value);
			ullist.push(node);
		}
	}
	for (i=0; i<ullist.length; i++)
		ullist[i].scanSub(ullist);
	return ullist;
}

function myNode(id) {
	this.id = id;
	var ids = this.id.split('_');
	this.parID = ids[1];
	this.catID = ids[2];
	this.visible = false;
	this.subcat = new Array();
	this.show = function() {
		this.visible = true;
		if (document.getElementById(this.id)) {
			document.getElementById(this.id).style.visibility = 'visible';
			document.getElementById(this.id).style.display = 'block';
		}
	}
	this.hide = function() {
		this.visible = false;
		if (document.getElementById(this.id)) {
			document.getElementById(this.id).style.visibility = 'hidden';
			document.getElementById(this.id).style.display = 'none';
			if (document.getElementById('a_' + this.parID + '_' + this.catID)) {
				var a = document.getElementById('a_' + this.parID + '_' + this.catID);
				a.innerHTML = '+';
			}
		}
	}
	this.scanSub = function(trees) {
		var ullist = new Array();
		for (var j=0; j<trees.length; j++) {
			if (trees[j].parID == this.catID) {
				var node = new myNode(trees[j].id);
				ullist.push(node);
			}
		}
		this.subcat = ullist;
	}
}

function openTree(alink, statusOpen, statusClose) {

	if (statusClose == alink.innerHTML) {
		alink.innerHTML = statusOpen;
		var status = 'open';
	}
	else {
		alink.innerHTML = statusClose;
		var status = 'close';
	}
	ids = alink.id.split('_');
	moveTree(ids[2], status);
	return false;
}


function moveTree(parent, status) {

	for (var i=0; i<tree.ulobjs.length; i++) {
		if (tree.ulobjs[i].parID == parent) {
			if (status == 'open') {
				tree.ulobjs[i].show();
			}
			else if (status == 'close') {
				actual = tree.ulobjs[i];
				actual.hide();
				for (var j=0; j<actual.subcat.length; j++)
					moveTree(actual.subcat[j].parID, status);
			}
		}
	}
}

function getContent(filename, thisBut, tID, sez, lang) {

	ajaxRun(filename + '.php?tID=' + tID + '&q=' + sez + '&l=' + lang, 'ajaxcontent', sez, thisBut);
}

function getData(filename, tID) {

	ajaxEval(filename + '.php?tID=' + tID);
}

function searchArchive(file, team, tor, button) {

	if (team.value > 0 || button != 'Vedi') {
		var cond = "";
		if (tor && tor.value != '---')
			cond = " AND torID="+tor.value;
		if (button != 'Vedi') var id = "";
		else var id = team.value;
		document.location.href= file + id + cond;
	}
	else {
		alert('Seleziona una squadra tra quelle trovate');
		return false;
	}
}

function newTeam(obj, iddest) {
	
	ajaxEval('ajaxLoad.php?class=squadre&search=reset&dest='+iddest);
	obj.value='';
}

function searchTeam(value, iddest) {

	if (value.length > 2) {
		var time = new Date();
		ajaxEval('ajaxLoad.php?class=squadre&time='+Math.floor(time.getTime())+'&search='+value+'&dest='+iddest);
	}
}

function fillTeam(value, iddest) {
	
	ajaxEval('ajaxLoad.php?class=squadre&id='+value+'&dest='+iddest);
}

function recordTree(value) {
	
	ajaxEval('ajaxLoad.php?class=tree&id='+value);
}

function calcDates(value) {
	
	ajaxEval('ajaxLoad.php?class=torneo&id='+value);
}

function annullaRoom(olink, tab, idcam, cam, let, idp) {
	
	var labels = new Array('Annulla','Ripristina');
	var values = new Array('unset','set');
	if (olink.innerHTML == labels[0]) { var dest = values[0]; olink.innerHTML = labels[1]; }
	else if (olink.innerHTML == labels[1]) { var dest = values[1]; olink.innerHTML = labels[0]; }
	for (n=1;n<=let;n++) {
		var idr = eval('document.pernotto.rooID_'+idcam+'_'+cam+'_'+n+'.value');
		ajaxEval('ajaxLoad.php?class=rooming&id='+idr+'&search='+tab+','+idp+'&dest='+dest);
	}
}

function getRooms(idPr, idCam) {
	ajaxEval('ajaxLoad.php?class=pernotto&id='+idPr+'&search='+idCam);
}

function getRooming(type, iscID, dest) {
	ajaxEval('ajaxLoad.php?class=voucher&id='+iscID+'&search='+type+'&dest='+dest);
}

function setRoom(label, num, value) {
	for (i=1; i<=num; i++)
		eval('document.pernotto.'+label+i+'.value='+value);
}

function newHotel(obj, iddest) {
	ajaxEval('ajaxLoad.php?class=hotel&search=reset&dest='+iddest);
	obj.value='';
}

function searchHotel(value, iddest) {

	if (value.length > 2) {
		var time = new Date();
		ajaxEval('ajaxLoad.php?class=hotel&time='+Math.floor(time.getTime())+'&search='+value+'&dest='+iddest);
	}
}

function sendMail(objF) {
	if (objF.mail.value.match(/[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]{2,})+/))
		ajaxEval('ajaxLoad.php?class=sendmail&search='+objF.mail.value+'&dest='+objF.dest.value+'&params='+objF.params.value);
	else alert('Formato E-Mail non valido');	
	objF.mail.value='';
}

function viewFile(id) {
	var w = window.open();
	w.location.href='ajaxLoad.php?class=viewfile&id='+id;
}

function closeFollow(row, id) {
	ajaxEval('ajaxLoad.php?class=chiamata&search='+id);
	delRow(row, 'tabfollow');
}

function extraLocation(file, tor) {

	if (tor.value == '---') {
		alert('Selezionare un torneo dal menu a tendina');
		return false;
	}
	if (tor.value > 0) var param = tor.value;
	else var param = MD5(tor.value);
	document.location.href=file+param;
}

function ajaxRun(request, div, sez, thisBut) {

			if (thisBut > 0) {
				init('ajaxloading');
				var mov = setInterval('text(\'...\',\'ajax\',\'loading\')',500);
			}
            var oXmlHttp = zXmlHttp.createRequest();
            oXmlHttp.open("get", request + "&div=" + div, true);
            oXmlHttp.onreadystatechange = function () {
                if (oXmlHttp.readyState == 4) {
					if (thisBut > 0) {
						visibile('ajaxloading','no');
						clearInterval(mov);
					}
                    if (oXmlHttp.status == 200) {
						var data = oXmlHttp.responseText.split("||");
						if (data[0] && data[0] != "") showInfo(data[0], 'textVert');
                        if (data[1] && data[1] != "") showInfo(data[1], div);
						if (thisBut > 0) setArrow(sez, thisBut);
						if (sez == 'mappa') {
							if (data[3] > 0 && data[4] > 0) {
								setvisible('', 0, 'map');
								GoogleLoad(data[2],data[3],data[4]);
							}
						}
                    } else {
                        showInfo("Impossibile recuperare i dati: " + oXmlHttp.statusText, div); //statusText is not always accurate
                    }
                }
				else if (thisBut > 0) visibile('ajaxloading','si');
            };
            oXmlHttp.send(null);
}

function ajaxEval(request) {

	var oXmlHttp = zXmlHttp.createRequest();
    oXmlHttp.open("get", request, true);
    oXmlHttp.onreadystatechange = function () {
    	if (oXmlHttp.readyState == 4) {
    		if (oXmlHttp.status == 200) {
				eval(oXmlHttp.responseText);
        	} else {
        		alert("Impossibile recuperare i dati: " + oXmlHttp.statusText); //statusText is not always accurate
        	}
     	}
    };
    oXmlHttp.send(null);
}

function ajaxSend(request, params) {

	var oXmlHttp = zXmlHttp.createRequest();
    oXmlHttp.open("post", request, true);
	oXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	var data = "";
	if (typeof(params) == "string") {
		data = params;
	}
	else {
		for (var key in params) {
			if (data != "")
				data += "&";
			data += key + "=" + escape(params[key]).replace(/\+/, "%2B");
		}
	}
	oXmlHttp.onreadystatechange = function () {
    	if (oXmlHttp.readyState == 4) {
    		if (oXmlHttp.status == 200) {
				eval(oXmlHttp.responseText);
        	} else {
        		alert("Impossibile recuperare i dati: " + oXmlHttp.statusText); //statusText is not always accurate
        	}
     	}
    };
	oXmlHttp.send(data);
}

function quickInsert(data, classe) {

	var url = "admin_process.php?type=" + classe;
	var data = data.split(",");
	var params = 'ajax=true&status=diretto';
	for (i=0; i<data.length; i=i+2)
		params += '&' + data[i] + '=' + data[i+1];
	ajaxSend(url, params);
}

function addOption(id, label, value) {

	var sel = eval('document.forms[0].'+ id);
	var n = sel.options.length;
	sel.options[n] = new Option (label,value);
	sel.selectedIndex = n;
	sel.focus();
}

function showOrder() {

	var obj = document.forms[0].required.value;
	obj = obj.replace(/_req/, '');
	ajaxEval('ajaxLoad.php?task=ordine&id=' + obj);
}

function init(div)
{
	var dom = document.getElementById(div);
	var domL = document.getElementById(div + 'L');
	dom.innerHTML = domL.innerHTML;
	visibile(div, 'si');
}

function replaceAll (text, strTarget, strSubString) {

	var intIndexOfMatch = text.indexOf(strTarget);
	while (intIndexOfMatch != -1){
		text = text.replace(strTarget, strSubString);
		intIndexOfMatch = text.indexOf(strTarget);
	}
	return(text);
}

function showInfo(sText, div) {

	var htmlent = new Array("&agrave;", "&egrave;", "&eacute;", "&igrave;", "&ograve;", "&oacute;", "&ugrave", "&euro;", "", "&#39;");
	var utf8 = new Array("à", "è", "é", "ì", "ò", "ó", "ù", "€", "\\", "'");
	if (document.getElementById(div)) {
		var place = document.getElementById(div);
		for (i=0; i < htmlent.length; i++) sText = replaceAll(sText, utf8[i], htmlent[i]);
		place.style.display = 'block';
		place.innerHTML = sText;
	}

}

function initHidden(div, liv) {

	for (i=0; i < liv; i++) {
		var dom = document.getElementById(div + i).style;
		dom.display = 'none';
	}
}

function text (char, div, actual) {
	var dom = document.getElementById(div + actual);
	dom.innerHTML += ' '+char;
}

function setvisible(div, numdiv, actual) {

	var type = 'block';
	var dom = document.getElementById(div + actual);
	if (dom.nodeName == 'TR') {
		if (window.navigator.userAgent.indexOf('MSIE') != -1) type = 'inline';
		else type = 'table-row';
	}
	for (i=0; i < numdiv; i++) document.getElementById(div + i).style.display = 'none';
	dom.style.display = type;
}

function visibile (id, stato) {

	if (document.getElementById && document.getElementById(id)) {
		var type = 'block';
		var dom = document.getElementById(id);
		if (dom.nodeName == 'TR') {
			if (window.navigator.userAgent.indexOf('MSIE') != -1) type = 'inline';
			else type = 'table-row';
		}
		if (stato == 'si') dom.style.display = type;
		else if (stato == 'no') dom.style.display = 'none';
	}
	return;
}

function sovrapponi (layer, tot) {

	if (document.getElementById && document.getElementById(layer)) {
		document.getElementById(layer).style.display = 'block';
		for (l=1; l<=tot; l++) {
			var nlayer = layer.split('_');
			if (l != nlayer[1])
				document.getElementById(nlayer[0]+'_'+l).style.display = 'none';
		}
	}
}

function toggleTransl(div, langs) {

	var arrLangs = langs.replace(/,/g, "\',\'");
	eval('var langs = new Array (\''+arrLangs+'\');');
	//if (document.getElementById(langs[1] + div).style.display == 'none') {
	if (document.getElementById(div + langs[1]).style.display == 'none') {
		if (window.navigator.userAgent.indexOf('MSIE') != -1) status = 'inline';
		else status = 'table-row';
	}
	else status = 'none';
	if (div.match(/langquo\d+_/)) var s = 0;
	else var s = 1;
	for (i=s; i < langs.length; i++) {
		var row = document.getElementById(div + langs[i]);
		row.style.display = status;
		for (t=0; t<row.childNodes.length; t++) {
			for (c=0; c<row.childNodes[t].childNodes.length; c++)
			if (row.childNodes[t].childNodes[c].nodeName == "INPUT")
				if (row.childNodes[t].childNodes[c].disabled)
					row.childNodes[t].childNodes[c].disabled = false;
		}

	}
	//for (i=1; i < langs.length; i++) document.getElementById(langs[i] + div).style.display = status;
}

function activeChoice(div, numq, langs) {

	var arrLangs = langs.replace(/,/g, "\',\'");
	eval('var langs = new Array (\''+arrLangs+'\');');

	for (i=0; i < numq; i++) {
		var dom = document.getElementById(div + '_' + i);

		if (dom.disabled == true) {
			if (document.getElementById(div + '_td'))
				document.getElementById(div + '_td').className = 'active';
			dom.disabled = false;
			dom.className = 'active';
		}
		else if (dom.disabled == false) {
			if (document.getElementById(div + '_td'))
				document.getElementById(div + '_td').className = 'deactive';
			dom.disabled = true;
			dom.className = 'deactive';
		}
		for (x=0; x < langs.length; x++)
			if (document.getElementById(div + '_' + langs[x] + '_' + i))
				document.getElementById(div + '_' + langs[x] + '_' + i).className = dom.className;
		if (document.getElementById(div + '_tab')) {
			var tab = document.getElementById(div + '_tab');
			for (r=0; r<tab.rows.length; r++)
				for (t=0; t<tab.rows[r].childNodes.length; t++) {
					var td = tab.rows[r].childNodes[t];
					for (e=0; e<td.childNodes.length; e++)
						if (td.childNodes[e].nodeName == 'SELECT') {
							td.childNodes[e].disabled = dom.disabled;
							td.childNodes[e].className = dom.className;
						}
				}
		}
	}
}

function activeRow(div, numq) {

	for (i=0; i < numq; i++) {
		var dom = document.getElementById(div + '_' + i);

		if (dom.className == 'deactive') {
			dom.className = 'active';
		}
		else if (dom.className == 'active') {
			dom.className = 'deactive';
		}
	}
}

function delRow(rowid, tabid) {
	var thistab = document.getElementById(tabid);
	var i = 0;
	while (thistab.rows[i].id != rowid) i = i + 1;
	var index = i;
	thistab.deleteRow(index);
}

function doTesti(id) {
	var cod = document.getElementById(id).value;
	if (cod % 2 == 0 || cod % 2 == 1 && cod > 0)
		document.location.href='admin_form.php?type=testi&action=modifica&field=' + cod;
	else
		document.location.href='admin_list.php?type=testi&action=modifica&field=txtID&q=' + cod;
}

function doOverview(cat,grp) {
	var catID = eval('document.forms[0].'+cat+'.value');
	var faseID = eval('document.forms[0].'+grp+'.value');
	if (catID > 0 && faseID > 0)
		document.location.href='admin_form.php?type=partita&action=overview&cat=' + catID + '&grp=' + faseID;
	else
		alert('Selezionare una categoria e una tipologia di fase');
}

function doPartite(id) {
	var cod = document.getElementById(id).value;
	if ((cod % 2 == 0 || cod % 2 == 1) && cod <= 14 && cod > 0)
		document.location.href='admin_form.php?type=partita&num=' + cod;
	else if (cod > 14)
		alert ('Numero di partite troppo alto da gestire');
	else
		alert('Inserire numero partite da aggiungere');
}

function doLogin(objform) {

	var msg = false;
	if (!objform.user.value.length > 0) msg = true;
	if (!objform.pass.value.length > 0) msg = true;
	if (!msg && objform.pass.value != "") {
		pwdID = MD5(objform.pass.value);
		objform.securepwd.value = MD5(pwdID + objform.addID.value);
		objform.pass.value = "";
	}
	if (msg) {
		objform.reset();
		return false;
	}
	return true;
}

function CopyMatch(riga) {

	var rigaprec = riga - 1;
	var rigasucc = riga;
	var campi = Array ('id_strutt_', 'id_fase_', 'data_', 'id_campo_');
	numcampi = campi.length;
	for (i=0; i < numcampi; i++) {
		var precTUR = eval('document.partita.'+campi[i]+rigaprec+'.value');
		var succTUR = eval('document.partita.'+campi[i]+rigasucc);
		if (precTUR) succTUR.value = precTUR;
	}
}

function paganti() {
	var tot = document.getElementById('tot');
	var persone = 0;
	var letti = document.forms['pernotto'].letti.value.split(',');
	if (tot.value == "") tot.value = 0;
	for (i=1; i <= 12; i++) {
		arrCamere = document.getElementById('camera'+i);
		num = letti[i-1];
		if (arrCamere.value > 0) persone += parseInt(arrCamere.value) * num;
	}
	tot.value = parseInt(persone);
}

function addLetti(label, oForm, dest) {

	var letti = oForm.typeposti.value.split(',');
	var f = oForm.length;
	var pos = let = 0;
	for (i=0; i<f; i++) {
		if (oForm[i].name.indexOf(label) != -1) {
			let += parseInt(oForm[i].value) * letti[pos];
			pos++;
		}
	}
	eval('oForm.'+dest+'.value=parseInt('+let+')');
}

function addComitiva() {
	var tot = document.iscrizione.numcomit.value;
	var sum = 0;
	for (i=1; i <= tot-1; i++) {
		if (document.getElementById('comit_'+i).value > 0)
			sum += parseInt(document.getElementById('comit_'+i).value);
	}
	document.getElementById('comit_'+tot).value = sum;
}

function mapCoordinate(oForm) {

	var value = oForm.maplink.value;
	var chop = value.split('&ll=');
	var grades = chop[1].split('&');
	var coord = grades[0].split(',');
	oForm.mapLAT.value = coord[0];
	oForm.mapLONG.value = coord[1];
	oForm.maplink.value = '';
}

function getCookie(c_name)
{
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
  		if (c_start!=-1) {
    		c_start=c_start + c_name.length+1;
    		c_end=document.cookie.indexOf(";",c_start);
    		if (c_end==-1) c_end=document.cookie.length;
    		return unescape(document.cookie.substring(c_start,c_end));
    	}
  	}
	return "";
}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function ultimaCat(oTag) {

	oTag.value = getCookie('ultimaCat');
}

function privacy(dato) {

	if (dato == 'si') {
		document.getElementById('consenso').disabled = false;
	}
	else if (dato == 'no') {
		document.getElementById('consenso').disabled = true;
	}
}

function number_format (number, decimals, dec_point, thousands_sep)
{
	  var exponent = "";
	  var numberstr = number.toString ();
	  var eindex = numberstr.indexOf ("e");
	  if (eindex > -1)
	  {
		exponent = numberstr.substring (eindex);
		number = parseFloat (numberstr.substring (0, eindex));
	  }
	
	  if (decimals != null)
	  {
		var temp = Math.pow (10, decimals);
		number = Math.round (number * temp) / temp;
	  }
	  var sign = number < 0 ? "-" : "";
	  var integer = (number > 0 ?
		  Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
	
	  var fractional = number.toString ().substring (integer.length + sign.length);
	  dec_point = dec_point != null ? dec_point : ".";
	  fractional = decimals != null && decimals > 0 || fractional.length > 1 ?
				   (dec_point + fractional.substring (1)) : "";
	  if (decimals != null && decimals > 0)
	  {
		for (i = fractional.length - 1, z = decimals; i < z; ++i)
		  fractional += "0";
	  }
	
	  thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ?
					  thousands_sep : null;
	  if (thousands_sep != null && thousands_sep != "")
	  {
	  for (i = integer.length - 3; i > 0; i -= 3)
		  integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
	  }
	
	  return sign + integer + fractional + exponent;
}

function conteggi(row) {
	
	var s = eval('document.iscrizione.cont3_' + row);
	var q = eval('document.iscrizione.cont5_' + row);
	var uni = eval('document.iscrizione.cont6_' + row);
	var tot = eval('document.iscrizione.cont4_' + row);
	var saldo = document.getElementById('saldo');
	if (s.value != '' && q.value > 0 && uni.value > 0) {
		if (s.value == 'A') { sign = '+'; clas = 'posit'; }
		else { sign = '-'; clas = 'negat'; }
		imp = parseFloat(q.value * uni.value);
		tot.className = clas;
		tot.value = sign + ' ' + number_format(imp,2,".","");
		var importi = 0;
		for (i=0; i<document.iscrizione.numcont.value; i++) {
			var imp = eval('document.iscrizione.cont4_' + i);
			if (imp.value.match(/(\+|-) \d+\.\d+/)) {
				imp = imp.value.split(" ");
				eval('importi ' + imp[0] + '= ' + parseFloat(imp[1])); 
			}
		}
		if (importi > 0) saldo.className = 'posit';
		else saldo.className = 'negat';
		saldo.innerHTML = number_format(importi,2,".","");
	}
}
