function mouseoverlink(){
	document.body.style.cursor="url('resource/images/extra/hand_cursor.gif')";
}
function mouseoutlink(){
	document.body.style.cursor='auto';
}

function pagereload(p){
	document.location.href=p;
}
function in_array(string, array){
	for (i = 0; i < array.length; i++){
		if(array[i] == string){
			return true;
		}
	}
	return false;
}

function IsDecimal(str){
	mystring = str;
	if (mystring.match(/^\d+,\d{2}$/ ) ) {
		return true;
	}
	else{
		return false;
	}
}
function validateInt(){
      var o = document.frmInput.txtInput;
      switch (isInteger(o.value))
      {
         case true:
            alert(o.value + " is an integer")
            break;
         case false:
            alert(o.value + " is not an integer")
      }
}

function validateRange(){
      var s = document.frmInput.txtInput.value;
      var A = document.frmInput.txtA.value;
      var B = document.frmInput.txtB.value;

      switch (isIntegerInRange(s, A, B))
      {
         case true:
            alert(s + " is in range from " + A + " to " + B)
            break;
         case false:
            alert(s + " is not in range from " + A + " to " + B)
      }
}
// isIntegerInRange (STRING s, INTEGER a, INTEGER b)
function isIntegerInRange (s, a, b){
   if (isEmpty(s))
         if (isIntegerInRange.arguments.length == 1) return false;
         else return (isIntegerInRange.arguments[1] == true);

      // Catch non-integer strings to avoid creating a NaN below,
      // which isn't available on JavaScript 1.0 for Windows.
      if (!isInteger(s, false)) return false;

      // Now, explicitly change the type to integer via parseInt
      // so that the comparison code below will work both on
      // JavaScript 1.2 (which typechecks in equality comparisons)
      // and JavaScript 1.1 and before (which doesn't).
      var num = parseInt (s);
      return ((num >= a) && (num <= b));
}

function isInteger (s){
      var i;

      if (isEmpty(s))
      if (isInteger.arguments.length == 1) return 0;
      else return (isInteger.arguments[1] == true);

      for (i = 0; i < s.length; i++)
      {
         var c = s.charAt(i);

         if (!isDigit(c)) return false;
      }

      return true;
}

function isEmpty(s){
      return ((s == null) || (s.length == 0))
}

function isDigit (c){
      return ((c >= "0") && (c <= "9"))
}



// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function ck_string(str,regexp) {
    var patternvalido = regexp;
    var reg = new RegExp(patternvalido);
    return str.match(reg);
	 // sarebbe valido anche
    // return reg.test(str);
}

// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
var debugMode = true;
// hide loading data

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() {
	// will store the reference to the XMLHttpRequest object
	var xmlHttp;
	// this should work for all browsers except IE6 and older
	try{
		// try to create XMLHttpRequest object
		xmlHttp = new XMLHttpRequest();
	}
	catch(e){
		// assume IE6 or older
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                        "MSXML2.XMLHTTP.5.0",
                                        "MSXML2.XMLHTTP.4.0",
                                        "MSXML2.XMLHTTP.3.0",
                                        "MSXML2.XMLHTTP",
                                        "Microsoft.XMLHTTP");
		// try every prog id until one works
		for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) {
			try { 
				// try to create XMLHttpRequest object
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			} 
			catch (e) {
			}
		}
	}
	// return the created object or display an error message
	if (!xmlHttp){
		//	var ld = document.getElementById("loadingdata");
		//	ld.style.display="";
		alert("Error creating the XMLHttpRequest object.");
	}
	else {
		return xmlHttp;
	}
}

// function called when the state of the HTTP request changes
function handleRequestStateChange() {
	// when readyState is 4, we are ready to read the server response
	if (xmlHttp.readyState == 4) {
		// continue only if HTTP status is "OK"
		if (xmlHttp.status == 200) {
			try{
				// do something with the response from the server
				handleServerResponse();
			}
			catch(e){
				// display error message
				//alert("Error reading the response: " + e.toString());
				alert("rg58 - Errore nel leggere la risposta! Può causare questo errore: " + e.toString());
				// 	var ld = document.getElementById("loadingdata");
				//	ld.style.display="";
			}
		} 
		else{
			// display status message
			//alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
			alert("rg66 - C'è stato un problema nella ricezione dei dati:\n" + xmlHttp.statusText);
			//	var ld = document.getElementById("loadingdata");
			//	ld.style.display="";
		}
	}
}
function handleServerResponse(){
	// retrieve the server's response packaged as an XML DOM object
	var xmlResponse = xmlHttp.responseXML;
	// catching potential errors with IE and Opera
	if (!xmlResponse || !xmlResponse.documentElement)
		throw("rg77 - Struttura dati non valida:\n" + xmlHttp.responseText);
 
	// catching potential errors with Firefox
	var rootNodeName = xmlResponse.documentElement.nodeName;
	if (rootNodeName == "parsererror") 
		throw("rg82 - Struttura dati non valida:\n" + xmlHttp.responseText);
	// getting the root element (the document element)
	xmlRoot = xmlResponse.documentElement;
    
	var testoX = xmlRoot.firstChild.firstChild.nodeValue;
	var targ = xmlRoot.firstChild.getAttribute("targ");
 
	responseText = testoX;

	// display the user message
	myDiv = document.getElementById(targ);
	myDiv.innerHTML = responseText;
	//alert("compeltato");
	//var ld2 = document.getElementById("loadingdata");
	//ld2.style.display="none";


}

function nowStr() {
	var now=new Date()
	var hours=now.getHours()
	var minutes=now.getMinutes()
	var seconds=now.getSeconds()
	timeStr=""+((hours > 12) ? hours - 12 : hours)
	timeStr+=((minutes < 10) ? ":0" : ":") + minutes
	timeStr+=":" + seconds 
	return timeStr
}

function display_message_on_div(div,msg){
	var data_update=nowStr();
	document.getElementById(div).innerHTML=msg;
}


function start_control(divfield,tipo,urlpass){
	var msg04 = "Sto verificando...";

	if (xmlHttp){
		// try to connect to the server
		try {
//			display_message_on_div("checknickresponse",msg04);

			// initiate the asynchronous HTTP request
			xmlHttp.open("GET", urlpass, true);
			// xmlHttp.onreadystatechange = handleRequestStateChange;
			xmlHttp.onreadystatechange = handleRequestStateChange;
			xmlHttp.send(null);
		}
		// display the error in case of failure
		catch (e){
			alert("Non è stato possibile connettersi alla sorgente dati. Non cliccare il bottone ripetutamente:\n" + e.toString());
			//	var ld = document.getElementById("loadingdata");
			//	ld.style.display="";
		}
	}
}


function user_segnala_impegno(divfield){

	var rag_soc= document.getElementById("rag_soc").value;
	var citta= document.getElementById("citta").value;
	var persona= document.getElementById("persona").value;
	var telefono= document.getElementById("telefono").value;
	var mail= document.getElementById("mail").value;
	var descrizione = document.getElementById("descrizione").value;
	var code= document.getElementById("code").value;

	var butok = " <input type=\"submit\" value=\"Invia ORA\" name=\"submit\" id=\"bottone_conferma\" />";
	var filter = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/
	
	var msg01 = "Inserire la ragione sociale / nome scuola / nome ente";
	var msg02 = "Inserire il codice di sicurezza";
	var msg03 = "Inserire la citta";
	var msg04 = "Inserire il nome della persona di riferimento";
	var msg05 = "Inserire il telefono";
	var msg06 = "Occorre inserire la descrizione";
	var msg07 = "La email inserita non ha un formato corretto.";
	var msg08 = "La descrizione ha una lunghezza troppo elevata. Caratteri massimi: 1000 car.";

	if(code==""){
		display_message_on_div("alertbox",msg02);
	}
	else if(rag_soc==""){
		display_message_on_div("alertbox",msg01);
	}
	else if(citta==""){
		display_message_on_div("alertbox",msg03);
	}
	else if(persona==""){
		display_message_on_div("alertbox",msg04);
	}
	else if(telefono==""){
		display_message_on_div("alertbox",msg05);
	}
	else if(descrizione==""){
		display_message_on_div("alertbox",msg06);
	}
	else if(!ck_string(mail,filter)){
		display_message_on_div("alertbox",msg07);
	}
	else if (descrizione.length > 1000){
		display_message_on_div("alertbox",msg08);
	}
	else{
		display_message_on_div("alertbox",butok);
	}
	

	
}




function admin_ckeck_user(divfield,tipo){
	// only continue if xmlHttp isn't void
	var nk= document.getElementById("username").value;
	var psw= document.getElementById("password").value;
	var c_psw= document.getElementById("c_password").value;
	var mail= document.getElementById("mail").value;

	var sendmail = getCheckedValue(document.forms['form'].elements['sendmail']);
	
	var urlpass = "compose.php?divfield=" + divfield + "&nick=" + nk + "&tipo=" + tipo + "&mail=" + mail;
		
	var msg01 = "Lo username scelto non ha un formato corretto. Min 5 max 15 caratteri. \n\nCaratteri non ammessi: \n\nspazio : ; , . lettere accentate ! \" £ $ % & / ( ) = ? ^ \\ | < - _>";
	var msg02 = "Lo username deve contenre almeno 5 caratteri.";
	var msg03 = "Controlla la corrispondeza tra le due password inserite.";
	var msg05 = "Se vuoi spedire una email all'utente devi inserire una email valida...";

	
	if(nk==""){
		display_message_on_div("checknickresponse",msg02);
		// alert("Mi dispiace ma il nickname non puo avere una stringa vuota.");
	}
	else if(!ck_string(nk,"^[a-zA-Z0-9]{5,15}$")){
		display_message_on_div("checknickresponse",msg01);
		//alert("Lo username scelto non ha un formato corretto. Min 5 max 15 caratteri. \n\nCaratteri non ammessi: \n\nspazio : ; , . è é ò à ù ì ! \" £ $ % & / ( ) = ? ^ \\ | < - _>");
	}
	else{
		if(psw!=c_psw || psw ==""){
			display_message_on_div("checknickresponse",msg03);
		}
		else{

			if(sendmail=="1"){
				var filter = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/
				
				if(!ck_string(mail,filter)){
					display_message_on_div("checknickresponse",msg05);
				}
				else{
					start_control(divfield,tipo,urlpass);
				}
			}
			else{
				start_control(divfield,tipo,urlpass);
			}

		}
	}
}






function check_registrazione_completa(divfield,tipo){
	var code= document.getElementById("code").value;
	var nulli= document.getElementById("nulli").value;
	var provincia_id= document.getElementById("provincia_id").value;
	var nk= document.getElementById("username").value;
	var psw= document.getElementById("password").value;
	var c_psw= document.getElementById("c_password").value;
	var mail= document.getElementById("mail").value;

	// force strto lower
	document.getElementById("username").value = nk.toLowerCase();
	nk= document.getElementById("username").value;


	var urlpass = "http://calcolatore.stopthefever.org/compose.php?divfield=" + divfield + "&nick=" + nk + "&tipo=" + tipo + "&mail=" + mail;
		
	var msg01 = "Lo username scelto non ha un formato corretto. Min 5 max 15 caratteri. <br/><br/>Caratteri  ammessi: <br />lettere non accentate e numeri";
	var msg02 = "Lo username deve contenre almeno 5 caratteri.";
	var msg03 = "Controlla la corrispondeza tra le due password inserite.";
	var msg04 = "Seleziona una provincia per favore.";
	var msg05 = "Inserisci un indirizzo email valido per favore.";
	var msg06 = "Inserisci il codice antispam.";

	errore=false;
	msgerrore = "";
	num=0;


	
	if(code==""){
		display_message_on_div("alertbox",msg06);
		//display_message_on_div("checknickresponse",msg06);
	}
	else{
		for(i=0; i<document.form.elements.length; i++){
			nome=document.form.elements[i].name;
			valore=document.form.elements[i].value;
			if(valore==""){
				if(nulli!=""){
					if(nulli.indexOf(nome)==-1){
						errore = true
						num++;
						
					}
				}
				else{
					errore = true
					num++;
				}
			}
		}
		if(errore){
			if(num>1){
				msg00= "Ci sono " + num + " campi non compilati. Verifica di aver completato tutti i campi.";
			}
			else{
				msg00= "C'e' un campo non compilato. Verifica di aver completato tutti i campi.";
			}
			display_message_on_div("alertbox",msg00);
			//display_message_on_div("checknickresponse",msg00);
		}	
		else if(provincia_id=="NULL"){
			display_message_on_div("alertbox",msg04);
			//display_message_on_div("checknickresponse",msg04);
		}
		else if(!ck_string(nk,"^[a-zA-Z0-9]{5,15}$")){
			display_message_on_div("alertbox",msg01);
			//display_message_on_div("checknickresponse",msg01);
		}
		else{
			if(psw!=c_psw || psw ==""){
				display_message_on_div("alertbox",msg03);
				//display_message_on_div("checknickresponse",msg03);
			}
			else{
	
				var filter = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/
				
				if(!ck_string(mail,filter)){
					display_message_on_div("alertbox",msg05);
					//display_message_on_div("checknickresponse",msg05);
				}
				else{
					start_control(divfield,tipo,urlpass);
				}
			}
		}
	}
}




function user_update_impegni(){

	errore=false;
	
/*
	for(i=0; i<document.form.elements.length; i++){
		nome=document.form.elements[i].name;
		valore=document.form.elements[i].value;

		if(nome!="categoria" && nome != undefined){
			if(!isInteger(valore)){
				errore=true;
			}
		}
	}
*/

	for(i=0; i<document.forms[0].elements.length; i++){

		tipo=document.forms[0].elements[i].type;
		
		if(tipo=="text"){

			ilnome=document.forms[0].elements[i].name;
			valore=document.forms[0].elements[i].value;
	
			if(ilnome!="categoria" && ilnome != undefined){
				if(!isInteger(valore)){
					errore=true;
				}
			}
		}
	}


	var msg01 = "I valori devono essere numeri interi!";

	var butok = "<p><input type=\"submit\" value=\"Aggiorna il tuo calcolatore\" name=\"submit\" id=\"bottone_conferma\" /></p>";
	
	if(errore){
		display_message_on_div("alertbox",msg01);
	}
	else{
		display_message_on_div("alertbox",butok);
	}
}



function admin_process_new_passwd(){
	var psw= document.getElementById("password").value;
	var c_psw= document.getElementById("c_password").value;
	var mail= document.getElementById("mail").value;
	var sendmail = getCheckedValue(document.forms['form'].elements['sendmail']);
	
	var msg03 = "Controlla la corrispondeza tra le due password inserite.";
	var msg05 = "Se vuoi spedire una email all'utente devi inserire una email valida...";

	var butok = "<p><input type=\"submit\" value=\"Modifica\" name=\"submit\" id=\"bottone_conferma\" /></p>";
	
	if(psw!=c_psw || psw ==""){
		display_message_on_div("checknickresponse",msg03);
	}
	else{

		if(sendmail=="1"){
			var filter = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/
			
			if(!ck_string(mail,filter)){
				display_message_on_div("checknickresponse",msg05);
			}
			else{
				display_message_on_div("checknickresponse",butok);
			}
		}
		else{
			display_message_on_div("checknickresponse",butok);
		}

	}
}

function user_process_new_passwd(){
	var psw= document.getElementById("password").value;
	var c_psw= document.getElementById("c_password").value;
	
	var msg03 = "Controlla la corrispondeza tra le due password inserite.";

	var butok = "<span class=\"messaggio\"><strong>5:49:47</strong> - OK! Clicca sul bottone 'Modifica la tua passowrd'</span>";
	butok+= "<input value=\"Modifica la tua Password\" name=\"submit\" id=\"bottone_conferma\" type=\"submit\">";
	butok+= "<div class=\"cleaner\"></div>";

	
	if(psw!=c_psw || psw ==""){
		display_message_on_div("alertbox",msg03);
	}
	else{
		display_message_on_div("alertbox",butok);
	}
}

function get_estensione(path) {
    posizione_punto=path.lastIndexOf(".");
	lunghezza_stringa=path.length;
	estensione=path.substring(posizione_punto+1,lunghezza_stringa);
	return estensione;
}

function user_process_new_comunita(){

	var titolo= document.getElementById("titolo").value;
	var descrizione= document.getElementById("descrizione").value;
	var nomefile= document.getElementById("nomefile").value;
	
	var msg01 = "Attenzione non hai completato tutti i campi.";
	var msg02 = "Attenzione l'immagine deve essere un JPG.";

	var butok = "<span class=\"messaggio\"><strong>5:49:47</strong> - OK! Clicca sul bottone 'Crea la comunit&agrave'</span>";
	butok+= "<input value=\"Crea la comunit&agrave;\" name=\"submit\" id=\"bottone_conferma\" type=\"submit\">";
	butok+= "<div class=\"cleaner\"></div>";
	
	if(titolo=="" || descrizione =="" || nomefile ==""){
		display_message_on_div("alertbox",msg01);
	}
	else if(get_estensione(nomefile)!="jpg") {
		display_message_on_div("alertbox",msg02);
	}
	else{
		display_message_on_div("alertbox",butok);
	}
}


function admin_ckeck_impegno(divfield){
	var valore_limite= document.getElementById("valore_limite").value;
	var titolo= document.getElementById("titolo").value;
	var descrizione= document.getElementById("descrizione").value;
	var risparmio_co2= document.getElementById("risparmio_co2").value;

	var msg01 = "Titolo, descrizione e risparmio di co2 non possono essere vuoti.";
	var msg02 = "La quantita' di CO2 deve essere un numero decimale. Ad es. 12,00 ";
	var msg03 = "La quantita' limite deve essere un numero intero";

	var butok = "<input type=\"submit\" value=\"Avvia\" name=\"submit\" id=\"bottone_conferma\" />";

	if(!isInteger(valore_limite)){
		display_message_on_div(divfield,msg03);
	}
	else if(titolo=="" | descrizione=="" | risparmio_co2==""){
		display_message_on_div(divfield,msg01);
	}
	else if(!IsDecimal(risparmio_co2)){
		display_message_on_div(divfield,msg02);
	}
//	else if(!isInteger(risparmio_co2)){
//		display_message_on_div(divfield,msg02);
//	}
	else{
		display_message_on_div(divfield,butok);
	}
}


function admin_ckeck_categoria(divfield){
	var categoria= document.getElementById("categoria").value;
	
	var msg03 = "La categoria non puo' essere vuota.";

	var butok = "<input type=\"submit\" value=\"Avvia\" name=\"submit\" id=\"bottone_conferma\" />";
	
	if(categoria ==""){
		display_message_on_div(divfield,msg03);
	}
	else{
		display_message_on_div(divfield,butok);
	}
}