
//general

function mySubmit(f){
  var ok = true;
  return ok;
}

function mySubmitClick(field,event,buttonname){

  if(event)
    key = event.keyCode;
  else
    key = event.which;
// alert(key);
  if(key==13){
	  el = document.getElementById(buttonname);
// 	  el = document.getElementById('cerca');
// alert(el);
		if(el) el.click();
		// $(buttonname).click();
  }else{
    return true;
  }

}

function get_title(a, type){

// alert('get_title');
  if(type=='modello'){
// alert('modello');
    url = "modelli.dhtml?save=1&";
    v1 = "Assegna un nome a questo modello:";
    v2 = "esempio: modello x";
  }else{
    if(type=='bozza'){
// alert('bozza');
      url = "bozze.dhtml?save=1&";
      v1 = "Assegna un nome a questa bozza:";
      v2 = "esempio: bozza x";
    }else{
//alert('errore');
      alert('il tipo di documento da salvare non \u00E8 valido');
      exit;
    }
  }
  title = prompt(v1, v2);
  if(title!=null){
    url = url+"title="+title;
    if(a.href)
      a.href = url;
    else{
      pn = location.pathname;
      re = /(.+)riepilogo\.dhtml$/;
      m = pn.match(re);
      window.location.replace(m[1]+url);
    }
  }

}

//menu sinistra

function ricarica(tipo, come){

  conf = true;
  if(come)
    conf = confirm('Cambiando il tipo di documento si dovr\u00E0 scegliere nuovamente il tipo di pdf da scaricare.');
  if(conf!=false){
    url = ""+window.location;
    re = /\?.+$/;
    url = url.replace(re,"");
    return location.replace(url+'?tipo='+tipo);
  }else{
    o = document.getElementById('tipo_ord');
    p = document.getElementById('tipo_prev');
    or = document.getElementById('tipo_ordric');
    if(tipo=="ordine"){
      o.checked = false;
      or.checked = false;
      p.checked = true;
    }else if(tipo=="ordinericambi"){
      o.checked = false;
      or.checked = true;
      p.checked = false;
    }else{
      o.checked = true;
      or.checked = false;
      p.checked = false;
    }
  }
  return false;

}
/*
function dis_attiva(tipo){
  if(tipo=="ordine"){
    f = document.intprev;
    num = f.length;
    for(i=0; i<num; i++){
      f.elements[i].disabled = true;
    }
  }
}
*/

//intestatario

function anagrafica_new(tipo){

  ap = document.getElementById('anag_prev').style;
  ao = document.getElementById('anag_ord').style;

  if(tipo=="preventivo"){
    ap.display="block";
    ao.display="none";
  }else if(tipo="ordine"){
    ap.display="none";
    ao.display="block";
  }

}

//riepilogo intestatario

function checkDest(dest, stato){
  dest = dest.value;
  if(dest==1 && stato==1){
    return confirm('La destinazione \u00E8 gi\u00E0 stata inserita nella sezione apposita. Facendo "Procedi" verr\u00E0 modificata.');
  }
  return true;
}

function display_discount(listini){

  navName = navigator.appName;
  
  if(listini)
    keyList = listini.split(',');

  el = document.getElementById('display_sconti');
  if(!el) return false;

  selInd = el.selectedIndex;
  el1 = document.getElementById('sconti1');
  
  if(selInd==1){
    if(navName!="Microsoft Internet Explorer"){
      display1 = 'table-row';
    }else{
      display1 = 'inline';
    }
    display2 = 'none';
  }else if(selInd==2){
    display1 = 'none';
    if(navName!="Microsoft Internet Explorer"){
      display2 = 'table-row';
    }else{
      display2 = 'inline';
    }
  }else{
    display1 = 'none';
    display2 = 'none';
  }
  
  el1.style.display = display1;
  if(keyList.length>0){
    el2 = document.getElementById('sconti2');
    el2.style.display = display2;
    for(i=0; i<keyList.length; i++){
      el = document.getElementById('sconti2_'+keyList[i]);
      el.style.display = display2;
    }
  }
  
}

//destinazione

function ins_destinazione(dest, tipo){
  if(dest==1){
    str = "La destinazione era gi\u00E0 stata inserita come quella dell\'intestatario del";
    re = /^ordine/;
    if(re.test(tipo)==true){
      str += "l'";
    }else{
      str = " ";
    }
    str += tipo;
    str += ". Sei sicuro di voler cambiare?";
    return confirm(str);
  }else{
    return true;
  }
}

//carrello

function verify_input(data){
//verifica se lo sconto � superiore al 50%
  if(data){
    v = data.value;
    if(v==100){
      sconti[1] = 100*1;
    }else{
      re = /^([0-9]{1,2})\+?([0-9]{1,2}(\.[0-9]{1,2})?)?$/;
      sconti = re.exec(v);
    }
    if(!sconti){
      alert('Lo sconto inserito non \u00E8 valido: i formati validi sono "30" o "30+5"');
      data.value = "";
    }else{
      var sconto = 0;
      if(!sconti[2]){
        sconto = sconti[1];
	data.value=sconti[1];
      }else{
        sconto = sconti[1]*1+sconti[2]*1-(sconti[1]*sconti[2]/100);
      }
      if(sconto>50){
        alert('Lo sconto inserito \u00E8 superiore al 50% l\'ordine sar\u00E0 soggetto ad autorizzazione.');
      }
    }
  }
}

function auto_free(codice){
  f = document.forms[0];
  if(codice){
    free = document.getElementById('free_'+codice);
    auto = document.getElementById('auto_'+codice);
//    document.forms[0].elements["sconto_reale["+codice+"]"].value;
    if(!free.style.display || free.style.display=="inline"){
      free.style.display = "none";
      auto.style.display = "inline";
      f.elements["sconto_reale["+codice+"]"].value = "auto";
    }else{
      free.style.display = "inline";
      auto.style.display = "none";
      f.elements["sconto_reale["+codice+"]"].value = "free";
    }
  }else{
    fp = document.getElementById('free_partner');
    ap = document.getElementById('auto_partner');
//alert(f.elements['partner_display'].value);
    if(!fp.style.display || fp.style.display=="inline"){
      fp.style.display = "none";
      ap.style.display = "inline";
      f.elements['partner_display'].value = "auto";
//alert(f.elements['partner_display'].value);
    }else{
      fp.style.display = "inline";
      ap.style.display = "none";
      f.elements['partner_display'].value = "free";
//alert(f.elements['partner_display'].value);
    }
  }
}

function checkLotmin(n, warning, oldqty, event){

  if(!n) return false;
  else{
    re = /^(\d+)[\.|,]?(\d*)$/;
    var results = n.value.match(re);
    if(results && results.length>1){
      nv = results[1];
      if(results[2]) nv = nv+'.'+results[2];
      nv = parseFloat(nv);
      nv = Math.round(nv*100)/100;
      results = null;
    }else{
      alert('ATTENZIONE: sono stati inseriti caratteri non ammessi');
      return false;
    }
  }
  
  re = /^add\[(\d+(X_X_X\d+)?)\]$/;
  var results = n.name.match(re);
  e = document.getElementById('lotmin['+results[1]+']');
// alert(e);
  ev = e.value;
  ev = parseFloat(ev);
  if(ev && ev>0){
/*
alert('value: '+n.value+' - lotto minimo: '+ev+' - resto: '+n.value%ev);
    if(n.value-ev<0) alert(n.value+'<'+ev);
    if(n.value%ev!=0) alert('resto!='.n.value%ev);
alert((Math.floor((nv%ev)*100))/100);
*/
    if(nv<ev || (Math.floor((nv%ev)*100))/100!=0){
      sup = Math.round(Math.ceil(nv/ev)*ev*100)/100;
      if(warning){
        en = document.getElementById('artname['+results[1]+']').value;
        alert('ATTENZIONE: il lotto minimo dell\'articolo '+en+'  \u00E8 '+ev+'.\nIl sistema inserir\u00E0 nel carrello il multiplo del lotto minimo superiore alla quantit\u00E0 inserita.');
      }
      n.value = sup;
      return true;
    }
    mySubmitClick(n,event,'cart1['+results[1]+']');
    return true;
  }
}

function attention_popup(){
 searchWin = window.open('attenzione.dhtml','popup2','scrollbars=yes,resizable=no,width=650,height=370,status=no,location=no,toolbar=no');
};

function euro_perc(val){
  if(val){
    switch (val) {
      case 'perc':
        val1 = 'euro';
        break;
      case 'euro':
        val1 = 'perc';
        break;
    }
    eltext = document.getElementById(val);
    elicon = document.getElementById(val+'_icon');
    eltext.style.display = 'inline';
    elicon.style.display = 'none';
    eltext1 = document.getElementById(val1);
    elicon1 = document.getElementById(val1+'_icon');
    eltext1.style.display = 'none';
    elicon1.style.display = 'inline';
    el = document.getElementById('mod_sp_acc');
    el.value = val;
  }
}

//info

function pdfCon(come){

  e = document.getElementById('pdf_con');
  if(e){
    if(come=="corpo" || come=="dett" || come=="breve"){
      e.style.display = "block";
    }else{
      e.style.display = "none";
    }
  }

}

// function display_magazzino(){
// // alert('display_magazzino');
//   el = document.getElementById('resa_merce');
//   if(el){
//     selInd = el.selectedIndex;
// // alert(selInd);
//     el = document.getElementById('magazzino');
//     if(selInd==2){
//       if(el) el.style.display = 'inline';
//     }else{
//       if(el) el.style.display = 'none';
//     }
//   }
// 
// }

function ismaxlength(obj){
  var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "";
  if (obj.getAttribute && obj.value.length>mlength)
    obj.value=obj.value.substring(0,mlength);
}

function display_cal(val, d){
  primo:
  if(!val){
    el = document.getElementById('Parziale');
    if(el.checked==true){
      val = 'Parziale';
      break primo;
    }
    el = document.getElementById('Totale');
    if(el.checked==true)
      val = 'Totale';
  }
  if(val=='Parziale'){
    el = document.getElementById('title_datacons');
    el.style.display = 'none';
    el = document.getElementById('cal_datacons');
    el.style.display = 'none';
  }else if(val=='Totale'){
    conf = confirm('I prodotti ordinati verrano spediti il '+d+'.\nLe date di consegna richiesta inserite nel carrello verranno tutte modificate di conseguenza.\nSei sicuro di voler procedere?');
    if(conf){
      el = document.getElementById('title_datacons');
      el.style.display = 'inline';
      el = document.getElementById('cal_datacons');
      el.style.display = 'inline';
    }else{
      el = document.getElementById('Parziale');
      el.checked = true;
    }
  }
}

//riepilogo

function popup2(str) {
 searchWin = window.open(str,'popup2','scrollbars=yes,resizable=no,width=650,height=400,status=no,location=no,toolbar=no');
}

function verify_data(tipo,intestatario,destinatario,carrello,info,capitolato){
  str = "";
  if(!tipo){
    alert('Errore: manca il tipo di documento');
    return false;
  }
  if(intestatario==0 || carrello==0){
    str = "Impossibile procedere: il passo \"intestatario\" e/o il passo \"carrello\" non sono stati compilati o conclusi correttamente";
    alert(str);
    return false;
  }
  if(
    (tipo=='ordine capitolato' || tipo=='preventivo capitolato')
    &&
    capitolato==0
  ){
    str = "Impossibile procedere: il passo \"scegli capitolato\" non \u00E8 stato compilato o concluso correttamente";
    alert(str);
    return false;
  }else if(destinatario==0 || info==0){
    switch (tipo){
      case 'preventivo':
        str = "Il passo \"destinazione\" e/o il passo \"info\" non sono stati compilati o conclusi correttamente. Vuoi procedere lo stesso?";
        return confirm(str);
      break;
      case 'preventivo capitolato':
        str = "Il passo \"destinazione\" e/o il passo \"info\" non sono stati compilati o conclusi correttamente. Vuoi procedere lo stesso?";
        return confirm(str);
      break;
      case 'ordine':
        str = "Impossibile procedere: il passo \"destinazione\" e/o il passo \"info\" non sono stati compilati o conclusi correttamente";
        alert(str);
        return false;
      break;
      case 'ordine capitolato':
        str = "Impossibile procedere: il passo \"destinazione\" e/o il passo \"info\" non sono stati compilati o conclusi correttamente";
        alert(str);
        return false;
      break;
    }
  }
  
 return true;
}

//intestario.dhtml

function onlyNumber(evt){
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if(charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
  return true;
}

function onlyNote(evt){
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  
  if(!(charCode<33 || (charCode>39 && charCode<60) || (charCode>64 && charCode<91) || (charCode>96 && charCode<123)))
    return false;
  return true;
}

//risultati tracking, scheda cliente e disponibilit� articoli

function enableCausaleStato(sel){
  if(sel){
    ind = sel.selectedIndex;
    val = sel.options[sel.selectedIndex].value;
    causale = document.getElementById('causale');
    stato = document.getElementById('stato');
    if(val=="ordine"){
      causale.disabled = false;
      stato.disabled = false;
    }else{
      causale.options[0].selected = true;
      stato.options[0].selected = true;
      causale.disabled = true;
      stato.disabled = true;
    }
  }
}

// submit scadenzario

function scadenzariosubmit(what, email){

  if(what){
    scadform = document.getElementById('scadenzarioform');
    hiddenel = document.getElementById('hidden');
    hiddenel.name = what;
    hiddenel.value = 1;
//     texthidden = document.getElementById('texthidden');
//     texthidden.value = document.getElementById('testomail').value;
    if(email){
      emailel = document.getElementById('email');
      emailel.value = email;
    }
    scadform.submit();
  }
}

function insertEmail(what){
// alert('insertemail');
  if(what){
    email = prompt('Per questo cliente il sistema non ha trovato un indirizzo email.\nInseriscine uno se vuoi inviargli lo scadenzario.');
    if(email){
      conf = confirm('Lo scadenzario sar\u00E0 inviato all\'indirizzo email: '+email);
      if(conf==true) scadenzariosubmit(what, email);
    }
  }

}

function popupscad(str) {
 searchWin = window.open(str,'popupscad','scrollbars=yes,resizable=no,width=570,height=380,status=no,location=no,toolbar=no');
}

function fireEvent(obj,evt,objdoc){
  var fireOnThis = obj;
//   wo = window.opener;
  if(objdoc.createEvent){
// alert('1');
    var evObj = objdoc.createEvent('MouseEvents');
// alert(evObj);
    evObj.initEvent(evt, true, false);
    fireOnThis.dispatchEvent(evObj);
  }else if(objdoc.createEventObject){
// alert('2');
    fireOnThis.fireEvent('on'+evt);
  }
}
/*
 function toggle(tipo){
  var f = document.forms['doc-search'];
  var e = f.elements[tipo];
  e.value = 1-e.value;
  img = document.getElementById(tipo+'-img');
  if(img.src.match(/-on\.gif$/)){
    img.src = img.src.replace(/-on\.gif$/,".gif");
  }else{
    img.src = img.src.replace(/\.gif$/,"-on.gif");
  }
  t = new Array('radiante', 'solare', 'esecutivo');
  err = 0;
  for(i=0;i<t.length;i++){
   e = f.elements[t[i]].value;
   err = err+e;
  }
  if(err==0){
  alert('Questa ricerca non porta a nessun risultato.\n Deve essere selezionato almeno un tipo d\'offerta.');
   for(i=0;i<t.length;i++){
    f.elements[t[i]].value = 1;
    document.getElementById(t[i]+'-img').src = "images/"+t[i]+"-on.gif";
   }
  }
 }
*/

function switchRadio(){
  document.cercaForm.periodo[0].checked=true;
}

function changeRowsColor(page, bolle, nolast){
//alert('changeRowsColor');

 if(nolast)
 	var nolast = nolast;

 switch(page){
   case "tracking-ricerca":
     if(bolle && bolle==1)
       page = "tracking-bolle";
     else
       page = "tracking-dettagli";
     break;
   case "disponibilita":
     page = "disponibilita_dettaglio";
     break;
   case "scheda_cliente":
     page = "scheda_cliente_dettaglio";
     break;
   case "scadenzario":
     page = "scadenzario_dettaglio";
     break;
   case "compensi":
     page = "compensi_dettaglio";
     break;
 }
 
 var myRules = {
   '#tabella1 tr' : function(element){
     var cells=element.cells;
     if(element.id.match(/^id\d+$/)){
//alert(element.id);
      var id=element.id.replace(/^id/,'');
      var i;
      var totcells = cells.length;
      if(nolast)
      	totcells = totcells-1;
      for(i=0;i<totcells;i++){
//alert(id);
       cells[i].link = page+'.dhtml?id='+id;
       cells[i].title= "Mostra"
       cells[i].alt  = cells[i].title;
       cells[i].style.cursor="pointer";
       cells[i].onclick=function(){document.location.href=this.link};
      }
/*
      i=cells.length-2;
      cells[i].link ='offerte-modulo.dhtml?id='+id+'&mod=1';
      cells[i].title= "Modifica"
      cells[i].alt  = cells[i].title;
      cells[i].style.cursor="pointer";
      cells[i].onclick=function(){document.location.href=this.link};
      i++;
      cells[i].offerta=id;
      cells[i].link  ='offerte.dhtml?del='+id;
      cells[i].title= "Elimina"
      cells[i].alt  = cells[i].title;
      cells[i].style.cursor="pointer";
      cells[i].onclick=function(){
       if(confirm('Sei sicuro di voler cancellare l\'offerta?')){
        document.location.href=this.link;
	return true;
       }
       return false;
      }
*/
     }
     element.onmouseover = function(){this.className+=" sel";};
     element.onmouseout = function(){this.className=this.className.replace(/ ?sel$/,"");};
   }
 };
 Behaviour.register(myRules);
 Behaviour.apply();
}

function popup(str, w, h, resize) {

  if(!w || (w && isNaN(parseInt(w))))
    w = 620;
  if(!h || (h && isNaN(parseInt(h))))
    h = 550;
  if(!resize || resize!='no')
    resize = 'yes';
  
        searchWin = window.open(str,'popup','scrollbars=yes,resizable='+resize+',width='+w+',height='+h+',status=no,location=no,toolbar=no');

}
function popupS(str) {

        searchWin = window.open(str,'popupS','scrollbars=yes,resizable=no,width=620,height=253,status=no,location=no,toolbar=no');

}

// function myReset(idform){
// }


