/*****************************************************************************************************/
/*********************************************** AJOUT PSA *******************************************/
/*****************************************************************************************************/
// AO, 18/12/2009
var footerHeight = 45;

// AUTHENTIFICATION
var adr_email;
var password;
var remember_login;
/*****************************************************************************************************/
/*****************************************************************************************************/
/*****************************************************************************************************/

/*****************************************************************************************************/
/*********************************************** DEBUT DAGOBERT **************************************/
/*****************************************************************************************************/
function DinitLoad() {
    //Attachement pour l'événement LOAD
    if (navigator.appName == "Microsoft Internet Explorer" && window.attachEvent)
        window.attachEvent("onload", DinitCall);
    else if (window.addEventListener)
        window.addEventListener("load", DinitCall, false);
}

function DinitCall() {
    //Initialisation de la popin
    initPopin();
    //Initialisation du widget 
    initWidget();
    //Initialisation du footer
    initFooterHeight();
    //Rollover du texte de l'input "nouvel_onglet"
    rollTxtInput();
}

function IsFirefoxInf35() {
    if (navigator.platform == 'Win32') {
        if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
            var ffversion = new Number(RegExp.$1);

            if (ffversion < 3.5)
                return true;
            else
                return false;
        }
        else if (/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent))
            return true;
    }
}

/**********************************/
/*** FONCTIONS LIEES A LA POPIN ***/
/**********************************/
function initPopin() {
    var el = document.getElementById('popinclose1');
    if (el)
        el.onclick = closePopin;
}

function closePopin() {
    var fl = document.getElementById("content_header_flash");
    if (fl) fl.backFromGrey();
    var el = document.getElementById('popin1');
    if (el)
        el.className = 'invisible';
}

function showPopin() {
    var fl = document.getElementById("content_header_flash");
    if (fl) fl.fadeToGrey();
    var el = document.getElementById('popin1');
    if (el)
        el.className = 'popin';
}

/**********************************/
/*** FONCTIONS LIEES AU WIDGET  ***/
/**********************************/
function initWidget() {
    var el = document.getElementById('widgetclose1');
    if (el)
        el.onclick = closeWidget;
}

function closeWidget() {
    var el = document.getElementById('widget1');
    if (el)
        el.className = 'invisible2';
}

function showWidget() {
    var el = document.getElementById('widget1');
    if (el)
        el.className = 'visible2';
}

// AO, 18/12/2009
function getFooterHeight() {
    return footerHeight;
}

/****************************************************/
/*** FONCTIONS LIEES AU FORMULAIRE HTML DU HEADER ***/
/****************************************************/
function switchPasswordToInput(idLabel, idInput) {
    var el = document.getElementById(idLabel);
    if (el) {
        if (el.style.display != 'none') {
            el.style.display = 'none';
            var passInput = document.getElementById(idInput);
            if (passInput) passInput.focus();
        }
    }
}

function switchPasswordToLabel(idLabel, idInput) {
    var passInput = document.getElementById(idInput);
    if (passInput) {
        if (passInput.value == '') {
            passInput.value = '';
            var el = document.getElementById(idLabel);
            if (el) el.style.display = '';
        }
    }
}

function showHeaderFormulaire() {
    var el = document.getElementById(idHeaderFormulaire);
    if (el)
        el.style.display = 'block';
}

function hideHeaderFormulaire() {
    var el = document.getElementById(idHeaderFormulaire);
    if (el)
        el.style.display = 'none';
}

/************************************************/
/*** FONCTIONS APPELEES PAR LE FLASH "FOOTER" ***/
/************************************************/
function initFooterHeight() {
    var el = document.getElementById('footer_flash');
    if (el) el.style.height = getFooterHeight() + "px";
}

function setWarning() {
    jQuery("#header_formulaire").addClass('warning');
}

function setLoged() {
    var el = document.getElementById("content_header_flash");

    if (el && el.setLoged) el.setLoged();

    var mc = document.getElementById("infos_compte");
    if (mc) mc.className = 'infos_compte';

    hideHeaderFormulaire();
}

function setNotLoged() {
    var el = document.getElementById("content_header_flash");
    if (el) el.setNotLoged();

    var mc = document.getElementById("infos_compte");
    if (mc) mc.className = 'invisible';
    showHeaderFormulaire();
}

function LogOut() {
    // AO, 18/11/2009
    if (userId != undefined && userId != "" && userId != GuidEmpty) {
        document.getElementById(hdShowPopinTemplateArgumentId).value = logoutConfirmMessage;
        document.getElementById(hdShowPopinYesActionId).value = "LogOutConfirmed();return false;";
        document.getElementById(hdShowPopinYesNoShowDisableMessageCheckboxId).value = "0";
        ShowPopinMessageYesNo();
    }
}

function _doconnect(email, password, memoriser) {
    var _email = document.getElementById(email).value;
    var _mdp = document.getElementById(password).value;
    var _remember = document.getElementById(memoriser).checked;

    if (_email.length == 0 || _email == libelleEmail || _mdp.length == 0 || _mdp == libellePassword)
        OnErrorAuthentication();
    else
        GetAuthentification(_email, _mdp, _remember);
}

function LogIn() {
    _doconnect('email', 'password', 'memoriser');
}

function showLegale() {
    var fl = document.getElementById("content_header_flash");
    if (fl) fl.fadeToGrey();
    var el = document.getElementById('popin_legale');
    if (el)
        el.className = 'popin';
}

function closeLegale() {
    var fl = document.getElementById("content_header_flash");
    if (fl) fl.backFromGrey();
    var el = document.getElementById('popin_legale');
    if (el)
        el.className = 'invisible';
}
/*****************************************************************************************************/
/*********************************************** FIN DAGOBERT ****************************************/
/*****************************************************************************************************/

/*****************************************************************************************************/
/*********************************************** DEBUT PSA *******************************************/
/*****************************************************************************************************/
// AO, 11/10/2010
function SetCurrentWidgetOnTop(widgetId) {
    var iFrame = parent.document.getElementById(parent.iFrameDependantId).contentWindow;
    var Manager = iFrame.GetRadWindowManager();
    var currentWindow = Manager.getWindowById(widgetId);
    
    patchIsActive = true;
    currentWindow.setActive(true);
    patchIsActive = false;
}

// AO, 18/11/2009
function LogOutConfirmed() {
    var data = 'type=logout';
    var url = AppBasePath + 'ESP/AjaxAsyncRecord.aspx?' + data + '&Lan=' + languageId + '&rnd=' + randomString('abcdecfhijklmnopqrstuvwxyz', 64);
    var xhrWindowLogout = createXHR();

    xhrWindowLogout.open("GET", url, true);
    xhrWindowLogout.onreadystatechange = function() {
        if (xhrWindowLogout.readyState == 4 && xhrWindowLogout.status == 200) {
            if (xhrWindowLogout.responseText) {
                response = eval('(' + xhrWindowLogout.responseText + ')');

                if (response != null)
                    window.location.reload();
            }
        }
    };

    xhrWindowLogout.send(null);
}

function showPopinLogin() {
    document.getElementById(popinControlHiddenFieldId).value = "ucLogin";
    ShowPopinTemplate();
}

function GrayFlashHeader() {
    return;
}

function UnGrayFlashHeader() {
    return;
}

var gURLToReload = "";

function GetAuthentification(email, mdp, remember, URLToReload) {
    adr_email = email;
    password = mdp;
    remember_login = remember;

    gURLToReload = "";
    if (typeof (ESPAuthentification) != "undefined")
        ESPAuthentification.AuthentificateUser(email, mdp, remember, OnCompleteAuthentification, OnErrorAuthentication, OnTimeOutAuthentification);
    else if (typeof (parent.ESPAuthentification) != "undefined") {
        if (URLToReload) {
            gURLToReload = URLToReload;
            parent.gURLToReload = URLToReload;
            parent.ESPAuthentification.AuthentificateUser(email, mdp, remember, parent.OnCompleteAuthentification, parent.OnErrorAuthentication, parent.OnTimeOutAuthentification);

        }    //parent.location.href=URLToReload;
    }
}

function CallAjaxRecord(data, actionType) {
    var url = AppBasePath + "ESP/AjaxAsyncRecord.aspx?lan=" + languageId + "&rnd=" + randomString("abcdecfhijklmnopqrstuvwxyz", 64);
    var xhr = createXHR();
    xhr.open("POST", url, true);
    xhr.onreadystatechange = function() { WaitAjaxResponse(xhr, actionType) };
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(data);
}

function WaitAjaxResponse(xhr, actionType) {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            if (xhr.responseXML) {
                response = xhr.responseXML.documentElement;

                if (actionType == "createWidget")
                    RefreshWidgetList();
            }
        }
    }
}

function randomString(sChrs, iLen) {
    var sRnd = '';

    for (var i = 0; i < iLen; i++) {
        var randomPoz = Math.floor(Math.random() * sChrs.length);
        sRnd += sChrs.substring(randomPoz, randomPoz + 1);
    }

    return sRnd;
}

function OnCompleteAuthentification(arg) {
    // AO, 13/01/2010 : important : traduction des libéllés en anglais pour corriger l'erreur Javascript au chargement du widget "Tableau de bord", 
    //                  qui était dûe au accents des commentaires ("é" dans "bloqué",...)
    if (arg == 6)      // The account is locked
    {
        document.getElementById(popinControlHiddenFieldId).value = "ucMessage";
        document.getElementById(codeMessageHiddenFieldId).value = "ESP_LOCKED_ACCOUNT";
        ShowPopinTemplate();
        setWarning();
        setNotLoged();
    }
    else if (arg == 5) // The account will be locked
    {
        document.getElementById(popinControlHiddenFieldId).value = "ucMessage";
        document.getElementById(codeMessageHiddenFieldId).value = "ESP_LOCK_ACCOUNT";
        ShowPopinTemplate();
        setWarning();
        setNotLoged();
    }
    else if (arg == 4) // Incorrect email adress
    {
        document.getElementById(popinControlHiddenFieldId).value = "ucMessage";
        document.getElementById(codeMessageHiddenFieldId).value = "ESP_USER_EMAIL_INVALID";
        ShowPopinTemplate();

        setWarning();
        setNotLoged();
    }
    else if (arg == 3) // Missing Password
    {
        document.getElementById(popinControlHiddenFieldId).value = "ucMessage";
        document.getElementById(codeMessageHiddenFieldId).value = "ESP_PASSWORD_REQUIS";
        ShowPopinTemplate();
        setWarning();
        setNotLoged();
    }
    else if (arg == 2) // Unactive account
    {
        document.getElementById(popinControlHiddenFieldId).value = "ucInactiveAccount";
        document.getElementById(codeMessageHiddenFieldId).value = adr_email;
        ShowPopinTemplate();
        setNotLoged();
    }
    else if (arg == 0) // Authentication succedeed
    {
        if (gURLToReload != "") {
            parent.location.href = gURLToReload;
            gURLToReload = "";
        }
        else {
            if (document.location.href.indexOf("id=Validation") == -1) {
                document.location.reload();
            }
            else {
                var returnLoc = parent.location.href;
                returnLoc = returnLoc.substr(0, returnLoc.indexOf('?'));
                parent.location.href = gURLToReload;
            }
        }
    }
    else if (arg == 1)  // Authentication failed
    {
        document.getElementById(popinControlHiddenFieldId).value = "ucMessage";
        document.getElementById(codeMessageHiddenFieldId).value = "ESP_AUTHENTIFICATION_FAILED";
        ShowPopinTemplate();
        setWarning();
        setNotLoged();
    }
}

function OnTimeOutAuthentification(arg) {
    document.getElementById(popinControlHiddenFieldId).value = "ucMessage";
    document.getElementById(codeMessageHiddenFieldId).value = "ESP_SESSION_TIMEOUT";
    ShowPopinTemplate();
}

function OnErrorAuthentication(arg) {
    setWarning();

    document.getElementById(popinControlHiddenFieldId).value = "ucMessage";
    document.getElementById(codeMessageHiddenFieldId).value = "ESP_AUTHENTIFICATION_ERRROR";
    ShowPopinTemplate();
}

function GetNewPassword() {
    document.getElementById(popinControlHiddenFieldId).value = "ucLostPassword";
    ShowPopinTemplate();
}

function CreateAccount() {
    var popinVerticalOffset = 0;
    var arguments;
    arguments = popinVerticalOffset + ";" + false;
    document.getElementById(hdShowPopinTemplateSpecialArgumentId).value = "CREATE";
    document.getElementById(popinControlHiddenFieldId).value = "ucAccount";
    //  ShowPopinTemplateSpecial(arguments);
    ShowPopinCreateAccount();
}

function ShowPopinMessageYesNo(modeConfirm) {
    var obj;

    if (parent.popinControlHiddenFieldId)
        obj = parent;
    else if (parent.parent.popinControlHiddenFieldId)
        obj = parent.parent;

    obj.document.getElementById(obj.popinControlHiddenFieldId).value = "ucMessageYesNo";
    obj.document.getElementById(obj.hdShowPopinYesNoConfirmModeId).value = modeConfirm;
    obj.ShowPopinTemplate();
}

function ShowWidgetPlace() {
    var obj;

    if (parent.popinControlHiddenFieldId)
        obj = parent;
    else if (parent.parent.popinControlHiddenFieldId)
        obj = parent.parent;

    obj.document.getElementById(obj.popinControlHiddenFieldId).value = "ucWidgetPlace";
    obj.ShowPopinTemplate();
}


// AO, 17/11/2009
function CloseRadWindow(RadWindowId) {
    ClosePopinTemplate(true);

    if (RadWindowId) {
        var iFrameWidgets = document.getElementById(iFrameDependantId);

        if (iFrameWidgets) {
            var oWnd = iFrameWidgets.contentWindow.$find(RadWindowId);

            if (oWnd) {
                oWnd.remove_beforeClose(iFrameWidgets.contentWindow.RadWindowClientBeforeClose);
                oWnd.close();
            }
        }
    }
}

function ShowPopinMessage() {
    var obj;

    if (parent.popinControlHiddenFieldId)
        obj = parent;
    else if (parent.parent.popinControlHiddenFieldId)
        obj = parent.parent;

    obj.document.getElementById(obj.popinControlHiddenFieldId).value = "ucMessage";
    obj.ShowPopinTemplate();
}

function ShowPopinMessageAndConnect() {
    var obj;

    if (parent.popinControlHiddenFieldId)
        obj = parent;
    else if (parent.parent.popinControlHiddenFieldId)
        obj = parent.parent;
    obj.document.getElementById(obj.popinControlHiddenFieldId).value = "ucMessage";
    obj.ShowPopinTemplate();

    parent.location.href = parent.location.pathname;
}

function DisplayDashBoardLegalMentions(params) {
    parent.parent.ShowPopinIframe(params);
}

function AddServices() {
    var iFrameWidgets = document.getElementById(iFrameDependantId);
    if (iFrameWidgets) {
        var nbWidgetsInCurrentTab = eval(iFrameWidgets.contentWindow.document.getElementById(iFrameWidgets.contentWindow.hdNbWidgetsInCurrentTabId).value);
        var nbMaxWidgetsAllowed = eval(iFrameWidgets.contentWindow.document.getElementById(iFrameWidgets.contentWindow.hdMaxNbWidgetsAllowedId).value);

        if (nbWidgetsInCurrentTab >= nbMaxWidgetsAllowed) {
            document.getElementById(popinControlHiddenFieldId).value = "ucMessage";
            document.getElementById(codeMessageHiddenFieldId).value = maxNbWidgetsForTabReachedMessage;
            parameters = new Array();
            parameters['perform'] = 'true';
            parameters['hdCodeMessage'] = 'ESP_MAX_NB_WIDGETS_FOR_TAB_REACHED';
            ShowPopinTemplate2(parameters);
        }
        else {
            document.getElementById(hdShowPopinTemplateSpecialArgumentId).value = "";  // AO, 25/11/2009

            document.getElementById(popinControlHiddenFieldId).value = "ucWidgetPlace";
            ShowPopinTemplate2();
        }
    }
}

function Customize() {
    document.getElementById(hdShowPopinTemplateSpecialArgumentId).value = "";  // AO, 26/11/2009
    document.getElementById(popinControlHiddenFieldId).value = "ucBackGroundSelection";
    ShowPopinTemplateSpecial();
}

function InviteAFriend() {
    document.getElementById(popinControlHiddenFieldId).value = "ucInviteFriend";
    ShowPopinTemplate();
}

function ShowClubDSSite(sitURL)
{
    window.open(sitURL);
}

function GetAccount() 
{
    if (parent.popinControlHiddenFieldId) 
    {
        var popinVerticalOffset = 0;
        var arguments;
        arguments = popinVerticalOffset + ";" + true;
        parent.document.getElementById(hdShowPopinTemplateSpecialArgumentId).value = arguments;
        parent.document.getElementById(parent.popinControlHiddenFieldId).value = "ucAccount";
        parent.ShowPopinEditAccount();

    }
}

function WidgetUserExists(widgetModelId) {
    // On regarde dans l'onglet courant
    var iFrame = document.getElementById(iFrameDependantId).contentWindow;
    var Manager = iFrame.GetRadWindowManager();
    var windows = "";

    if (Manager) {
        windows = Manager.GetWindows();
        for (i = 0; i < windows.length; i++) {
            var widgetCountryId = iFrame.document.getElementById(Manager.get_id())["widgetCountryId_" + windows[i].get_id()];
            if (widgetCountryId == undefined || widgetCountryId == "")
                widgetCountryId = iFrame.document.getElementById(Manager.get_id()).getAttribute("widgetCountryId_" + windows[i].get_id());

            if (widgetCountryId == widgetModelId) {
                if (windows[i].IsMinimized())
                    windows[i].Restore();

                if (windows.length > 1)
                    windows[i].setActive(true);

                return false;
            }
        }
    }

    var lanId = document.getElementById(iFrameDependantId).contentWindow.document.getElementById("hdLanguageId").value;
    var data = "type=WidgetUserExists&widgetModelId=" + widgetModelId;
    var url = AppBasePath + "ESP/AjaxAsyncDesktop.aspx?" + data + "&Lan=" + lanId + "&rnd=" + randomString("abcdecfhijklmnopqrstuvwxyz", 64);
    var xhr = createXHR();

    xhr.open("GET", url, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            if (xhr.responseText) {
                response = eval('(' + xhr.responseText + ')');
                if (response != null) {
                    if (response.widgetFound == "true") {
                        // On bascule sur l'onglet contenant le widget
                        defaultTabLoaded = false;
                        var tabIndex = GetTabIndexFromId(response.tabId);
                        var tabName = GetTabNameFromId(response.tabId);
                        var tabIndexFromDB = GetTabIndexFromDBFromId(response.tabId);
                        if (tabIndex > -1)
                            ChangeTabHeadersStyle(tabIndex, 0);
                        LoadDefaultTab2(response.tabId, tabName, tabIndex, widgetModelId, randomString("abcdecfhijklmnopqrstuvwxyz", 64))
                        hideOptions();
                        iActiveTabName = tabName;
                        iActiveTabId = response.tabId;
                        iActiveTabIndexFromDB = tabIndexFromDB;
                    }
                    else
                        AddWidget(widgetModelId);
                }
            }
            else {
                document.getElementById(popinControlHiddenFieldId).value = "ucMessage";
                document.getElementById(codeMessageHiddenFieldId).value = "ESP_WIDGET_UNAVAILABLE";
                ShowPopinTemplate();
                setWarning();
            }
        }
    };

    xhr.send(null);
}

function GetHelp() {
    GetWidgetLinked('ESP_HELP');
}

function GetWidgetLinked(mode) {
    var data;
    if (mode == '')
        data = "type=findWidgetLinked&widgetNameParam=ESP_HELP";
    else
        data = "type=findWidgetLinked&widgetNameParam=" + mode;

    var lanId = document.getElementById(iFrameDependantId).contentWindow.document.getElementById("hdLanguageId").value;
    var url = AppBasePath + "ESP/AjaxAsyncDesktop.aspx?" + data + "&Lan=" + lanId + "&rnd=" + randomString("abcdecfhijklmnopqrstuvwxyz", 64);
    var xhr = createXHR();

    xhr.open("GET", url, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            if (mode == 'ESP_HELP' || mode == 'ESP_HELP_CONNECTED') {
                SetSophusTag_JS('Help')
            }

            if (xhr.responseText) {
                response = eval('(' + xhr.responseText + ')');

                if (response != null) {
                    if (response.widgetModelId != undefined && response.widgetModelId != "")
                        WidgetUserExists(response.widgetModelId);
                    else {
                        document.getElementById(popinControlHiddenFieldId).value = "ucMessage";
                        document.getElementById(codeMessageHiddenFieldId).value = "ESP_HELP_UNVAILABLE";
                        ShowPopinTemplate();
                        setWarning();
                    }
                }
            }
            else {
                document.getElementById(popinControlHiddenFieldId).value = "ucMessage";
                document.getElementById(codeMessageHiddenFieldId).value = "ESP_HELP_UNVAILABLE";
                ShowPopinTemplate();
                setWarning();
            }
        }
    };

    xhr.send(null);
}

function GetHelpConnected() {
    GetWidgetLinked('ESP_HELP_CONNECTED');
}

function showWidgets(widgets) {
    var el = document.getElementById(widgets);

    if (el) {
        el.className = 'visible';
        el.parentNode.className = 'on';
    }
}

function hideWidgets(widgets) {
    var el = document.getElementById(widgets);

    if (el) {
        el.className = 'invisible';
        el.parentNode.className = '';
    }
}

function IE6Transparency() {
    if (isIEBelow7) {
        alphaBackgrounds();
        fnLoadPngs();
    }
}

// Ajax
function createXHR() {
    var xhr = null;

    if (window.XMLHttpRequest || window.ActiveXObject) {
        if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        else
            xhr = new XMLHttpRequest();
    }
    else
        return null;

    return xhr;
}

/*=======================================================GH - AMELIORATION DES PERFORMANCES DES OVERLAYS=======================================================*/
function ShowPopinMessageYesNo2(parameters) {
    var obj;

    if (parent.popinControlHiddenFieldId)
        obj = parent;
    else if (parent.parent.popinControlHiddenFieldId)
        obj = parent.parent;

    obj.document.getElementById(obj.popinControlHiddenFieldId).value = "ucMessageYesNo";
    obj.ShowPopinTemplate2(parameters);
}
/*=============================================================================================================================================================*/

function ShowSessionExpiredMessage(msg) {
    var obj;

    if (parent.codeMessageHiddenFieldId)
        obj = parent;
    else
        obj = parent.parent;

    var message = obj.document.getElementById(obj.codeMessageHiddenFieldId);
    //message.value = msg;
    message.value = "ESP_SESSION_TIMEOUT";
    obj.document.getElementById(obj.hdShowPopinOkActionId).value = "window." + ((obj == "parent") ? "parent" : "parent.parent") + ".window.location.reload();";
    obj.document.getElementById(obj.hdShowPopinClosingCrossActionId).value = "window." + ((obj == "parent") ? "parent" : "parent.parent") + ".window.location.reload();";
    obj.ShowPopinMessage();
}

// AO, 31/08/2009
function getElementsByClassName(classname, node) {
    if (!node)
        node = document.getElementsByTagName("body")[0];

    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");

    for (var i = 0, j = els.length; i < j; i++)
        if (re.test(els[i].className))
        a.push(els[i]);

    return a;
}

/*** FONCTIONS LIEES AU CHAMPS INPUT "NOUVEL_ONGLET" ***/
function rollTxtInput() {
    var el = document.getElementById('nouvel_onglet');
    if (el) {
        var myvalue = el.value;
        el.onclick = function() { onclickRollTxtInput.call(this, myvalue); };
        el.onblur = function() { onblurRollTxtInput.call(this, myvalue); };
    }
}

function onclickRollTxtInput(myvalue) {
    if (this.value == myvalue) this.value = '';
}

function onblurRollTxtInput(myvalue) {
    if (this.value == '') this.value = myvalue;
}

