﻿// JScript File


//////////////////////////////////////////////////
//      FUNZIONI DI CONTROLLO E VERIFICA        //
//////////////////////////////////////////////////

// Funzione per la verifica dell'Obbligatorietà dei campi
function VerificaObbligatorieta(strNomeDiv) {

    var errors=false;
    var hdEl = document.getElementById('hd' + strNomeDiv + 'Obb'); // Recupero la stringa nascosta con la definizione dei campi
    
    if (hdEl) {
        var elsToCheck = hdEl.value.split(','); // Matrice di definizione dei controlli
        
        for (j in elsToCheck) {
            var inputEl = document.getElementById(elsToCheck[j].split(':')[0]); // Singolo elemento
            
            if (inputEl) {
                if (inputEl.value=="") {/* Se l'elemento è vuoto */
		            inputEl.className+=' ErroreCampi';        /* Inserisco la classe CSS dell'errore */
		            errors=true;
	            } else {
	                inputEl.className = inputEl.className.split(' ')[0]; // Ripristino la classe iniziale
	            }
            }
        }
    }
    return errors;
}

// Funzione per la verifica del formato dei campi
function VerificaFormato(strNomeDiv) {

    var blnMail = false;
    var blnPriv = false;
    var blnDate = false;
    var blnUso = false;
    var strErr = '';
    var hdEl = document.getElementById('hd' + strNomeDiv + 'Obb'); // Recupero la stringa nascosta con la definizione dei campi
    
    if (hdEl) {
        var elsToCheck = hdEl.value.split(','); // Matrice di definizione dei controlli
        
        for (j in elsToCheck) {
            var inputEl = document.getElementById(elsToCheck[j].split(':')[0]); // Singolo elemento
            var defEl = elsToCheck[j].split(':')[1];
            
            switch (defEl) {
            
                case 'E': // controllo E-Mail
                    if (!chkMail(inputEl.value)) {
                        inputEl.className+=' ErroreCampi';        /* Inserisco la classe CSS dell'errore */
                        blnMail = true;
                    } else {
                        inputEl.className = inputEl.className.split(' ')[0]; // Ripristino la classe iniziale
                    }
                    
                break;
                
                case 'P': //Controllo Radiobutton privacy
                    if (!inputEl.checked) { blnPriv = true }
                    
                break;
                
                case 'D': // Controllo date
                    if (!Page_ClientValidate('MKE')) { 
                        inputEl.className+=' ErroreCampi';        /* Inserisco la classe CSS dell'errore */
                        blnDate = true;
                    } else {
                        inputEl.className = inputEl.className.split(' ')[0]; // Ripristino la classe iniziale
                    }
                break;
                
                case 'U':
                    if (!inputEl.checked) { blnUso = true }
                    
                break;
            
            }
        }
        
        if (blnMail) { strErr += ' - L\'E-Mail inserita non risulta valida. <br /> ' }
        if (blnUso) { strErr += ' - Per proseguire devi accettare i termini d\'uso del servizio. <br />' }
        if (blnPriv) { strErr += ' - Per proseguire devi acconsentire al trattamento dei dati personali' }
        if (blnDate) { strErr += ' - Le date inserite non sono valide' }
    }
    
    return strErr;
}

// funzione per la verifica della e-mail lato client
function chkMail(email) {
    if (window.RegExp) {
        
        var nonvalido = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
        var valido = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
        var regnv = new RegExp(nonvalido);
        var regv = new RegExp(valido);
        
        if (!regnv.test(email) && regv.test(email))
            return true;
        return false;
        
    } else {
    
    if(email.indexOf("@") >= 0)
        return true;
    return false;
    
    }
}
/************************************************/
/*    FINE FUNZIONI DI CONTROLLO E VERIFICA     */
/************************************************/

// funzione che verifica la correttezza dei dati e passa alla schermata successiva
function chkForm(currEl) {

    var errors = false;
    var blnObb = VerificaObbligatorieta(currEl); //verifica il completamento dei campi obbligatori
    var strFor = VerificaFormato(currEl); // verifica il formato di campi specifici (e-mail, date etc...)
    var ErrDescr = '';
    var NextEl = '';
    
    if (blnObb) { // se qualche campo obbligatorio non è stato completato inserisco un errore
        ErrDescr = '  - Compilare i campi contrassegnati dall\'asterisco (*)';
        errors=true;
    }
    
    if (strFor != '') {
        if (ErrDescr != '') { ErrDescr += ' <br /> ' }
        ErrDescr += strFor;
        errors=true;
    }
    
    
    switch (currEl) { // seleziono in base all'elemento corrente
    
        case 'Dati': //siamo nella prima schermata
            NextEl = 'Evento';

        break;
        
        case 'Evento': //seconda schermata
            
            NextEl = 'Stile';
            
            // controllo le date inserite
            if (Page_ClientValidate('MKE')) { //controllo di confronto delle date
                var strData = document.getElementById('txtData').value;
                var strScad = document.getElementById('txtScadenza').value;
                var isoData = strData.substr(6,4) + strData.substr(3,2) + strData.substr(0,2);
                var isoScad = strScad.substr(6,4) + strScad.substr(3,2) + strScad.substr(0,2);
                
                if (parseInt(isoScad) < parseInt(isoData)) { //la data di scadenza non può essere anteriore alla data dell'evento
                    if (ErrDescr != '') { ErrDescr += ' <br /> ' }
                    ErrDescr += ' - La data di scadenza non può essere antecedente alla data dell\'evento';
                    errors = true;
                }
            }
            ///////////////////////////////////////////
            
            // controllo che sia impostato un tipo di evento
            var ElTipo = document.getElementById('ddlTipo');
            var ElAltro = document.getElementById('txtTipoAltro');
            
            if (ElTipo.value == 100 && ElAltro.value == '') {
                if (ErrDescr) { ErrDescr += ' <br /> ' }
                ErrDescr += '  - Selezionando \'Altro\' è necessario specificare il tipo di evento';
                ElAltro.className += ' ErroreCampi';
            } else {
                ElAltro.className = ElAltro.className.split(' ')[0];
            }
            ///////////////////////////////////////////
            
            // Per passare al terzo blocco controllo se ci sono gia immagini in upload
            // in caso affermativo carico l'immagine tra la selezione delle immagini
            if (!errors) { ckPrecaricata() }
            ////////////////////////////////

        break;

    }
    
    if (!errors) { //se non ci sono errori
        
        if (currEl=='Dati') { document.getElementById('TestoInizio').style.display='none' }
        
        // resetto i controllo dell'errore
        var elDescr = document.getElementById('Err' + currEl + 'Descr');
        elDescr.innerHTML = '';
        ////////////////////////////////
        
        Naviga(currEl, NextEl); // passo alla schermata successiva

    } else {
        var elDescr = document.getElementById('Err' + currEl + 'Descr');
        elDescr.innerHTML = ErrDescr; //messaggio di errore
    }

}

// funzione che permette la creazione della pagina di Preview
function CreaPreview(strState) {

    // imposto il colore di background
    for(var i = 0;i < document.getElementsByName('BGC').length;i++) {
        if (document.getElementsByName('BGC')[i].checked) {
            document.getElementById('gabbia-evento').style.backgroundColor = document.getElementsByName('BGC')[i].value;
        }
    }
    //////////////////////////////////
    
    // inserisco l'icona in base al tipo di evento selezionato
    // l'immagine dell'icona viene caricata dinamicamente in un input hidden
    document.getElementById('IcoTipo').attributes['src'].value = document.getElementById('hdImgTipo').value;                
    document.getElementById('Titolo').innerHTML = document.getElementById('txtTitolo').value; //imposto il titolo
    
    var strMess = document.getElementById('txtMessaggio').value;
    var oldChar = '\n';
    var newChar = '<br />';
    
    while (strMess.indexOf(oldChar) > -1) {
        PosReplace = strMess.indexOf(oldChar);
        strMess = "" + (strMess.substring(0, PosReplace) + newChar + strMess.substring((PosReplace + oldChar.length), strMess.length));
    }

    document.getElementById('Messaggio').innerHTML = strMess; //imposto il messaggio
    
    /*if (strState == 'Mod') {
        ModLoadImg();
    } else {
        CreaLoadImg();
    }*/
    
    if (document.getElementById('ckTotale').checked) {
        document.getElementById('cDonazioni').style.display = 'block';
    } else {
        document.getElementById('cDonazioni').style.display = 'none';
    }
    
    if (document.getElementById('ckNomi').checked) {
        document.getElementById('cNomi').style.display = 'block';
    } else {
        document.getElementById('cNomi').style.display = 'none';
    }
    
    if (document.getElementById('ckMessaggi').checked) {
        document.getElementById('cMessaggi').style.display = 'block';
    } else {
        document.getElementById('cMessaggi').style.display = 'none';
    }
    
}


//function CreaLoadImg() {

//// se non c'è gia un file in upload carico l'immagine precaricata selezionata
//    // altrimenti carico il file in upload
//    var hdEl = document.getElementById('hdFileExist');
//    if (hdEl && hdEl.value == '') {

//        for(var i = 0;i < document.getElementsByName('IMG').length;i++) {
//            if (document.getElementsByName('IMG')[i].checked) {
//                document.getElementById('Immagine').attributes['src'].value = document.getElementsByName('IMG')[i].value;
//            }
//        }
//           
//    } else {
//        document.getElementById('Immagine').attributes['src'].value = hdEl.value;
//    }
//    ///////////////////////////////////////
//    
//}

//function ModLoadImg() {

//    // se non c'è gia un file in upload carico l'immagine precaricata selezionata
//    // altrimenti carico il file in upload
//    var hdEl = document.getElementById('hdFileExist');
//    if (hdEl && hdEl.value == '') {
//    
//        var hdOldEl = document.getElementById('hdOldFile');
//        if (hdOldEl && hdOldEl.value == '') {
//        
//            for(var i = 0;i < document.getElementsByName('IMG').length;i++) {
//                if (document.getElementsByName('IMG')[i].checked) {
//                    document.getElementById('Immagine').attributes['src'].value = document.getElementsByName('IMG')[i].value;
//                }
//            }
//            
//        } else {
//            document.getElementById('Immagine').attributes['src'].value = hdOldEl.value;
//        } 
//           
//    } else {
//        document.getElementById('Immagine').attributes['src'].value = hdEl.value;
//    }
//    ///////////////////////////////////////

//}


// funzione per la navigazione tra le schermate
// CurrEl: schermata corrente
// NextEl: schermata di destinazione
function Naviga (CurrEl, NextEl) {

    var elTI = document.getElementById('TestoInizio');
    
    if (elTI) {
        if (NextEl == 'Dati') { 
            elTI.style.display='block';
        } else {
            elTI.style.display='none';
        }
    }
    
    var iCurr = getImgIndex(CurrEl); // recupero l'indice della schermata corrente
    var iNext = getImgIndex(NextEl); // recupero l'indice della schermata di destinazione
    
    // cambio la schermata e l'immagine di TabStrip
    document.getElementById(CurrEl).style.display = 'none';
    document.getElementById(NextEl).style.display = 'block';
    
    var elIMG = document.getElementById('img' + iCurr);
    
    if (elIMG) {
        elIMG.attributes['src'].value = '/img/' + iCurr + '-off.gif';
        document.getElementById('img' + iNext).attributes['src'].value = '/img/' + iNext + '-on.gif';
    }
    ////////////////////////////////////////////
    
    // se ritorno da un Preview controllo che non sia gia caricato un file in upload
    if (CurrEl == 'Preview' && NextEl == 'Stile') {
        ckPrecaricata();
    }
    ////////////////
    
    return false;
}

// funzione che recupera l'indice della pagina passata
function getImgIndex(CurrEl) {
    
    switch (CurrEl) {
    
        case 'Dati':
            return '1';
        break;
        
        case 'Evento':
            return '2';
        break;
        
        case 'Stile':
            return '3';
        break;
        
        case 'Preview':
            return '4';
        break;
    
    }
    
}

// funzione che controlla se c'è gia un file un upload
// in caso affermativo visualizza il file nella schermata 'Stile' e imposta i controlli associati
function ckPrecaricata()  {
    
    var hdEl = document.getElementById('hdFileExist');
    if (hdEl && hdEl.value != '') {
        var imgEl = document.getElementById('imgPre').attributes['src'].value = hdEl.value;
        document.getElementById('divCaricata').style.display = 'block';
        document.getElementById('rbImgPre').checked = true;
        document.getElementById('rbImgPre').value = hdEl.value;
    }
    
}

function ckModImg (ckEl) {
    if (ckEl.id == 'rbImgPre') {
        var srcUp = document.getElementById('imgPre').attributes['src'].value;
        var matUp = srcUp.split('/');
        document.getElementById('hdOldFile').value = '/' + matUp[(matUp.length-3)] + '/' + matUp[(matUp.length-2)] + '/' + matUp[(matUp.length-1)];  
    } else {
        document.getElementById('hdOldFile').value = '';
    }
}