function ShowHide(div,speed){
	$(div).animate({"height": "toggle"}, { duration: speed });
}

function apri_chiudi(liv) {
       obj = document.getElementById(liv) 
       obj.style.visibility=='visible'?obj.style.visibility='hidden':obj.style.visibility='visible'
}

function aprineuno_chiudialtro(liv1,liv2) {
       apri_chiudi(liv1)
       obj2 = document.getElementById(liv2) 
       if (obj2.style.visibility=='visible') obj2.style.visibility='hidden'
}

function aprineuno_chiudinedue(liv1,liv2,liv3) {
       apri_chiudi(liv1)
       obj2 = document.getElementById(liv2) 
       if (obj2.style.visibility=='visible') obj2.style.visibility='hidden'
       obj3 = document.getElementById(liv3) 
       if (obj3.style.visibility=='visible') obj3.style.visibility='hidden'
}


function delDefaultValue(elem) {	
	elemChange = document.getElementById(elem);	
		if (elemChange.value == elemChange.defaultValue) {		
			elemChange.value='';	
		}	
	//elemChange.style.color = '#000';
}

function checkEmptyValue(elem) {	
	elemChange = document.getElementById(elem);	
		if (elemChange.value == '') {		
			//elemChange.style.color = '#000';
			elemChange.value = elemChange.defaultValue;	
		}
}

function submitenter(myfield,e)
    {
        var keycode;
        if (window.event) keycode = window.event.keyCode;
        else if (e) keycode = e.which;
        else return true;

        if (keycode == 13)
        {
            myfield.form.submit();
            return false;
        }
        else
            return true;
    }
	

function altezza(iddiv) {	
	var yScroll;
	if (window.innerHeight && window.scrollMaxY) {
	    yScroll = window.innerHeight + window.scrollMaxY;
	}else if (document.body.scrollHeight > document.body.offsetHeight){
	    yScroll = document.body.scrollHeight;
	}else{
	    yScroll = document.body.offsetHeight;
	}
	var fade = document.getElementById(iddiv);
	fade.style.height = yScroll+"px"
}

function VerificaAltezzaFormazioni() {	
	if (document.getElementById('formazione_Casa')) { 	
		
		if (document.getElementById('panchina_Casa')) {
		var Div1Height = document.getElementById('panchina_Casa').offsetHeight;
		} else {
		var Div1Height = 0;
		}
		var Div2Height = document.getElementById('logo_Casa').offsetHeight;
		var DivFormazCasa = document.getElementById('formazione_Casa');
		var DivCasa = (Div1Height + Div2Height);
		
		if (document.getElementById('panchina_Fuori')) {
		var Div3Height = document.getElementById('panchina_Fuori').offsetHeight;
		} else {
		var Div3Height = 0;
		}
		var Div4Height = document.getElementById('logo_Fuori').offsetHeight;
		var DivFormazFuori = document.getElementById('formazione_Fuori');
		var DivFuori = (Div3Height + Div4Height);
		
		//var DivVersus = document.getElementById('versus').offsetHeight;
		
		if (DivCasa >= DivFuori) {
        var Hmax = DivCasa;
		} else {
		var Hmax = DivFuori;
		}
		
		DivFormazCasa.style.height = Hmax + 15 + 'px';
		DivFormazFuori.style.height = Hmax + 15 + 'px';
		//DivVersus.style.height = Hmax + 15 + 'px';

	}
}

function Check_Campi(){
var Titolo = document.u_news_name.titolo.value;
var SottoTitolo =  document.u_news_name.sottotitolo.value;
var Testo = $('#u_news').find('.nicEdit-main').text();

if (Titolo != "" && SottoTitolo != "" && Testo != "") {
     return true;
} else {
    alert("Attenzione!\nAlcuni campi sono vuoti!");
    return false;
}

}

function verifica_campi() {
var Call = ($("#MlTermCall").find("option:selected").attr("text"))+$("#MlTermCallOra").val();
var Int = ($("#MlTermInt").find("option:selected").attr("text"))+$("#MlTermIntOra").val();
var Ril = ($("#MlTermRil").find("option:selected").attr("text"))+$("#MlTermRilOra").val();

var Simpli = $("#MlSimpli").attr('checked');

if((Call == Int || Call == Ril || Int == Ril) && Simpli == false) {
  alert("Attenzione!\nScadenze coincidenti tra le fasi Chiamata, Intenzioni di rlancio o apertura buste!");
  return false;
}

var ArrayBasiRuoli = new Array("#MlbaseAstaP", "#MlbaseAstaD", "#MlbaseAstaC", "#MlbaseAstaA")
var BaseScelta = $("input[name='MlBaseAsta']:checked").val();
var conta = 0
  for (var i in ArrayBasiRuoli ) {
         if($(ArrayBasiRuoli[i]).val().length) conta++;
       }

   if (conta != 4 && BaseScelta == 3) {
       alert("Attenzione!\nHai scelto di personalizzare i valori di base d'asta del Mercato Libero.\nAssicurati d'aver inserito un valore per ogni ruolo!");
       return false;
   }


var capoclassifica = document.config.CompetizioneCapoclassifica.selectedIndex;
var bigmatch = document.config.CompetizioneBigMatch.selectedIndex;
var records = document.config.CompetizioneRecord.selectedIndex;
var miniclassifica = document.config.CompetizioneMiniClassifica.selectedIndex;

var TopManager = document.config.CompetizioneTopmanager.selectedIndex;
var TmVotoUff =  document.config.TmVotoUff.value;

var preslega =  document.config.PresLega.value;
var IFMittMail =  document.config.IFMittMail.value;

var email_reg_exp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
var regex = /[0-9]|\./;

if (preslega != "" && !email_reg_exp.test(preslega)) {
    alert("Formato email Presidente di Lega non valido!");
    return false;
}

if (IFMittMail != "" && !email_reg_exp.test(IFMittMail)) {
    alert("Formato email Mittente non valido!");
    return false;
}

 if  ((capoclassifica == 0) || (bigmatch == 0) || (records == 0) || (miniclassifica == 0) || (TopManager == 0)){
	alert("Controlla d'aver impostato TUTTE le competizioni dei widget!");
	return false;
}

if (TmVotoUff == "") {
    alert("Attezione!\nDevi impostare la casella VOTO D'UFFICIO.");
    return false;
}

    document.config.submit();
    return true;
}


function numbersonly(myfield, e, dec, decimali)
{
var key;
var keychar;
var range = (decimali == "si") ? "0123456789." : "0123456789";

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 ((("0123456789.").indexOf(keychar) > -1))
else if (((range).indexOf(keychar) > -1))
   return true;

// decimal point jump
else if (dec && (keychar == "."))
   {
   myfield.form.elements[dec].focus();
   return false;
   }
else
   return false;
}



function verifica_associazione() {
var utente = document.utenti.ElencoUtenti.selectedIndex;
var squadra = document.utenti.ElencoSquadre.selectedIndex;

 if  ((utente == 0) || (squadra == 0)){
	alert("Controlla d'aver selezionato SIA l'utente CHE la squadra!");
	return false;
} 
	document.utenti.submit();
return true;
}

function inserisci_utente() {
var user = document.nuovi_utenti.username.value;
var mail = document.nuovi_utenti.email.value;
var pwd = document.nuovi_utenti.password.value;

 //if  ((utente == 0) || (squadra == 0)){
	alert(user+" - "+mail+" "+pwd); //"Controlla d'aver selezionato SIA l'utente CHE la squadra!");
//	return false;
//} 
	document.nuovi_utenti.submit();
return true;
}

function countAreaChars(areaName,counter,limit)
{
if (areaName.value.length>limit)
areaName.value=areaName.value.substring(0,limit);
else
counter.value = limit - areaName.value.length;
}


function verifica_nome(campo)
  {
  filesEsistenti=new Array();
  filesEsistenti=['FAX','DOCUMENTO GENERICO','COMUNICAZIONI INTERNE','COMMESSA'];
  // array eventualmente costruito dinamicamente da PHP.
 
  if (filesEsistenti.in_array(campo.value.toUpperCase()))
    {
    alert ("Il nome utilizzato e' gia' esistente. ");
    campo.value = "";
    campo.focus();
    return true;
    }
  }

//---Inizio Modifica Aggiunta da Frungillo-------------------
//---Funzione per ordinamento elenco in Statistiche----------
function inviaOrd (){
 var elem = document.getElementsByName("ord_"); 
   var txt_ar = document.getElementsByName("ord_txt");
   if (txt_ar[0].value == ""){
     txt_ar[0].value =  elem[0].value;
   }else{
    document.getElementById('verso_ord').disabled = true;
    txt_ar[0].value = txt_ar[0].value + ", " + elem[0].value ;
   }

   	indice_selezionato = document.getElementById('ord_').selectedIndex;
	if(indice_selezionato>=0){
		indice_selezionato = document.getElementById('ord_').selectedIndex=0;
    }   
   
}

function inviaVis (){
 var elem = document.getElementsByName("vis_"); 
   var txt_ar = document.getElementsByName("vis_txt");
   if (txt_ar[0].value == ""){
     txt_ar[0].value = elem[0].value;
   }else{
    txt_ar[0].value = txt_ar[0].value + ", " + elem[0].value ;
   }

   	indice_selezionato = document.getElementById(elem[0].id).selectedIndex;
	if(indice_selezionato>=0){
		document.getElementById(elem[0].id).options[indice_selezionato]=null;
    }
}

function resetta(){
 document.getElementById("agg").disabled = false;
 document.getElementById("agg_and").disabled = true;
 document.getElementById("agg_or").disabled = true;
 document.getElementById("agg_par_left").disabled = false;
 document.getElementById("agg_par_right").disabled = true;
 document.getElementById("agg_end").disabled = true;
 document.getElementById("first_qry").value = "";
 document.getElementById("second_qry").value = "";
 document.getElementById("third_qry").value = "";
}

function blocca(){
  var select = document.getElementById("minutidalblocco");
  var check = document.getElementById("TermineInvio");
  if (check.checked === false) {
      select.disabled = false;
  } else if (check.checked === true) {
      select.disabled = true;
  }
}

function RoseLibere(){

  if ($('#MlroseLibere').is(':checked')) {

  $('#Mlrosa1').attr('disabled', true);
  $('#Mlrosa2').attr('disabled', true);
  $('#Mlrosa3').attr('disabled', true);
  $('#Mlrosa4').attr('disabled', true);
  } else {

  $('#Mlrosa1').removeAttr("disabled");
  $('#Mlrosa2').removeAttr("disabled");
  $('#Mlrosa3').removeAttr("disabled");
  $('#Mlrosa4').removeAttr("disabled");
  }
}

//--------------------fine modifiche frungillo---------------

//-----------------------inv form----------------------------
	function nomecognome (nomecompleto){
	 pezzi = nomecompleto.split(" ");
	 for (var i=0; i<pezzi.length; i++){
	  if (pezzi[i]!=pezzi[i].toUpperCase()){
	   pezzi[i] = pezzi[i].substring(0,1)+".";
	  }
	  pezzi[i] = pezzi[i].substring(0,1).toUpperCase() + pezzi[i].substring(1).toLowerCase();
	 }
	 return pezzi.join(" ");
	}

	function findObj(theObj,theDoc) {
	var p,i,foundObj;
	if(!theDoc)theDoc=document;
	if((p=theObj.indexOf("?"))>0&&parent.frames.length) {
	theDoc=parent.frames[theObj.substring(p+1)].document;theObj=theObj.substring(0,p);
	}
	if(!(foundObj=theDoc[theObj])&&theDoc.all)foundObj=theDoc.all[theObj];
		for(i=0;!foundObj&&i<theDoc.forms.length;i++)
		foundObj=theDoc.forms[i][theObj];
		for(i=0;!foundObj&&theDoc.layers&&i<theDoc.layers.length;i++)
		foundObj=findObj(theObj,theDoc.layers[i].document);
		if(!foundObj&&document.getElementById)foundObj=document.getElementById(theObj);
		return foundObj;
	}

	function visu_rigo(liv) {
		if((obj=findObj(liv))!=null){
			if(obj.style)obj=obj.style
			obj.visibility=='visible'?obj.visibility='hidden':obj.visibility='visible'
		}
	}
	
    function resize(divID,TopHeigh) {
		/*var divh = document.getElementById('if_body').offsetHeight;
		document.getElementById('if_body').style.height = (divh - 40) +'px';*/
                var divh = document.getElementById(divID).offsetHeight;
		document.getElementById(divID).style.height = (divh - TopHeigh) +'px';
                //alert(divh+" - "+document.getElementById(divID).style.height);
	}


//------------------------------------------
//-------pannello di configurazione per invio formazioni

function modTermine (){
 var e = document.getElementById("minutidalblocco");
 var elem = e.options[e.selectedIndex].value;
 var ora = elem.split("%")[0];

 //var tempo_da_sottrarre = elem[0].value.split("%")[1];
 var tempo_da_sottrarre = elem.split("%")[1];
 var h_tds =  (tempo_da_sottrarre.split(":")[0]).replace("0","");
 var m_tds =  tempo_da_sottrarre.split(":")[1];

 if (h_tds == "") {
    differenza = m_tds;
 } else {
    differenza = h_tds*60+parseInt(m_tds);
 }

 var ora_minuti = parseInt((ora.split(":")[0]))*60+parseInt((ora.split(":")[1]*1));
 var nuovo_termine_in_minuti = (ora_minuti-differenza);

  //Formatto la stringa di uscita
  var res = "";
  var nDiffMin = 0;
  var nDiffHour  = 0;
  if (nuovo_termine_in_minuti > 59) {
      nDiffMin = nuovo_termine_in_minuti % 60;
      nDiffHour = (nuovo_termine_in_minuti - nDiffMin) / 60;
  } else {
      nDiffMin = nuovo_termine_in_minuti;
  }
  if (nDiffHour < 10) res += "0";
  res += nDiffHour;
  res += ":";
  if (nDiffMin < 10) res += "0";
  res += nDiffMin;

  var stampa = document.getElementById("termine_invio");
  stampa.innerHTML = res;

  var out = document.getElementById("DeltaDalBloccoInvio");
  out.value = tempo_da_sottrarre;

}

function reset_mp(){
    $("select#ElencoUtenti option[value='0']").attr("selected", "selected");
    document.getElementById("oggetto").value = "";
    document.getElementById("testo_tm").value = "";
}

function reply_quote(id,r_q){
      $('#new_mp').slideDown('slow');
      reset_mp();
      dest = document.getElementById('dest_'+id).value;
      nomemitt = document.getElementById('nomemitt_'+id).value;
      oggetto = document.getElementById('oggetto_'+id).value;
      testodaquotare = document.getElementById('testodaq_'+id).value;

      //alert(dest+"\n"+nomemitt+"\n"+oggetto+"\n"+testodaquotare)

      document.getElementById('ElencoUtenti').value = dest+"&&&"+nomemitt;

      var Re = document.getElementById("oggetto");
          Re.value = "Re: "+oggetto;

      $("#ElencoUtenti").val(dest+"???"+nomemitt);

      if(r_q == 1) {
          var testo = document.getElementById("testo_tm");
          testo.value = "["+testodaquotare+"]";
      }

}

    //function mp_letto(testo,lunghezzatesto,testo_corto,id_mp){
    //alert(testo+"\n"+lunghezzatesto+"\n"+testo_corto+"\n"+id_mp);
    //alert(mpnonletti);
function mp_letto(id_mp){
    testo = document.getElementById('testodaq_'+id_mp).value;
    lunghezzatesto = document.getElementById('lnt_'+id_mp).value;
    testo_corto = document.getElementById('tc_'+id_mp).value;

    riassunto = "";
    corpo_testo = "<div id='testo_"+id_mp+"' class='testo_allungato_mp_vis'>"+testo+"</div>";
    if (lunghezzatesto >80) {
       riassunto = "<a id='click_testo_mp' onclick=\"ShowHide('#testo_"+id_mp+",500'); ShowHide('#testo_corto_"+id_mp+",500'); return false; \" href=\"#\"><img alt=\"\" src=\"skin/"+SubSkinReVo+"/img/eject_8x8dg.png\"/></a>";
       corpo_testo = "<div id='testo_corto_"+id_mp+"' class='testo_corto_mp'>"+testo_corto+"</div><div id='testo_"+id_mp+"' class='testo_allungato_mp'>"+testo+"</div>";
    }

    $.ajax({
     url: "core_main/update_mp.php",
     dataType: "text",
     data: "id="+id_mp,
     success: function(data) {
       if (data.indexOf("OK") !=-1){
            var icona = document.getElementById("riass_mp_"+id_mp);
            icona.innerHTML = riassunto;

            var corpo_mp = document.getElementById("cp_mp_"+id_mp);
            corpo_mp.innerHTML = corpo_testo;

            var mp_nl_ora = document.getElementById("nonletti").innerHTML;

            var mp_nl = document.getElementById("nonletti");
            mp_nl.innerHTML = mp_nl_ora-1;

            if((mp_nl_ora-1) == 0) {
                $("#nonletti").removeClass('num_non_letti_si');
                $("#nonletti").addClass('num_non_letti_no');
                $("#nonlettibis").removeClass('num_non_letti_si');
                $("#nonlettibis").addClass('num_non_letti_no');
                document.getElementById("notifica").innerHTML = "<img alt='' src='skin/"+SubSkinReVo+"/img/no_mp.gif'/>";
            }

       }
     }
   });
}


function ChangeLetti(){
    var contenuto = document.getElementById("leggi").innerHTML;
    var contenuto2 = document.getElementById("elenco_mp").innerHTML;
    document.getElementById("leggi").innerHTML = (contenuto == "inviati") ? "ricevuti" : "inviati";

    if(contenuto2 == "Ricevuti") {
        document.getElementById("elenco_mp").innerHTML =  "Inviati";
        $('.identifica_elenco').css("background-image", "url(skin/"+SubSkinReVo+"/img/mp_inviati.png)");
    } else {
        document.getElementById("elenco_mp").innerHTML =  "Ricevuti";
        $('.identifica_elenco').css("background-image", "url(skin/"+SubSkinReVo+"/img/mp_ricevuti.png)");
    }

}

function RechargeSent(info,Dest){

        $.post("core_main/inviati_mp.php", function(output) {
                $("#mp_inviati").html(output);
                var messaggio = (info == 'uno') ? "Messaggio correttamente inviato all\'utente "+Dest+"." : "Messaggio correttamente inviato all\'utente "+Dest+" ma non notificato.";
                $("#attesa").css("display", "none");
                alert(messaggio);
        });
           
}

function verifica_MP() {
$("#attesa").css("display", "block");
var Destinatario = document.form_mp.ElencoUtenti.selectedIndex;
var DatiDestinatario = document.form_mp.ElencoUtenti.value;
var Oggetto =  document.form_mp.oggetto.value;
var Testo =  document.form_mp.testo_tm.value;

var ElencoDest= new Array()

if (DatiDestinatario.indexOf("___")!=-1)  {
    ElencoDest = DatiDestinatario.split("___");
    ElencoDest.splice(ElencoDest.length-1,1);

} else {
    ElencoDest[0] = DatiDestinatario;
}



if (Oggetto == "" || Testo == ""){
    alert("Attenzione!\nOggetto o corpo del testo vuoti.");
    $("#attesa").css("display", "none");
    return false;
}

 if  (Destinatario == 0){
	alert("Controlla d'aver selezionato il destinatario del messaggio!");
        $("#attesa").css("display", "none");
	return false;
}


    for (i=0;i<=ElencoDest.length-1;i++) {
            IDDest = ElencoDest[i].split("???")[0];
            var Inviati = parseInt(document.getElementById("mp_sent").innerHTML);
            $.ajax({
	         async: false,
                 url: "core_main/insert_mp.php",
                 dataType: "text",
                 data: "Destinatario="+IDDest+"&Oggetto="+encodeURIComponent(Oggetto)+"&Testo="+encodeURIComponent(Testo),
                 success: function(data) {
                        if (data.indexOf("OK_Not_si") != -1){
                          NomeDest = ElencoDest[i].split("???")[1];
                          //alert('Messaggio correttamente inviato all\'utente '+NomeDest+'.');
                          reset_mp();
                          $("#mp_sent").text(Inviati+1);
                          RechargeSent('uno',NomeDest);
                        } else if(data.indexOf("OK_Not_no") != -1){
                            NomeDest = ElencoDest[i].split("???")[1];
			    //alert('Messaggio correttamente inviato all\'utente '+NomeDest+' ma non notificato.');
                            $("#mp_sent").text(Inviati+1);
                            RechargeSent('due',NomeDest);
                        } else if(data.indexOf("KO") != -1){
                            $("#attesa").css("display", "none");
                            alert('ATTENZIONE: Sessione scaduta, messaggio non inviato!\nRiesegui il login prima di riprovare.');
                            window.location='index.php'
                            return false;
                        } else {
                            $("#attesa").css("display", "none");
                            alert("Errore nell'invio.\nMessaggio non inviato!");

                        }
                   }


             });
    }

    return true;
}
