function controlNewsletter (CampoEmail) {

    if (testEmail(CampoEmail, true)) {
        document.frm_newsletter.submit();
    }
    alert('Attenzione\n\nL\'indirizzo email inserito non è valido')
    return false;
    
}

function controlfield(campo,strcampo){
	objcampo = eval(campo)
	valore = objcampo.value
	valore = valore.replace(" ","")
	if (valore==""){
		alert("Il campo " + strcampo + " è obbligatorio");
		objcampo.value = valore;
		objcampo.focus();
		return false;
	}
	else{
		return true;
	}
}

function RemoveBad(strTemp) { 
    strTemp = strTemp.replace(/\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-/g,""); 
    return strTemp;
} 

function ControlloCaratteri (strTemp) {

        var espressione = new RegExp("^[A-Za-z0-9]+$");
        var stringa = strTemp;
        return (espressione.test(stringa))
        {
          return false;
        }
       return true;
}

function isSoloNumeri(strTesto)
{
    var espressione = new RegExp("^[0-9]+$");
    return (espressione.test(strTesto))
    {
      return false;
    }
    return true;
}

function testEmail(oggTextfield, boolObbligatorio) {
    oggTextfield.value = oggTextfield.value.replace(/\s+$|^\s+/g,"")

    if (oggTextfield.value == "")
        if (boolObbligatorio)
	        return false
        else
	        return true
	        
    var re = /^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,}$/g
    return(re.test(oggTextfield.value))
}

function apriWin(Indirizzo,Larg,Alt,Nome){
	var top = 0;
	var left = 0;
		var w=Larg;
		var h=Alt;
		var sUrl = Indirizzo
		if (screen.width > w) left = (screen.width - w) / 2;
		if (screen.height > h) top = (screen.height - h) / 2;
		var sFeatures="width=" + w + ",height=" + h + ",left=" + left +",top=" + top+ ",resizable=no,menubar=no,directories=no,toolbar=no,scrollbars=yes";
		//alert(sFeatures)
	var win = window.open(sUrl,Nome,sFeatures);
	if (navigator.appName != 'Microsoft Internet Explorer')  { if ( window.focus )  win.focus()};
	win.focus();
	return;
}

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	//var strDay=dtStr.substring(pos1+1,pos2)
	//var strMonth=dtStr.substring(0,pos1)
	
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("Il formato della data deve essere : dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Inserire un mese valido")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Inserire un giorno corretto")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("L'anno deve essere compreso tra "+minYear+" e "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Inserire una data valida")
		return false
	}
return true
}

function GetUnicode(testo) {
    testo = escape(testo);
    testo = testo.replace(/%/g, "%u00");
    return testo;
}

//  *****  Oggetto SELECT *******

//Elimina tutti gli elementi (option) di un oggetto Select
function clearAllSelect(objSelect)
{
    var dim = objSelect.length;
    for (i=0; i<dim; ++i)
        objSelect.remove(0);
}
//Aggiunge un elemento (option) ad un oggetto Select (setta Text e Value all'identico valore)
function addSelectItemValue(objSelect, itemValue)
{
    var newElem=document.createElement('option');
    newElem.text = itemValue;
    newElem.value = itemValue;
    try
      {
      objSelect.add(newElem,null); // standards compliant
      }
    catch(ex)
      {
      objSelect.add(newElem); // IE only
      }
      return newElem;
  }

  //Aggiunge un elemento (option) ad un oggetto Select
  function addSelectItem(objSelect, itemValue, itemText) {
      var newElem = document.createElement('option');
      newElem.text = itemText;
      newElem.value = itemValue;
      try {
          objSelect.add(newElem, null); // standards compliant
      }
      catch (ex) {
          objSelect.add(newElem); // IE only
      }
      return newElem;
  }

  ///Restituisce un array con gli elementi risultato splittando in base al separatore sep
  function getElementiBySep(unione, sep) {
      return unione.split(sep);
  }


// *****  AJAX  *****
function CreateXmlHttpReq(handler) {
    var xmlhttp = null;
    try 
    {
        xmlhttp = new XMLHttpRequest();
    } 
    catch(e) 
    {
        try 
        {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch(e) 
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    xmlhttp.onreadystatechange = handler;
    return xmlhttp;
}


var AJAX_xmlHttpReq = null;

//return true se la risposta ad una richiesta asincrona è valida
function AJAX_isRispostaOk() {
    if (AJAX_xmlHttpReq != null && AJAX_xmlHttpReq.readyState == 4 && AJAX_xmlHttpReq.status == 200)
        return true;
    else
        return false;
}


///Restituisce un array con gli elementi risultato (usato per le Select)
function AJAX_getElementi() {
    if (AJAX_xmlHttpReq != null)
        return AJAX_xmlHttpReq.responseText.split('###');
    else
        return "";
}



///Restituisce un array con gli elementi risultato splittando in base al separatore sep
function AJAX_getElementiBySep(sep) {
    if (AJAX_xmlHttpReq != null)
        return AJAX_xmlHttpReq.responseText.split(sep);
    else
        return "";
}

//Invia una richiesta asincrona di tipo XmlHttpReq per conoscere i quartieri appartenenti ad una zona
//objSel è l'oggetto Select relativo alla zona di cui si vuole conoscere i quartieri

function AJAX_getQuartieri(objSelZona, objSelPrv) {
    var zona = objSelZona.value;
    var prv = objSelPrv.value;
    var url="/site/AJAX_query.asp?query=getQuartieri&target=" + zona + "&target2=" + prv;
    AJAX_xmlHttpReq = CreateXmlHttpReq(setSelectQuartieri); //setSelectQuartieri è la funzione che prende l'output
    AJAX_xmlHttpReq.open("GET", url);
    AJAX_xmlHttpReq.send(null);
}
 
//Invia una richiesta asincrona di tipo XmlHttpReq per conoscere le zone appartenenti ad una provincia
//objSel è l'oggetto Select relativo alla provincia di cui si vuole conoscere le zone
function AJAX_getZone(objSel)
{   var prov=objSel.value;
    var url="/site/AJAX_query.asp?query=getZone&target=" + prov;
    AJAX_xmlHttpReq = CreateXmlHttpReq(setSelectZone); //setSelectZone è la funzione che prende l'output
    AJAX_xmlHttpReq.open("GET", url);
    AJAX_xmlHttpReq.send(null);
}

//Invia una richiesta asincrona di tipo XmlHttpReq per ottenere l'elenco dei prezzi per un dato periodo ed un prezzoStanza
function AJAX_getElencoPrezziPeriodo(dataStart, dataEnd, idPrezzoStanza)
{   var url="/site/AJAX_query.asp?query=getElencoPrezziPeriodo&dataStart=" + dataStart + "&dataEnd=" + dataEnd + "&idPrezzoStanza=" + idPrezzoStanza;
    AJAX_xmlHttpReq=CreateXmlHttpReq(setElencoPrezziPeriodo); //setElencoPrezziPeriodo è la funzione che prende l'output
    AJAX_xmlHttpReq.open("GET",url);
    AJAX_xmlHttpReq.send(null);
}

//Invia una richiesta asincrona di tipo XmlHttpReq per ottenere l'elenco dei comuni appartenenti alla provincia selezionata
function AJAX_getComuni(objSel) {
    var prov = objSel.value;
    var url = "/site/AJAX_query.asp?query=getComuni&target=" + prov;
    AJAX_xmlHttpReq = CreateXmlHttpReq(setSelectComuni); //setSelectComuni è la funzione che prende l'output
    AJAX_xmlHttpReq.open("GET", url);
    AJAX_xmlHttpReq.send(null);
}

//Invia una richiesta asincrona di tipo XmlHttpReq per settare per una struttura il campo booleano 'ContrattoAccettato'
function AJAX_setContrattoAccettato(idStruttura, isAccettato) {
    var accettato = 0;
    if (isAccettato)
        accettato = 1;
    var url = "/site/AJAX_query.asp?query=setContrattoAccettato&target=" + idStruttura + "&target2=" + accettato;
    AJAX_xmlHttpReq = CreateXmlHttpReq(onSetContrattoAccettato); //onSetContrattoAccettato è la funzione che prende l'output
    AJAX_xmlHttpReq.open("GET", url);
    AJAX_xmlHttpReq.send(null);
} 


// *********** Goole Map *******

function GMAPI_creaMarker(lat, lng, img, info, html)
{
    icona = new GIcon();
    icona.image = img;
    icona.iconSize = new GSize(38, 38);
    icona.iconAnchor = new GPoint(6, 40);
    icona.infoWindowAnchor = new GPoint(12, 20);
    //markerOptions = { icon:icona, title:info };
    markerOptions = { title:info };
    
    punto=new GLatLng(lat,lng);
    var marker=new GMarker(punto, markerOptions);
    //var marker=new GMarker(punto);
    
//    ind=img.lastIndexOf('/');
//    ind=ind+1;
//    var tipo=img.substr(ind);
//    dimTipo=tipo.length;
//    tipo=tipo.substr(0,dimTipo-4);
    GEvent.addListener(marker, "click", function() {    
            marker.openInfoWindowHtml(html); 
            
        });
    
    return marker;
}

// ******** Funzioni di supporto al DatePicker *****

// Controlla che non vengano immesse date non valide
//come data check out precedente a data check in
//oppure date precedenti alla data odierna
function datepicker_cambioData_CheckIn_CheckOut(nomeCampo)
{
    var data_ora=new Date();
    var data = document.getElementsByName(nomeCampo).item(0).value; 
    var cStart = 'CheckIn';
    var cEnd = 'CheckOut';
    var checkDateNow = true; //Se true verifico di non inserire una data anteriore alla data odierna
    var addOneDay = true; //Se true, incremento di un giorno la data del dateTime finale
    switch (nomeCampo)
    {
        case 'DataInizio':
        case 'DataFine':
            cStart = 'DataInizio';
            cEnd = 'DataFine';
            checkDateNow = true;
            addOneDay = true;
            break;
        case 'DataRegistrazione':
        case 'DataAttivazione':
            cStart = 'DataRegistrazione';
            cEnd = 'DataAttivazione';
            checkDateNow = false;
            addOneDay = false;
            break;
        case 'DataFineValidita':
            cStart = 'DataAttivazione';
            cEnd = 'DataFineValidita';
            checkDateNow = false;
            addOneDay = false;
            break;
    }
    if (nomeCampo==cStart)
    {
        var dataOut=document.getElementsByName(cEnd).item(0).value;
        
        var arr1 = data.split('/');
        var arr2 = dataOut.split('/');

        var d1 = new Date(arr1[2],arr1[1]-1,arr1[0]);
        var d2 = new Date(arr2[2],arr2[1]-1,arr2[0]);

        var r1 = d1.getTime();
        var r2 = d2.getTime();
        
        if (checkDateNow & r1<data_ora.getTime())
        {
            var mese=data_ora.getMonth()+1;
            var mese_str=mese.toString();
            if (mese_str.length==1)
                mese_str="0"+mese_str;
            var oggi=data_ora.getDate()+"/"+mese_str+"/"+data_ora.getFullYear();
            document.getElementsByName(nomeCampo).item(0).value=oggi;
            arr1 = oggi.split('/');
            d1 = new Date(arr1[2],arr1[1]-1,arr1[0]);
            r1 = d1.getTime();
            data=oggi;
        }

        if (r1>=r2)
        {
            if (addOneDay)
                document.getElementsByName(cEnd).item(0).value=addGiorni(data,1);
            else
                document.getElementsByName(cEnd).item(0).value=data;
        }
    }
    else
    {
        var dataIn=document.getElementsByName(cStart).item(0).value;
        var arr1 = dataIn.split('/');
        var arr2 = data.split('/');

        var d1 = new Date(arr1[2],arr1[1]-1,arr1[0]);
        var d2 = new Date(arr2[2],arr2[1]-1,arr2[0]);

        var r1 = d1.getTime();
        var r2 = d2.getTime();
        if (r1>=r2)
        {
            if (addOneDay)
                document.getElementsByName(cEnd).item(0).value=addGiorni(dataIn,1);
            else
                document.getElementsByName(cEnd).item(0).value=dataIn;
        }

    }
}
//Aggiunge ad una data in forma di stringa il numero di giorni indicato. restituisce la data in forma di stringa
function addGiorni(dataStr, giorni)
{
    var arr = dataStr.split('/');
    var newData = new Date(arr[2],arr[1]-1,arr[0]);
    newData.setDate(newData.getDate() + giorni);
    var mese = newData.getMonth()+1;
    var mese_str = mese.toString();
    if (mese_str.length==1)
        mese_str="0"+mese_str;
    var giorno_str = newData.getDate().toString();
    if (giorno_str.length==1)
        giorno_str="0"+giorno_str;
    var data = giorno_str+"/"+mese_str+"/"+newData.getFullYear();
    return data;
    
}

// ****************************************************************************
// ** Funzioni di supporto alla stampa del contratto **

function compilaCampiContratto()
{
    var doc=document.getElementById('DIV_Contratto').innerHTML;  
    var campoCognome = '[#COGNOME#]';
    var campoNome = '[#NOME#]';
    var campoStruttura = '[#STRUTTURA#]';
    var campoIndirizzo = '[#INDIRIZZO#]';
    var campoCitta = '[#CITTA#]';
    var campoCap = '[#CAP#]';
    var campoProv = '[#PROV#]';
    var campoStIndirizzo = '[#ST_INDIRIZZO#]';
    var campoStCitta = '[#ST_CITTA#]';
    var campoStCap = '[#ST_CAP#]';
    var campoStProv = '[#ST_PROV#]';
    var campoCfPiva = '[#CF_PIVA#]';
    
    var compilareContratto = document.getElementById("compilare").value;
    
    if (compilareContratto=='false')
    {
        doc = testoEliminaTag(doc, campoCognome);
        doc = testoEliminaTag(doc, campoNome);
        doc = testoEliminaTag(doc, campoStruttura);
        doc = testoEliminaTag(doc, campoIndirizzo);
        doc = testoEliminaTag(doc, campoCitta);
        doc = testoEliminaTag(doc, campoCap);
        doc = testoEliminaTag(doc, campoProv);
        doc = testoEliminaTag(doc, campoCfPiva);

        doc = testoEliminaTag(doc, campoStIndirizzo);
        doc = testoEliminaTag(doc, campoStCitta);
        doc = testoEliminaTag(doc, campoStCap);
        doc = testoEliminaTag(doc, campoStProv);
    }
    else
    {
        var cognome=document.getElementById('cognome').value;
        var nome=document.getElementById('nome').value;
        var indirizzo=document.getElementById('indirizzo').value;
        var citta=document.getElementById('citta').value;
        var prov=document.getElementById('prov').value;
        var cap=document.getElementById('cap').value;
        var struttura = document.getElementById('struttura').value;

        var st_indirizzo = document.getElementById('st_indirizzo').value;
        var st_citta = document.getElementById('st_citta').value;
        var st_prov = document.getElementById('st_prov').value;
        var st_cap = document.getElementById('st_cap').value;

        var cf_piva = document.getElementById('cf_piva').value;
        
        doc = sostituisciCampo(doc, campoCognome, cognome);
        doc = sostituisciCampo(doc, campoNome, nome);
        doc = sostituisciCampo(doc, campoStruttura, struttura);
        doc = sostituisciCampo(doc, campoCfPiva, cf_piva);
        doc = sostituisciCampo(doc, campoIndirizzo, indirizzo);
        doc = sostituisciCampo(doc, campoCitta, citta);
        doc = sostituisciCampo(doc, campoCap, cap);
        doc = sostituisciCampo(doc, campoProv, prov);
        doc = sostituisciCampo(doc, campoStIndirizzo, st_indirizzo);
        doc = sostituisciCampo(doc, campoStCitta, st_citta);
        doc = sostituisciCampo(doc, campoStCap, st_cap);
        doc = sostituisciCampo(doc, campoStProv, st_prov);
    }
    document.getElementById('DIV_Contratto').innerHTML = doc;
}

function testoEliminaTag(testo, targetTag)
{
    while (testo.indexOf(targetTag)!=-1)
    {
        testo = testo.replace(targetTag, '');
    }
    return testo;
}

function sostituisciCampo(testo, targetTag, valore)
{
    while (testo.indexOf(targetTag)!=-1)
    {
        var indStart=testo.indexOf(targetTag);
        var indStop=testo.indexOf(targetTag, indStart + 1);
        indStop+=targetTag.length;
        var testoPre=testo.slice(0,indStart);
        var testoPost = testo.slice(indStop);
        testo = testoPre + valore + testoPost;
    }
    return testo;
}



//**** Funzione per aprire una modal box centrata nelle schermo
function showModalDIV(DIV_id, DIV_w, DIV_h) 
{
    var w = DIV_w; //400;
    var h = DIV_h; //300;
    var x = (window.screen.width - w) / 2;
    var offset = window.pageYOffset ? window.pageYOffset : 0;
    if (offset == 0) {
        offset = document.documentElement.scrollTop ? document.documentElement.scrollTop : 0;
    }
    if (offset == 0) {
        offset = document.documentElement.scrollTop ? document.documentElement.scrollTop : 0;
    }
    if (offset == 0) {
        offset = document.body.scrollTop ? document.body.scrollTop : 0;
    }

    var y = (window.screen.height - h) / 2 + offset;
    var objDiv = document.getElementById(DIV_id);
    objDiv.style.width = w + "px";
    objDiv.style.height = h + "px";
    objDiv.style.left = x + "px";
    objDiv.style.top = y + "px";
    objDiv.style.display = "block";
}





