/*
 *  _common.js
 *      Classe per la gestione di funzionalitÃ  di utilizzo comune.
 */

var _page = "";



// **************** Set funzioni per la validazione dei campi ****************
function controllaCampi(){
if (( document.form1.nomeTF.value == 0) ||(document.form1.cognomeTF.value.length == 0) || (document.form1.emailTF.value.length == 0) || (document.form1.istitutoTF.value.length == 0) || (document.form1.viaTF.value.length == 0) || (document.form1.ncTF.value.length == 0) || (document.form1.cittaTF.value.length == 0) || (document.form1.telefonoTF.value.length == 0) || (document.form1.username_tf.value.length == 0) || (document.form1.password_tf.value.length == 0) || (document.form1.cpassword_tf.value.length == 0)  )     { alert('I campi con il simbolo * sono obbligatori');
//alert("qui e false");
return false;}
else {
//alert("qui e true");
return true;
	}
}

function validateEmail(e)
{
    if (e.length == 0)
        return false;
    if(containsSpecialChar(e)) return false;
      
    var pos = e.indexOf("@");
    if (pos>0 && e.substring(pos).indexOf(".") > 0 && e.substring(pos).indexOf(".") == e.substring(pos).lastIndexOf("."))
        return true;
    if(pos>0 && e.substring(pos).indexOf(".") > 0)
        return true;
    return false;
}

function containsSpecialChar(e){
    caratteriSpeciali = new Array("|",    "\\",    "!",   "\"",   "£",   "$",   "%",   "&",    "/",    "(",    ")",    "=",    "?",   "'",    "^",    "ì",    "<",    ">",
                                            ";", ":",   "ò",    "ç",   "à",    "°",   "è",   "é",   "+",   "*",   "ù",   "§",   "#",   "]",   "[",   "{",   "}");    
    var pos = null;
    for(i = 0; i<caratteriSpeciali.lenght; i++){
        pos = e.indexOf(caratteriSpeciali(i));
        if(pos>=0) return true;
    }
    return false;
}

function validateInsertDigitOnly(e){
    var keynum; 
    var keychar;
    var numcheck;
    if(window.event) { // IE
	keynum = e.keyCode
    } else if(e.which) { // Netscape/Firefox/Opera
	keynum = e.which
    }
    if (keynum==8) {
        return true;
    } else {
        keychar = String.fromCharCode(keynum);
        numcheck = /\D/
        return !numcheck.test(keychar)
    }
}

function validateInsertFloatDigitOnly(e){
    var keynum; 
    var keychar;
    var numcheck;
    if(window.event) { // IE
	keynum = e.keyCode
    } else if(e.which) { // Netscape/Firefox/Opera
	keynum = e.which
    }
    if (keynum==8) {
        return true;
    } else if (keynum==46) {
        return true;
    } else {
        keychar = String.fromCharCode(keynum);
        numcheck = /\D/
        return !numcheck.test(keychar)
    }
}

function validateInsertDateDigitOnly(e){
    var keynum; 
    var keychar;
    var numcheck;
    if(window.event) { // IE
	keynum = e.keyCode
    } else if(e.which) { // Netscape/Firefox/Opera
	keynum = e.which
    }

    if (keynum==8) {
        return true;
    } else if (keynum==45) {
        return true;
    } else {
        keychar = String.fromCharCode(keynum);
        numcheck = /\D/
        return !numcheck.test(keychar)
    }
}

function validateInsertCharOnly(e){
    var keynum; 
    var keychar;
    var numcheck;
    if(window.event) { // IE
	keynum = e.keyCode
    } else if(e.which) { // Netscape/Firefox/Opera
	keynum = e.which
    }
    if (keynum==8) {
        return true;
    } else {
        keychar = String.fromCharCode(keynum)
        numcheck = /\d/
        return !numcheck.test(keychar)
    }
}

function setValueFrom(objname, objto){
    from = document.getElementById(objname);
    to = document.getElementById(objto);
    //alert("setting value '"+from.value+"' to object '"+to+"'");
    to.value = from.value;
}

function assignValue(val, to){
    obj = document.getElementById(to);
    obj.value = val;
}

function ckeckMe(checkbox){
    //alert(checkbox);
    obj = document.getElementById(checkbox);
    //alert(obj);
    if (obj.checked)
        obj.value = "s";
    else
        obj.value = "n";
}


//**************funzione per il recupero della login e password ********
function recuperoPassword()
{
    DWRUtil.useLoadingMessage();
    var e = DWRUtil.getValue("email_recpwd");
    if (!validateEmail(e))
    {
        alert("L'email inserita non è valida.");
    }else
    {
        BI.inviaEmail( visualizzaEsitoRecupero, e);
e='';
    }


}

function visualizzaEsitoRecupero(esito)
{
    if (esito)
       DWRUtil.setValue("esito_recupero", "login e password inviate");
    else
       DWRUtil.setValue("esito_recupero", "<b>Impossibile il recupero.</b><br/> Si prega di contattare l'amministaratore del sito all'indirizzo <a href=\"mailto:università@carocci.it?subject=Recupero%20password\" title=\"Invia una e-mail\">università@carocci.it</a>");
}

function loadDatiUtente(page)
{
    _page = page;
    var messaggio = "Attenzione sono stati riscontrati i seguenti errori:\n";
    var valido = true;
    var str = "";

    DWRUtil.useLoadingMessage();
    var login = DWRUtil.getValue("user");
    var password = DWRUtil.getValue("password");
    
    str = check_username(login);
    if (str.length >0){
        messaggio += str;
        valido = false;      
    }
    str = check_password(password);
    if (str.length >0){
        messaggio += str;
        valido = false;      
    }
    
    if (!valido) alert(messaggio);
    else
    {
        BI.loadDatiUtente(doLoadDatiUtente, login, password); 
    }
}

function doLoadDatiUtente(esito)
{
    DWRUtil.setValue("user", "");  
    DWRUtil.setValue("password", "");
    if (!esito) {
       DWRUtil.setValue("risultato", "username o password errate !");
       alert("username o password errate !");
    }
    else
        go_to_page(_page);
}

function go_and_remember_page(str)
{
    BI.setEsitomail("");
    if (str != "")
        BI.setReturnPage(go_to_page(str), str);
    else 
        retrieveURL("./Controller.do?query=__BOOK_CAROCCI_HOME");

//document.getElementById('casaEditrice').style.color='white';   
//document.getElementById('Catalogo').style.color='white'; 
//document.getElementById('Novita').style.color='white';
//document.getElementById('Riviste').style.color='white';
//document.getElementById('Notizie').style.color='white';
//alert("  _common.js      go_and_remember_page");
//document.getElementById('Mailing').style.color='white';
BI.setPage_pubblicazioni(1);
}

function go_and_remember_page_tipo_ute(str, tipo_ute)
{
    if (tipo_ute == "0")
        BI.setTipoUte(0);
    else
        BI.setTipoUte(1);

    BI.setEsitomail("");
    if (str != "")
        BI.setReturnPage(go_to_page(str), str);
    else 
        retrieveURL("./Controller.do?query=__BOOK_CAROCCI_HOME");

    BI.setPage_pubblicazioni(1);
}

function go_to_page(str)
{
    if (str != "")
        retrieveURL("./Controller.do?query="+str);
    else
        alert("Error in go_to_page, file _common.js: Passata stringa vuota.");
}

// **************** Set funzioni per AJAX ****************

function retrieveCheckedURL(url,nameOfFormToPost) {

  //   alert("__________________________________________________");
  //convert the url to a string
  if (nameOfFormToPost!=null) {
    url=url+getCheckedFormAsString(nameOfFormToPost);
  } 


  //Do the AJAX call
  if (window.XMLHttpRequest) { 
    // Non-IE browsers
    req = new XMLHttpRequest();
    req.onreadystatechange = retrieve;
    try {
          req.open("GET", url, true); 
    } catch (e) {
      alert("Server Communication Problem\n"+e+"sono in common.js");
    }
    req.send(null);
  } else if (window.ActiveXObject) {
    // IE
   
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      req.onreadystatechange=processStateChange;
      req.open("GET", url, true);
      req.send();
    }
  }
}

function getCheckedFormAsString(formName){
        
  //Setup the return String
  returnString ="";
        
  //Get the form values
  formElements=document.forms[formName].elements;
  //alert(formElements);
  //alert(formElements.length);
        
  //loop through the array, building up the url
  //in the format '/strutsaction.do&name=value'
 
  for(var i=formElements.length-1;i>=0; --i ){
        //we escape (encode) each value
        //alert("analizzo: "+formElements[i].value);
        if (formElements[i].checked) {
            //alert("seleziono: "+formElements[i].value);
            returnString+="&" 
            +escape(formElements[i].name)+"=" 
            +escape(formElements[i].value);
        } 
        //alert("scarto: "+formElements[i].value);
        //alert(returnString);
 }
 //return the values
 return returnString; 
}


/*
 * Function takes a parameter of the URL of the server and the name 
 * of the Struts form. The URL will be called using AJAX and the values 
 * of the form passed to the server.
 */
function retrieveURL(url,home) {

//alert("URL = " + url);
//alert("HOME = " + home);

  //Do the AJAX call
  if (window.XMLHttpRequest) { 
     
    // Non-IE browsers
    req = new XMLHttpRequest();
    req.onreadystatechange = processStateChange;
    try {
        req.open("GET", url, true);
        req.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
    } catch (e) {
      alert("Server Communication Problem\n"+e+"eccezione di retrieveURL");
    }
    req.send(null);
  } else if (window.ActiveXObject) {
    // IE
    
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      req.onreadystatechange=processStateChange;
      req.open("GET", url, true);
      req.send();           
    }
  }
}

/*
 * Function takes a parameter of the URL of the server and the name 
 * of the Struts form. The URL will be called using AJAX and the values 
 * of the form passed to the server.
 */
function retrieveURLtoSet(url,home) {

//alert("URL = " + url);
//alert("HOME = " + home);

  //Do the AJAX call
  if (window.XMLHttpRequest) { 
     
    // Non-IE browsers
    req = new XMLHttpRequest();
    //req.onreadystatechange = processStateChange;
    try {
        req.open("GET", url, false);
        req.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
    } catch (e) {
      alert("Server Communication Problem\n"+e+"eccezione di retrieveURLtoSet");
    }
    req.send(null);
  } else if (window.ActiveXObject) {
    // IE
    
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      //req.onreadystatechange=processStateChangeToSet;
      req.open("GET", url, false);
      req.send();           
    }
  }
}

function retrieveURL2(url,home) {

//alert("URL = " + url);
//alert("HOME = " + home);

  //Do the AJAX call
  if (window.XMLHttpRequest) { 
     
    // Non-IE browsers
    req = new XMLHttpRequest();
    req.onreadystatechange = processStateChange2;
    try {
        req.open("GET", url, true);
        req.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
    } catch (e) {
      alert("Server Communication Problem\n"+e+"eccezione di retrieveURL");
    }
    req.send(null);
  } else if (window.ActiveXObject) {
    // IE
    
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      req.onreadystatechange=processStateChange2;
      req.open("GET", url, true);
      req.send();           
    }
  }
}

/*
Esecutore di URL HTTP
*/
function executor(url) {
//alert(url);
document.location.href = url;
}

/*
 * Is a function that converts the values on the form named in 
 * retrieveURL() into a query string suitable for posting to Struts 
 * on the server.
 */
function getFormAsString(formName){
        
  //Setup the return String
  returnString ="";
        
  //Get the form values
  formElements=document.forms[formName].elements;
  //alert(formElements);
  //alert(formElements.length);
        
  //loop through the array, building up the url
  //in the format '/strutsaction.do&name=value'
 
  for(var i=formElements.length-1;i>=0; --i ){
        //we escape (encode) each value
        returnString+="&" 
        +escape(formElements[i].name)+"=" 
        +escape(formElements[i].value);
        //alert(returnString);
 }
        
 //return the values
 return returnString; 
}


/*
 * The method name that we set before making the AJAX call. 
 * This method is called by the XMLHttpRequest/Microsoft.XMLHTTP 
 * object once the server has completed sending back its response.
 */
function processStateChange() { 
  //alert("#########       req.readyState="+req.readyState);
  if (req.readyState == 4) { // Complete

    //alert("req.status="+req.status);
    if (req.status == 200) { // OK response
    
        /* Cristiano Ceglia 08/10/2006 - gruppo di istruzioni usate rimpiazzate da innerHTML 
        //Split the text response into Span elements
        spanElements = splitTextIntoSpan(req.responseText);
        //Use these span elements to update the page
        replaceExistingWithNewHtml(spanElements);*/

        //alert("req.status="+req.status);
        //alert("response="+req.responseText);
        document.getElementById("spanContent").innerHTML=req.responseText
        BI.getAlertMessage( function(f) { if(f!="") { alert(f); BI.setAlertMessage(""); } } );        
       
    } else {
        //alert("req.responseText="+req.responseText);
        alert("SE002: Dato incongruente");
    } 
  }
}

/*
 * The method name that we set before making the AJAX call. 
 * This method is called by the XMLHttpRequest/Microsoft.XMLHTTP 
 * object once the server has completed sending back its response.
 */
function processStateChangeToSet() { 
  //alert("#########       req.readyState="+req.readyState);
  if (req.readyState == 4) { // Complete

    //alert("req.status="+req.status);
    if (req.status == 200) { // OK response
        //alert("req.status="+req.status);
        //alert("response="+req.responseText);
        BI.getAlertMessage( function(f) { if(f!="") { alert(f); BI.setAlertMessage(""); } } );        
    } else {
        alert("SE005: Dato incongruente");
    } 
  }
}

function processStateChange2() { 
  //alert("#########       req.readyState="+req.readyState);

     //   alert("req.status="+req.status);
  if (req.readyState == 4) { // Complete

    //alert("req.status="+req.status);
    if (req.status == 200) { // OK response
    
        /* Cristiano Ceglia 08/10/2006 - gruppo di istruzioni usate rimpiazzate da innerHTML 
        //Split the text response into Span elements
        spanElements = splitTextIntoSpan(req.responseText);
        //Use these span elements to update the page
        replaceExistingWithNewHtml(spanElements);*/

       // alert("req.status="+req.status);
      //  alert("req.responseText="+req.responseText);
      document.getElementById("popup").innerHTML=req.responseText


        document.getElementById("popup_acquisto").style.visibility = 'visible'; 


     //   document.getElementById("popup_acquisto").innerHTML="<b>prova popup</b>"
       
   BI.getAlertMessage( function(f) { if(f!="") { alert(f); BI.setAlertMessage(""); } } );        
       
    } else {
        alert("SE003: Dato incongruente");
     //   alert("SE002: Problem with server response:\n " + req.statusText+ "  in processStateChange  ");
    } 
  }
}

/*
 * Loops through this array of span elements, searching for <span> 
 * elements in the existing page with 'someName' and replacing them 
 * with the new content from the server. Note that we get the returned 
 * content via req.responseText for robustness (since it allows us to 
 * manipulate any text response), rather than req.responseXml (which is 
 * more powerful, but requires that you return valid XHTML or XML).
 */
function replaceExistingWithNewHtml(newTextElements){
 
  //loop through newTextElements
  for(var i=newTextElements.length-1;i>=0;--i){
  
    //check that this begins with <span
    if(newTextElements[i]. 
        indexOf("<span")>-1){
                        
                  //get the span name - sits
              // between the 1st and 2nd quote mark
              //Make sure your spans are in the format
              //<span id="someName">NewContent</span>
                  startNamePos=newTextElements[i]. 
                      indexOf('"')+1;
              endNamePos=newTextElements[i]. 
                      indexOf('"',startNamePos);
              name=newTextElements[i]. 
                      substring(startNamePos,endNamePos);

              //get the content - everything 
              // after the first > mark
              startContentPos=newTextElements[i]. 
                       indexOf('>')+1; 
              content=newTextElements[i].
                       substring(startContentPos);

               //alert("content: "+content);

             //Now update the existing Document 
             // with this element, checking that 
             // this element exists in the document
             if(document.getElementById(name)){
                        document.getElementById(name). 
                        innerHTML = content;
             }
        }
    }
}


/*
 * Loops through the response, picking out an array of 
 * <span id="someName">NewContent</span> elements.
 */
function splitTextIntoSpan(textToSplit){
 
  //Split the document
  returnElements=textToSplit. 
            split("</span>")
        
  //Process each of the elements        
  for(var i=returnElements.length-1;i>=0;--i){
                
    //Remove everything before the 1st span
    spanPos = returnElements[i]. 
             indexOf("<span");               
                
    //if we find a match, take out 
    //everything before the span
    if(spanPos>0){
          subString=returnElements[i].
              substring(spanPos);
          returnElements[i]=subString;
    } 
  }
  return returnElements;
}

function open_popup_acquisto() {
    //var stili = "top=350, left=400, width=400, height=200, status=no, menubar=no, toolbar=no scrollbar=no";
    var stili = "top=350, left=400, width=480, height=300, status=no, menubar=no, toolbar=no scrollbar=no";
    window.open("./acquisto_popup.jsp", "popup", stili);
}

//NV
function open_popup_acquisto_articoli() {
    //var stili = "top=350, left=400, width=400, height=200, status=no, menubar=no, toolbar=no scrollbar=no";
    var stili = "top=350, left=400, width=480, height=300, status=no, menubar=no, toolbar=no scrollbar=no";
    window.open("./acquisto_popup_articoli.jsp", "popup", stili);
}


/**function close_window() {
     if (req.readyState == 4) {
        window.close();
     }
}*/

function retrieveParentURL(url) {

 //   alert("__________________________________________________3");
     //Do the AJAX call
     if (window.XMLHttpRequest) {    
        // Non-IE browsers
        req = new XMLHttpRequest();
        req.onreadystatechange = parent_processStateChange;
        try {
            req.open("GET", url, true);
            req.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
        } catch (e) {
        alert("Server Communication Problem\n"+e+"eccezione di refresh_parent_to_carrello");
        }
        req.send(null);
    } else if (window.ActiveXObject) {
        // IE
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = parent_processStateChange; 
            req.open("GET", url, true);
            req.send();
        }
    }
}

function parent_processStateChange() { 
  if (req.readyState == 4) { // Complete
    if (req.status == 200) { // OK response
    
        /* Cristiano Ceglia 08/10/2006 - gruppo di istruzioni usate rimpiazzate da innerHTML 
        //Split the text response into Span elements
        //spanElements = splitTextIntoSpan(req.responseText);
        //Use these span elements to update the page
        //replaceExistingWithNewHtml(spanElements);*/
        
        if(window.opener && window.opener.open && !window.opener.closed) 
        {
            var opener = window.opener;
            opener.document.getElementById("spanContent").innerHTML=req.responseText;                        
        } else {                  
            alert('Finestra principale chiusa!');
        }
    } else {        
       // alert("Req1="+req.responseText);
        alert("SE004: Dato incongruente");
    } 
    window.close();
  }  
}

function sleep(n)
{
    var now = new Date();
    var exitTime = now.getTime() + (n*1000);
    while (true) {
        now = new Date();
            if (now.getTime() > exitTime) return;
    }
}
function gestcataloghi(sito,dettaglio,percorso){   
    var url = './allegatiDownload?act=catalogo&percorso='+percorso+'&sito='+sito+'&dettaglio='+dettaglio;
 // window.open(url, '_self');
    window.open(percorso);
// retrieveURL('./Controller.do?query=catalogo&percorso='+percorso+'&sito='+sito+'&dettaglio='+dettaglio+'&path=/TEMPLATE/ARGOMENTO/argomentopdf.jsp'); 
//commentata perchè dava un messaggio di dato incongruente all'apertura dei file pdf di catalogo
}

