﻿
// Funzione di inizializzazione della chat. Si occupa di recuperare eventuali
// informazioni contenute nella chat (se è stato premuto F5 ad esempio).

var fbStyleChat__chatUpdateTimer;
var fbStyleChat__OperWantChatTimer;

function fbStyleChat_Init() {
    // Determina se il controllo è utilizzato all'interno della pagina.
    if (!fbStyleChat_IsUsed()) {
        alert('UserControl fbStyleChat non utilizzato. Non è necessario richiamare fbStyleChat_Init()');
        return (false);
    }
    fbStyleChat__OperWantChatTimer = setInterval("fbStyleChat_CheckOperInterval();", 5000);
    return true;
}

// PROMETHEUS: "Gli operatori interni saranno ora in grado di aprire la chat relatia
// al cliente"
function fbStyleChat_CheckOperInterval() {
    var MyArray = new Array();
    MyArray["opType"] = 'CheckOperIfWantToChatWithMe';
    parent.invoke(NetSell_XalpServiceUrl + '/CommonService/fbStyleChatServ.aspx', MyArray, 'fbStyleChat_CheckOperInterval_XalpCallBack', 15000,null,true);
    MyArray = null;
}
function fbStyleChat_CheckOperInterval_XalpCallBack(_xO) {
    if (_xO["fbStyleChat_RequestOperChat"] == "True") {

        // blocca temporaneamente il timer e apre la chat
        clearInterval(fbStyleChat__OperWantChatTimer);
        fbStyleChat_ShowChatWindow();
    }
    
}


function fbStyleChat_IsUsed() {
    var ObjID = document.getElementById("fbStyleChat_UserControl");
    return (ObjID != null);
}


// Questa funzione gestice il click sul pulsante di apertura della chat.
function fbStyleChat_ShowChatWindow() {

    // check se il controllo è utilizzato
    if (!fbStyleChat_IsUsed()) return false;

    // check orari di servizio
    var _d = new Date();
    var _thistime;
    if (_d.getHours() < 10) _thistime = '0' + _d.getHours();
    else _thistime = _d.getHours();
    if (_d.getMinutes() < 10) _thistime = _thistime + '0' + _d.getMinutes();
    else _thistime = _thistime +''+ _d.getMinutes();
    
    if (!((_thistime >= NetSell_ChatEnabledTime[0] && _thistime <= NetSell_ChatEnabledTime[1]) || (_thistime >= NetSell_ChatEnabledTime[2] && _thistime <= NetSell_ChatEnabledTime[3])))
        alert('La chat non è operativa in questo orario. Clicca su Contatti per maggiori informazioni su come contattarci.');
    
    var cwin = document.getElementById("fbStyleChat_ChatWindow");
    if (cwin.style.visibility == "hidden" || cwin.style.visibility == "") {
        // Avvia una sessione di chat segnalando al server che il client
        // ha aperto la finestra. Se il server riesce a registare in tempo
        // richiama la callback e mostra la finestra.
        var MyArray = new Array();
        MyArray["opType"] = 'SignalMe';
        parent.invoke(NetSell_XalpServiceUrl + '/CommonService/fbStyleChatServ.aspx', MyArray, 'fbStyleChat_SignalXalpCallBack', 15000);
        MyArray = null;
    }
    else {
        if (confirm('Attenzione: Se si chiude la finestra di chat i nostri operatori non potranno comunicare con te finché non la aprirai di nuovo.') == true) {
            // Segnala la chiusura della chat
            var MyArray = new Array();
            MyArray["opType"] = 'UnsignalMe';
            parent.invoke(NetSell_XalpServiceUrl + '/CommonService/fbStyleChatServ.aspx', MyArray, 'fbStyleChat_SignalXalpCallBack', 15000);
            MyArray = null;
            // riattiva il timer di rilevazione da operatore remoto
            fbStyleChat__OperWantChatTimer = setInterval("fbStyleChat_CheckOperInterval();", 5000);
        }
    }
}
// La callback richiamata dalle segnalazioni di Signal e Unsignal
function fbStyleChat_SignalXalpCallBack(_xO) {
    if (_xO['result'] == 0) {   // se sta mostrando la finestra richiama anche un aggiornamento.
        var cwin = document.getElementById("fbStyleChat_ChatWindow");
        if (cwin.style.visibility == "hidden" || cwin.style.visibility == "") {
            cwin.style.visibility = "visible";
            fbStyleChat_CallByTimerToRefresh();
            fbStyleChat__chatUpdateTimer = setInterval('fbStyleChat_CallByTimerToRefresh();', 5000);
        }
        else {
            cwin.style.visibility = "hidden";
            // Spegne il timer di aggiornamento.
            clearInterval(fbStyleChat__chatUpdateTimer);
        }
    }
}


// Questo è l'handler per il tasto invio [keyascii=13] che gestisce l'invio dei messaggi.
function fbStyleChat_checkEventOnText(e) {
    if (e.keyCode == 13) {
        fbStyleChat_Send(document.getElementById("fbStyleChat_ToSend").value);
    }
}

/**
    LE FUNZIONI SEGUENTI SI OCCUPANO DELL'INVIO DEI MESSAGGI E DEL RECUPERO
    AD INTERVALLI FISSI DI QUELLI RICEVUTI. AD OGNI RICEZIONE O INVIO 
    IL POSIZIONAMENTO VIENE ESEGUITO IN AUTOMATICO. 
**/

function fbStyleChat_Send(msg) {

    if (msg.match('(<)+')) { alert('Carattere < non ammesso');return false;}
    if (msg.match('(>)+')) { alert('Carattere > non ammesso'); return false; }
    if (msg.match('(//)+')) { alert('Carattere / non ammesso'); return false; }

    // sostituisce il carattere & non supportato
    msg = msg.replace('&', 'e');
    var MyArray = new Array();
    MyArray["msg"] = msg;
    MyArray["opType"] = 'sendMsg';
    parent.invoke(NetSell_XalpServiceUrl + '/CommonService/fbStyleChatServ.aspx', MyArray,'fbStyleChat_SXalpCallBack', 15000);
}
// CallBack per la Send. Se l'invio riesce pulisce il testo che ha scritto
// in caso contrario non lo tocca.
function fbStyleChat_SXalpCallBack(_xO) {
    if (_xO["result"] != "0") {
        alert('Si è verificato un errore durante il tentativo di invio dei dati. Riprovare di nuovo.');
        return false;
    }
    document.getElementById("fbStyleChat_ToSend").value = '';
    fbStyleChat__refreshBody(_xO['currentHistory']);
}

// Questa funzione si occupa di aggiornare il corpo aggiungendo i vari <span>
function fbStyleChat__refreshBody(HistoryBody) {
    
    // Variabili di esecuzione
    var TimeStamp;
    var UserName;
    var TheBody;
    var theRoot = document.getElementById("fbStyleChat_ChatBody");
    
    // Controllo stato chat
    var checkId;
    var kId;
    var itKID;
    var founded = false;
    var i;
 
    // itera su tutta la cronologia e cerca se sono presenti nuovi messaggi da aggiungere.
    for (itBody in HistoryBody) {
        
        // Effettua lo split dei valori ritornati dal servizio di lettura memoria
        TimeStamp = itBody;
        UserName = HistoryBody[itBody].split('|')[0];
        TheBody = HistoryBody[itBody].substring(HistoryBody[itBody].indexOf('|', 0) + 1, HistoryBody[itBody].length);
        
        // recupera il corpo della chat e ricerca all'interno
        // se già è presente il messaggio in analisi.
        founded = false;
        kId = "fbStyleChat_ChatBody_Span" + TimeStamp + UserName
        checkId = theRoot.getElementsByTagName("span");
        if (checkId.length > 0) {
            for (i = 0; i < checkId.length; i++) {
                itKID = checkId[i];
                if (itKID.getAttribute("kID") == kId) founded = true;  // già c'è            
            }
        }

        // Se non trova l'item lo aggiunge. Qui gestisce la compatibilità con FIREFOX
        // usando innerHTML al posto del DOM
        if (founded == false) {
            if (navigator.userAgent.toString().match('(Firefox)+') || navigator.userAgent.toString().match('(Meleon)+')) {
                

                // Qui trovano posto gli esterEgg. Benediciamo Juliana per prima
                if (TheBody == 'ilovejulianamoreira') {
                    theRoot.innerHTML += '<span kID=\'' + kId + '\' class=\'fbStyleChat_ChatBody_ChatSpan\'>' + UserName + '><img src=\'' + NetSell_XalpServiceUrl + '/Coders_Help/Egg/lovemoreira1.png\'></span><br/>';
                // Altra benedizione
                } else if (TheBody == 'ilovejulianamoreira1') {
                    theRoot.innerHTML += '<span kID=\'' + kId + '\' class=\'fbStyleChat_ChatBody_ChatSpan\'>' + UserName + '><img src=\'' + NetSell_XalpServiceUrl + '/Coders_Help/Egg/lovemoreira2.png\'></span><br/>';
                }
                else {
                    theRoot.innerHTML += '<span kID=\'' + kId + '\' class=\'fbStyleChat_ChatBody_ChatSpan\'>' + UserName + '> ' + TheBody + '</span><br/>';
                }
            }
            else {
                checkId = document.createElement("span");
                checkId.setAttribute("kID", kId);
                // Applica lo stile ad ogni singolo elemento della chat
                checkId.setAttribute("class", "fbStyleChat_ChatBody_ChatSpan");
                var imgmo;
                if (TheBody == 'ilovejulianamoreira') {
                    imgmo = document.createElement("img");
                    imgmo.setAttribute("src", NetSell_XalpServiceUrl + "/Coders_Help/Egg/lovemoreira1.png");
                    checkId.appendChild(imgmo);
                } else if (TheBody == 'ilovejulianamoreira1') {
                    imgmo = document.createElement("img");
                    imgmo.setAttribute("src", NetSell_XalpServiceUrl + "/Coders_Help/Egg/lovemoreira2.png");
                    checkId.appendChild(imgmo);
                }
                else {
                    checkId.innerText = UserName + '> ' + TheBody;
                    if (UserName == 'OPER') { checkId.style.color = "#ff0000"; }
                }
                theRoot.appendChild(checkId);
                theRoot.appendChild(document.createElement("br"));
            }
            theRoot.scrollTop += 50;
            
        }            
    }
}

// Questa funzione si occupa di aggiornare la chat ad intervalli prefissati di 5 secondi
function fbStyleChat_CallByTimerToRefresh() {
    var MyArray = new Array();
    MyArray["opType"] = 'getHistory';
    parent.invoke(NetSell_XalpServiceUrl + '/CommonService/fbStyleChatServ.aspx', MyArray, 'fbStyleChat_CallByTimerXalpCallBack', 15000);
  
}
function fbStyleChat_CallByTimerXalpCallBack(_xO) {
    if (_xO['result'] == 0)
        fbStyleChat__refreshBody(_xO['currentHistory']);
    if (_xO['result'] == 2)
        document.getElementById("fbStyleChat_ChatBody").innerHTML = NetSellGui_Costumize_fbStyleChat_NoMsgDefaultValue;
}
