/*  mySoap
 *  (c) 2006 Massimiliano Balestrieri <massimiliano.balestrieri@gmail.com>
 *--------------------------------------------------------------------------*/
///////////////////TESTING///////////////////////////
var debug = 0;
var arr_exclude = new Array();
var arr_target = new Array();
var CONFIG_NUM_TARGET;
var CONFIG_CONTROLLER;

// FrontController js per la RICERCA IN BASE AL COMUNE per la chiamata dei metodi remoti
// resetta i valori delle select e delle label se gli viene passato il valore booleano reset = true
// chiama il metodo solo se questo non e' stato escluso dai metodi chiamabili (arr_exclude) 
// cioe' se una tendina ha un solo valore questa autoesclude i propri metodi remoti dai metodi chiamabili in modo che non ci siano
// chiamate inutili
function ajaxSoapRicercaComune(reset) {
  CONFIG_CONTROLLER = 'ajaxSoapRicercaComune';
  CONFIG_NUM_TARGET = 3;

  
  //parametri: prende i valori scelti finora
  var comune   = document.getElementById("comune").value;
  var fermata  = document.getElementById("fermata").value;   
  var linea    = document.getElementById("linea").value;
  var percorso = document.getElementById("percorso").value;
  
  
  //se viene scelto un comune, si azzerano le select di fermata/linea/percorso e le label 
  if(reset == 'trueComune'){
  	  
      arr_exclude = new Array();
		  cleanDdl('fermata');   
		  //var fermata  = document.getElementById("fermata").value;  	
      cleanLabel('labelNFermate'); 
      cleanDdl('linea'); 
      cleanLabel('labelNLinee');
      cleanDdl('percorso');
      cleanLabel('labelNPercorsi');
      cleanLabel('label');
  }
  if(reset == 'trueFermata'){
      arr_exclude = new Array();
      if (!fermata) { cleanDdl('fermata'); cleanLabel('labelNFermate'); } // onchange che porta alla option vuota
      cleanDdl('linea'); 
      cleanLabel('labelNLinee');
      cleanDdl('percorso');
      cleanLabel('labelNPercorsi');
      cleanLabel('label');
  }
  if(reset == 'trueLinea'){
      arr_exclude = new Array();
      if (!linea) { cleanDdl('linea'); cleanLabel('labelNLinee'); } // onchange che porta alla option vuota
      cleanDdl('percorso');
      cleanLabel('labelNPercorsi');
      cleanLabel('label');
  }
  
  
  //se nella tendona del comune scelgo la riga vuota, svuoto le select di fermata/linea/percorso 
  if(!comune){
       arr_exclude = new Array();
       cleanDdl('fermata');  cleanLabel('labelNFermate');    
       cleanDdl('linea');    cleanLabel('labelNLinee');
       cleanDdl('percorso'); cleanLabel('labelNPercorsi');
       cleanLabel('label');
       
       //Riccardo: rendo invisibile
       //document.getElementById("fermatatr").style.cssText="display:none"; 
       //document.getElementById("lineatr").style.cssText="display:none";   
       //document.getElementById("percorsotr").style.cssText="display:none";
       
       return;
  }
  //se nella tendona della linea scelgo la riga vuota, svuoto le select di percorso 
  if(!linea){ cleanDdl('percorso'); }
  
  
  
  //Riccardo e Paolo: rileggo i parametri per evitare dopo le clean
  var fermata  = document.getElementById("fermata").value;     
  var linea    = document.getElementById("linea").value;
  var percorso = document.getElementById("percorso").value;
  
  //Riccardo: rendo invisibile
  //if (!fermata)  {document.getElementById("fermatatr").style.cssText="display:none";}
  //if (!linea)    {document.getElementById("lineatr").style.cssText="display:none";}
  //if (!percorso) {document.getElementById("percorsotr").style.cssText="display:none";}
      
  
  
  //controller porting ricerca_comune.cgi 18/07/2006 ore 11:11 righe 75-105
  var arr_method = new Array();
  var arr_param = new Array();
  var im =0; var ip = 0;var it = 0;
  
  if(comune){  
  	// FERMATE
    if (!js_in_array('fermata', arr_exclude)) {
      //ricerca fermata non esclusa
      arr_method[im++] = 'getElencoFermateByComuneSoap';
      arr_param[ip++] = new Array( {name:'comune', value:comune} );
      arr_target[it++] = 'fermata';
    } 
      
    // LINEE: se scelgo un comune, valorizzo le select a cascata
    if (!js_in_array('linea',arr_exclude)) {
      //ricerca linea non esclusa
      if (fermata) { 
      	  //se ho scelto la fermata, prendo le linee che passano per essa
          arr_method[im++] = 'getElencoLineeByFermataSoap';
          arr_param[ip++] = new Array( {name:'fermata', value:fermata} );
          arr_target[it++] = 'linea';
      } else { 
      	  //non ho scelto la fermata, prendo le linee passanti per il comune scelto
          arr_method[im++] = 'getElencoLineeByComuneSoap';
          arr_param[ip++] = new Array( {name:'comune', value:comune} );
          arr_target[it++] = 'linea';
      }
    } 
    
    // PERCORSI
    if (!js_in_array('percorso', arr_exclude)) {
      //ricerca percorso non esclusa
      if (linea) {
      	  // se ho scelto la linea, valorizzo i percorsi
          arr_method[im++] = 'getElencoPercorsiByLineaInComuneSoap';
          arr_param[ip++] = new Array( {name:'linea', value:linea}, {name:'comune', value:comune} );
          arr_target[it++] = 'percorso';
      }
    }
    
  }
  
  
  
  callSoapMethods(arr_method,arr_param,arr_target);
}

// FrontController js per la RICERCA IN BASE ALLA LINEA per la chiamata dei metodi remoti
// resetta i valori delle select e delle label se gli viene passato il valore booleano reset = true
// chiama il metodo solo se questo non e' stato escluso dai metodi chiamabili (arr_exclude) 
// cioe' se una tendina ha un solo valore questa autoesclude i propri metodi remoti dai metodi chiamabili in modo che non ci siano
// chiamate inutili
function ajaxSoapRicercaLinea(reset){
  CONFIG_CONTROLLER = 'ajaxSoapRicercaLinea';
  CONFIG_NUM_TARGET = 1;

  if(reset){
       arr_exclude = new Array();
       cleanDdl('percorso');
       cleanLabel('labelNPercorsi');
  }

  //parametri
  var linea    = document.getElementById("linea").value;

  //controllo valori
  if(!linea){
       //document.getElementById("percorsotr").style.cssText="display:none"; //Riccardo: rendo invisibile
       arr_exclude = new Array();
       cleanDdl('percorso');
       return;
  }
  //controller semplice
  var arr_method = new Array();
  //var arr_target = new Array();
  var arr_param = new Array();
  var im =0; var ip = 0;var it = 0;
  
  if (!js_in_array('percorso',arr_exclude))
  if (linea) {
      arr_method[im++] = 'getElencoPercorsiByLineaSoap';
      arr_param[ip++] = new Array(
                        {name:'linea', value:linea}
                        );
      arr_target[it++] = 'percorso';
  }
  callSoapMethods(arr_method,arr_param,arr_target);
  
}
// analizza i metodi remoti da chiamare e invoca la funzione wsCall. 
//Se e' l'ultima chiamata passa il parametro isLast valorizzato a true
function callSoapMethods(arr_method,arr_param,arr_target){

  var last = false;
  onLoading();
  for(var xmethod=0;xmethod<arr_method.length;xmethod++){
      
    if(xmethod == arr_method.length -1) last = true; //isLast ora è true
    
    //ora ho i metodi da chiamare e i relativi parametri
    if(debug>=2) alert("Lancio metodo: " + arr_method[xmethod]);
    if(debug>=2) alert("Parametri: " + arr_param[xmethod]);
    if(debug>=2) alert("Target: " + arr_target[xmethod]);
    wsCall(arr_method[xmethod], arr_param[xmethod], arr_target[xmethod], last);
    if(debug>=2) alert("Aspetta il popolamento della ddl: " + arr_target[xmethod]);
    

  }
}

// funzione che viene chiamata quando tutti i webservices sono stati chiamati
// nasconde il loading
// popola le label (Percorsi/Linee/Fermate)
function soapCallBack(){
    onLoaded(); 
    //Riccardo e Paolo: la costruzione messaggi avviene al termine della popolazione delle liste: altrim errore!
    //msgPercorsi(); 
    //msgLinee();
    //msgFermate();
}

// funzione che invoca il web service.
// prende come paramteri
// metodo da invocare : string
// parametri da passare : array/object
// ws_target e' l'id della select obiettivo : string
// islast serve per invocare la funzione di callBack : boolean
function wsCall(metodo, parametri, ws_target, islast){
    
    var records;
    var wscall;
    var nsuri;
    var qn_op;
    var qn_op_resp;
    var vhost = window.location.host;
    wscall = new WS.Call('http://'+vhost+'/cgi-bin/territorio-provto/orario/soap.cgi'); 
    nsuri = 'Orario';
    
    qn_op = new WS.QName(metodo,nsuri);
    qn_op_resp = new WS.QName(metodo+'Response',nsuri);
    
    wscall.invoke_rpc(
      qn_op,
      parametri,
      null,
      function(wscall,envelope) {
        //onLoading();
        
        if(debug>=1) innerSoap(arguments[2],'soap');
        records = envelope.get_body().get_all_children()[0].get_all_children();
        if(debug>=2) alert("il Target è: " + ws_target);
        elaboraDati(records,ws_target);       
        if(islast == true) {	soapCallBack(); }
      }
    );
    if(debug>=3){
        for(var zz in wscall){
            alert("Capiamo wscall?:" + wscall[zz]);
        }
    }
    
    
}
// serve per convertire in un array js i dati xml della risposta soap
// parsa tutti i dati per la funzione checkBase64
// una volta popolato l'array js questo viene passato a popolaDdl
function elaboraDati(records,ws_target){
    var dati = Array();
    if(debug>=2) alert("Elaboro i dati di: " + ws_target);
    for(var x in records){
      if(typeof(records[x])== "object"){
          if(debug>=3) alert("Elaboro il record : " + x);
          dati[x] = records[x].get_all_children();
          for(y=0;y<dati[x].length;y++){
              dati[x][y] = checkBase64(dati[x][y]);
          }
      }
    }
    if(debug>=2) alert("Dati: " + dati);
    popolaDdl(dati,ws_target);
    return true;
}
// svuota una select 
function cleanDdl(element){
     var ddl = document.getElementById(element);
     var parenteid = ddl.parentNode.id;
     var parente = document.getElementById(parenteid);
     var nuovo = ddl.cloneNode(false);
     parente.replaceChild(nuovo, ddl); 
     ddl = nuovo;
     ddloption = document.createElement("option");
     ddloption.setAttribute("value","");
     ddloption.appendChild(document.createTextNode(""));
     ddl.appendChild(ddloption);
 
     
}
// passati i dati sottoforma di array (id/value) popola una select con id uguale a ws_target
// NB : se i dati di una select sono uguali a 1 non viene valorizzata la option vuota e vengono disabilitati tutti i metodi remoti coinvolti
// da questa select
// se i dati sono uguali a 1 popola arr_exclude con il valore del ws_target : if(!js_in_array(ws_target,arr_exclude)) arr_exclude[arr_exclude.length++] = ws_target;
// se i dati sono uguali a 1 chiama il FRONT_CONTROLLER delegato : eval(CONFIG_CONTROLLER + '();');
function popolaDdl(dati,ws_target){
      if(debug>=2) alert("Sto per popolare: " + ws_target);
      
      var exvalue = document.getElementById(ws_target).value;
      var ddl = document.getElementById(ws_target);
      var parenteid = ddl.parentNode.id;
      var parente = document.getElementById(parenteid);
      var nuovo = ddl.cloneNode(false);
          
      parente.replaceChild(nuovo, ddl); 
      ddl = nuovo;
      
      var ddloption = null;
      
      if(dati.length > 1){
        //aggiungo un valore vuoto
        ddloption = document.createElement("option");
        ddloption.setAttribute("value","");
        ddloption.appendChild(document.createTextNode(""));
        ddl.appendChild(ddloption);
      } else {
        //se la select ha 1 valore, popola arr_exclude con il valore del ws_target
        if(!js_in_array(ws_target,arr_exclude)) {arr_exclude[arr_exclude.length++] = ws_target; }
      }

      for(x=0;x<dati.length;x++){
         
         ddloption = document.createElement("option");
         ddloption.setAttribute("value",dati[x][1].element.childNodes[0].nodeValue.toUpperCase());
         if(exvalue == dati[x][1].element.childNodes[0].nodeValue) ddloption.setAttribute("selected", "selected");
         ddloption.appendChild(document.createTextNode(dati[x][0].element.childNodes[0].nodeValue.toUpperCase()));
         ddl.appendChild(ddloption);
				 if (ws_target == 'linea' || ws_target == 'fermata') {
				 	 //se trovato 1 fermata, cerco anche i percorsi				 	
				 	 //se trovato 1 linea, cerco anche i percorsi
           if(dati.length < 2 && arr_exclude.length < CONFIG_NUM_TARGET) {
           	 eval(CONFIG_CONTROLLER + '();'); //valorizza a cascata nel caso di unica scelta per la linea 
           }	 
         }
      }
       
       // Riccardo e Paolo: esegue la popolazione dei messaggi direttamente       
       if (ws_target == "fermata") { msgFermate(); }
       if (ws_target == "linea") { msgLinee();  }
       if (ws_target == "percorso") {msgLinee();  msgPercorsi(); }
       //Riccardo: rendo visibile
       if (document.getElementById(ws_target)) {document.getElementById(ws_target+"tr").style.cssText="display:table-row";}
      
      return;
}
// restituisce il testo codificato in base 64 in codifica standard
function checkBase64(record){
      //alert(record.element.getAttribute("xsi:type"));
      if(record.element.getAttribute("xsi:type") == 'SOAP-ENC:base64'){
          var jsBase64 = new JavaScriptBase64;
          jsBase64.JavaScriptBase64("");
          jsBase64.string = record.element.childNodes[0].nodeValue;
          var dec = jsBase64.decode();
          var dectrim = dec.substring(0,dec.length-1);
          var dectextnode = document.createTextNode(dectrim);
          var oldtextnode = record.element.childNodes[0];
          //alert(oldtextnode.nodeName);
          //record.element.replaceChild(dectextnode,oldtextnode);
          //record.element.removeChild(oldtextnode.nodeName);
          //record.element.appendChild(dectextnode);
          //record.element.innerHTML(dectextnode);
          //alert(record.element.childNodes[0].nodeValue);
          record.element.childNodes[0].nodeValue = dectrim;
          //alert(record.element.childNodes[0].nodeValue);
          
      }
      return record;
}
// funzione per il debug dei messaggi soap - ATTIVATA SOLO SE LA VARIABILE GLOBALE debug E' > 1
function innerSoap(text,id){
      var dom = document.getElementById(id);
      var div = document.createElement("div");
      div.setAttribute("style","border-bottom:1px solid black;");
      div.appendChild(document.createTextNode(text));
      dom.appendChild(div);
}
//inserisce un testo nella label indicata nell'argomento
function innerMsg(text,id){
      var dom = document.getElementById(id);
      dom.innerHTML = text;
}
// svuota la label indicata in argomento
function cleanLabel(id){
    innerMsg("",id);    
}
// popola la label "label" con un messaggio
function msgLinee(){
    var idlinea    = document.getElementById("linea");
    if(idlinea){ 
    	   if (document.getElementById('lineatr')) {// Riccardo: Nella ricerca per comune costruisce la label
    	   	var NLinea = document.getElementById("linea").options.length - 1;
          if(NLinea == 0) { var NLinea = 1; } //nel caso di compilazione automatica
          
	  msgLinea = "(ci sono "+NLinea+" linee in corrispondenza del comune/fermata scelti) "; 
	  //alert(NLinea);
	  if(NLinea != -1){
  	  	innerMsg(msgLinea,'labelNLinee'); 
	  }
         } // Fine Riccardo 
    }	
    // Costruisco msg al fondo del form	
    var linea    = document.getElementById("linea").value;
    if(linea){
        var msgPercorso = "";
        var labelLinea = document.getElementById("linea").options[document.getElementById("linea").selectedIndex].text;
        var labelPercorso = document.getElementById("percorso").options[document.getElementById("percorso").selectedIndex].text;
        if(labelPercorso.length > 0) 
            msgPercorso = " - percorso <strong>"+labelPercorso+"</strong> - ";
        var msg = "È possibile accedere ai dati della linea <strong>"+labelLinea+"</strong>" + msgPercorso +" in tre modalità:";
        innerMsg(msg,'label');
    }
}
// popola la label labelNPercorsi con un messaggio
function msgPercorsi(){
    var linea    = document.getElementById("linea").value;
    if(linea){
        var msgPercorso = "";
        var NPercorso = document.getElementById("percorso").options.length - 1;
        if (document.getElementById("percorso")) { if (NPercorso == 0) {  var NPercorso = 1; } } // Caso unica option
        if(NPercorso > 0) {
            msgPercorso = "(ci sono "+NPercorso+" percorsi in corrispondenza della linea scelta) ";
            if(NPercorso != -1){
	    	innerMsg(msgPercorso,'labelNPercorsi');
	    }
        }
    }
}
// popola la label labelNFermate con un messaggio
function msgFermate(){
	  
    var idfermata    = document.getElementById("comune").value;
    var fermata = document.getElementById("fermata").value;
    if(idfermata){
        var msgFermata = "";
        var NFermate = document.getElementById("fermata").options.length - 1;
        if (document.getElementById("fermata")) { if (NFermate == 0) {  var NFermate = 1;  } } // Caso unica option
        if(NFermate > 0) {
            msgFermata = "(ci sono "+NFermate+"  fermate in corrispondenza del comune scelto)";
	    if(NFermate != -1){
            	innerMsg(msgFermata,'labelNFermate');
	    }
        }
    }
}

function checkFormComuni(){
	var check2 = checkValuesComuni();
	if(!check2){
		return false
	}
	var check1 = validateDate();
	if(!check1){
		return false
	}
}
function checkFormLinee(){
	var check2 = checkValuesLinee();
	if(!check2){
		return false
	}
	var check1 = validateDate();
	if(!check1){
		return false
	}
}

function validateDate(){
   
   var nome = "giorno";
   var valore = document.getElementById(nome).value;
   if(valore.length==0)return true;
   // controllo preliminare
   if(!valore.match(/\d\d\/\d\d\/\d\d\d\d/)){
   	alert('Attenzione: il campo data contiene caratteri non validi');
        return false;
   }
        
   var day = valore.substring(0,2);
   var month = valore.substring(3,5);
   var year = valore.substring(6,10);
    
   // zero based!
   month = month -1;

   if((month > 11) || (day>31)){
   	alert('Attenzione: la data inviata non risulta valida');
        return false;
   }
        


   var myDate = new Date();
   myDate.setFullYear(year, month, day);

   if(myDate.getMonth() != month){
 	alert('Attenzione: la data inviata non risulta valida');
        return false;
   }
   return true;
}
// verifica che alemno la linea sia stata scelta
function checkValuesLinee(){
    var linea    = document.getElementById("linea").value;
    var idform    = document.getElementById("ricercaComune");
    
    if(!linea){
            alert("Devi selezionare una linea per proseguire");
            return false;
    }
    return true;
    
}
// verifica che alemno il comune sia stato scelto
function checkValuesComuni(){
    var linea    = document.getElementById("linea").value;
    var comune    = document.getElementById("comune").value;
    
    if(!comune){
        alert("Devi selezionare un comune per proseguire");
        return false;
    }
    if(!linea){
        alert("Devi selezionare una linea per proseguire");
        return false;
    }
    return true;
    
}
// matcha una stringa in un array - torna true se la stringa e' presente
function js_in_array(the_needle, the_haystack){
        var the_hay = the_haystack.toString();
        if(the_hay == ''){
            return false;
        }
        var the_pattern = new RegExp(the_needle, 'g');
        var matched = the_pattern.test(the_haystack);
        return matched;
}
