var lastUrl = null;
var oldHtml = null;
var alternateSpiralePageNumber = 0;
var alternateSpiraleItemsNumber = 0;
var articleThemaId = null;

function Chargement() {
    // currentURL = document.location;
}
onLoad = Chargement();

// ------------------------------------------------
// logic link
// ------------------------------------------------

function linkNavigation(c, cid) {
    getHTMLCmsContent(cid, c);
    callSpiraleFeeder(c + "," + cid);
    // var testValue = $(this).html();
    // $.history.add(testValue);
}

function lienAllArticles(url) {
    var path = getHostName();
    document.location = path + url;
}

function typeToRubrique(type) {
    var rubrique;
    if (type == "Article_C") {
        rubrique = "savoir-tout-savoir";
    } else if (type == "Projet_C") {
        rubrique = "prepare-un-projet";
    } else if (type == "RubriqueProduit") {
        rubrique = "souscrire-produit";
    } else if ((type == "RubriqueExpert") || (type == "RubriqueParoleExpert") || (type == "RubriqueFormation") || (type == "RubriqueQuestionReponse")) {
        rubrique = "consulter-des-experts";
    } else if (type == "RubriqueCalculerComparer") {
        rubrique = "calculer-comparer";
    }
    return rubrique;
}

function linkInternalContent(c, cid, type) {
    var rubrique = typeToRubrique(type);
    document.location = getContextPath() + "/cms/cmsContent.action?page=" + c + "#" + rubrique + "/" + type + "/" + cid;
    return false;
}

// ------------------------------------------------
// light current Thematic
// ------------------------------------------------
function lightCurrent(current) {
    $("#navSTS").removeClass('light');
    $("#navPROJ").removeClass('light');
    $("#navPROD").removeClass('light');
    $("#navCC").removeClass('light');
    $("#navEXP").removeClass('light');
    $("#" + current).addClass('light');
}

// ------------------------------------------------
// treat current Thematic
// ------------------------------------------------
function treatCurrentSection(assetType, assetId) {
    if ((assetType == "Article_C") || (assetType == "RubriqueArticle")) {
        lightCurrent("navSTS");
        document.title = "Savoir tout savoir";
        $.history.add("savoir-tout-savoir/" + assetType + "/" + assetId);
    } else if (assetType == "Projet_C") {
        lightCurrent("navPROJ");
        document.title = "Préparer un projet";
        // $.history.add("preparer-projet/"+assetType+"/"+assetId);
    } else if (assetType == "Produit_C") {
        lightCurrent("navPROD");
        document.title = "Souscrire un produit";
        $.history.add("souscrire-produit/" + assetType + "/" + assetId);
    } else if (
                (assetType == "RubriqueExpert") ||
                (assetType == "RubriqueConference") ||
                (assetType == "RubriqueFormation") ||
                (assetType == "RubriqueQuestionReponse") ||
                (assetType == "RubriqueParoleExpert") ||
                (assetType == "Conference") ||
                (assetType == "Formation") ||
                (assetType == "ParoleExpert") ||
                (assetType == "QR")
              ){
        lightCurrent("navEXP");
        document.title = "Consulter un expert";
        $.history.add("consulter-des-experts/" + assetType + "/" + assetId);
    } else if ((assetType == "Outil_C") || (assetType == "RubriqueCalculerComparer")) {
        lightCurrent("navCC");
        document.title = "Calculer Comparer";
        $.history.add("calculer-comparer/" + assetType + "/" + assetId);
    } else if ((assetType == "Portefeuilles") || (assetType == "Societes") || (assetType == "RubriqueFond") || (assetType == "Produit_P")
            || (assetType == "Portefeuille")) {
        $.history.add("souscrire-produit/" + assetType + "/" + assetId);
    } else if ((assetType == "Societes")) {
        $.history.add("souscrire-produit/" + assetType + "/" + assetId);
    } else if ((assetType == "RubriqueFond")) {
        $.history.add("souscrire-produit/" + assetType + "/" + assetId);
    } else if ((assetType == "RubriqueBourse")) {
        $.history.add("souscrire-produit/" + assetType + "/" + assetId);
    }

}

// ------------------------------------------------
// get XML file
// ------------------------------------------------
function getXMLSpiraleContent(id, type, callback) {
    var xmlFile = null;
    var path = getHostName();
    var cmsRequest = path + "/Satellite?pagename=SEL_V1/SpiraleFeeder";
    $.ajax( {
        type : "GET",
        url : cmsRequest,
        async : callback ? true : false,
        data : "id=" + id + "&type=" + type,
        error : function() {
            var windowHref = window.location.href;
            var errorContentClass = null;
            if ((windowHref.indexOf("preparer-projet") != -1) || (windowHref.indexOf("savoir-tout-savoir") != -1)
                    || (windowHref.indexOf("souscrire-produit") != -1) || (windowHref.indexOf("consulter-des-experts") != -1)) {
                errorContentClass = "ErreurSpirale";
            } else {
                errorContentClass = "ErreurSpirale ErreurSpiraleHome";
            }
            var errorContent = "<div id=\"errorContentSpirale\" class=\"" + errorContentClass + "\"><div id=\"RubContent\">"
                    + "<span class=\"topLeft\"/><span class=\"topRight\"/><span class=\"bottomLeft\"/><span class=\"bottomRight\"/>"
                    + "<div class=\"global-content\"><div class=\"panneau\"></div><div class=\"top-content\">";
            errorContent += "Une erreur technique s'est produite, nous mettons tous les moyens en oeuvre pour la rectifier. ";
            errorContent += getErrorContent();
            errorContent += "</div></div></div></div>";
            if ($("#errorContentSpirale").html() == null) {
                $("#flash").append(errorContent);
            } else {
                $("#errorContentSpirale").replaceWith(errorContent);
            }
        },
        success : function(xmlData) {
            if ($("#errorContentSpirale").html() != null) {
                $("#errorContentSpirale").remove();
            }
            if (callback) {
                callback(xmlData);
            } else {
                xmlFile = xmlData;
            }
        }

    });
    return xmlFile;
}

function getErrorContent() {
    var errorContent = "Veuillez nous excuser pour la gêne occasionnée. "
            + "<br/><br/>Par ailleurs, les conseillers BforBank restent à votre disposition pour vous aider : " + "<br/>De 8h à 22h du lundi au vendredi "
            + "<br/>De 9h à 18h le samedi " + "<br/>- Si vous êtes client BforBank : 09 74 75 75 00 (appel non surtaxé) "
            + "<br/>- Si vous n'êtes pas client BforBank : 09 74 75 08 08 (appel non surtaxé)";
    return errorContent;
}

// ------------------------------------------------
// get CMS MashUp RubriqueSousHomeExpert
// ------------------------------------------------
function getHTMLCmsContent(id, type) {
    var url = getHostName();
    if ((type == "Portefeuilles") || (type == "Societes")) {
        url += "/Satellite?c=DescDossierFond&cid=" + id + "&pagename=SEL_V1/DescDossierFond/Detail";
    } else if ((type == "Actions") || (type == "thematiqueFond")) {
        url += "/Satellite?c=Produit_P&cid=" + id + "&pagename=SEL_V1/Produit_P/Detail";
    } else if ((type == "RubriqueConference") || (type == "RubriqueFormation") || (type == "RubriqueParoleExpert")) {
        url += "/Satellite?c=RubriqueSousHomeExpert&cid=" + id + "&pagename=SEL_V1/RubriqueSousHomeExpert/Detail";
    } else if (type == "Rubrique_C") {
        url += "/Satellite?c=" + type + "&cid=1238511282575&pagename=SEL_V1/" + type + "/Detail";
    } else if (type == "RubriqueFond") {
        url += "/Satellite?c=RubriqueFond&cid=1238511089726&pagename=SEL_V1/RubriqueFond/Detail";
    } else {
        url += "/Satellite?c=" + type + "&cid=" + id + "&pagename=SEL_V1/" + type + "/Detail";
    }
    $("#cmsContent").load(
            url,
            function(responseText, textStatus, req) {
                if (textStatus == "error") {
                    var windowHref = window.location.href;
                    var errorContentClass = null;
                    if ((windowHref.indexOf("preparer-projet") != -1) || (windowHref.indexOf("savoir-tout-savoir") != -1)
                            || (windowHref.indexOf("souscrire-produit") != -1) || (windowHref.indexOf("consulter-des-experts") != -1)) {
                        errorContentClass = "ErreurContent";
                    } else {
                        errorContentClass = "ErreurContent ErreurContentHome";
                    }
                    var errorContent = "<div id=\"errorContentCms\" class=\"" + errorContentClass + "\"><div id=\"RubContent\">"
                            + "<span class=\"topLeft\"/><span class=\"topRight\"/><span class=\"bottomLeft\"/><span class=\"bottomRight\"/>"
                            + "<div class=\"global-content\"><div class=\"panneau\"></div><div class=\"top-content\">";
                    errorContent += "L'information que vous avez demandée est indisponible, nous mettons tous les moyens en oeuvre pour la rétablir. ";
                    errorContent += getErrorContent();
                    errorContent += "</div></div></div></div>";
                    $("#cmsContent").html(errorContent);
                }
            });
    $("#blocTemplate").css("height", "auto");
}

// ------------------------------------------------
// reload Spirale
// ------------------------------------------------
function callSpiraleFeeder(number) {
	
    if (hasFlashPlayer) {    	
        getSpirale().newPage(number);       
    } else {
        alternateSpiralePageNumber = 0;
        alternateSpiraleItemsNumber = 0;
        var alternateContent = getFlashPlayerContent();
        alternateContent += getAlternateSpiraleContent(number);
        alternateContent += getPagerContent();
        $("#flash").html(alternateContent);
        if (alternateSpiraleItemsNumber > 5) {
            showElement($("#nextSpiraleButton"), true);
        }
    }
}

function getSpirale() {
    var id = "id_flash";
    var spirale = document.getElementById(id);
    if (!spirale) {
        spirale = document[id];
    }
    if (!spirale) {
        spirale = window[id];
    }
    return spirale;
}

function isHomeRelated(url){
    var homeRelated = 
        (url.indexOf("preparer_un_projet") != -1) ||
        (url.indexOf("savoir_tout_savoir") != -1) ||
        (url.indexOf("souscrire_un_produit") != -1) ||
        (url.indexOf("searchContent.action") != -1) ||
        (url.indexOf("sendEmail.action") != -1) ||
        (url.indexOf("nous_contacter") != -1) ||
        (url.indexOf("qui_sommes_nous") != -1) ||
        (url.indexOf("nous_rejoindre") != -1) ||
        (url.indexOf("plan_du_site") != -1) ||
        (url.indexOf("mentions_legales") != -1) ||
        (url.indexOf("aide") != -1) ||
        (url.indexOf("nos_tarifs") != -1) ||
        (url.indexOf("documentation") != -1);
    return homeRelated;
}

// ------------------------------------------------
// managing navigation buttons (sts, projet, produit ...)
// ------------------------------------------------
$(document).ready(
    function() {

        $('#navSTS').click(
            function() {
                var url = window.location.href;
                if (isHomeRelated(url)){
                    document.location = getContextPath() + "/cms/cmsContent.action?page=homepage#savoir-tout-savoir/RubriqueArticle/1238511010648";
                } else {
                    callSpiraleFeeder(0);
                    lightCurrent("navSTS");
                    getHTMLCmsContent("1238511010648", "RubriqueArticle");
                    $.history.add("savoir-tout-savoir/RubriqueArticle/1238511010648");
                    $("#flash").removeClass('SpiraleHome');
                    $("#flash").addClass('Spirale');
                }
                xt_med('C', '1', 'Home::STS', 'N');
                return false;
            }
        );

        $('#navPROJ').click(function() {
            document.location = getContextPath() + "/cms/cmsContent.action?page=preparer_un_projet";
            xt_med('C', '1', 'Home::PROJ', 'N');
            return false;
        });

        $('#navPROD').click(
            function() {
                var url = window.location.href;
                if (isHomeRelated(url)){
                    document.location = getContextPath() + "/cms/cmsContent.action?page=homepage#souscrire-produit/RubriqueProduit/1238511020853";
                } else {
                    callSpiraleFeeder(2);
                    lightCurrent("navPROD");
                    getHTMLCmsContent("1238511020853", "RubriqueProduit");
                    $.history.add("souscrire-produit/RubriqueProduit/1238511020853");
                    document.title = "Souscrire un produit";
                    $("#flash").removeClass('SpiraleHome');
                    $("#flash").addClass('Spirale');
                }
                xt_med('C', '1', 'Home::PROD', 'N');
                return false;
            });

        $('#navCC').click(
            function() {
                var url = window.location.href;
                if (isHomeRelated(url)){
                    document.location = getContextPath() + "/cms/cmsContent.action?page=homepage#calculer-comparer/RubriqueCalculerComparer/1238511079110";
                } else {
                    callSpiraleFeeder(4);
                    lightCurrent("navCC");
                    getHTMLCmsContent("1238511079110", "RubriqueCalculerComparer");
                    $.history.add("calculer-comparer/RubriqueCalculerComparer/1238511079110");
                    document.title = "Calculer Comparer";
                    $("#flash").removeClass('SpiraleHome');
                    $("#flash").addClass('Spirale');
                }
                xt_med('C', '1', 'Home::CC', 'N');
                return false;
            });

        $('#navEXP').click(
            function() {
                var url = window.location.href;
                if (isHomeRelated(url)){
                    document.location = getContextPath() + "/cms/cmsContent.action?page=homepage#consulter-des-experts/RubriqueExpert/1238511031073";
                } else {
                    callSpiraleFeeder(3);
                    lightCurrent("navEXP");
                    getHTMLCmsContent("1238511031073", "RubriqueExpert");
                    var url = window.location.href;
                    // window.location.href = url + "#consulter-des-experts/RubriqueExpert/1238511031073";
                    $.history.add("consulter-des-experts/RubriqueExpert/1238511031073");
                    document.title = "Souscrire à un produit";
                    $("#flash").removeClass('SpiraleHome');
                    $("#flash").addClass('Spirale');
                }
                xt_med('C', '1', 'Home::EXP', 'N');
                return false;
            });

        $('#navCONT').click(function() {
            document.location = getContextPath() + "/cms/cmsContent.action?page=nous_contacter";
            xt_med('C', '1', 'nous_contacter', 'N');
            return false;
        });

        $('#navCONTP').click(function() {
            document.location = getContextPath() + "/cms/cmsContent.action?page=nous_contacter";
            xt_med('C', '1', 'nous_contacter_Phone', 'N');
            return false;
        });

        $('#navCONTM').click(function() {
            document.location = getContextPath() + "/cms/cmsContent.action?page=nous_contacter";
            xt_med('C', '1', 'nous_contacter_Mail', 'N');
            return false;
        });

        $('#navQUIS').click(function() {
            document.location = getContextPath() + "/cms/cmsContent.action?page=qui_sommes_nous";
            xt_med('C', '1', 'qui_sommes_nous', 'N');
            return false;
        });

        $('#navREJOI').click(function() {
            document.location = getContextPath() + "/cms/cmsContent.action?page=nous_rejoindre";
            xt_med('C', '1', 'nous_rejoindre', 'N');
            return false;
        });

        $('#navPLAN').click(function() {
            document.location = getContextPath() + "/cms/cmsContent.action?page=plan_du_site";
            xt_med('C', '1', 'plan_du_site', 'N');
            return false;
        });

        $('#navMENT').click(function() {
            document.location = getContextPath() + "/cms/cmsContent.action?page=mentions_legales";
            xt_med('C', '1', 'mentions_legales', 'N');
            return false;
        });

        $('#navAIDE').click(function() {
            document.location = getContextPath() + "/cms/cmsContent.action?page=aide";
            xt_med('C', '1', 'aide', 'N');
            return false;
        });

        $('#navTARI').click(function() {
            document.location = getContextPath() + "/cms/cmsContent.action?page=nos_tarifs";
            xt_med('C', '1', 'nos_tarifs', 'N');
            return false;
        });

        $('#navDOCU').click(function() {
            document.location = getContextPath() + "/cms/cmsContent.action?page=documentation";
            xt_med('C', '1', 'documentation', 'N');
            return false;
        });

        $('#cmsContent').historyadd(function(e, currentHash, previousHash) {
            // $(this).html("<h1>EMPTY ARTICLE</h1>");
                // alert("status : historyadd : currentHash -> : " +
                // currentHash);
            });

        // ------------------------------------------------
        // logic navigation history
        // ------------------------------------------------

        $('#cmsContent').history(function(e, currentHash, previousHash) {
            var currentType = currentHash.split("/")[1];
            var currentId = currentHash.split("/")[2];
            var thematique = currentHash.split("/")[0];
            lastUrl = currentHash.split("!")[1];          
            // register home nav history
                if (currentHash == '') {
                    callSpiraleFeeder(null);
                    $("#flash").removeClass('Spirale');
                    $("#flash").addClass('SpiraleHome');
                    getHTMLCmsContent("1238511282575", "Rubrique_C");
                } else if (currentId != null) {
                    callSpiraleFeeder(currentType + "," + currentId);
                    getHTMLCmsContent(currentId, currentType);
                    treatCurrentSection(currentType, currentId);
                    // register home savoir tout savoir nav
                    // history
                } else if (currentHash == "savoir-tout-savoir") {
                    callSpiraleFeeder(0);
                    getHTMLCmsContent("1238511010648", "RubriqueArticle");
                    lightCurrent("navSTS");
                    // register Preparer un project nav history
                } else if (thematique == "souscrire-produit") {
                    callSpiraleFeeder(2);
                    getHTMLCmsContent("1238511020853", "RubriqueProduit");
                    lightCurrent("navPROD");
                } else if (thematique == "consulter-des-experts") {
                    callSpiraleFeeder(3);
                    getHTMLCmsContent("1238511031073", "RubriqueExpert");
                    lightCurrent("navEXP");
                } else if (thematique == "calculer-comparer") {
                    getHTMLCmsContent("1238511079110", "RubriqueCalculerComparer");
                    lightCurrent("navCC");
                } else if (currentHash == "souscrire-produit/fonds/portefeuilles-types") {
                    currentType = currentHash.split("/")[3];
                    var currentId = currentHash.split("/")[4];
                    // getHTMLCmsContent(currentType,
                    // currentId);
                    getHTMLCmsContent(currentId, currentType);
                    lightCurrent("navPROD");
                } else if ((currentHash.split("/")[2] == "portefeuilles-types") || (currentHash.split("/")[2] == "societes-gestion")) {
                    currentType = currentHash.split("/")[3];
                    var currentId = currentHash.split("/")[4];
                    // getHTMLCmsContent(currentType,
                    // currentId);
                    getHTMLCmsContent(currentId, currentType);
                    lightCurrent("navPROD");
                } else if ((currentHash.split("/")[1] == "Fonds")) {                	
                    callSpiraleFeeder("RubriqueFond,0");
                    var fondId = currentHash.split("/")[3];
                    getHTMLCmsContent(fondId, "Produit_P");
                    lightCurrent("navPROD");
                }

            });

        var url = window.location.href;
        if (url.indexOf("searchContent.action") == -1 && url.indexOf("sendMail.action") == -1) {
            var initialHash = $.history.getCurrent();
            if (initialHash == '') {
                getHTMLCmsContent("1238511282575", "Rubrique_C");
            } else {
                var currentType = initialHash.split("/")[1];
                var currentId = initialHash.split("/")[2];
                var temp = initialHash.split("/")[3];
                if (temp != null) {
                    var currentId = initialHash.split("/")[3];
                    var currentType = initialHash.split("/")[2];
                }
                getHTMLCmsContent(currentId, currentType);
                currentURL = currentType + "," + currentId;
            }
            $("#cmsContent").html(initialHash);

            // En cas de non presence du player Flash (ou version
            // incompatible)
            // affichage de la spirale en mode dégradé via la méhode
            // callSpiraleFeeder
            if (!hasFlashPlayer) {
                callSpiraleFeeder(null);
                $("#flash").removeClass('SpiraleHome');
                $("#flash").addClass('Spirale');
            }
        }

        $("#loginRequiredDialog").dialog( {
            autoOpen : false,
            bgiframe : true,
            resizable : false,
            width : 500,
            modal : true,
            overlay : {
                backgroundColor : '#000',
                opacity : 0.5
            },
            buttons : {
                'Devenir membre' : function() {
                    window.location = getContextPath() + "/signup/index.action";
                },
                'Se connecter' : function() {
                    window.location = getClientRoot() + "/login/index.action";
                }
            }
        });

    });
    
// ------------------------------------------------
// Breadcrumb
// ------------------------------------------------
function getBreadCrumbItemContent(index, label, jsAction) {
    return "<li>></li><li id=\"item" + index + "\"><a href=\"#\" onclick=\"" + jsAction + "\">" + label + "</a></li>";
}

function updateBreadCrumb(xmlContent) {
    var htmlContent = "<ul><li id=\"item0\"><a href=\"" + getContextPath() + "/\">Accueil</a></li>";
    if (xmlContent != null) {
        var index = "";
        var label = "";
        var url = "";
        var jsAction = "";
        var item;

        // XML parsing for Internet Explorer
        if ($.browser.msie) {
            var xmlObj = new ActiveXObject('Microsoft.XMLDOM');
            xmlObj.async = false;
            xmlObj.loadXML(xmlContent);
            for ( var i = 0; i < xmlObj.getElementsByTagName('breadCrumb')[0].childNodes.length; i++) {
                item = xmlObj.getElementsByTagName('breadCrumb')[0].childNodes(i);
                index = item.getAttribute("index");
                if (index > 0) {
                    label = item.getElementsByTagName('label')[0].text;
                    url = item.getElementsByTagName('link')[0].text;
                    jsAction = getBreadCrumbItemJSAction(url, index);
                    htmlContent += getBreadCrumbItemContent(index, label, jsAction);
                }
            }
        } else { // XML parsing for other browsers
            $(xmlContent).find("item").each(function() {
                index = $(this).attr("index");
                if (index > 0) {
                    label = $(this).find("label").text();
                    $(this).html($(this).html().replace("<link>", "<url>"));
                    url = $(this).find("url").html();
                    jsAction = getBreadCrumbItemJSAction(url, index);
                    htmlContent += getBreadCrumbItemContent(index, label, jsAction);
                }
            });
        }
    }
    htmlContent += "</ul>";
    $("#Poucet > ul").remove();
    $("#Poucet").append(htmlContent);
}

function getBreadCrumbItemJSAction(url, index) {
    var jsAction = "";
    var locationHref = window.location.href;
    var pageName = locationHref.split("?page=")[1];
    var splittedUrl = url.split(",");
    if ((splittedUrl[0] == "" && pageName != "preparer_un_projet")) { 
        // Cas lien "Préparer un projet" (page différente donc pas de rechargement AJAX)
        url = getContextPath() + "/cms/cmsContent.action?page=preparer_un_projet";
        jsAction = "window.location = '" + url + "'; return false;";
    } else if ((locationHref.indexOf("souscrire_un_produit") != -1)) {
        url = getContextPath() + "/cms/cmsContent.action?page=homepage#souscrire-produit/" + splittedUrl[0] + "/" + splittedUrl[1];
        jsAction = "window.location = '" + url + "'; return false;";
        lightCurrent("navPROD");
    } else if ((locationHref.indexOf("savoir_tout_savoir") != -1)) {
        url = getContextPath() + "/cms/cmsContent.action?page=homepage#savoir-tout-savoir/" + splittedUrl[0] + "/" + splittedUrl[1];
        jsAction = "window.location = '" + url + "'; return false;";
        lightCurrent("navSTS");
    } else if ((locationHref.indexOf("fiche_fonds") != -1)) {
        url = getContextPath() + "/cms/cmsContent.action?page=homepage#souscrire-produit/" + splittedUrl[0] + "/" + splittedUrl[1];
        jsAction = "window.location = '" + url + "'; return false;";
        lightCurrent("navPROD");
    } else if ((locationHref.indexOf("toutes_questionreponses") != -1)) {
        url = getContextPath() + "/cms/cmsContent.action?page=homepage#consulter-des-experts/" + splittedUrl[0] + "/" + splittedUrl[1];
        jsAction = "window.location = '" + url + "'; return false;";
        lightCurrent("navEXP");
    } else if ((locationHref.indexOf("toutes_formations") != -1)) {
        url = getContextPath() + "/cms/cmsContent.action?page=homepage#consulter-des-experts/" + splittedUrl[0] + "/" + splittedUrl[1];
        jsAction = "window.location = '" + url + "'; return false;";
        lightCurrent("navEXP");
    } else if ((locationHref.indexOf("touts_entretiens") != -1)) {
        url = getContextPath() + "/cms/cmsContent.action?page=homepage#consulter-des-experts/" + splittedUrl[0] + "/" + splittedUrl[1];
        jsAction = "window.location = '" + url + "'; return false;";
        lightCurrent("navEXP");
    } else if ((locationHref.indexOf("actualites_sectorielles") != -1)) {
        url = getContextPath() + "/cms/cmsContent.action?page=homepage#souscrire-produit/" + splittedUrl[0] + "/" + splittedUrl[1];
        jsAction = "window.location = '" + url + "'; return false;";
        lightCurrent("navPROD");
    }else if ((locationHref.indexOf("tendance") != -1)) {
        url = getContextPath() + "/cms/cmsContent.action?page=homepage#souscrire-produit/" + splittedUrl[0] + "/" + splittedUrl[1];
        jsAction = "window.location = '" + url + "'; return false;";
        lightCurrent("navPROD");
    }else if ((locationHref.indexOf("analyse_valeurs") != -1)) {
        url = getContextPath() + "/cms/cmsContent.action?page=homepage#souscrire-produit/" + splittedUrl[0] + "/" + splittedUrl[1];
        jsAction = "window.location = '" + url + "'; return false;";
        lightCurrent("navPROD");
    } else {
        jsAction = "callSpiraleFeeder('" + url + "');return false;";
    }
    return jsAction;
}

// ------------------------------------------------
// Spirale Controller
// ------------------------------------------------
function getCardSet(url, callbackFashFunctionName) {
	
    var xmlfile = null;
    var myurl = window.location.href;
    var anchor = myurl.split("#")[1];
    // alert(anchor);
    // alert(url);     
    if ((url == null) && ((anchor == undefined))) {
        var callback = function(string) {

            // update breadcrumb
            updateBreadCrumb(string);
            // update design
            $("#flash").removeClass('Spirale');
            $("#flash").addClass('SpiraleHome');
            $("#Main").removeClass('sousHome');
            $("#Main").addClass('home');
            if (callbackFashFunctionName) {
                getSpirale()[callbackFashFunctionName](string);
            }
            return string;
        };

        // get Data
        if (callbackFashFunctionName) {
            getXMLSpiraleContent("1238510985215", "Rubrique_C", callback);
            return true;
        } else {
            xmlfile = getXMLSpiraleContent("1238510985215", "Rubrique_C");
            callback(xmlfile);
        }       
        return xmlfile;
    } else if (url == "bourse") {
    	xt_med('C', '1', 'spiralehome::bourse', 'N'); 
        $.modal.defaults.closeClass = "modalClose";
        $.modal('<iframe src="' + getStockExchangeDataUrl() + '" height="550" width="900" style="border-color:#44332C">', {
            onOpen : function(dialog) {
                dialog.overlay.fadeIn('slow', function() {
                    dialog.data.hide();
                    dialog.container.fadeIn('slow', function() {
                        dialog.data.slideDown('slow');
                    });
                });
            },
            containerCss : {
                height : 550,
                padding : 0,
                width : 900
            },
            overlayClose : false,
            overlay : 30,
            overlayCss : {
                backgroundColor : "#000"
            }
        }, {
            onClose : function(dialog) {
                dialog.data.fadeOut('slow', function() {
                    dialog.container.hide('slow', function() {
                        dialog.overlay.slideUp('slow', function() {
                            $.modal.close();
                        });
                    });
                });
            }
        });

        var callback = function(string) {

            // update breadcrumb
            // updateBreadCrumb(xmlfile);
            // update design
            $("#flash").removeClass('Spirale');
            $("#flash").addClass('SpiraleHome');
            $("#Main").removeClass('sousHome');
            $("#Main").addClass('home');

            if (callbackFashFunctionName) {
                getSpirale()[callbackFashFunctionName](string);
            }
            return string;
        };
        // get Data
        if (callbackFashFunctionName) {
            getXMLSpiraleContent("1238510985215", "Rubrique_C", callback);
            return true;

        } else {
            xmlfile = getXMLSpiraleContent("1238510985215", "Rubrique_C");
            callback(xmlfile);
        }
        return xmlfile;
    } else if ((url == 0)) {
        var callback = function(string) {

            // update breadcrumb
            updateBreadCrumb(string);
            // update design
            $("#flash").removeClass('SpiraleHome');
            $("#flash").addClass('Spirale');
            $("#Main").removeClass('home');
            $("#Main").addClass('sousHome');
            if (anchor == "savoir-tout-savoir") {
                getHTMLCmsContent("1238511010648", "RubriqueArticle");
            }

            if (callbackFashFunctionName) {
                getSpirale()[callbackFashFunctionName](string);
            }            
            return string;
        };

        // get Data        
        if (callbackFashFunctionName) {
            getXMLSpiraleContent("1238511010648", "RubriqueArticle", callback);
            return true;

        } else {
            xmlfile = getXMLSpiraleContent("1238511010648", "RubriqueArticle");
            callback(xmlfile);
        }        
        return xmlfile;
    } else if (url == 2) {
    	

        var callback = function(string) {

            // update breadcrumb
            updateBreadCrumb(string);
            // update design
            $("#flash").removeClass('SpiraleHome');
            $("#flash").addClass('Spirale');
            $("#Main").removeClass('home');
            $("#Main").addClass('sousHome');

            if (callbackFashFunctionName) {
                getSpirale()[callbackFashFunctionName](string);
            }
            return string;
        };

        // get Data
        if (callbackFashFunctionName) {
            getXMLSpiraleContent("1238511020853", "RubriqueProduit", callback);
            return true;

        } else {
            xmlfile = getXMLSpiraleContent("1238511020853", "RubriqueProduit");
            callback(xmlfile);
        }
        
        return xmlfile;

    } else if (url == 3) {
    	
        var callback = function(string) {

            // update breadcrumb
            updateBreadCrumb(string);
            // update design
            $("#flash").removeClass('SpiraleHome');
            $("#flash").addClass('Spirale');
            $("#Main").removeClass('home');
            $("#Main").addClass('sousHome');
            treatCurrentSection("RubriqueExpert", "1238511031073");

            if (callbackFashFunctionName) {
                getSpirale()[callbackFashFunctionName](string);
            }
            return string;
        };

        // get Data
        if (callbackFashFunctionName) {
            getXMLSpiraleContent("1238511031073", "RubriqueExpert", callback);
            return true;

        } else {
            xmlfile = getXMLSpiraleContent("1238511031073", "RubriqueExpert");
            callback(xmlfile);
        }
        
        return xmlfile;

    } else if (url == 4) {
    	
        var callback = function(string) {

            // update breadcrumb
            updateBreadCrumb(string);
            // update design
            $("#flash").removeClass('SpiraleHome');
            $("#flash").addClass('Spirale');
            $("#Main").removeClass('home');
            $("#Main").addClass('sousHome');
            treatCurrentSection("RubriqueCalculerComparer", "1238511079110");

            if (callbackFashFunctionName) {
                getSpirale()[callbackFashFunctionName](string);
            }
            return string;
        };

        // get Data
        if (callbackFashFunctionName) {
            getXMLSpiraleContent("1238511079110", "RubriqueCalculerComparer", callback);
            return true;

        } else {
            xmlfile = getXMLSpiraleContent("1238511079110", "RubriqueCalculerComparer");
            callback(xmlfile);
        }
        
        return xmlfile;

    } else if ((url != null)) {
    	//alert(url.split(",")[0]+"\n"+url.split(",")[1]+"\n"+url.split(",")[2]+"\n"+url.split(",")[3]);
    	
    	if (url.indexOf("http") != -1) {
    		//Comparateurs Simulateurs
    		//tag Xiti
    		var tagPosition = url.split(",")[2]; 
    		var tagTitre = url.split(",")[1];
    		if(tagPosition=="spiralehome")
            {
    			xt_med('C', '5', 'spiralehome::Outil::'+tagTitre, 'N');    			
            }
    		else 
    		{
    			xt_med('C', '5', 'spirale::'+ tagPosition +'::'+tagTitre, 'N'); 
    		}
    		window.location = url.split(",")[0];
        } else {
            // get Data
            var assetId = url.split(",")[1];
            var assetType = url.split(",")[0];

           //tag Xiti
           var tagPosition = url.split(",")[3]; 
           var tagTitre = url.split(",")[2]; 
           //nuage tag
           if(tagPosition=="nuagetag")
           {
        	   xt_med('C', niveauTagByTypeasset(assetType), 'nuagetag::'+tagTitre, 'N');
           }
           //spirale Home
           else if(tagPosition=="spiralehome")
           {
        	   xt_med('C', niveauTagByTypeasset(assetType), 'spiralehome::'+ typeTagByTypeasset(assetType) +'::'+tagTitre, 'N');
           }
           //all spirale
           else if(tagPosition!=null && tagTitre!=null)
           {           	   
        	   xt_med('C', niveauTagByTypeasset(assetType), 'spirale::'+ tagPosition +'::'+tagTitre, 'N');
           }
        	   
            
            var callback = function(string) {

                // alert("XML FILE : -> " + xmlfile);
                getHTMLCmsContent(assetId, assetType);
                treatCurrentSection(assetType, assetId);
                // update design
                $("#flash").removeClass('SpiraleHome');
                $("#flash").addClass('Spirale');
                $("#Main").removeClass('home');
                $("#Main").removeClass('sousHome');
                // update breadcrumb
                updateBreadCrumb(string);

                if (callbackFashFunctionName) {
                    getSpirale()[callbackFashFunctionName](string);
                }
                return string;
            };

            // get Data
            if (callbackFashFunctionName) {
                getXMLSpiraleContent(assetId, assetType, callback);
                return true;

            } else {
                xmlfile = getXMLSpiraleContent(assetId, assetType);
                callback(xmlfile);
            }
            return xmlfile;
        }
    } else {
    	
        var assetId = anchor.split("/")[2];
        var assetType = anchor.split("/")[1];
        // alert(assetType +" : " + assetId );
        var temp = anchor.split("/")[3];
        if (temp != null) {
            assetId = anchor.split("/")[3];
            assetType = anchor.split("/")[2];
        }

        var callback = function(string) {

            $("#flash").removeClass('SpiraleHome');
            $("#flash").addClass('Spirale');
            treatCurrentSection(assetType, assetId);
            // updateBreadCrumb(string);

            if (callbackFashFunctionName) {
                getSpirale()[callbackFashFunctionName](string);
            }
            return string;
        };

        // get Data
        if (callbackFashFunctionName) {
            getXMLSpiraleContent(assetId, assetType, callback);
            return true;

        } else {
            xmlfile = getXMLSpiraleContent(assetId, assetType);
            callback(xmlfile);
        }
        return xmlfile;
    }

}
//------------------------------------------------
//niveau Tag By Typeasset
//------------------------------------------------
function typeTagByTypeasset(type){ 
	var typePage=""; 
	var niv="";

	 switch (type)
	 {
	 case "Article_C":{typePage="Articles";niv="2";break;}
	 case "Projet_C":{typePage="projets";niv="3";break;}
	 case "Produit_C": {typePage="Produits";niv="7";break;}
	 case "Fond":{typePage="Fonds";niv="7";break;}
	 case "Portefeuille":{typePage="Portefeuille";niv="7";break;}
	 case "RubriqueFond":{typePage="homefond";niv="7";break;}
	 case "RubriqueBourse":{typePage="homebourse";niv="7";break;}
	 case "ActuSecto":{typePage="ActuSecto";niv="7";break;}
	 case "AnalyseValeurs":{typePage="AnalyseValeurs";niv="7";break;}
	 case "Tendance":{typePage="Tendance";niv="7";break;}
	 case "Societes":{typePage="dossierfonds";niv="7";break;}
	 case "Actions":{typePage="dossierfonds";niv="7";break;}
	 case "Portefeuilles":{typePage="dossierfonds";niv="7";break;}
	 case "DescDossierFond":{typePage="dossierfonds";niv="7";break;}
	 case "Produit_P":{typePage="societe";niv="7";break;}
	 case "thematiqueFond":{typePage="dossierfonds";niv="7";break;}
	 case "Formation":{typePage="Formations Videos";niv="4";break;}
	 case "QR": {typePage="Questions Reponses";niv="4";break;}
	 case "ParoleExpert":{typePage="Paroles experts";niv="4";break;}
	 case "Conference":{typePage="Conferences";niv="4";break;}
	 case "RubriqueFormation":{typePage="homeformationvideo";niv="4";break;}
	 case "RubriqueConference":{typePage="homeconference";niv="4";break;}
	 case "RubriqueParoleExpert":{typePage="homeparoleexpert";niv="4";break;}
	 case "RubriqueQuestionReponse":{typePage="homequestionreponse";niv="4";break;}
	                 	 
	 default: {typePage="Outil";niv="5";break;}
	 }
	 return typePage;
}

//------------------------------------------------
//niveau Tag By Typeasset
//------------------------------------------------
function niveauTagByTypeasset(type){ 
	var typePage=""; 
	var niv="";

	 switch (type)
	 {
	 case "Article_C":{typePage="Articles";niv="2";break;}
	 case "Projet_C":{typePage="projets";niv="3";break;}
	 case "Produit_C": {typePage="Produits";niv="7";break;}
	 case "Fond":{typePage="Fonds";niv="7";break;}
	 case "Portefeuille":{typePage="Portefeuille";niv="7";break;}
	 case "RubriqueFond":{typePage="homefond";niv="7";break;}
	 case "RubriqueBourse":{typePage="homebourse";niv="7";break;}
	 case "ActuSecto":{typePage="ActuSecto";niv="7";break;}
	 case "AnalyseValeurs":{typePage="AnalyseValeurs";niv="7";break;}
	 case "Tendance":{typePage="Tendance";niv="7";break;}
	 case "Societes":{typePage="dossierfonds";niv="7";break;}
	 case "Actions":{typePage="dossierfonds";niv="7";break;}
	 case "Portefeuilles":{typePage="dossierfonds";niv="7";break;}
	 case "DescDossierFond":{typePage="dossierfonds";niv="7";break;}
	 case "Produit_P":{typePage="societe";niv="7";break;}
	 case "thematiqueFond":{typePage="dossierfonds";niv="7";break;}
	 case "Formation":{typePage="Formations Videos";niv="4";break;}
	 case "QR": {typePage="Questions Reponses";niv="4";break;}
	 case "ParoleExpert":{typePage="Paroles experts";niv="4";break;}
	 case "Conference":{typePage="Conferences";niv="4";break;}
	 case "RubriqueFormation":{typePage="homeformationvideo";niv="4";break;}
	 case "RubriqueConference":{typePage="homeconference";niv="4";break;}
	 case "RubriqueParoleExpert":{typePage="homeparoleexpert";niv="4";break;}
	 case "RubriqueQuestionReponse":{typePage="homequestionreponse";niv="4";break;}
	 
	 default: {typePage="Outil";niv="5";break;}
	 }
	 return niv;
}
// ------------------------------------------------
// module bourse data
// ------------------------------------------------
function getBourse(callbackFashFunctionName) {
    var xmlFile = null;
    $.ajax( {
        type : "GET",
        url : getContextPath() + "/bourse/cac/data.action",
        async : callbackFashFunctionName ? true : false,
        dataType : callbackFashFunctionName ? "text" : "xml",
        success : function(xmlData) {

            if (callbackFashFunctionName) {
                getSpirale()[callbackFashFunctionName](xmlData);
            } else {

                var string = (new XMLSerializer()).serializeToString(xmlData);
                xmlFile = string;
            }
        }
    });
    return xmlFile;
}

// ------------------------------------------------
// Spirale Mode Degrade
// ------------------------------------------------

function getCardTypeStyleName(cardTypeNumber) {
    switch (cardTypeNumber) {
    case "0":
        return "folder";
    case "1":
        return "file";
    case "2":
        return "file";
    }
}

function getRubTypeStyleName(rubTypeNumber) {
    switch (rubTypeNumber) {
    case "0":
        return "orange";
    case "1":
        return "yellow";
    case "2":
        return "pink";
    case "3":
        return "green";
    case "4":
        return "blue";
    }
}

function getSpiraleItemContent(index, rubtype, url, label) {
    var style = "";
    if (alternateSpiraleItemsNumber > 4) {
        style = "display:none;";
    }
    var itemContent = "<li id=\"spiraleItem" + alternateSpiraleItemsNumber + "\" style=\"" + style + "\" class='" + getRubTypeStyleName(rubtype) + "'>";
    itemContent += "<a href=\"#\" onclick=\"callSpiraleFeeder('" + url + "');return false;\">" + label + "</a></li>";
    return itemContent;
}

function getFlashPlayerContent() {
    var content = "<p class=\"presentation_spirale\">Pour une meilleure navigation, installez<br/>la derni&egrave;re version du player Flash<br/>"
            + "<a href=\"http://www.adobe.com/go/getflashplayer\" target=\"_blank\">" + "<img src=\"../images/get_flash_player.gif\" "
            + "alt=\"Installer Adobe Flash player\" />" + "</a></p>";
    return content;
}

function getAlternateSpiraleContent(id) {
    var htmlContent = "";
    var xmlContent = getCardSet(id);
    var cardType = "";
    var card;
    var rubtype = "";
    var label = "";
    var url = "";
    var style = "";

    // XML parsing for Internet Explorer
    if ($.browser.msie) {
        var xmlObj = new ActiveXObject('Microsoft.XMLDOM');
        xmlObj.async = false;
        xmlObj.loadXML(xmlContent);
        cardType = xmlObj.getElementsByTagName('cardset')[0].childNodes[0].getAttribute("cardtype");
        htmlContent += "<ul class='" + getCardTypeStyleName(cardType) + "'>";
        for ( var i = 0; i < xmlObj.getElementsByTagName('cardset')[0].childNodes.length; i++) {
            card = xmlObj.getElementsByTagName('cardset')[0].childNodes(i);
            rubtype = card.getAttribute("rubtype");
            label = card.getElementsByTagName('label')[0].text;
            label = label.replace(/<[^>]*>/g, " ");
            url = card.getElementsByTagName('link')[0].text;
            htmlContent += getSpiraleItemContent(alternateSpiraleItemsNumber, rubtype, url, label);
            alternateSpiraleItemsNumber++;
        }
    } else { // XML parsing for other browsers
        cardType = $(xmlContent).find("card").attr("cardtype");
        htmlContent += "<ul class='" + getCardTypeStyleName(cardType) + "'>";
        $(xmlContent).find("card").each(function() {
            rubtype = $(this).attr("rubtype");
            label = $(this).find("label").text();
            label = label.replace(/<[^>]*>/g, " ");
            $(this).html($(this).html().replace("<link>", "<url>"));
            $(this).html($(this).html().replace("<description>", "</url><description>"));
            url = $(this).find("url").html();
            htmlContent += getSpiraleItemContent(alternateSpiraleItemsNumber, rubtype, url, label);
            alternateSpiraleItemsNumber++;
        });
    }
    htmlContent += "</ul>";
    return htmlContent;
}

function getPagerContent() {
    var pagerContent = "";
    pagerContent += "<div class=\"pager\">";
    pagerContent += "<div id=\"previousSpiraleButton\" style=\"display:none;\" class=\"previous\"><a href=\"#\" onclick=\"showPreviousPage();return false;\">Precedents</a></div>";
    pagerContent += "<div id=\"nextSpiraleButton\" style=\"display:none;\" class=\"next\"><a href=\"#\" onclick=\"showNextPage();return false;\">Suivants</a></div>";
    pagerContent += "</div>";
    return pagerContent;
}

function showElement(element, visible) {
    if (visible) {
        $(element).show();
    } else {
        $(element).hide();
    }
}

function showElementAnimated(element, visible) {
    if (visible) {
        $(element).show();
    } else {
        $(element).hide();
    }
}

function showCurrentPageItems(visible) {
    for ( var i = 0; i < 5; i++) {
        showElement($("#spiraleItem" + ((alternateSpiralePageNumber * 5) + i)), visible);
    }
}

function showPreviousPage() {
    showCurrentPageItems(false);
    alternateSpiralePageNumber--;
    showCurrentPageItems(true);
    if (alternateSpiralePageNumber == 0) {
        showElementAnimated($("#previousSpiraleButton"), false);
    }
    showElementAnimated($("#nextSpiraleButton"), true);
}

function showNextPage() {
    showCurrentPageItems(false);
    alternateSpiralePageNumber++;
    showCurrentPageItems(true);
    if (alternateSpiraleItemsNumber <= ((alternateSpiralePageNumber + 1) * 5)) {
        showElementAnimated($("#nextSpiraleButton"), false);
    }
    showElementAnimated($("#previousSpiraleButton"), true);
}

function addBookMark(c, cid) {
	if (getCrmId() != null && getCrmId() != '') {
        if (cid != null) {
        	$.ajax( {
                type : "POST",
                url : getHostName() + "/Satellite?pagename=SEL/BookMarks/BookMarks",
                data : "crmid=" + getCrmId() + "&cid=" + cid + "&c=" + c,
                async : false,
                success : function(msg) {
                    alert(getAddBookmarkConfirmation());
                },
                error : function(msg) {
                    alert("erreur");
                }
            });
        }
    } else {
    	$("#loginRequiredDialog").dialog('open');
    }
}

function gotoDiagnosticPatrimonial(url)
{
	if (getCrmId() != null && getCrmId() != '') {
		window.location = url;
	}
	else
	{
		$("#loginRequiredDialog").dialog('open');
	}
}

// ------------------------------------------------
// Moteur de recherche
// ------------------------------------------------
function searchContent(context, q, o, s, c, p, reset) {
    var url = context + "/cms/searchContent.action?";

    var t = "";
    if (reset == false) {
        t += getCurrentTotal() + "_" + getCurrentTotalArticles() + "_" + getCurrentTotalProjets();
        t += "_" + getCurrentTotalProduits() + "_" + getCurrentTotalExperts() + "_" + getCurrentTotalOutils();
    }
    url += "q=" + escape(q) + "&";
    var params = {
        o : (o ? o : ""),
        s : (s ? s : ""),
        c : (c ? c : ""),
        p : (p ? p : "1"),
        t : t
    };
    url += jQuery.param(params);

    window.location = url;
}

function changeCategory(category) {
    searchContent(getContextPath(), getCurrentQuery(), getCurrentOrder(), getCurrentSort(), category, null, false);
}

function changePage(page) {
    searchContent(getContextPath(), getCurrentQuery(), getCurrentOrder(), getCurrentSort(), getCurrentCategory(), page, false);
}

function changeOrderSort(order, sort) {
    searchContent(getContextPath(), getCurrentQuery(), order, sort, getCurrentCategory(), null, false);
}
