﻿var common =
{
    init: function (root) {
        common.ready = true;

        // comportement des liens
        common.showCounter = 0;

        common.initSub(root);

        var panel = $("PANEL");
        if (panel) {
            panel.addEvent("mouseover", common.checkSub.bindWithEvent(this, 1));
            panel.addEvent("mouseout", common.checkSub.bindWithEvent(this, -1));
        }

        // valeur par d�faut dans les formulaires
        $$("input").each(function (item) {
            if (item.getProperty("alt")) {
                if (item.value == "") item.value = item.getProperty("alt");
                item.addEvent("focus", common.fieldFocus);
                item.addEvent("blur", common.fieldBlur);
            }
        });
        $$("textarea").each(function (item) {
            if (item.getProperty("alt")) {
                if (item.value == "") item.value = item.getProperty("alt");
                item.addEvent("focus", common.fieldFocus);
                item.addEvent("blur", common.fieldBlur);
            }
        });

        // ouverture d'un popup au d�marrage
        if (common.autoLaunch) {
            common.launchFrame.apply(common, common.autoLaunch);
            common.autoLaunch = null;
        }
    },


    /*** MENU NAVIGATION ***/
    initSub: function (root) {
        if (root == undefined) root = document;
        root.getElements("a[rel]").each(function (item) {
            if (item.rel.split("|")[0] == "nav") {
                item.addEvent("mouseover", common.tempoSub);
                item.addEvent("mouseout", common.cancelSub);
            }
            else item.addEvent("click", common.handleLink);
        });
    },

    tempoSub: function (event) {
        common.menuDisplayed = true;

        event = new Event(event);
        while (event.target && event.target.nodeName != "A") event.target = $(event.target.parentNode);
        common.urlToLoad = event.target.rel.split("|")[1];
        if (common.currentItem) {
            if (common.hideTimer) clearTimeout(common.hideTimer);
            if (common.showTimer) clearTimeout(common.showTimer);
            common.hideSub();
        }
        common.showCounter = 1;
        common.keepSub(event.target);
    },

    cancelSub: function () {
        common.menuDisplayed = false;
        if (common.showTimer) {
            clearTimeout(common.showTimer);
            common.showTimer = 0;
        }
        if (common.currentItem && !common.currentItem.hasClass("over")) common.currentItem = null;

        common.showCounter = 0;
        common.showCounter -= 1;
        common.keepSub();
    },

    showSub: function () {
        common.showTimer = 0;
        common.currentItem.addClass("over");

        var left = common.currentItem.parentNode.offsetLeft;
        if (left == 0) left = 2;
        var offset = $("PERMA").offsetLeft;
        var panel = $("PANEL");
        panel.setStyles({
            display: "block",
            left: offset + Math.min(left, 678 - 265),
            opacity: 0
        });
        if (common.heightEffect) common.heightEffect.stop();
        common.loadNavContent();
        $("PANEL").getElement(".inner").innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;loading...";
        $("PANEL").getElement(".inner").setStyle("height", 40);
        if (common.showEffect) common.showEffect.stop();
        common.showEffect = new Fx.Style(panel, "opacity", { duration: 200 });
        common.showEffect.start(0, 1);

        common.showWhiteMask();
    },

    hideSub: function () {
        common.hideTimer = 0;
        if (common.currentItem) {
            common.currentItem.removeClass("over");
            common.currentItem = null;
        }
        if (common.showEffect) common.showEffect.stop();
        $("PANEL").setStyle("display", "none");

        if (!common.menuDisplayed && !common.frameDisplayed) common.hideWhiteMask();

        common.keepSub();
    },

    // compteurs pour savoir si le menu deroulant doit �tre en position ouverte ou ferm�e
    keepSub: function (target) {
        if (common.hideTimer) clearTimeout(common.hideTimer);
        if (common.showTimer) clearTimeout(common.showTimer);

        if (common.showCounter > 0) {
            if (target) {
                common.currentItem = target;
                common.showTimer = setTimeout("common.showSub()", 100);
            }
        }
        else if (common.showCounter <= 0) {
            common.hideTimer = setTimeout("common.hideSub()", 500);
            common.showCounter = 0;
        }
    },
    checkSub: function (e, b) {
        common.showCounter += b;
        common.keepSub();
    },


    /* Chargement des contenus de la NAV */

    loadNavContent: function () {
        var navCt = new Ajax(common.urlToLoad, { onComplete: common.navContentLoaded, method: 'get' }).request();
    },

    navContentLoaded: function (request) {
        var inner = $("PANEL").getElement("div[class=inner]");
        inner.innerHTML = common.extractSourceBody(request);

        var navLoaded = $("NAV");
        if (common.inputs) {
            for (var i = 0; i < common.inputs.length; i++) {
                common.inputs[i].removeEvents();
            }
        }
        // Gestions du focus des champs de textes dans les differents menus

        common.inputs = $("NAV").getElements("input");
        if (!common.inputs.length) common.inputs = [common.inputs];
        for (var i = 0; i < common.inputs.length; i++) {
            common.inputs[i].addEvent("focus", common.checkSub.bindWithEvent(this, 1));
            common.inputs[i].addEvent("blur", common.checkSub.bindWithEvent(this, -1));
        }

        navLoaded.setStyle("visibility", "hidden");

        common.heightEffect = new Fx.Style(inner, "height", { duration: 200, onComplete: common.viewNavContent }).start(inner.getCoordinates().height, navLoaded.getCoordinates().height);
    },

    viewNavContent: function () {
        if ($("NAV")) $("NAV").setStyle("visibility", "visible");
    },

    /**
    * Comportement liens :
    * - blank : <a rel="external">
    * - popup : <a rel="popup|width|height|sizeable|scrollable">
    * - popup : <a rel="popup|name|width|height|sizeable|scrollable">
    */
    handleLink: function (event) {
        event = new Event(event);
        if (event) {
            event = new Event(event);
            event.preventDefault();
            while (event.target && event.target.nodeName != "A") event.target = $(event.target.parentNode);
            var href = event.target.href;
            var rel = event.target.rel.split("|");
        }

        // fenetre _blank
        if (rel[0] == "external") {
            var win = window.open(href);
            if (win != null) event.preventDefault();
        }
        // fenetre popup
        else if (rel[0] == "popup") {
            var name = "_blank";
            if (isNaN(rel[1])) name = rel.splice(1, 1).toString();

            var resizable = (isNaN(rel[3])) ? "1" : rel[3];
            var scrollbars = (isNaN(rel[4])) ? "1" : rel[4];
            var left = (screen.width - parseInt(rel[1])) / 2;
            var top = (screen.height - parseInt(rel[2])) / 2;

            var params = "width=" + rel[1] + ",height=" + rel[2] + ",scrollbars=" + scrollbars + ",resizable=" + resizable;
            if (window.gecko) params + ",screenx=" + left + ",screeny=" + top;
            params += ",left=" + left + ",top=" + top;

            var win = window.open(href, name, params);
            if (win != null) event.preventDefault();
        }
        // layer/iframe
        else if (common.IS_POPUP_ACTION[rel[0]]) {
            if (window.top.common) window.top.common.layoutPopup(event.target, rel);
            else common.layoutPopup(event.target, rel);
            event.preventDefault();
        }
        // autre gestionnaire
        else if (common.onRelLink) {
            if (common.onRelLink(event.target, rel)) event.preventDefault();
        }
    },
    switchToLink: function (l, t) {
        while (l && l.nodeName != t) l = $(l.parentNode);
        return l;
    },


    /*** GESTION POPUPS DHTML ***/

    IS_POPUP_ACTION: { divpopup: true, framepopup: true, closepopup: true, modalpopup: true },

    layoutPopup: function (item, rel/*Array*/) {
        if (rel[0] == "framepopup") {
            common.launchFrame(rel[1], rel[2], item.href);
            return true;
        }
        else if (rel[0] == "divpopup") {
            common.launchFrame(rel[1], rel[2], item.href, true);
            return true;
        }
        else if (rel[0] == "closepopup") {
            common.clearFrame();
            return true;
        }
        else if (rel[0] == "modalpopup") {
            common.launchFrame(rel[1], rel[2], item.href, false, true);
            return true;
        }
    },

    showWhiteMask: function () {
        /*var content = $("CONTENT");
        var wMask = $("WHITEMASK");
        var footer = $("FOOTER");

        wMask.setStyle("display", "block");
        var contentCoords = content.getCoordinates();
        contentCoords.left = 0;

        // On r�cup�re le top du footer
        // pour d�terminer la hauteur que le masque doit avoir
        // pour r�couvrir toute la page jusqu'au footer
        var bottom = footer.getCoordinates().bottom;
        contentCoords.top = 0;
        contentCoords.height = bottom;

        wMask.setStyles(contentCoords);

        // Opacit� du masque
        document.body.className = "bodymask";
        wMask.setOpacity(0.20); // BLACK
        if (window.ie6) $$("select").setStyle("visibility", "hidden");*/
    },

    hideWhiteMask: function () {
        var wMask = $("WHITEMASK");

        document.body.className = "bodyback";

        wMask.setStyle("display", "none");
        if (window.ie6) $$("select").setStyle("visibility", "visible");
    },

    launchFrame: function (width, height, link, doAjaxLoad, isModal) {
        if (!common.ready) {
            // mise en attente
            common.autoLaunch = [width, height, link, doAjaxLoad, isModal];
            return;
        }

        common.frameDisplayed = true;

        // parametre indicatif
        //link += (link.indexOf('?') > 0) ? "&popup=1" : "?popup=1";

        var wMask = $("WHITEMASK");

        //... Hide the menu bar under the mask
        var vheader = $("HEADER");
        vheader.setStyle("z-index", "99");

        var vperma = $("PERMA");
        vperma.setStyle("z-index", "99");

        if (isModal) {
            //... Deactivate the click on the mask
            wMask.addEvent('click', common.doNothing);
        }
        else {
            //... Reactivate the click on the mask
            wMask.addEvent('click', common.clearFrame);
        }

        // positionnement popup
        var content = $("CONTENT");
        var contentCoords = content.getCoordinates();
        common.showWhiteMask();

        var popup = $("DIVPOPUP");
        // contenu initial

        if (doAjaxLoad) popup.innerHTML = "<strong>loading...</strong>";
        else popup.innerHTML = "<iframe src='" + link + "' width='" + width + "' height='" + height + "' "
			+ "name='pop" + Math.round(Math.random() * 65536) + "' scrolling='no' frameborder='no' "
			+ "style='border:none; overflow:hidden' scrollbars></iframe>";

        var popupCoords = popup.getCoordinates();
        popup.setStyles({
            width: width + "px",
            height: "35px",
            left: contentCoords.width / 2 - width / 2,
            display: "block"
        });
        var top = Math.max(Window.getScrollTop() + (Window.getHeight() - height) / 2, 90);
        popup.setStyle("top", top);

        if (common.frameEffect) common.frameEffect.stop();
        common.frameHeight = height;

        // chargement Ajax ?
        if (doAjaxLoad) var myAjax = new Ajax(link, { onComplete: common.fillPopup, method: 'get' }).request();
        else common.startFrameEffect();
    },

    fillPopup: function (request) {
        var popup = $("DIVPOPUP");
        popup.innerHTML = common.extractSourceBody(request);
        common.init(popup);
        common.startFrameEffect();
    },

    startFrameEffect: function () {
        common.frameEffect = new Fx.Style("DIVPOPUP", "height", { duration: 500 });
        common.frameEffect.start(35, common.frameHeight);
    },

    clearFrame: function (e) {
        common.frameDisplayed = false;

        if (e) {
            var evt = new Event(e);
            evt.preventDefault();
        }

        var vheader = $("HEADER");
        vheader.setStyle("z-index", "100");

        var vperma = $("PERMA");
        vperma.setStyle("z-index", "200");

        common.hideWhiteMask();

        // cacher le bouton close
        var closep = $$("#DIVPOPUP div.close a")[0];
        if (closep) closep.remove();

        // supprimer tous les evenements
        $$("#DIVPOPUP a").each(function (item) {
            item.removeEvents();
        });

        if (common.frameEffect) common.frameEffect.stop();
        common.frameEffect = new Fx.Style("DIVPOPUP", "height", { duration: 500, onComplete: function () {
            $("DIVPOPUP").setStyle("display", "none");
            $("DIVPOPUP").innerHTML = "";
        } 
        });
        common.frameEffect.start(0);
    },


    /*** VALIDATION DES FORMULAIRES ***/

    fieldFocus: function (e) {
        var item = $(new Event(e).target);
        if (item.value == item.getProperty("alt")) item.value = "";
    },
    fieldBlur: function (e) {
        var item = $(new Event(e).target);
        if (item.value == "") item.value = item.getProperty("alt");
    },

    checkForm: function (forms) {
        if (!forms.length) forms = [forms];
        // Recuperation de tout les elements
        forms.each(function (formItem) {
            textInput = formItem.getElements("input[type=text]");
            passInput = formItem.getElements("input[type=password]");
            //checkInput = formItem.getElements("input[type=checkbox]");
            //radioInput = formItem.getElements("input[type=radio]");
            //textArea = formItem.getElements("textarea");
            //selects = formItem.getElements("select");

            textInput.each(function (item) {
                if (item.hasClass("mandatory")) {
                    item.addEvent("focus", common.resetField);
                    item.addEvent("blur", common.checkField);
                }
            });

            passInput.each(function (item) {
                if (item.hasClass("mandatory")) {
                    item.addEvent("focus", common.resetField);
                    item.addEvent("blur", common.checkField);
                }
            });
        });

    },

    resetField: function (e) {
        var evt = new Event(e);
        var item = evt.target;
        item.removeClass("error");
    },
    checkField: function (e) {
        var evt = new Event(e);
        var item = evt.target;
        item.removeClass("error");
        if (!item.value.length || item.value == item.getProperty("alt")) item.addClass("error");
        else {
            if (item.id == "mail" || item.id == "confirmmail") {
                if (item.id == "mail") common.mail = item;
                var checkMail = /^[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}$/;
                if (checkMail.test(item.value)) {
                    if (item.id == "confirmmail") {
                        if (!common.mail) item.addClass("error");
                        else if (item.value != common.mail.value) item.addClass("error");
                    }
                }
                else item.addClass("error");
            }
            else if (item.id.indexOf("birth") != -1) {
                if (!isNaN(parseInt(item.value))) {
                    if (item.id.indexOf("day") != -1) {
                        if (parseInt(item.id.indexOf("day")) > 31 || parseInt(item.id.indexOf("day")) < 1)
                            item.addClass("error");
                    }

                    if (item.id.indexOf("month") != -1) {
                        if (parseInt(item.id.indexOf("month")) > 12 || parseInt(item.id.indexOf("month")) < 1)
                            item.addClass("error");
                    }

                    if (item.id.indexOf("year") != -1) {
                        if (parseInt(item.id.indexOf("year")) > 2000 || parseInt(item.id.indexOf("year")) < 1900)
                            item.addClass("error");
                    }
                }
                else item.addClass("error");
            }
        }
    },

    doNothing: function () {
    },

    /*** LANGUAGES ***/
    targetUrl: String(),

    //... Set the language into the thread
    setLanguage: function (codeCulture, url) {
        common.targetUrl = (url == null ? top.document.location.href : url);

        var myAjax = new Ajax("/LanguageSelection.aspx?culture=" + codeCulture, { onComplete: common.reloadPage, method: 'get' }).request();
    },

    reloadPage: function () {
        top.document.location.href = common.targetUrl;
    },


    /*** TOOLS ***/

    //... Function used for client-side tagging
    tagPage: function (urlPage) {
        /* ga.js
        if (window.pageTracker)
        {
        pageTracker._trackPageview(urlPage);
        }
        */
        if (window.urchinTracker) {
            urchinTracker(urlPage);
        }

        var imgSageMetrics = document.getElementById("imgSageMetrics");
        if (imgSageMetrics) {
            var imgSrc = imgSageMetrics.src.split("pg=")[0] + "pg=" + urlPage + "&ai=";
            imgSageMetrics.src = imgSrc;
        }
    },

    getCookieValue: function (check_name) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        //alert(document.cookie)
        var a_all_cookies = document.cookie.split(';');
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f

        for (i = 0; i < a_all_cookies.length; i++) {
            // now we'll split apart each name=value pair
            a_temp_cookie = a_all_cookies[i].split('=');

            // and trim left/right whitespace while we're at it
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

            // if the extracted name matches passed check_name
            if (cookie_name == check_name) {
                b_cookie_found = true;
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if (a_temp_cookie.length > 1) {
                    cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
                }
                // note that in cases where cookie is initialized but no value, null is returned
                return cookie_value;
                break;
            }

            a_temp_cookie = null;
            cookie_name = '';
        }

        if (!b_cookie_found) {
            return null;
        }
    },

    setCookieValue: function (name, value) {
        var expires = 1000;

        // set time, it's in milliseconds
        var today = new Date();
        today.setTime(today.getTime());

        // if the expires variable is set, make the correct expires time, the
        // current script below will set it for x number of days, to make it
        // for hours, delete * 24, for minutes, delete * 60 * 24
        if (expires) {
            expires = expires * 1000 * 60 * 60 * 24;
        }

        var expires_date = new Date(today.getTime() + (expires));
        document.cookie = name + "=" + escape(value) + ";expires=" + expires_date.toGMTString();
    },

    //... Set the value in the cookie and in the database session
    setSessionValue: function (name, value) {
        common.setCookieValue(name, value);

        var myAjax = new Ajax("/vconsult/Session.ashx?name=" + name + "&value=" + value, { onComplete: common.doNothing, method: 'get' }).request();
    },

    //... Get the value from the cookie
    getSessionValue: function (name) {
        return common.getCookieValue(name);
    },

    //... Determine if this is the user first visit of the current application (duration=mins)
    isUserFirstVisit: function (duration) {
        //... Check if a date already exists into the cookie
        var dateCookie = common.getCookieValue("FirstVisitDate");
        var today = new Date();

        if (dateCookie != null) {
            //... The value exists, check if the user is still in the first visit duration
            var arrDateCookie = dateCookie.split(",");
            var dateFirstVisit = new Date(parseInt(arrDateCookie[0]), parseInt(arrDateCookie[1]), parseInt(arrDateCookie[2]), parseInt(arrDateCookie[3]), parseInt(arrDateCookie[4]));

            //... Calculate the number of minutes since the first visit
            var diff = today - dateFirstVisit; //unit is milliseconds
            diff = Math.round((diff % (1000 * 60 * 60)) / (1000 * 60)); //contains minutes passed since first visit

            //... If the number of minutes doesn't exceed the duration, return false
            if (diff <= duration) {
                common.setCookieValue("FirstVisit", "0");
                return false;
            }
        }

        //... If the value doesn't exist or if the duration has expired, create it and return true
        common.setCookieValue("FirstVisitDate", today.getFullYear() + "," + today.getMonth() + "," + today.getDate() + "," + today.getHours() + "," + today.getMinutes());
        common.setCookieValue("FirstVisit", "1");
        return true;
    },


    /**
    * Extraire le contenu du <body> d'un source HTML
    */
    extractSourceBody: function (src) {
        var reBody = /<body[^>]*>/i;
        var match = reBody.exec(src);
        if (match == null) return src;

        if (src.indexOf("<div id=\"POPUP\">") > 0) {
            var start = src.indexOf("<div id=\"POPUP\">");
            var end = src.lastIndexOf("</div>") + 6;
        }
        else if (src.indexOf("<div id=\"NAV\">") > 0) {
            var start = src.indexOf("<div id=\"NAV\">");
            var end = src.lastIndexOf("</div>") + 6;
        }
        else {
            var start = Math.max(0, src.indexOf(match[0])) + match[0].length;
            var end = src.toLowerCase().indexOf("</body>");
        }

        if (end < start) end = src.length;

        return src.substr(start, end - start);
    },

    arrWindow: Array(),

    openWindow: function (src, name, width, height) {
        var wnd = common.arrWindow[name];

        //... Close the window if already opened
        var isClosed = (wnd == null);
        if (!isClosed) isClosed = (wnd.closed);
        if (!isClosed) wnd.close();

        //... Open a centered window
        var scrHeight = (screen.availheight ? screen.availheight : screen.height - 20);
        var scrWidth = (screen.availwidth ? screen.availwidth : screen.width - 10);

        var top = (scrHeight - height) / 2;
        var left = (scrWidth - width) / 2;

        common.arrWindow[name] = window.open(src, name, "width=" + width + ",height=" + height + ",top=" + top + ",left=" + left + ",scrollbars=yes,location=yes,directories=no,status=yes,toolbar=no,resizable=yes");
        common.arrWindow[name].focus();
    },

    getQueryString: function (variableName) {
        var result = "";

        var querystring = location.search;
        if (!querystring) return result;

        var pairs = querystring.substring(1).split("&");

        for (var i = 0; i < pairs.length; i++) {
            if (pairs[i].split("=")[0] == variableName) result = pairs[i].split("=")[1];
        }

        return result;
    },

    openFrameByQueryString: function () {
        var urlPop = common.getQueryString("urlpopup");
        var width = common.getQueryString("widthpopup");
        var height = common.getQueryString("heightpopup");

        if (width == "") width = 640;
        if (height == "") height = 480;
        if (urlPop != "") common.launchFrame(width, height, '/popup.aspx?urlpopup=' + urlPop + '&heightpopup=' + (height - 40));
    }
}

window.addEvent("domready", common.init);
window.setTimeout("common.init()", 1000);

//... Check if there is an iframe pop-up window to open
if (window.addEventListener)
    window.addEventListener("load", common.openFrameByQueryString, false);
else
    window.attachEvent("onload", common.openFrameByQueryString);

// appel� par Flash apr�s une op�ration client/serveur
function cmpnConfirm(cmpnId, siteId, operation, details, uid) {
    //if (window.console) console.info("Track: cmpn="+cmpnId+", site="+siteId+", op="+operation+", details="+details+", uid="+uid);
}
