

var ns; var ie;
if (navigator.userAgent.indexOf('MSIE') >= 0)
	ie = true;
else
	ns = true;


/**
@public
@brief Include nella pagina un js e lo appende nel tag <head>
@param fileJS Percorso del file da includere
*/
function include (fileJS) {
	if (typeof(fileJS) == 'string') {
		var srcFileJS = fileJS.indexOf('http://') == 0 ? fileJS : fileJS;
		var scriptJS = document.createElement('script');
		scriptJS.setAttribute('src', srcFileJS);
		scriptJS.setAttribute('type', 'text/javascript');
		document.getElementsByTagName('head')[0].appendChild(scriptJS);
		return true;
	} else {
		alert('il parametro passato alla funzione include non č una stringa');
		return false;
	}
}

/**
@public
@brief Include nella pagina un php che genera un js e lo appende nel tag <head>
@param url Percorso del file da includere

Alias di include()
*/
function callPhpScript(url) {
	include(url);
}

function appendScript (txt) {
	/* var scriptJS = document.createElement('script');
	scriptJS.setAttribute('type', 'text/javascript');
	scriptJS.setAttribute('src', '');

	txtJS = document.createTextNode("WWW");
	scriptJS.innerHTML = (txtJS);
	//alert(document.getElementsByTagName('head'));

	document.getElementsByTagName('head')[0].appendChild(scriptJS);
	return true; */
	var e=new Function('return '+txt)();
	return e[0];
}


/**
@public
@brief Include nella pagina un css e lo appende nel tag <head>
@param fileJS Percorso del file da includere
@param fileCSS Percorso del file da includere
*/
function callCssScript (fileCSS) {
	if (typeof(fileCSS) == 'string') {
		var scriptCSS = document.createElement('link');
		scriptCSS.setAttribute('href', '/templates/' + fileCSS);

		scriptCSS.setAttribute('type', 'text/css');
		scriptCSS.setAttribute('rel', 'stylesheet');
		document.getElementsByTagName('head')[0].appendChild(scriptCSS);
		return true;
	} else {
		alert('il parametro passato alla funzione include non č una stringa');
		return false;
	}
}


/**
@public
@brief Alert temporizzato che compare nella pagina
@param txt Testo da visualizzare
@param bgColor Colore di sfondo. Se non specificato usa #FF9900

*/
var intervalloTimeout = '';
function outputAlertAdmin (txt, bgColor) {
	if (bgColor == undefined)
		bgColor = '#F90';

	var avvisi = document.getElementById('avvisi');
	avvisi.innerHTML = txt;
	avvisi.style.background = bgColor;

	// l'avviso scompare dopo 3 secondi
	intervalloTimeout = setTimeout('outputAlertAdmin("&nbsp;","transparent");clearTimeout(intervalloTimeout);', 3000);
}

/**
@public
@brief Alert temporizzato con sfondo rosso (quindi indicante un errore) che compare nella pagina
@param txt il testo dell'errore

E' un alias di outputAlertAdmin, la differenza č che gli viene passato il colore
*/
function outputErrorAdmin (txt) {
	outputAlertAdmin(txt, '#f00');
}

// From http://www.bigbold.com/snippets/posts/show/899
String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};


/**
@public
@brief Cerca un nodo in base ad un attributo del nodo stesso
@param tagFather nodo padre da cui partire
@param nomeTag nome del tag da cercare
@param nomeAttributo nome dell'attributo del nodo da cercare
@param valoreAttributo valore della proprietā nomeAttributo del nodo da cercare
@return il nodo oppure @c false se non lo trova

Funzione ricursiva che cerca in tutti i figli di tutti i nodi figli del padre passato come parametro. E' possibile non passare nomeAttributo e valoreAttributo: in questo caso non vengono fatti i confronti con l'attributo
*/
var debugSearchChilds = new Array();
function searchChild (tagFather, nomeTag, nomeAttributo, valoreAttributo, retrieveCollection) {
	var chiaveDebug = nomeTag + "-" + nomeAttributo + "-" + valoreAttributo;
	var dataCorrente1 = new Date();
	var beginTime = dataCorrente1.getTime();
	var r = performSearchChilds (tagFather, nomeTag, nomeAttributo, valoreAttributo, retrieveCollection);
	var dataCorrente2 = new Date();
	var endTime = dataCorrente2.getTime();
	debugSearchChilds[chiaveDebug]['time'] += parseInt(endTime-beginTime);

	var txt='';
	for(var ii in debugSearchChilds){
		var key = ii.split('-');
		if (key[0] != undefined && key[1] != undefined && key[2] != undefined &&  debugSearchChilds[ii]['time']!= undefined && debugSearchChilds[ii]['cnt'] != undefined ) {
			txt+='<'+key[0]+' '+key[1]+ '="' + key[2]+'"> Tempo ricerca: '+parseInt(debugSearchChilds[ii]['time'])+" #"+debugSearchChilds[ii]['cnt']+" elem\n";
		};
	};
	//addJSDebug(txt, 'timeSearchChilds');
	return r;
}
function performSearchChilds (tagFather, nomeTag, nomeAttributo, valoreAttributo, retrieveCollection) {
	var chiaveDebug = nomeTag + "-" + nomeAttributo + "-" + valoreAttributo;
	if (debugSearchChilds[chiaveDebug] != undefined) {
		debugSearchChilds[chiaveDebug]['cnt']++;
		// debugSearchChilds[chiaveDebug]['time'] += 2;
	} else {
		debugSearchChilds[chiaveDebug] = new Array();
		debugSearchChilds[chiaveDebug]['cnt'] = 1;
		debugSearchChilds[chiaveDebug]['time'] = 0;
	}
	var collection = Array();
	// for (var i in tagFather.childNodes) {
	nomeTag = nomeTag.toLowerCase();
	for (var i=0; i < tagFather.childNodes.length; i++) {
		var elem = tagFather.childNodes[i];

		if (elem.tagName != undefined && elem.tagName.toLowerCase() == nomeTag.toLowerCase()) {
			if (nomeAttributo == undefined && valoreAttributo == undefined) {
				a = elem;
			} else {
				if (elem.tagName.toLowerCase() == 'label' && nomeAttributo.toLowerCase() == 'for') {
					if(elem.getAttribute('htmlFor') == valoreAttributo ^ elem.getAttribute('for') == valoreAttributo) {
						// in InternetExplorer non esiste elem.getAttribute('for')
						var a = elem;
					}
				} else if (nomeAttributo.toLowerCase() == 'class' && elem.className == valoreAttributo) {
					var a = elem;
				} else if (nomeAttributo.toLowerCase() == 'checked' && elem.checked != undefined && elem.checked == valoreAttributo) {
					var a = elem;
				} else if (elem.getAttribute(nomeAttributo) == valoreAttributo) {
					var a = elem;
				};
			}
			if (retrieveCollection != true) {
				if (a != undefined) {
					return a;
				};
			} else {
				if (a != undefined) {
					collection.push(a);
					/* var qq1 = '';
					for (var q1 in collection) {
						qq1 += collection[q1].className+"--"+collection[q1].innerHTML+"#";
					} */
				};

			};
		};

		if (elem.childNodes != undefined && elem.childNodes.length > 0) {
			if (elem.childNodes.length > 0) {
				var b = performSearchChilds(elem, nomeTag, nomeAttributo, valoreAttributo, true);
				if (b != false) {
					if (retrieveCollection != true) {
						return b.pop();
					} else if (b.length > 0) {
						for (var q1 in b) {
							collection.push(b[q1]);
						};
					}
				};
			};
		};
		a = undefined;
	}
	if (collection.length > 0) {
		//var qq = '';
		var ww = Array();
		for (var q in collection) {
			ww[q] = collection[q];
		}
		return ww;
	}
	return false;
}

/**
@public
@brief restituisce una collection di nodi che hanno i parametri specificati
@see searchChild
@return un array con la collection dei nodi oppure @c false se non viene trovato nessun nodo
*/
function searchChildsCollection (tagFather, nomeTag, nomeAttributo, valoreAttributo) {
	var ee = searchChild(tagFather, nomeTag, nomeAttributo, valoreAttributo, true);
	return ee;
}


/**
@public
@brief La comune funzione trim. Toglie spazi, tab, e invii
*/
function trim(txt) {
	txt = txt.replace(/^[\s\t\n\r]+/g, '');
	txt = txt.replace(/[\s\t\n\r]+$/g, '');
	return txt;
}



/**
@public
@brief Aggiunge la funzione passata come parametro a window.onload
@param func La funziona da aggiungere. Non č la stringa del nome della funzione, ma la funzione stessa
*/
var oldOnload = new Array();
function addOnload (func) {
	oldOnload.push(func);
}
window.onload = function () {
	if (oldOnload.length > 0) {
		for (var i =0; i<oldOnload.length; i++) {
			oldOnload[i]();

		}
		/* for (var i in oldOnload) {
			alert(i);
			oldOnload[i]();
		} */
	}
}


/**
@public
@brief come nextSibling e prevSibling, ma ritorna un nodo che non sia quello di testo
*/
function nextTag (prevTag) {
	do {
		var currElem = currElem != undefined ? currElem.nextSibling : prevTag.nextSibling;
		if (currElem.tagName != undefined) {
			return currElem;
		};
	} while (currElem.nextSibling != undefined);
	return false;
}

function prevTag () {

}


function getParentForm (elemInternal) {
	while (elemInternal != undefined) {
		elemInternal = elemInternal.parentNode;

		if (elemInternal.tagName.toLowerCase() == 'form') {
			return elemInternal;
		};
	};

	return false;
}


/**
@brief ritorna la stringa da inviare travite javascript da mettere nel GET. Il primo parametro č il tag form, il secondo č un array con i nomi dei campi da inviare.
*/
function strFromElements (frm, arrNameElem) {
	var strToSend = new Array();

	if (frm.tagName.toLowerCase() != 'form') {
		alert("errore: non č un form!");
		return false;
	};

	for (var i in arrNameElem) {
		if (frm.elements[arrNameElem[i]] != undefined) {
			var elem = frm.elements[arrNameElem[i]]
			switch (frm.elements[arrNameElem[i]].tagName.toLowerCase()) {
				case 'select':
					// se č una select e l'option selezionata č dentro un <optgroup> verrā inviato optgroup|option
					var optionSselected = elem[elem.selectedIndex];
					var value = optionSselected.value;
					if (optionSselected.parentNode.tagName.toLowerCase() == 'optgroup' && optionSselected.parentNode.getAttribute('label') != '') {
						value = optionSselected.parentNode.getAttribute('label') + '|' + value;
					}
					break;
				default:
					var value = frm.elements[arrNameElem[i]].value;
			};
			strToSend.push(arrNameElem[i] + '=' + escape(value));
		};
	}

	if (strToSend.length == arrNameElem.length) {
		return strToSend.join('&');
	};

	return false;
}



//////////////////////////////////////////////////////////////////////////////////////////////
var busyApplication = new Array();
var totBusy = 0;
function showBusy (title) {
	if (title == '' || title == undefined) {
		alert('specificare un titolo per il l\'icona di wait (showBusy)');
		return false;
	};

	var icon = document.getElementById('busyApplication');
	if (icon) {
		busyApplication.push(title);
		var newTitle = document.createElement('div');
		newTitle.innerHTML = title;
		newTitle.id = 'busy' + (busyApplication.length - 1);
		icon.appendChild(newTitle);
		icon.style.display = 'block';
	};
	totBusy++;
	return true;
}
function clearBusy (title) {
	if (title == '' || title == undefined) {
		alert('specificare un titolo per il l\'icona di wait (clearBusy)');
		return false;
	}

	var icon = document.getElementById('busyApplication');
	for (var i in busyApplication) {
		if (busyApplication[i] == title) {
			document.getElementById('busy' + i).parentNode.removeChild(document.getElementById('busy' + i));
			busyApplication[i] = undefined;
		};
	}
	totBusy--;

	if (icon && totBusy == 0) {
		icon.style.display = 'none';
	};
	return true;
}


///////////////////////////////////////////////////////////////////////////////////////////
function getRadioChecked (radioElemCollection) {
	for (var i in radioElemCollection) {
		if (radioElemCollection[i].checked) {
			return radioElemCollection[i];
		};
	}
	return false;
}
///////////////////////////////////////////////////////////////////////////////////////////

/**
#public
@brief dato un array di elementi, gli mette il display=none e gli mette prima il testo che era contenuto nell'elemento. In aggiunta mette un tasto "<<prev" davanti al tasto e un tasto "invia" e nasconde il tasto
@param elemList l'array degli elementi da convertire
@param funzioneInvio La funzione che deve essere messa nell'onclick del tasto "invia"
*/
function convertElemInHidden (elemList, funzioneInvio) {
	var listaElemConvertiti = new Array();
	for (var i in elemList) {
		var elem = elemList[i];
		// se sono degli elementi esegue questa parte
		if (elem.tagName != undefined && elem.getAttribute('type') != 'hidden' && elem.name != '') {
			listaElemConvertiti.push(elem);
			switch (elem.tagName.toLowerCase()) {
				case 'select':
					var valore = elem.options[elem.selectedIndex].innerHTML;
					break;
				default:
					var valore = elem.value;
			};
			if (valore == '') {
				valore = '<i>vuoto</i>';
			};

			elem.style.display = 'none'; // nascondo il campo
			var txt = document.createElement('span');
			txt.innerHTML = valore;
			txt.className = 'txtDaConfermare';
			elem.parentNode.insertBefore( txt, elem);
		} else if (elem.tagName != undefined && elem.getAttribute('type') == 'button') {
			var bottone = elem; // mi salvo il bottone a cui aggiungere il tasto <<prev
			bottone.style.display = 'none'; // nascondo il tasto
			listaElemConvertiti.push(bottone);
		};
	}
	if (bottone != undefined) {
		// se č un type=button aggiunge il bottone <<prev prima del tasto
		var elemPrev = document.createElement('input');
		elemPrev.setAttribute('type', 'button');
		elemPrev.value = '<<prev';
		elemPrev.onclick = function () {
			// se viene premuto il tasto <<prev riporta visibili gli elementi che sono stati nascosti e cancello il tasto
			for (var j in listaElemConvertiti) {
				listaElemConvertiti[j].style.display = ''; // mostro l'elemento
				listaElemConvertiti[j].parentNode.removeChild(listaElemConvertiti[j].previousSibling); // cancello il testo
				addJSDebugDiv(listaElemConvertiti[j].value + ' === ' + listaElemConvertiti[j].style.display);
			}
			//this.parentNode.removeChild(this.nextSibling); // cancello il tasto "invia"
			this.parentNode.removeChild(this); // cancello il tasto <<prev
		}
		bottone.parentNode.insertBefore( elemPrev, bottone );

		// tasto "invia"
		var elemInvia = document.createElement('input');
		elemInvia.setAttribute('type', 'button');
		elemInvia.value = 'invia';
		elemInvia.onclick = function () { eval(funzioneInvio); };
		bottone.parentNode.insertBefore( elemInvia, bottone);




	};


}




///////////////////////////////////////////////////////////////////////////////////////////////////
function showHide (elem) {
	if (typeof(elem) == 'string') {
		elem = document.getElementById(elem);
	};

	if (typeof(elem) == 'object') {
		if (elem.style.display == 'none') {
			elem.style.display = '';
		} else {
			elem.style.display = 'none';
		};
	};
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// BETA VERSION : XMLHttpRequest
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
@brief inizializzazone XMLHttpRequest
@see http://www.jibbering.com/2002/4/httprequest.html
*/
var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
	try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (E) {
		xmlhttp = false;
	}
}
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	try {
		xmlhttp = new XMLHttpRequest();
	} catch (e) {
		xmlhttp=false;
	}
}
if (!xmlhttp && window.createRequest) {
	try {
		xmlhttp = window.createRequest();
	} catch (e) {
		xmlhttp=false;
	}
}

function callPage (page, method) {
	var a = page.match(/^[a-z]:\/\//)

	if (method != undefined)
		method = method.toUpperCase();

	if (method != 'POST')
		method = 'GET';

	if (page == undefined || page == '')
		return false;

	xmlhttp.open(method, page, false);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) {
			var txt = '';
			txt += xmlhttp.status + "\n-----------------------------------\n";
			txt += xmlhttp.getAllResponseHeaders() + "\n-----------------------------------\n";
			txt += xmlhttp.responseText;
			// alert(txt);
		}
	}
	xmlhttp.send(null);
	return executeAjaxTest();
}

function executeAjaxTest () {
	return appendScript(xmlhttp.responseText);
}
