spyweb_addrScriptTraceur = "/cgi-bin/spyweb.pl";
spyweb_idPage=-1;        //id number of the page
spyweb_timeToReload=3000;    //number of seconds before next reload
spyweb_idTimeout=0;        //id of reload thread
spyweb_nbCheck=0;
spyweb_refreshForced=0;
//authentified=0;

// main function

var parameters = window.location.search.split( "&");
var shouldTrace = 0;
var dontTrace = 0;

//check if the traceur must be enable
for ( i=0; i<parameters.length; i++)
{
    var keysValues = parameters[i].split( "=");
    var key = keysValues[0];
    if ( key.indexOf("trace") >= 0)
    {
        dontTrace = ( keysValues[1] == "no");
    }
}
if ( spyweb_lire_cookie("CGISESSID")!="" && !dontTrace)
{
    shouldTrace = 1;
}

//check the port
var spyweb_url = String(document.location).split(":");
if (spyweb_url.length == 3)
{
    var port = spyweb_url[2].split("/");
    if ( port!=80 && port!=440)
    {
        //alert("on ne trace pas");
        shouldTrace=0;
    }
}

//if trace=no then we exit
if ( shouldTrace == 1)
{
    spyweb_traceur();
}
else
{
   // exit();
}

//document.getElementById( "reloadTime").innerHTML = "Reload Time : " + spyweb_timeToReload ;
//check if we have a session

function spyweb_traceur()
{
    if ( spyweb_lire_cookie( "CGISESSID") == "")
    {
        //if not we create a new one
        spyweb_createSession();
    }
    else
    {
        //we just have to retrieve an id page
        if ( spyweb_idPage==-1)
        {
            window.setTimeout(spyweb_getCompteur, 1000);
        }
    }
}

//get an id from server and save it in a cookie
function spyweb_createSession()
{
    url = spyweb_addrScriptTraceur + "?action=createSession";
    request = new ajaxRequest( url, spyweb_saveCookie);
    request.send();
}

//save the cookie which will contains the id
function spyweb_saveCookie(object)
{
    document.getElementById( "saveCookie").innerHTML = object.xhr.responseText;
    spyweb_getCompteur();
}

//ask the server for an id of page
function spyweb_getCompteur()
{
    var request=null;
    var loc = String(document.location);
    var url = spyweb_addrScriptTraceur + "?action=getNextIdPage&CGISESSID=" +spyweb_lire_cookie( "CGISESSID")+ "&page=" + loc;
    var params="&action=getNextIdPage&page=" + loc;
    //check if we are in the manager
    //WARNING : NAME OF COOKIE DIFFERS BETWEEN OVH AND SDEV
    //ovhsessionId = spyweb_lire_cookie( "OVHSESSIONID_SDEV34");
//    if (ovhsessionId!="" && loc.indexOf("https") != -1)
    if (loc.indexOf("https") != -1 || loc.indexOf(".cgi") != -1 )
    {
        var content = "";
        var elem = document.getElementsByTagName('html');
        elem = elem[0];
        for(i=0; i<elem.childNodes.length; i++){
            content += elem.childNodes.item(i).innerHTML;
        }
/*        elem = document.getElementsByTagName('body');
        elem = elem[0];
        for(i=0; i<elem.childNodes.length; i++){
            content += elem.childNodes.item(i).innerHTML;
        } 
*/      
//        content = content.replace(/href=\"/g,"href=\"https://www.ovh.com/managerv3/" );
//        content = content.replace(/src=\"/g,"src=\"https://www.ovh.com/managerv3/" );
        encContent = Base64.encode(content);
        url = spyweb_addrScriptTraceur;
//        params+="&CGISESSID=" +spyweb_lire_cookie( "CGISESSID")+ "&ovhsessionId=" + ovhsessionId + "&page=" + loc + "&content=" + encContent;
        params+="&CGISESSID=" +spyweb_lire_cookie( "CGISESSID")+ "&page=" + loc + "&content=" + encContent;
        request = new ajaxRequest( url, spyweb_gotCompteur, 'POST');
    }
    else
    {
        request = new ajaxRequest( url, spyweb_gotCompteur);
    }
    request.send(params);
}

//save the page's id
function spyweb_gotCompteur(object)
{
    spyweb_idPage = object.xhr.responseText;
//    document.getElementById( "saveCookie").innerHTML = object.xhr.responseText;
    spyweb_forceAllPageRefresh();
    spyweb_checkTimeoutValue();
}

function spyweb_forceAllPageRefresh()
{
    document.cookie = "Refresh_now=" +spyweb_idPage+"; path=/";
}

//check every second the value of the timetoReload, which is stored in a cookie
function spyweb_checkTimeoutValue()
{
    // read the value in the cookie
    spyweb_timeToReload = spyweb_lire_cookie( "Timeout");
    refreshNow = spyweb_lire_cookie( "Refresh_now");
//    ovhsessionId = spyweb_lire_cookie( "OVHSESSIONID_SDEV34");
    // if cookie is not yet present
    if ( spyweb_timeToReload=="")
    {
        // we create one
        document.cookie = "Timeout=30; path=/";
        spyweb_timeToReload=30;
    }
    
    if ( spyweb_nbCheck>=spyweb_timeToReload)
    {
        spyweb_nbCheck=0;
        spyweb_reloadTraceur();
    }
    if ( refreshNow!="" && refreshNow!=spyweb_idPage && refreshNow!=-1 && !spyweb_refreshForced)
    {
        spyweb_refreshForced=1;
        spyweb_reloadTraceur();
    }
    
    if (refreshNow==-1)
    {
        spyweb_refreshForced=0;
    }
    spyweb_nbCheck++;
    if ( spyweb_lire_cookie('CGISESSID') != '')
    {
        window.setTimeout( spyweb_checkTimeoutValue, 1000);
    }
}

// informs the server that we have to change the time to reload for the specified client
function spyweb_sendCode()
{
    url = spyweb_addrScriptTraceur + "?action=createSession";
    request = new ajaxRequest( url, null);
    request.send();
    spyweb_waitForSession();
}

function spyweb_waitForSession()
{
    if (spyweb_lire_cookie( "CGISESSID")!='')
    {
        var url = spyweb_addrScriptTraceur + "?action=sendCode&CGISESSID=" +spyweb_lire_cookie( "CGISESSID")+"&codeClient=" + document.getElementById( "codeClient").value;
        var request = new ajaxRequest( url, spyweb_codeSent);
        request.send();
    }
    else
    {
         window.setTimeout( spyweb_waitForSession, 1000);
    }
}

// get the response : write the new value of the time to reload and save it in a cookie
function spyweb_codeSent(object)
{
    switch(object.xhr.responseText)
    {
        case '0' :
            alert('Vous n\'etes pas connecte');
            document.cookie="CGISESSID=; expires=now; path=/;";
            break;
        case '2' :
            alert('Vous êtes déjà connecté');
            break;
        default:
            alert("Vous êtes connecté");
            document.getElementById( "saveCookie").innerHTML = object.xhr.responseText;
            document.getElementById( "divCodeSupportFG").style.display = "none";
            document.getElementById( "divCodeSupportBG").style.display = "none";
            spyweb_getCompteur();
    }
}

// informs the server that the page is still active
function spyweb_reloadTraceur()
{
    refreshNow = spyweb_lire_cookie("Refresh_now");
    if ( refreshNow==spyweb_idPage)
    {
        document.cookie = "Refresh_now=-1; path=/";
    }
//    document.getElementById( "reloadTemoin").innerHTML += ".";
    spyweb_keepPageActivity();
}

//send a request to the server to informs that the page is still active
function spyweb_keepPageActivity()
{
    var url = spyweb_addrScriptTraceur + "?action=setActif&CGISESSID=" +spyweb_lire_cookie( "CGISESSID")+ "&idPage=" + spyweb_idPage;
    var request = new ajaxRequest( url, null);
    request.send();
}

// read a cookie which is given
function spyweb_lire_cookie( CookieName)
{
    var CookieString = document.cookie;
    var CookieSet = CookieString.split (';');
    var SetSize = CookieSet.length;
    var CookiePieces;
    var ReturnValue = "";
    var x = 0;
    for ( x = 0; ((x < SetSize) && (ReturnValue == "")); x++)
    {
        CookiePieces = CookieSet[x].split ('=');
        if ( CookiePieces[0].substring (0,1) == ' ')
        {
            CookiePieces[0] = CookiePieces[0].substring (1, CookiePieces[0].length);
        }
        if (CookiePieces[0] == CookieName)
        {
            ReturnValue = CookiePieces[1];
        }
    }
    return ReturnValue;
}

function enterCodeSupport()
{
    var BGdiv = document.createElement('DIV');
    set_attribute( BGdiv, 'id', 'divCodeSupportBG');
    set_attribute( BGdiv, 'style', 'position:absolute; top: 0; left: 0;width:100%;z-index:500;background-color:black;display:block;height:100%;opacity: 0.75; filter:alpha(opacity=75);');

    document.body.appendChild( BGdiv);

    var divFG = document.createElement('DIV');
    set_attribute( divFG, 'id', 'divCodeSupportFG');
    set_attribute( divFG, 'style', 'position:absolute; top: 0; left: 0;width:100%;z-index:5000;display:block;opacity: 1.0; filter:alpha(opacity=50);text-align:center; height: 100%;');
    document.body.appendChild( divFG);

    divFG.innerHTML = ' <table width="100%" height="100%">\
        <tr><td align="center">\
            <div style="width: 600px;background: #FFD400; padding: 12px; border: 1px solid #d40000; text-align: center;">\
                <br>\
                Entrez le code fournit par notre support téléphonique afin de vous aider au mieux dans votre recherche.<br>\
                Si vous êtes arrivé par erreur, cliquez sur le bouton Annuler.<br><br>\
                <input type="text" name="codeClient" id="codeClient" size="4"/>\
                <input type="button" name="sendCode" id="sendCode" value="Envoyer" onclick="spyweb_sendCode()"/><br/>\
                <input type="button" name="cancelCode" id="cancelCode" value="Annuler" onclick="spyweb_hideDivCode()"/><br/>\
                <p id="saveCookie" name="saveCookie"></p>\
            </div>\
        </td></tr></table>';
}

function spyweb_hideDivCode()
{
    document.getElementById("divCodeSupportFG").style.display = "none";
    document.getElementById("divCodeSupportBG").style.display = "none";
}
