//##################################################################################
//## FORM SUBMIT WITH AJAX                                                        ##
//## @Author: Simone Rodriguez aka Pukos <http://www.SimoneRodriguez.com>         ##
//## @Version: 1.2                                                                ##
//## @Released: 28/08/2007                                                        ##
//## @License: GNU/GPL v. 2 <http://www.gnu.org/copyleft/gpl.html>                ##
//##################################################################################


function xmlhttpPost(strURL,formname,responsediv,responsemsg) {
    
    var xmlHttpReq = false;
    var self = this;
    // Xhr per Mozilla/Safari/Ie7
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // per tutte le altre versioni di IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
          // Quando pronta, visualizzo la risposta del form
          updatepage(self.xmlHttpReq.responseText,responsediv);
        }else{
          // In attesa della risposta del form visualizzo il msg di attesa
          //alert(self.xmlHttpReq.responseText);
          updatepage(responsemsg,responsediv);
          //alert(self.xmlHttpReq.readyState);
        }
    }
    self.xmlHttpReq.send(getquerystring(formname));
}

function getquerystring(formname) {
    var form = document.forms[formname];
	var qstr = "";

    function GetElemValue(name, value) {
        qstr += (qstr.length > 0 ? "&" : "")
            + escape(name).replace(/\+/g, "%2B") + "="
            + escape(value ? value : "").replace(/\+/g, "%2B");
            //+ escape(value ? value : "").replace(/\n/g, "%0D");
    }
	
	var elemArray = form.elements;
    for (var i = 0; i < elemArray.length; i++) {
        var element = elemArray[i];
        var elemType = element.type.toUpperCase();
        var elemName = element.name;
        if (elemName) {
            if (elemType == "TEXT"
                    || elemType == "TEXTAREA"
                    || elemType == "PASSWORD"
                    // || elemType == "BUTTON"
                    // || elemType == "RESET"
                    // || elemType == "SUBMIT"
                    || elemType == "FILE"
                    || elemType == "IMAGE"
                    || elemType == "HIDDEN")
                GetElemValue(elemName, element.value);
            else if (elemType == "CHECKBOX" && element.checked)
                GetElemValue(elemName, element.value ? element.value : "On");
            else if (elemType == "RADIO" && element.checked)
                GetElemValue(elemName, element.value);
            else if (elemType.indexOf("SELECT") != -1)
                for (var j = 0; j < element.options.length; j++) {
                    var option = element.options[j];
                    if (option.selected)
                        GetElemValue(elemName, option.value ? option.value : option.text);
                }
        }
    }
    return qstr;
}
function updatepage(str,responsediv){
    
    document.getElementById(responsediv).style.display = 'block';
    document.getElementById(responsediv).innerHTML = str;
}

//#################################

  function getEleId(element_id){
    var elemento;
    
    if (document.getElementById){
      
      // If exist getElementById method use it and return the given element handle
      elemento = document.getElementById(element_id);
    }else{ 
      // User browser doesn't support the getElementById method
      elemento = document.all[element_id];
    }
    
    return elemento;
    
  } // function getEleId ends here

//#################################

/*************************************************************************************************************
 * valida_mailBis(campo, alertmsg)                                                                           *
 *************************************************************************************************************
 * Autore: Passaglia Massimiliano                                                                            *
 * Data creazione: 31/08/2004                                                                                *
 * Questa funzione controlla il valore inseito, l'idirizzo viene validato se:                                *
 * contiene il carattere "@"                                                                                 *
 * contiene un punto "."                                                                                     *
 * il numero di caratteri dopo il punto deve essere maggiore di uno e minore di 4                            *
 *                                                                                                           *
 *********************************************Esempio*********************************************************
 * Da inserire ne campo da validare                                                                          *
 * onBlur="valida_mailBis(this, 'Attenzione! La mail inserita non è valida.');"                              *
 *                                                                                                           *
 *************************************************************************************************************/
function valida_mailBis(valore, alertmsg){
  
  var espressione;
  espressione= /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  
  if (valore != ""){
    if (espressione.test(valore) == false){
      alert(alertmsg);
      //campo.focus();
      //campo.select();
      return false;
    }else{
      return true;
    }
  }
  
  // di default ritorna false
  return false;
  
}

//#################################
function submitForm(form){

  v_form = getEleId(form);
  php_func = 'php/function/' + v_form.phpFunc.value;
  
  var fields = {};
  var info_mail = "";
  var resp_div = "";
  var test = false;
  
  if(!controlla_form(v_form)){
    test = false;
  }else{
    info_mail = v_form.mail_field.value;
    if(!valida_mailBis(getEleId(info_mail).value, 'Attenzione! La mail inserita non e\' valida.')){
      test = false;
    }else{
      test = true;
    }
  }
  
  
  if (test){
    resp_div = v_form.responsediv.value;
    
    if (resp_div.indexOf(',') >= 1){
      fields = resp_div.split(','); 
      for(var a = 0, b = fields.length; a < b; a++) {
        getEleId(fields[a]).innerHTML = '';
      }
    }else{
      fields[0] = resp_div;
    }
    //         (strURL,formname,responsediv,responsemsg)
    xmlhttpPost(php_func, form, 'contact_ana', 'Please wait...');
    //xmlhttpPost(php_func, form, 'testMail', 'Please wait...');
  }
  
  return false;
  
}