//******************Ridirige ad una nuova finestra al momento della submit della form**************
// es. <form action="Auth" name="utente" method="post" onsubmit='redirectOutput(this)'> 
//     </form>
function redirectOutput(myForm,codinst) {
    param = 'scrollbars=yes,resizable=yes,left=0,top=0,width='+(screen.width-8)+',height='+(screen.height-55)+'';
    var w = window.open('about:blank','ZEROgis_Online_'+codinst,param);
    myForm.target = 'ZEROgis_Online_'+codinst;
    if (w!=null){
        w.focus();
        return true;
    }else{
        alert("Per il corretto funzionamento del programma disabilitare il blocco popup");
        return false;
    }
}
//********************Popup per il filtro*******************//
//window.open(url,'filtro','scrollbars=yes,resizable=yes,height=400,width=600');
var filtrowindow = '';
function popupfiltro(url,w,h){
    if (w == null) w = 400;
    if (h == null) h = 350;
    if (!filtrowindow.closed && filtrowindow.location) {
        filtrowindow.location.href = url;
    }else {
        param = 'scrollbars=yes,resizable=yes,height='+h+',width='+w;
        filtrowindow=window.open(url,'filtro',param);
        if (!filtrowindow.opener) filtrowindow.opener = self;
    }
    if (window.focus) {
        filtrowindow.focus()
        }
    return false;    
}
//********************Popup window*******************//
//window.open(url,'filtro','scrollbars=yes,resizable=yes,height=400,width=600');
var win = '';
function popupwindow(url,name,w,h){
    if (w == null) w = 400;
    if (h == null) h = 350;
    if (!win.closed && win.location) {
        win.location.href = url;
    }else {
        param = 'scrollbars=yes,resizable=yes,height='+h+',width='+w;
        win=window.open(url,name,param);
        if (!win.opener) win.opener = self;
    }
    if (window.focus) {
        win.focus()
        }
    return false;
}
//********************Popup per cartografia*******************//
var cartografiawindow = '';
function popupcartografia(paramurl){
    if (paramurl==null)paramurl='';
    if (!cartografiawindow.closed && cartografiawindow.location) {
        cartografiawindow.location.href = 'Cartografia'+paramurl;
    }else {
        param = 'left=0,top=0,width='+(screen.width-8)+',height='+(screen.height-55);
        cartografiawindow=window.open('Cartografia'+paramurl,'ZEROgis_Online_Cartografia',param);
        if (!cartografiawindow.opener) cartografiawindow.opener = self;
    }
    if (window.focus) {
        cartografiawindow.focus()
        }
    return false;
}

var cartografiaZerowindow = '';
function popupZeroCartografia(paramurl){
    if (paramurl==null) paramurl='';
    if (!cartografiaZerowindow.closed && cartografiaZerowindow.location) {
        cartografiaZerowindow.location.href = 'ZeroCartografia'+paramurl;
    }else {
        param = 'left=0,top=0,width='+(screen.width-8)+',height='+(screen.height-55);
        cartografiaZerowindow=window.open('ZeroCartografia'+paramurl,'ZEROgis_Online_ZeroCartografia',param);
        if (!cartografiaZerowindow.opener) cartografiaZerowindow.opener = self;
    }
    if (window.focus) {
        cartografiaZerowindow.focus();
    }
    return false;
}

var cartografiaZerowindowNew = '';
function popupZeroCartografia_New(paramurl){
    if (paramurl==null)paramurl='';
    if (!cartografiaZerowindowNew.closed && cartografiaZerowindowNew.location) {
        cartografiaZerowindowNew.location.href = 'ZeroCartografia'+paramurl;
    }else {
        param = 'left=0,top=0,width='+(screen.width-8)+',height='+(screen.height-55);
        cartografiaZerowindowNew=window.open('ZeroCartografia'+paramurl,'ZEROgis_Online_Cartografia',param);
        if (!cartografiaZerowindowNew.opener) cartografiaZerowindowNew.opener = self;
    }
    if (window.focus) {
        cartografiaZerowindowNew.focus()
        }
    return false;
}

var cartografiaWeb = '';
function popupcartografiaWeb(paramurl){
    if (paramurl==null) paramurl='';
    if (!cartografiaWeb.closed && cartografiaWeb.location) {
        cartografiaWeb.location.href = url;
    }else {
        param = 'left=0,top=0,width='+(screen.width-8)+',height='+(screen.height-55);
        cartografiaWeb=window.open('WebCartografia'+paramurl,'ZEROgis_Online_Cartografia_Web',param);
        if (!cartografiaWeb.opener) cartografiaWeb.opener = self;
    }
    if (window.focus) {
        cartografiaWeb.focus()
        }
    return false;
}

var cartografiaUrlAndParam = '';
function popupCartografiaUrlAndParam(urlAndParam){
    if (urlAndParam==null) urlAndParam='';
    if (!cartografiaUrlAndParam.closed && cartografiaUrlAndParam.location) {
        cartografiaUrlAndParam.location.href = url;
    }else {
        param = 'left=0,top=0,width='+(screen.width-8)+',height='+(screen.height-55);
        cartografiaUrlAndParam=window.open(urlAndParam,'ZEROgis_Online_Cartografia_Web',param);
        if (!cartografiaUrlAndParam.opener) cartografiaUrlAndParam.opener = self;
    }
    if (window.focus) {
        cartografiaUrlAndParam.focus()
        }
    return false;
}

//******************Funzione che rimuove gli spazi da una stringa**************
function TrimString(sInString) {
    sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
}

//******************Controllo del E-Mail**************
function checkEmailAddress(field) {
    mailchar = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";
    for(i=0; i < field.length ;i++) {
        if(mailchar.indexOf(field.charAt(i))<0) return false;
    }
    var x = field.value;
    var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(x)) return true;
    else return false;
}

//******************Controllo della data**************
// ritorna true se è una data, false altrimenti
function isA_data(gio,mes,ann){
    if (isNaN(gio) || isNaN(mes) || isNaN(ann)){
        return false;
    }
    if (gio== "" || mes == "" || ann == ""){
        return false;
    }
    a = eval(ann);
    m = eval(mes);
    g = eval(gio);
    if (a<1900) {
        return false;
    }
    if (m<1 || m>12) {
        return false;
    }
    else{
        var giorni = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,  31)[m - 1];
        if ((m == 2) && (a%4 == 0 && a%100 != 0 || a%400 == 0)) giorni++;
        if (g > giorni || g<1) {
            return false; 
        }
        else{
            return true;
        }
    }
}

//************Controllo per verificare che i tre campi della data siano diveri da vuoto**********
// data_to_test = nome della data es. datainizio
// tipoparam = estensione dei parametri es. GG, MM, AA oppure G, M, A
// data_to_test+tipoparam[0] = datainizioGG
// data_to_test+tipoparam[1] = datainizioMM
// data_to_test+tipoparam[2] = datainizioAA
function dataIsEmpty(data_to_test,tipoparam){
    retval = false;

    if (document.getElementById(data_to_test+tipoparam[0]).value=="" &&
        document.getElementById(data_to_test+tipoparam[1]).value=="" &&
        document.getElementById(data_to_test+tipoparam[2]).value=="" ){
        retval =  true
    }else{
        retval =  false;
    }
    return retval;
}

//******************Controllo dell' ora**************
// ritorna true se l'ora è corretta
function isA_time(ora,min,sec){
    if (isNaN(ora) || isNaN(min) ) return false;
    if (ora== "" || min == "") return false;
    if (ora<0 || ora>23) return false;
    if (min<0 || min>59) return false;
    if (sec){
        if (sec<0 || sec>59) return false;
    }
    return true;
}

//******************Controllo della Partita IVA**************
// ritorna una stringa "true" se � una PI Un messaggio di errore altrimenrti
function ControllaPIVA(pi){
    if( pi == '' )  return 'Inserire Una Partita IVA';
    if( pi.length != 11 )
        return "La lunghezza della partita IVA non e\' "+
        "corretta: la partita IVA dovrebbe essere lunga\n" +
        "esattamente 11 caratteri.\n";
    validi = "0123456789";
    for( i = 0; i < 11; i++ ){
        if( validi.indexOf( pi.charAt(i) ) == -1 )
            return "La partita IVA contiene un carattere non valido '" +
            pi.charAt(i) + "'.\nI caratteri validi sono 0123456789.\n";
    }
    s = 0;
    for( i = 0; i <= 9; i += 2 )
        s += pi.charCodeAt(i) - '0'.charCodeAt(0);
    for( i = 1; i <= 9; i += 2 ){
        c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
        if( c > 9 )  c = c - 9;
        s += c;
    }
    if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
        return "La partita IVA non e\' valida:\n" +
        "il codice di controllo non corrisponde.\n";
    return 'true';
}

/********************Controllo del Codice Fiscale*********************/
// ritorna una stringa "true" se è un CF Un messaggio di errore altrimenrti
function ControllaCF(cf){
    var validi, i, s, set1, set2, setpari, setdisp;
    if( cf == '' )  return '';
    cf = cf.toUpperCase();
    if( cf.length != 16 )
        return "La lunghezza del codice fiscale non è "
        +"corretta: il codice fiscale dovrebbe essere lungo\n"
        +"esattamente 16 caratteri.\n";
    if (cf == 'XXXXXXXXXXXXXXXX')
        return "Il codice XXXXXXXXXXXXXXXX non è corretto.";
    validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    for( i = 0; i < 16; i++ ){
        if( validi.indexOf( cf.charAt(i) ) == -1 )
            return "Il codice fiscale contiene un carattere non valido `" +
            cf.charAt(i) +
            "'.\nI caratteri validi sono le lettere e le cifre.\n";
    }
    set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
    setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
    s = 0;
    for( i = 1; i <= 13; i += 2 )
        s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
    for( i = 0; i <= 14; i += 2 )
        s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
    if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
        return "Il codice fiscale non è corretto:\n"+
        "il codice di controllo non corrisponde.\n";
    return 'true';
}



//******************Raddopia Apici**************
// Passato un stringa ritorna la stringa con gli apici rappopiati (sia apice singolo che doppio)
function AddApici(strr){
    strr = strr.replace(/"\""/g,"\"");
    strr = strr.replace(/"\'"/g,"\'");
    return strr;
}

//******************Permette la digitazione di soli numeri**************
// Inserire all'interno dell'oggetto il codice onKeyPress='return numbersonly(this, event);'  
// per aggiungere la virgola porre dec = true; 
// punto_o_virgola = per decidere se il separatore decimale è un punto '.' o unavirgola ','
function numbersonly(myfield, e, dec,punto_o_virgola) {
    var key;
    var keychar;

    if (window.event) { 
        key = window.event.keyCode;
    }
    else if (e) { 
        key = e.which;
    }
    else { 
        return true;
    }
    
    keychar = String.fromCharCode(key);

    key_x=44;
    if (punto_o_virgola == null)     { 
        key_x = 44;
    }
    else if (punto_o_virgola == '')  { 
        key_x = 44;
    }
    else if (punto_o_virgola == ',') { 
        key_x = 44;
    }
    else if (punto_o_virgola == '.') { 
        key_x = 46;
    }
    else if (punto_o_virgola == '/') { 
        key_x = 47;
    }
    else if (punto_o_virgola == ';') { 
        key_x = 59;
    }

    // control keys
    if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27)) {
        return true;
    }else if ((("0123456789").indexOf(keychar) > -1)) {
        return true;
    } else if (dec && key == key_x) {
        return true;
    } else return false;
}

/**
 * Permette l'inserimento di caratteri SOLO alfanumerici
 * Inserire all'interno dell'oggetto il codice onkeypress='return alfaNumericOnly(this, event);'  
 * 
 * @param myfield   il Campo da controllare (solitamente, "this")
 * @param e         l'Evento (solitamente, "event")
 * @return true se il numero è giusto, false altrimenti
 */
function alfaNumericOnly(myfield, e) {
    var key;
    var keychar;

    if (window.event) key = window.event.keyCode;
    else if (e) key = e.which;
    else return true;
    keychar = String.fromCharCode(key);


    // control keys
    if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27)) return true;

    // numbers
    else if ((("0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUwWxXyYzZ").indexOf(keychar) > -1)) return true;
    else return false;
}

//************Ritorna true se la stringa inserita è un numero************
// va utilizzata nella "checksubmit" questa funzione è valida se nel campo input
// separatore = '.' oppure ','
// viene utilizzata la funzione numberOnly()
function is_not_number(strNum,separatore) {
    if (strNum.length == 0) return true;
    f_char = strNum.charAt(0);
    if (f_char == "0" || f_char == "1" || f_char == "2" || f_char == "3" || f_char == "4" ||
        f_char == "5" || f_char == "6" || f_char == "7" || f_char == "8" || f_char == "9") {
        if (separatore == null) separatore='.';
        punto = strNum.indexOf(separatore);
        if (punto == -1){ 
            return false;
        } else if (strNum.substring(punto+1).indexOf(separatore) == -1) {
            return false;
        }else {
            return true;
        }
    } else {
        return true;
    }
}

// impedisce l'inserimento nel campoinput del carattere ["]
// onkeypress='return noDoppiApici(this,event)'
function noDoppiApici(myfield, e){
    var key;
    var keychar;

    if (window.event) key = window.event.keyCode;
    else if (e) key = e.which;
    else    return true;
    keychar = String.fromCharCode(key);
    
    // control keys
    if (key==34) {
        alert("Carattere non consentito");
        return false;
    }
    else return true;
}
// impedisce l'inserimento nel campoinput del carattere [']
// onkeypress='return numbersonly(this,event)'
function noApice(myfield, e){
    var key;
    var keychar;

    if (window.event) key = window.event.keyCode;
    else if (e) key = e.which;
    else    return true;
    keychar = String.fromCharCode(key);
    
    alert(key);
    // control keys
    if (key==39) {
        alert("Carattere non consentito");
        return false;
    }
    else return true;
}
//******************trasforma la letere digitata in una lettera maiuscola**************
// all'interno del campo onBlur="uppercase(this)" 
function uppercase(campo){
    campo.value=campo.value.toUpperCase();
}

//******************Aggiunge una nuova riga alla tabella**************
// tableop = nome della tabella
// cellHTMLAr = array contente il testo html di ogni cella
// al = array contente l'allinementdo di ogni fella
// idname = array contenente l'id che viene dato ad ogni cella;
function addRowToTable(tableop,cellHTMLAr,al,idname){
    var tbl = document.getElementById(tableop);
    var lastRow = tbl.rows.length;
    // if there's no header row in the table, then iteration = lastRow + 1
    var iteration = lastRow;
    var row = tbl.insertRow(lastRow);
    for (x=0;x<cellHTMLAr.length;x++){
        var newCell = row.insertCell(x);        
        newCell.innerHTML = cellHTMLAr[x];
        newCell.align = al[x];
        newCell.id = idname[x];
    }

    return row;
}

function addRowToTableTextInput(form,tableop,obj,al,idname){

    ff = document.getElementById(form);
    tbl = document.getElementById(tableop);
     
    lastRow = tbl.rows.length;
  
    // if there's no header row in the table, then iteration = lastRow + 1
    //iteration = lastRow;
    row = tbl.insertRow(lastRow);
  
    cellLeft = row.insertCell(0);
    cellLeft.align = al[0];
    cellLeft.id = idname[0];
    //var textNode = document.createTextNode(iteration);
    cellLeft.appendChild(obj[0]);
  
    cellRight = row.insertCell(1);
    cellRight.align = al[1];
    cellRight.id = idname[1];
    for (x=1; x<obj.length; x++){
        if (obj[x]!=null){
            cellRight.appendChild(ff.appendChild(obj[x]));
        }
    }
}

//******************Cambia il contenuto di una cella della tabella**************
function changeCellToTable(tableop,cellHTML,al,numcol,numrow){
    var tbl = document.getElementById(tableop);
    var x = tbl.rows[numrow].cells;
    x[numcol].innerHTML = cellHTML;
    x[numcol].align = al
}

//******************Rimuove L'ultima riga alla tabella**************
function remRowToTable(tableop){
    var tbl = document.getElementById(tableop);
    var lastRow = tbl.rows.length;
    if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}

//******************controlla che non venga superato il numero massimo di caratteri all'interno di una textarea**************
// va utilizzato all'interno del tag texarea cosi:  onKeyPress="return textareaMaxChar('areaname', max, event)"
function textareaMaxChar(areaname,max,e){
    var lenMax=max;
    var strlength = document.getElementById(areaname).value.length;
    if (window.event) key = window.event.keyCode;
    else if (e) key = e.which;
    else    return true;
    if (strlength >= lenMax && !(key == 8 || key==0)){
        alert("Il numero massimo di caratteri consentito per questo campo e\' di "+max);
        document.getElementById(areaname).value = document.getElementById(areaname).value.substring(0,max);
        return false;
    }else{
        return true;
    }
}

//****************Aggiusta/inserisce il colore delle righe di una tabella**********
// id = id della tabella
// NOTA: Deve esistere nel css che definisce gli stili due classi tsPari e trDispari
function classTable(id){
    if(document.getElementsByTagName){
        var table = document.getElementById(id);
        var rows = table.getElementsByTagName("tr");
        for(i = 0; i < rows.length; i++){
            if (i%2==0) { 
                rows[i].className = "trPari";
            }
            else { 
                rows[i].className = "trDispari";
            }
        } 
    }
}

//******************Detect del tipo di Browser utilizzato dall'utente**************
// E = Explorer; N = Netscape; A = Altro;
function detectionBrowserType(){
    var browserName = navigator.appName;
    if (browserName == "Netscape") return 'N';
    else if (browserName == "Microsoft Internet Explorer") return 'E';
    else return 'A';
}

//******************Detect della versione del Browser utilizzato dall'utente**************

function detectionBrowserVersion() {
    var b_version=navigator.appVersion;
    if (detectionBrowserType() == 'E') {
        b_version = b_version.substr(b_version.indexOf('MSIE'));
        b_version = b_version.substr(0, b_version.indexOf(';'));

        return b_version;

    } else {
        return b_version;
    }
}

//******************Generatore di password**************
// Generatore di stringhe casuali di lunghezza "plength"
function generatepass(plength){
    var keylist = "abcdefghijklmnopqrstuvwxyz1234567890";
    temp = '';
    for (i=0; i<plength; i++) temp += keylist.charAt(Math.floor(Math.random()*keylist.length));
    return temp;
}

//******************Separatore di migliaia con il punto**************
// utilizzto --> onblur="this.value=punti(this.value);"
// trasforma un numero 123456.78 in 123.456,78
function punti(numero){
    numero=numero.toString();
    numero = numero.replace(/\./g,"");  // serve per toglie i punti nel numero (reset)
    dp=numero.indexOf(",")!=-1?numero.substring(0,numero.indexOf(",")).length:numero.length;
    for (i=dp-3;i>0;i-=3) 
        numero=numero.substring(0,i)+"."+numero.substr(i);
    numero=numero.replace(/-,/,"-");  // Il replace serve per le stringhe negative (Non consentite)
    return numero
}

//******************funzione inversa di punti**************
// trasforma un numero 123.456,78 in 123456.78
function noDot(numero){
    return numero.replace(/\./g,"").replace(/,/,".");
}

//*****************Testa se il valore val e un valore in euro oppure no*********
// Si presuppone che val sia un valore composto da sole cifre (Cio� che sia utilizzato numbersonly() )
// viene acceto i valori scritti come: 12 -- 12, -- 12,0 -- 12,00
function isEuro(val){
    count = 0;
    div = ",";
    pos = val.indexOf(div);
    if (pos == -1){
        return true;  // Non c'� virgola OK
    }else{                        // C'� una virgola
        pos = val.indexOf(div,pos+1);     
        if ( pos != -1 ) {
            return false;   // C'� pi� di una virgola
        }else{
            pos = val.indexOf(div);        // Controllo che ci siano al massimo 2 numeri dopo la virgola
            if ( val.substring(pos+1).length > 2 ){ 
                return false;
            }
            else{ 
                return true;
            }
        }
    }
}

//**************Funzione per la ricerca in un array di un elemento************
// needle   = parametro cercato
// haystack = array della ricerca
function in_array(needle, haystack) {
    var n = haystack.length;
    for (var i=0; i<n; i++) {
        if (haystack[i]==needle) { 
            return true;
        }
    }
    return false;
}

//************Ritorna true se la stringa inserita è un numero
function is_number(a_string) {
    tc = a_string.charAt(0);
    if (tc == "0" || tc == "1" || tc == "2" || tc == "3" || tc == "4" ||
        tc == "5" || tc == "6" || tc == "7" || tc == "8" || tc == "9") {
        return true;
    } else {
        return false;
    }
}

// ********************  utilizzo della googole map  ricerca per indirizzo ****************
//  p_id =  campo provincia
//  c_id =  campo comune
//  i_id =  campo indirizzo
//  in_id = campo numero indirizzo
//  s_id =  campo nome della struttura
function googleMapAddr(p_id,c_id,i_id,in_id,s_id){
    url = 'GoogleMapAddr.jsp';
    prov = 'provincia=';    if (p_id!=null)  prov=prov+p_id;
    com =  'comune=';       if (c_id!=null)  com=com+c_id;
    ind = 'indirizzo=';     if (i_id!=null)  ind=ind+i_id;
    indn = 'indirizzonum=';    if (in_id!=null) indn=indn+in_id;
    str = 'nomestruttura='; if (s_id!=null)  str=str+s_id;
    url = url+'?'+prov+'&'+com+'&'+ind+'&'+indn+'&'+str;
    window.open(url,'indmapgoogle','scrollbars=yes,resizable=yes,width=650,height=550');
}

function abilitaAttesa(){
    document.getElementById('divfade').style.display='block';
    document.getElementById('divimageload').style.display='inline';
}
function disabilitaAttesa(){
    document.getElementById('divfade').style.display='none';
    document.getElementById('divimageload').style.display='none';
}

function arrotonda(numero,decimali) {
    var potenza = Math.pow(10,decimali);
    return Math.round(numero * potenza)/potenza;
}

// Apre la Galleria Fotografica. Unico tipo gestito finora: RUB (rubrica)
function apriGalleria(tipo, params) {
    var arrParams = new Array();
    var parametro = '';
    if (params!='') {
        arrParams=params.split(",");
        for (i=0;i<arrParams.length;i++) {
            parametro+='&'+arrParams[i];
        }
    }
    src = 'Galleria?sorg='+tipo+parametro;
    window.open(src,'galleria','width=800,height=650,left=10,top=10,screenX=10,screenY=10,directories=no,location=no,menubar=no,resizable=no,status=no,toolbar=no');
}

function apriFinestra(url, nome) {
    window.open(url, nome, 'width=800,height=500,left=50,top=50,screenX=10,screenY=10,directories=no,location=no,menubar=no,resizable=no,status=no,toolbar=no');
}

//********************Popup per la gestione dei campi*******************//
var campiwindow = '';
function popupcampi(paramurl){
    if (paramurl==null)paramurl='';
    if (!campiwindow.closed && campiwindow.location) {
        campiwindow.location.href = url;
    }else {
        param = 'left=0,top=0,width='+(screen.width-8)+',height='+(screen.height-55);
        campiwindow=window.open('CampiGestione'+paramurl,'ZEROgis_Online_Campi',param);
        if (!campiwindow.opener) campiwindow.opener = self;
    }
    if (window.focus) {
        campiwindow.focus()
        }
    return false;    
}

//********************Popup per la gestione del calendario attività*******************//
var calendariowindow = '';
function popupcalendario(paramurl){
    if (paramurl==null)paramurl='';
    if (!calendariowindow.closed && calendariowindow.location) {
        calendariowindow.location.href = url;
    }else {
        param = 'left=0,top=0,width='+(screen.width-8)+',height='+(screen.height-55);
        calendariowindow=window.open('ActAttivitaCalendario'+paramurl,'ZEROgis_Online_Calend',param);
        if (!calendariowindow.opener) calendariowindow.opener = self;
    }
    if (window.focus) {
        calendariowindow.focus()
        }
    return false;
}

//********************Popup per la gestione dei pma*******************//
var pmawindow = '';
function popuppma(paramurl){
    if (paramurl==null)paramurl='';
    if (!pmawindow .closed && pmawindow.location) {
        pmawindow.location.href = url;
    }else {
        param = 'left=0,top=0,width='+(screen.width-8)+',height='+(screen.height-55);
        pmawindow=window.open('PmaGestione'+paramurl,'ZEROgis_Online_Pma',param);
        if (!pmawindow.opener) pmawindow.opener = self;
    }
    if (window.focus) {
        pmawindow.focus()
        }
    return false;
}

// Questa istruzione per IE deve essere messa in fondo alla pagina, o almeno dopo il tag body
function getWidthW(){
    return (typeof window.innerWidth == 'undefined')?document.body.clientWidth:window.innerWidth;
}
function getHeightW(){
    return (typeof window.innerHeight == 'undefined')?document.body.clientHeight:window.innerHeight;
}

function changeWindowSize(gapw,gaph){
    window.resizeTo(gapw,gaph);
}

/*
 *pos = TL TC TR
 *      ML MC MR
 *      BL BC BR
 *
 * T = TOP - M = MIDDLE - B = BOTTOM
 * L = LEFT - C = CENTER - R = RIGHT
 *
 **/
function changeWindowPosition(pos,gapw,gaph){
    posh = (pos+"").substring(0, 1);
    posw = (pos+"").substring(1);

    if (posw=='L') w = 0;
    if (posw=='C') w = (screen.width/2) - (gapw/2);
    if (posw=='R') w = (screen.width-8) - gapw;

    if (posh == 'T') h = 0;
    if (posh == 'M') h = (screen.height/2) - (gaph/2);
    if (posh == 'B') h = (screen.height-8) - gaph;

    window.moveTo(w, h);
}

function addOption(selectbox,text,value ){
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

function remOptions(selectbox) {
    var i;
    for(i=selectbox.options.length-1;i>=0;i--) {
        if(selectbox.options[i].selected) selectbox.remove(i);
    }
}

/*
Senza il secondo parametro, la funzione fa il trim di questi caratteri
    * " " (ASCII 32 (0x20)), an ordinary space.
    * "\t" (ASCII 9 (0x09)), a tab.
    * "\n" (ASCII 10 (0x0A)), a new line (line feed).
    * "\r" (ASCII 13 (0x0D)), a carriage return.
    * "\0" (ASCII 0 (0x00)), the NUL-byte.
    * "\x0B" (ASCII 11 (0x0B)), a vertical tab.
*/
function trimz(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function AddSlashToApici(strr){
    strr = strr.replace("\'","\\\'");
    return strr;
}

var smsWindow = '';
function SendSMS(codicert, nome, numero) {
    hScr = screen.height;
    wScr = screen.width;
    lWnd = (wScr - 400) /2;
    tWnd = (hScr - 300) /2;
    param = 'left=' + lWnd + ',top=' + tWnd + ',width=400,height=300';
    param = param + 'screenX=10,screenY=10,directories=no,location=no,menubar=no,resizable=no,status=no,toolbar=no';



    if (smsWindow!='' && !smsWindow.closed) {
        alert('LA FINESTRA DI INVIO SMS E\' GIA\' APERTA.');
        if (window.focus) smsWindow.focus();
    }else {
        smsWindow=window.open('SendSMS?codicert=' + codicert + '&nome=' + AddSlashToApici(nome) + '&numero=' + numero,'ZEROgis_Online_SendSMS',param);
    }
    if (window.focus) {
        smsWindow.focus()
        }
    return false;
}

function LPad(ContentToSize, PadLength, PadChar) {
    var PaddedString = ContentToSize.toString();
    var LenString = PaddedString.length;

    for(i = LenString + 1; i <= PadLength; i++) {
        PaddedString = PadChar + PaddedString;
    }
    return PaddedString;
}

/**
 * restituisce la data corrente
 * @param ora       se True, restituisce anche ora e minuti correnti
 * @param numFormat se True, restituisce invece che la data in formato "gg/mm/aaaa hh:nn", la data in formato "aaaammgg.hhnn"
 *
 * @return  Una stringa contenente la data corrente, con la formattazione in base ai parametri
 */
function getDataCorrente(ora, numFormat) {
    var data = new Date();
    var gio, mes, ann;
    var Hh, Mm;
    var retDate;
    gio = LPad(data.getDate(), 2, '0');
    mes = LPad(data.getMonth() + 1, 2, '0');
    ann = data.getFullYear();

    retDate = gio  + '/' + mes + '/' + ann;

    if (ora) {
        Hh = LPad(data.getHours(), 2, '0');
        Mm = LPad(data.getMinutes(), 2, '0');
        retDate += ' ' + Hh + ':' + Mm;
    }

    if (numFormat) {
        retDate = ann + mes + gio;

        if (ora) {
            retDate += '.' + Hh + Mm;
        }
    }

    return retDate;
}

function getPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x) {
        curleft += obj.x;
    }

    //  alert(curleft);
    return curleft;
}

function getPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y) {
        curtop += obj.y;
    }

    //  alert(curtop);
    return curtop;
}

/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

/**
 * Muove il Focus da un campo ad un altro. va utilizzato normalmente all'interno del campo Ora per passare al Minuto, così:  onkeyup="spostaTab(this, 2, 'campominuto');"
 * @param myField   Il campo di partenza
 * @param numChars  Il numero di caratteri dopo i quali il focus si sposta
 * @param nextField Il nome del campo di destinazione
 */
function spostaTab(myField, numChars, nextField) {
    if (myField.value.length == numChars) {
        document.getElementById(nextField).focus();
        document.getElementById(nextField).select();
    }
}

function getTickCount() {
    var now = new Date();
    var ticks = now.getTime();
    return ticks;
}

var pannelloWindow = '';
function popupPannello(paramurl){
    if (paramurl==null)paramurl='';
    if (!pannelloWindow.closed && pannelloWindow.location) {
        pannelloWindow.location.href = url;
    }else {
        param = 'left=0,top=0,width='+(screen.width-8)+',height='+(screen.height-55);
        if (paramurl == '') paramurl = '?w='+(screen.width-8)+'&h='+(screen.height-55);
        pannelloWindow=window.open('PannelloSegnalazioni'+paramurl,'ZEROgis_Online_Pannello',param);
        if (!pannelloWindow.opener) pannelloWindow.opener = self;
    }
    if (window.focus) {
        pannelloWindow.focus();
    }
    return false;
}

var diarioSalaWindow = '';
function popupDiarioSala(paramUrl){
    var deltaW = 8;
    var deltaH = 55;

    if (detectionBrowserType() != 'E') {
        deltaW = 12;
        deltaH = 60;
    } else if (detectionBrowserType() == 'E') {
        deltaH = 30;
    }

    if (paramUrl == null) paramUrl = '';
    if (!diarioSalaWindow.closed && diarioSalaWindow.location) {
        diarioSalaWindow.location.href = url;
    }else {
        param = 'left=0,top=0,width=' + (screen.width - deltaW) + ',height=' + (screen.height - deltaH);
        if (paramUrl == '') paramUrl = '&w=' + (screen.width - deltaW) + '&h='+(screen.height - deltaH);
        diarioSalaWindow = window.open('DiarioSala?standalone=S&p=NEW'+paramUrl,'ZEROgis_Online_DiarioSala',param);
        if (!diarioSalaWindow.opener) diarioSalaWindow.opener = self;
    }
    if (window.focus) diarioSalaWindow.focus();
    return false;
}



function formatNumero(numero, decimali) {
    numToFormat = parseFloat(numero).toFixed(decimali);
    retValue =  String(numToFormat).replace('.', ',');
    return retValue;
}

function isNumeric(sNumero) {
    var ValidChars = '0123456789.';
    var isNumero = true;
    var charCode;

    for (i = 0; i < sNumero.length && isNumero == true; i++) {
        charCode = sNumero.charAt(i);
        if (ValidChars.indexOf(charCode) == -1) isNumero = false;
    }

    return isNumero;
}

/**
 * Inibisce la pressione dell'invio. Uso: onkeypress="return checkNoEnter(event);"
 * @param e l'event
 * @return  False se è invio, True altrimenti
 */
function checkNoEnter(e) {
    if (window.event) key = window.event.keyCode;
    else if (e) key = e.which;
    else return true;

    if (key == 13) {
        return false;
    } else {
        return true;
    }

}

function parseDate(dataIn) {
    var gg = '' + dataIn.getDate();
    if (gg.length == 1) gg = '0' + gg;
    var mm = '' + (dataIn.getMonth() + 1);
    if (mm.length == 1) mm = '0' + mm;
    var yyyy = dataIn.getFullYear();
    return gg + '/' + mm + '/' + yyyy;
}

function parseTime(dataIn) {
    var hh = '' + dataIn.getHours();
    if (hh.length == 1) hh = '0' + hh;
    var mm = '' + dataIn.getMinutes();
    if (mm.length == 1) mm = '0' + mm;
    return hh + ':' + mm;
}

function parseStringToDate(dataIn) {
    var gg = dataIn.substr(0, 2);
    var mm = dataIn.substr(3, 2);
    var aaaa = dataIn.substr(6, 4);
    if (gg.substr(0, 1) == '0') gg = gg.substr(1);
    if (mm.substr(0, 1) == '0') mm = mm.substr(1);
    return new Date(aaaa, parseInt(mm) - 1, parseInt(gg), 0, 0, 0);
}

function parseStringToDateTime(dataIn) {
    var gg = dataIn.substr(0, 2);
    if (gg.substr(0,1) == '0')
        gg = gg.substr(1);
    var ggI = parseInt(gg);

    var mm = dataIn.substr(3, 2);
    if (mm.substr(0,1) == '0')
        mm = mm.substr(1);
    var mmI = parseInt(mm);
    var aaaa = dataIn.substr(6, 4);

    var hh = dataIn.substr(11, 2);
    if (hh.substr(0,1) == '0')
        hh = hh.substr(1);
    var hhI = parseInt(hh);

    var nn = dataIn.substr(14, 2);
    if (nn.substr(0,1) == '0')
        nn = nn.substr(1);
    var nnI = parseInt(nn);
    
    var dataOut = new Date(aaaa, mmI - 1, ggI, hhI, nnI, 0, 0);
    return dataOut;
}

function addDateDay(dataIn, days) {
    dataMod = new Date(dataIn.getFullYear(), dataIn.getMonth(), dataIn.getDate(), 0,0,0);
    dataMod.setDate(dataMod.getDate() + days);
    return dataMod;
}
