/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

    //POST OR GET
    //POST:
    //xmlhttp.open("POST",'http://localhost/framework/ajax/FunctionsHandler.php',true);
    //xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //xmlhttp.send("functionName="+ functionName +"&cod="+ cod +"&nocache="+nocache);

    //GET:
    //xmlhttp.open("GET",'http://localhost/framework/ajax/FunctionsHandler.php?functionName='+ functionName +'&cod='+ cod +'&nocache='+nocache,true);
    //xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //xmlhttp.send();
//
//    function parseCSV(csv)
//    {
//        //var myTxt = document.getElementById('arrayDiv').innerHTML;
//        var array = array();
//        var myArr = csv.split(',');
//        for (var i=0; i<myArr.length; i+=1)
//        {
//            document.writeln(myArr[i]+'<br />');
//        }
//    }





// contextPath = <? echo $_CONFIG['indirizzoSito'] ?>




    function PreparaDati(formId){
      stringa = "";
      var form = document.getElementById(formId);//document.forms[0];
      var numeroElementi = form.elements.length;

      for(var i = 0; i < numeroElementi; i++){
        if(i < numeroElementi-1){
          stringa += form.elements[i].name+"="+encodeURIComponent(form.elements[i].value)+"&";
        }else{
          stringa += form.elements[i].name+"="+encodeURIComponent(form.elements[i].value);
        }
      }
    }

    function AJAXReq(method,url,bool){
      if(window.XMLHttpRequest){
        myReq = new XMLHttpRequest();
      } else

      if(window.ActiveXObject){
        myReq = new ActiveXObject("Microsoft.XMLHTTP");

        if(!myReq){
          myReq = new ActiveXObject("Msxml2.XMLHTTP");
        }
      }
      if(myReq){
        execfunc(method,url,bool);
      }else{
        alert("Impossibilitati ad usare AJAX");
      }
    }

    function execfunc(method,url,bool){
      myReq.onreadystatechange = handleResponse;
      myReq.open(method,url,bool);
      myReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
      myReq.send(stringa);
    }

    function InviaDati(method, urlPhp){
      PreparaDati();
//      originale
//      AJAXReq("POST","getform.php",true);
      AJAXReq(method, urlPhp, true);
    }

    function handleResponse(){
      if(myReq.readyState == 4){
        if(myReq.status == 200){
          alert(myReq.responseText);
        }else{
          alert("Niente da fare, AJAX non funziona :(");
        }
      }
    }

/*
 * esempio form submit
 */

//<form method="post" action="getform.php" onsubmit="InviaDati('POST','getform.php'); return false;">
//<label>Nick</label>: <input type="text" name="nick"><br />
//<label>Email</label>: <input type="text" name="email"><br />
//<label>Link</label>: <input type="text" name="link"><br />
//<input type="submit" name="submit" value="Invia Dati" />
//</form>

















function replaceWith(str, what, replace)
{
    var totalLength = str.length;
    //alert(totalLength);
    var idx = str.indexOf( what );
    var start = idx;
    //alert(start);
    var end = str.indexOf(what);

    if (totalLength > 0 && start != -1 && end != -1)
    {
        end = end +  + what.length;
        var newString = "";
        for (i = 0; i < start; i++)
        {
            newString += str[i];
        }
        newString += replace;
        for (i = end; i < totalLength; i++)
        {
            newString += str[i];
        }
        return newString;
    }
    return str;
}


function replaceFromToLast(str, from, to, replace)
{
    var totalLength = str.length;
    //alert(totalLength);
    var idx = str.indexOf( from );
    var start = idx;
    //alert(start);
    var end = str.lastIndexOf(to);

    if (totalLength > 0 && start != -1 && end != -1)
    {
        end = end + + to.length;
        var newString = "";
        for (i = 0; i < start; i++)
        {
            newString += str[i];
        }
        newString += "\n" + replace + "\n";
        for (i = end; i < totalLength; i++)
        {
            newString += str[i];
        }
        return newString;
    }
    return str;
}

function replaceFromTo(str, from, to, replace)
{
    var totalLength = str.length;
    //alert(totalLength);
    var idx = str.indexOf( from );
    var start = idx;
    //alert(start);
    var end = str.indexOf(to);

    if (totalLength > 0 && start != -1 && end != -1)
    {
        end = end + + to.length;
        var newString = "";
        for (i = 0; i < start; i++)
        {
            newString += str[i];
        }
        newString += "\n" + replace + "\n";
        for (i = end; i < totalLength; i++)
        {
            newString += str[i];
        }
        return newString;
    }
    return str;
}

function removeAll(str, from, to)
{
    var totalLength = str.length;
    //alert(totalLength);
    var idx = str.indexOf( from );
    var start = idx;
    //alert(start);
    var end = str.indexOf(to);

    if (totalLength > 0 && start != -1 && end != -1)
    {
        end = end + + to.length;
        var newString = "";
        for (i = 0; i < start; i++)
        {
            newString += str[i];
        }
        newString += "\n";
        for (i = end; i < totalLength; i++)
        {
            newString += str[i];
        }
        return newString;
    }
    return str;
}


function trimFromToSelect(oldString, newString)
{
    var string = replaceFromTo(oldString, "<select", "/select>", newString);
    return string;
}

function trimFromSelectToDiv(oldString, newString)
{
    trimFromSelectToDiv(oldString, newString, false);
}

function trimFromSelectToDiv(oldString, newString, bool)
{
    //if (oldString.indexOf("block") > -1 && bool == false)
    if (oldString.indexOf("block") > -1 && bool == false)
    {
        //alert("attenzione validazione presente! non cancellare il div!");
        alert("from: " + oldString);
        alert("To  : " + newString);
        return trimFromToSelect(oldString, newString);
    }
    if (bool == true)
    {
        if (oldString.indexOf("block") > -1)
        {
            //alert(oldString);
            var newS = replaceWith(oldString, "block", "none");
            //alert(newS);
            return newS;
        }
//        return trimFromToSelect;
    }
    var string = "";
    if (contains(oldString, "/div>"))
    {
        string = replaceFromToLast(oldString, "<select", "/div>", newString);
    }
    else
    {
        string = replaceFromToLast(oldString, "<select", "/select>", newString);
    }
    return string;
}

function contains(string, search)
{
    if (string.indexOf(search))
    {
        return true;
    }
    return false
}




/*
 * original combo
 */
/*
 *
    function combo(id, functionName, cod, csv)
    {

        var myArr = csv.split(',');
        for (var i=0; i<myArr.length; i++)
        {
            //alert(myArr[i]);
            if (document.getElementById(myArr[i]))
            {
                //document.getElementById(myArr[i]).innerHTML="trefgrsd";
            }
        }
//        document.getElementById('idRegioniDiv').innerHTML='empty';
//        document.getElementById('idProvinceDiv').innerHTML='empty';
//        document.getElementById('idComuniDiv').innerHTML='empty';
        if (id.length==0)
        {
            document.getElementById(id).innerHTML="";
            return;
        }
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4)
            {
                if (xmlhttp.status==200)
                {
                    document.getElementById(id).innerHTML=xmlhttp.responseText;
                }
                else
                {
                    document.getElementById(id).innerHTML='Error HTML';
                }
            }
        }
        //xmlhttp = getXMLHttp();
        nocache = Math.random();
        // Pass the login variables like URL variable
//        xmlhttp.open("POST",'http://localhost/framework/ajax/FunctionsHandler.php',true);
        xmlhttp.open("POST",contextPath+'/framework/ajax/FunctionsHandler.php',true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send("functionName="+ functionName +"&cod="+ cod +"&nocache="+nocache);
    }

    */

    function removeFirstElementFromCSV(csv)
    {
        var idx = csv.indexOf(",");
        //alert(csv);
        //alert(idx);
        if (csv != null && csv != "" && idx == -1)
        {
//            return null;
            return "";
        }
        else if (idx > -1)
        {
            return csv.substring(idx + 1, csv.length);
        }
        //alert(csv);
        return null;
    }

    function getFirstElementFromCsv(csv)
    {
        var idx = csv.indexOf(",");
        //alert(csv);
        //alert(idx);
        if (csv != null && csv != "" && idx == -1)
        {
            return csv;
        }
        else if (idx > -1)
        {
            return csv.substring(0, idx);
        }
        //alert(csv);
        return null;
    }


    function addEvent(obj, evType, fn)
    {
        if (obj.addEventListener)
        {
            obj.addEventListener(evType, fn, false);
            return true;
        }
        else if (obj.attachEvent)
        {
            var r = obj.attachEvent("on"+evType, fn);
            return r;
        }
        else
        {
            return false;
        }
    }
//addEvent(window, 'load', foo);
//addEvent(window, 'load', bar);


    /*
     * replace only from  <select> to </select>
     */
    function combo(id, functionName, cod, csv)
    {
        if (csv == null)
        {
            start(id);
            return;
        }
        var newCsv = removeFirstElementFromCSV(csv);
        var nextId = getFirstElementFromCsv(csv);
        var nextIdDiv = nextId + "Div";
        var text = document.getElementById(nextIdDiv);
        document.getElementById(nextId).innerHTML=trimFromSelectToDiv(text.innerHTML, "", true);
        if (id.length==0)
        {
            document.getElementById(id).innerHTML="";
            return;
        }
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4)
            {
                if (xmlhttp.status==200)
                {
                    document.getElementById(id).innerHTML=trimFromSelectToDiv(document.getElementById(id).innerHTML, xmlhttp.responseText);
                    start(id);
//                    combo(nextId, functionName, null, newCsv);
                    var singleCsv = getFirstElementFromCsv(newCsv);
                    combo(nextId, functionName, null, singleCsv);
                    $('#' + nextId).blur();
                }
                else
                {
                    document.getElementById(id).innerHTML='Error HTML';
                }
            }
        }
        //xmlhttp = getXMLHttp();
        nocache = Math.random();
        // Pass the login variables like URL variable
//        xmlhttp.open("POST",'http://localhost/framework/ajax/FunctionsHandler.php',true);
        xmlhttp.open("POST",contextPath+'/framework/ajax/FunctionsHandler.php',true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send("functionName="+ functionName +"&cod="+ cod +"&nocache="+nocache);
    }


    function addClick(id, value, name, link, ip)
    {
        if (value.length==0)
        {
            document.getElementById(id).innerHTML="";
            return;
        }
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                document.getElementById(id).innerHTML=xmlhttp.responseText;
            }
        }
        //xmlhttp = getXMLHttp();
        nocache = Math.random();
        // Pass the login variables like URL variable
//        xmlhttp.open("GET",'http://localhost/locale/countClicks.php?name='+name+'&link='+link+'&ip='+ip+'&nocache='+nocache,true);
        xmlhttp.open("GET",contextPath+'/locale/countClicks.php?name='+name+'&link='+link+'&ip='+ip+'&nocache='+nocache,true);
        xmlhttp.send();
    }




    function rankVoto(fName, value, idVoto)
    {
//        alert(value);
        if (value.length==0)
        {
            document.getElementById('voto_'+idVoto).innerHTML="";
            return;
        }
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4)
            {
                if (xmlhttp.status==200)
                {
                    //alert("200");
                    document.getElementById('voto_'+idVoto).innerHTML=xmlhttp.responseText;
                }
                else
                {
                    //alert("Error");
                    document.getElementById('voto_'+idVoto).innerHTML='Error HTML';
                }
            }
        }
        //xmlhttp = getXMLHttp();
        nocache = Math.random();
        // Pass the login variables like URL variable
//        xmlhttp.open("POST",'http://localhost/framework/ajax/FunctionsHandler.php',true);
        xmlhttp.open("POST", contextPath+'/framework/ajax/FunctionsHandler.php',true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send("fName="+ fName +"&idVoto="+ idVoto +"&value="+ value +"&nocache="+nocache);
    }


    function addNewElementToMap(fName, actualId, latValue, lngValue, points)
    {
        //alert(latValue + ' - ' + lngValue);
        if (latValue.length==0 && lngValue.length==0)
        {
            //document.getElementById('voto_'+idVoto).innerHTML="";
            return;
        }
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4)
            {
                if (xmlhttp.status==200)
                {
                    //alert("200");
                    var oScript = document.createElement('script');
                    oScript.text = xmlhttp.responseText;
                    document.getElementsByTagName("head").item(0).appendChild(oScript);
                    //document.getElementById('dynamicScriptGoogleMaps').innerHTML=xmlhttp.responseText;
                }
                else
                {
                    //alert("Error");
                    //document.getElementById('voto_'+idVoto).innerHTML='Error HTML';
                }
            }
        }
        //xmlhttp = getXMLHttp();
        nocache = Math.random();
        // Pass the login variables like URL variable
//        xmlhttp.open("POST",'http://localhost/framework/ajax/FunctionsHandler.php',true);
        xmlhttp.open("POST", contextPath+'/framework/ajax/FunctionsHandler.php',true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send("fName="+ fName +"&actualId="+ actualId +"&latValue="+ latValue +"&lngValue="+ lngValue +"&points="+ points +"&nocache="+nocache);
    }
