/*
esegue la post degli inpu della form passata come parametro (utilizzandone anche l'action)
ed assegna come callback la funzione il cui nome è contenuto nel parametro callbackName
*/
function postFormData( formElem, callbackName) {
    // composizione dei parametri
    var formParam = "dosearch=true";

    var formInput;
    for( var i=0; i<formElem.elements.length; i++ )
    {
        formInput = formElem.elements[i];
        if (!formInput.disabled) {
            if( formInput.type == 'text' )
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.value);
            else if( formInput.type == 'hidden' )
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.value);
            else if( formInput.type == 'radio' && formInput.checked )
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.value);
            else if (formInput.type == 'checkbox' && formInput.checked )
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.value);
            else if( formInput.type == 'select-one' && formInput.options[ formInput.selectedIndex ].value != "" )
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.options[ formInput.selectedIndex ].value);
            else if( formInput.type == 'select-multiple' )
            {
                for( var j=0; j<formInput.options.length; j++ )
                if( formInput.options[j].selected )
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.options[j].value);
            }
            else if( formInput.type == 'textarea' ) {
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.value);
            }
            else;
                //alert( formInput.name + "/" + formInput.type + " non supported" );
        }

    }

    // alert( formParam );
    // start dell'immagine di loading
    startLoading();

    /*
    alert(
            "formParam = " + formParam + "\n" +
            "action = "  + formElem.action + "\n"
    );
    */

    // esecuzione della richiesta
    req = getXmlHttp();

    if(req!=null) {
        req.onreadystatechange = eval( callbackName );
        req.open( "post", formElem.action, true);
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send( formParam );
    }

    return false;
}

/*
funzione per testare il loading: ritarda il callback
attualmente non utilizzata
*/
function manageDoSearchTimeout() {
    window.setTimeout("manageDoSearch()", 10);
}

/*
callback della richiesta di ricerca
costruisce una nuova tabella con nuovi valori
*/
function manageDoSearch() {
    document.getElementById('searchResults').innerHTML = '';
    // visualizzazione dei risultati
    if (req.readyState == 4) {
        if (req.status == 200) {
            //alert("manageDoSearch");
            var resText = trim(req.responseText);
            var queryResult = eval( resText );
            //tolgo il vecchio risultato
            createTable(queryResult);
        }
        else {
            //todo: completare la visualizzazione dei messaggi di errore
            createErrorMessage( req.responseText );
            //alert("stopping...");
        }
        stopLoading();
    }
}

/*
crea la tabella
*/
function createTable( queryResult ) {
    //alert("createTable");
    searchResultDiv = document.getElementById("searchResults");
    searchResultDiv.innerHTML = queryResult.getPaginazione();
}

var selElem;

function reloadOptions(removeFirst, url, val, selectElement, parentSelect){
    var lastRemove = 1;
    //alert('selectElement = ' + selectElement);
    if(removeFirst) lastRemove = 0;
    selElem = document.getElementById(selectElement);
    //alert(selElem.id);
    if(val == null || val == "") {
        for( i=0; i< parentSelect.options.length; i++) {
            var optVal = parentSelect.options[i].value;
            url+="&idArr="+optVal;
        }
    }
    else url+="id="+val;

    for(i=selElem.options.length; i>=lastRemove; i--){
        selElem.remove(i);
    }

    //alert(url);
    getUrl( url, "manageFillOptions" );

}

var receiver;
var container;

function reloadLinkedOptions(formElem, url, receiverId, containerId) {
    receiver = document.getElementById(receiverId);
    container = document.getElementById(containerId);
    var formParam = "";

    var formInput;
    for( var i=0; i<formElem.elements.length; i++ )
    {
        formInput = formElem.elements[i];
        if (!formInput.disabled) {
            if( formInput.type == 'text' )
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.value);
            else if( formInput.type == 'hidden' )
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.value);
            else if( formInput.type == 'radio' && formInput.checked )
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.value);
            else if (formInput.type == 'checkbox' && formInput.checked )
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.value);
            else if( formInput.type == 'select-one' && formInput.options[ formInput.selectedIndex ].value != "" )
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.options[ formInput.selectedIndex ].value);
            else if( formInput.type == 'select-multiple' )
            {
                for( var j=0; j<formInput.options.length; j++ )
                if( formInput.options[j].selected )
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.options[j].value);
            }
            else if( formInput.type == 'textarea' ) {
                formParam += "&" + formInput.name + "=" + encodeURIComponent(formInput.value);
            }
            else;
                //alert( formInput.name + "/" + formInput.type + " non supported" );
        }

    }
    url = url + formParam;
    //alert(url);
    getUrl( url, "manageFillLinkedOptions");

}

function manageFillLinkedOptions() {

    if (req.readyState == 4) {
        if (req.status == 200) {
            //alert("manageFillOptions");
            var resText = trim(req.responseText);
            var resultArray = eval( "( " + resText + " ) " );

            for(i=receiver.options.length; i>=0; i--){
                receiver.remove(i);
            }
            for(i=container.options.length; i>=0; i--){
                container.remove(i);
            }
            for(var i=0; i<resultArray.options.length; i++ ){
                // container e receiver sono i due elementi select da riempire
                if(resultArray.options[i][2]== "1") addOption(receiver, resultArray.options[i][1], resultArray.options[i][0]);
                else addOption(container, resultArray.options[i][1], resultArray.options[i][0]);

            }
            if(resultArray.message != null){
                 document.getElementById("message").innerHTML=resultArray.message;
                 document.getElementById("message").style.display= "block";
                 window.setTimeout('document.getElementById("message").style.display="none"',2000);
            }

        }
        else {
            //todo: completare la visualizzazione dei messaggi di errore
            //createErrorMessage( req.responseText );
            receiver = null;
            container = null;
            //alert("stopping...");
            stopLoading();
            return false;
        }
        receiver = null;
        container = null;
        stopLoading();

    }
}

function manageFillOptions() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            //alert("manageFillOptions");
            var resText = trim(req.responseText);
            var resultArray = eval(resText);
            //tolgo il vecchio risultato
            for(var i=0; i<resultArray.length; i++ ){
                addOption(selElem, resultArray[i][1], resultArray[i][0]);
            }
        }
        else {
            //todo: completare la visualizzazione dei messaggi di errore
            //createErrorMessage( req.responseText );
            selElem = null;
            //alert("stopping...");
            stopLoading();
            return false;
        }

        //selElem = null;
        //alert("stopping...");
        stopLoading();
        //propago l'evento onchange all'oggetto ricaricato
        onchangeFireEvent(selElem);
    }
}

function onchangeFireEvent(idElement){
    var fireOnThis = idElement;
    // controllo le compatibilità dei browsers
    // creo l'event object che deve essere startato
    if( document.createEvent )
    {
        var evObj = document.createEvent('HTMLEvents');
        evObj.initEvent( 'change', true, false );
        fireOnThis.dispatchEvent(evObj);
    } else if( document.createEventObject ) {
        fireOnThis.fireEvent('onchange');
    }
}

function addOption(selectbox,text,value )
{
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}
/*
ritorna l'altezza della finestra
*/
function getWinHeight() {
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
     myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
  return myHeight;
}

function createErrorMessage( reqText ) {
    searchResultDiv = document.getElementById("searchResults");
    searchResultDiv.innerHTML = reqText;
}


/*
Mi ritorna il valore del parametro GET a partire dal name
*/
function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (
        aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return strReturn;
}

