/*function selectDefaultValue(){
    for (var i = 0; i < this.length; i++) {
        if (this.options[i].defaultSelected == true) {
                 return this.options[i].value;
        }
      }

}


Object.Select.prototype.defaultValue=selectDefaultValue;*/

function contaElement(obj,elemento){
    var n=obj.childNodes.length;
    var conta=0;
    var xul;
//alert(obj.id);
    for (var i=0;i<n;i++){
        xul=obj.childNodes[i]; // estraggo gli elementi del fieldset
        if (xul.nodeName==elemento){
            //04-05-2011 conto solo se è previsto come checkcode
            //conta+=parseInt(xul.innerHTML,10);
            if(xul.className=="checkCode"){           
                conta+=parseInt(xul.innerHTML,10);
            }
        }else if (xul.nodeName!='#text'){
            conta+=contaElement(xul,elemento);
        }
    }
    return conta;
}



function contaInput(obj){
    var n=obj.childNodes.length;
    var conta=0;
    var xul;
    for (var i=0;i<n;i++){
        xul=obj.childNodes[i]; // estraggo gli elementi del fieldset
        if (xul.nodeName=='INPUT'){
            conta+=parseInt(xul.value,10);
        }else if (xul.nodeName!='#text'){
            conta+=contaInput(xul);
        }
    }
    return conta;
}

function calcolaTotale_e_Quadrature(obj){
    var xfld=obj.parentNode.parentNode;
    var xdiv=tornaElementoPerTag(xfld,'DIV', -1);
    //alert(xdiv);
    var xspan=tornaElementoPerTag(xdiv,'SPAN', 1);
    var xstrong=tornaElementoPerTag(xdiv,'STRONG', 1);    
    xdiv=tornaElementoPerTag(obj.parentNode,'SPAN',1);
    /** 29-04-2011 non moltiplichiamo più per 1000 e non si aggiunge più il numero di posizione
     * il nuovo metodo prevede che si valorizzi, solo per le caselle preposte il checkcode = num voti presi
    xdiv.innerHTML=parseInt(obj.value,10)+1000*parseInt(obj.id.substr(1,2),10);
    ****/    
    if(xdiv.className=="checkCode")
    {
        xdiv.innerHTML=parseInt(obj.value,10)
    }
    xspan.innerHTML=0;
    xstrong.innerHTML=contaInput(xfld);
    xspan.innerHTML=contaElement(xfld,'SPAN');

}

function calcolaTotalePreferenze(obj){

    var objTBody=obj.parentNode.parentNode.parentNode; // va a beccare il tbody
    var objTotRiga = objTBody.lastChild.previousSibling.firstChild; // la riga del risultato

    var objTotRigaCk = objTBody.lastChild.previousSibling.cells[1]; // la riga del risultato
    
    // sommatoria dei valori
    var totale = 0;
    var nRiga=0;
    var totaleCheck = 0;
    for (nRiga=0; nRiga<objTBody.rows.length - 1; nRiga++) {        
        objInput = objTBody.rows[nRiga];
        objInput2 = objInput.cells[4].childNodes[1];
        totale += parseInt(objInput2.value,10);
        //calcolo il codice di controllo (somma numero voti di preferenza al numero candidato)
        if(parseInt(objInput2.value,10)>0){
            var objInputCk1 = objInput.cells[2];        
            var objInputCk2 = objInput.cells[4].childNodes[1];
            var totaleCk = parseInt(objInputCk1.innerHTML,10) + parseInt(objInputCk2.value,10);                    
            var objTotCheck=objTBody.rows[nRiga].cells[5];
            objTotCheck.innerHTML=totaleCk;
            totaleCheck += totaleCk;        
        }
        else{
            var objTotCheck=objTBody.rows[nRiga].cells[5];
            objTotCheck.innerHTML="0";
        }
        //----------------------- fine calcolo codice di controllo        
    }
    objTotRiga.innerHTML = totale;
    //calcola il totale generale del riquadro
    objTotRigaCk.innerHTML=totaleCheck;
    calcolaTotaleVotiPreferenze();
}

function calcolaTotaleVotiPreferenze(){
	
	var objFieldset= document.getElementById("preferenze");

	var totale=0;
	for (var nTabella=0; nTabella<objFieldset.children.length; nTabella++) {
		if ( objFieldset.children[nTabella].attributes["class"].value == "dati" ) {
			var objTBody = objFieldset.children[nTabella].children[2];
			var nRiga=0;
			for (nRiga=0; nRiga<objTBody.rows.length - 1; nRiga++) {
				var objInput = objTBody.rows[nRiga];
				var objInput2 = objInput.cells[4].childNodes[1];
				totale += parseInt(objInput2.value,10);
			}
		}
	}
	document.getElementById("totaleTotalizzatore").textContent = totale;
}

/*function calcolaTotaleA(obj) {
    var tot=contaInput(obj);
    totaleA=document.getElementById('totaleA');

    tornaElementoPerTag(oggetto,tag, o,attivaRicorsione=false,contatore=0){


    totaleA.innerHTML= '<label>Totale Voti (A)</label> &nbsp;<strong>' + tot +'</strong>';
}

function calcolaTotaleF(obj) {
    var tot=contaInput(obj);
    totaleF=document.getElementById('totaleF');
    totaleF.innerHTML= 'Totale Voti (F) &nbsp;<strong>' + tot +'</strong>';
}
*/

function checkAllCheckbox(f){
    var i,l;
  f=f.form;
  l=f.elements.length;
    for (i=0;i<l;i++){
         if (f.elements[i].type=="checkbox"){
            if(f.elements[i].checked==true)
                 f.elements[i].checked=false;
            else
                f.elements[i].checked=true;
         }
    }
}


function ControllaCampi(obj,referendum){
    //alert(obj.name);

    // default value=0
    if (typeof(referendum)=='undefined'){
        referendum=false;
    }else{
        referendum=true;
    }    
       
    for (var i = 0; i < obj.stato.length; i++) {
        if (obj.stato.options[i].defaultSelected == true) {
                 statoDefault=obj.stato.options[i].value;
        }
      }

//alert (obj.stato.defaultValue()+' '+statoDefault + ' ' + obj.stato.value + ' '+ obj.stato.selectedIndex);

    if(statoDefault == 0){ alert('SEZIONE NON DISPONIBILE'); return false; }
    // stato =0 e a 1
    if(parseInt(obj.stato.value,10) < 2){ alert('SEZIONE BLOCCATA !!! Modificare lo Stato per proseguire.'); return false; }

    //controllo default
    i=statoDefault - obj.stato.value;

    if((i>1)||(i<-1)){alert('Impossibile saltare gli stati '+i); return false; }

    // stato = 2
    if(parseInt(obj.stato.value,10) >= 2){
        if(parseInt(obj.ad_totali.value,10) != 0 && obj.speciale.checked==false){
            if(parseInt(obj.votantiMaschi.value,10) > parseInt(obj.ad_maschi.value,10)){
                alert('ATTENZIONE !!! Il numero dei Votanti Maschi è superiore a quello degli Aventi Diritto !!!');
                return false;
            }
            if(parseInt(obj.votantiFemmine.value,10) > parseInt(obj.ad_femmine.value,10)){
                alert('ATTENZIONE !!! Il numero dei Votanti Femmine è superiore a quello degli Aventi Diritto !!!');
                return false;
            }
        }
        var tot= parseInt(obj.votantiMaschi.value,10) + parseInt(obj.votantiFemmine.value,10);
        if(tot != parseInt(obj.votantiTotali.value,10)){
            alert('ATTENZIONE !!! Il numero dei Votanti totali non corrisponde alla somma  maschi totali + femmine totali !!!');
            return false;
        }

    }

    // stato = 3
// parseInt(obj.contestati.value,10) +
    if(obj.stato.value >= 3){
        var SommaVoti = parseInt(obj.contestati.value,10) + parseInt(obj.validi.value,10) + parseInt(obj.nulli.value,10) + parseInt(obj.bianchi.value,10) ;
        /*if(SommaVoti == 0){  */
            /*alert('ATTENZIONE !!! com\'è che non ci sono schede????  !!!'); */
            /*return confirm('ATTENZIONE !!! non ci sono schede: proseguo ugualmente?');*/
            /*return false;  */
        /*}else*/ if(tot!=SommaVoti){
            alert('ATTENZIONE !!! La somma delle schede Valide, Nulle, Bianche, Contestate è diversa dai Votanti!');
            return false;
        }
        /*SommaVoti = parseInt(obj.validi.value,10) - parseInt(obj.contestati.value,10);
        if (SommaVoti<0){
            alert('ATTENZIONE !!! I voti contestati devono essere minori dei voti Validi!');
            return false;
        }*/
        if (referendum){
            SommaVoti = parseInt(obj.validi.value,10)- (parseInt(obj.si.value,10) + parseInt(obj.no.value,10));
            if (SommaVoti!=0){
                /*alert('ATTENZIONE !!! I voti Validi devono essere uguali alla somma di opzione1 (sì) e opzione2 (no)! '+ SommaVoti);*/
                alert('ATTENZIONE !!! I voti Validi devono essere uguali alla somma di opzione1 (B) e opzione2 (C)! '+ SommaVoti);
                return false;
            }
        }
        var SommaVotiPresidenti= 0;
        var SommaVotiLista= 0;

        var fldset=document.getElementById('votiPresidente');
        if (fldset){ //Se non ci sono va tutto bene
            SommaVotiPresidenti=contaInput(fldset);
            if(SommaVotiPresidenti != parseInt(obj.validi.value,10)){
                alert('ATTENZIONE !!! Il totale dei voti per il presidente sono diversi dai voti validi  !!!');
                return false;
            }
        }

        fldset=document.getElementById('votiLista');
        if (fldset){ //Se non ci sono va tutto bene
            SommaVotiLista=contaInput(fldset);

/*		n=fldset.childNodes.length;
        for (i=0;i<n;i++){
            xul=fldset.childNodes[i]; // estraggo gli elementi del fieldset
            if (xul.nodeName=='INPUT'){
                SommaVotiLista=SommaVotiLista+xul.value;
            }
        }*/
            var somma = SommaVotiLista + parseInt(obj.soloPresidente.value,10);
            if(somma != parseInt(obj.validi.value,10)){  alert('ATTENZIONE !!! I voti di lista piu quelli per il solo presidente sono diversi dai voti validi  !!!'); return false; }
        }
    }
return true;
}








/*
function controllaCampi(f) {
//    alert ('Inizio il controllo');

    with (f) {
    listaOggettiPericolosi = new Array(ELETTORIF, ELETTORIM, VOTANTIM, VOTANTIF,
                                       VOTANTIT, SI, NO, VALIDI, NONVALIDI,
                                       BIANCHE, CONTESTATE, NULLE);
    }

    //return true;
    valida = true;


    for ( nogg in listaOggettiPericolosi ) {
        if ( listaOggettiPericolosi[nogg].value.indexOf (".") != -1 ) {
           alert (listaOggettiPericolosi[nogg].name + ' contiene un puntino');
           valida = false;
           }
        if ( isNaN (listaOggettiPericolosi[nogg].value) ) {
           alert (listaOggettiPericolosi[nogg].name + ' contiene parti non numeriche');
           valida = false;
           }
        }

    with (f) { */
    // cerca la presenza di PUNTINI

      /*
        if ( isNaN (ELETTORIM.value) || isNaN (ELETTORIF.value)
           || isNaN (VOTANTIM.value) || isNaN (VOTANTIF.value) || isNaN (VOTANTIT.value)
           || isNaN (SI.value) || isNaN (NO.value) || isNaN (VALIDI.value)
           || isNaN (NONVALIDI.value) || isNaN (BIANCHE.value)
           || isNaN (CONTESTATE.value) || isNaN (NULLE.value) ) {
             alert ( 'Errore semantico. Trovate parti non numeriche.' );
             valida = false;
         }
        */
        /*
        if ((parseInt(ELETTORIM.value) < VOTANTIM.value)
         && ( parseInt(ELETTORIM.value) != 0 ) && ( parseInt(ELETTORIF.value) != 0 ) ) {
            alert ( 'Numero di votanti maschi maggiore del numero di elettori' );
            valida = false;
        }
        if ((parseInt(ELETTORIF.value) < VOTANTIF.value ) &&
         ( parseInt(ELETTORIM.value) != 0 ) && ( parseInt(ELETTORIF.value) != 0 ) ) {
            alert ( 'Numero di votanti femmine maggiore del numero di elettrici' );
            valida = false;
        }
        if ( parseInt(VOTANTIM.value) + parseInt(VOTANTIF.value) != VOTANTIT.value ) {
            alert ( 'Numero di votanti non valido' );
            valida = false;
        }
        if ( STATO.value == "3" ) {
          if ( parseInt(SI.value) + parseInt(NO.value) != VALIDI.value ) {
            alert ( 'Numero di Si + i No non corrispondente al numero di Validi' );
            valida = false;
        }
          if ( parseInt(BIANCHE.value) + parseInt(CONTESTATE.value) + parseInt(NULLE.value) != NONVALIDI.value ) {
            alert ( 'Errore nella somma di voti non validi (bianche + contestate + nulle)' );
            valida = false;
        }
          if ( parseInt(VALIDI.value) + parseInt(BIANCHE.value)+
               parseInt(CONTESTATE.value) + parseInt(NULLE.value) != VOTANTIT.value ) {
            alert ( 'Somma di votanti non uguale a Validi + Bianche + Contestate + Nulle' );
            valida = false;
          }
        }
    }
     return valida;
}
*/
