// Package BAM_ERMES_GUIJS / Copyright 2025 Archimed SA / JSE

//loading package...
packages.acknowledge('BAM_ERMES_GUIJS');

// file: iotbs.js

// Invasion of the Body Switchers
// This copyright statement must remain in place for both personal and commercial use
// ***********************************************************************************
// Creative Commons License -- http://creativecommons.org/licenses/by-nc-nd/2.0/
// Original concept and article by Malarkey (Andy Clarke) -- http://www.stuffandnonsense.co.uk/
// DOM scripting by Brothercake (James Edwards) -- http://www.brothercake.com/
// Create element and attributes based on a method by beetle -- http://www.peterbailey.net/
//************************************************
//open initialisation function
function iotbs() { 

switcher = new switchManager();
//************************************************

/*****************************************************************************
 Define switching controls
*****************************************************************************/

//create a switcher form ('container-id', 'label')
/*
if(document.getElementById('screen-switcher')!==null){
    var screenSwitcher = new bodySwitcher('screen-switcher', 'Taille du texte ');

    //add a new class option ('classname', 'label')
    screenSwitcher.defineClass('default', '-');
    screenSwitcher.defineClass('fontsize_medium', 'Moyen');
    screenSwitcher.defineClass('fontsize_big', 'Grand');
}

if(document.getElementById('screen-switcher2')!==null){
    var screenSwitcher2 = new bodySwitcher('screen-switcher2', 'Couleurs ');

    //add a new class option ('classname', 'label')
    screenSwitcher2.defineClass('default', '-');
    screenSwitcher2.defineClass('colors_blackwhite', 'Blanc sur noir');
    screenSwitcher2.defineClass('colors_whiteblack', 'Noir sur blanc');
    screenSwitcher2.defineClass('colors_blackyellow', 'Bleu sur jaune');
}

if(document.getElementById('screen-switcher3')!==null){
    var screenSwitcher3 = new bodySwitcher('screen-switcher3', 'Police ');

    //add a new class option ('classname', 'label')
    screenSwitcher3.defineClass('default', '-');
    screenSwitcher3.defineClass('fontfamily_courier', 'Courier');
    screenSwitcher3.defineClass('fontfamily_arial', 'Arial');
    screenSwitcher3.defineClass('fontfamily_tahoma', 'Tahoma');
	screenSwitcher3.defineClass('fontfamily_trebuchet_ms', 'Trebuchet MS');
}
*/
/*****************************************************************************
*****************************************************************************/



//close initialisation function
};


//global preferences manager reference
var switcher;


//setup initialisation function
//.. gecko, safari, konqueror and generic
if(typeof window.addEventListener != 'undefined')
{
	window.addEventListener('load', iotbs, false);
}
//.. opera 7
else if(typeof document.addEventListener != 'undefined')
{
	document.addEventListener('load', iotbs, false);
}
//.. win/ie
else if(typeof window.attachEvent != 'undefined')
{
	window.attachEvent('onload', iotbs);
}


//preferences manager 
function switchManager()
{
	//string for storing the overall custom classname
	//I was originally storing it in the body class name directly
	//but 1.7+ mozilla builds were not honouring the trailing whitespace we need
	this.string  = '';
	
	//store reference to body element
	this.body = document.getElementsByTagName('body')[0];

	//store the initial classname
	this.initial = this.body.className;
	
	//if the default classname is empty, add "iotbs"
	//because we need there to be at least one classname already - 
	//the leading and trailing space in each custom classname is required, 
	//but you can't set the body classname as " something" (beginning with a leading space)
	//because that may not work in Opera 7
	if(this.initial == '')
	{
		this.initial = 'itobs';
	}
	
	//look for a stored cookie
	this.cookie = this.read();

	//if it exists
	if(this.cookie != null)
	{
		//store cookie value to string
		this.string = this.cookie;
		
		//set new body class name
		
		// GJ-20071030 : Comme on fixe les classes c?t? serveur, on a pas besoin de refixer les classes en javascript (on cr?e des doublons sinon)
		this.body.className = this.initial + this.string;
	}
	
	//*** dev
	//document.title = '<' + this.body.className.replace(/ /g,'+') + '>   [' + this.string.replace(/ /g,'+') + ']';
	
};

//set a cookie method
switchManager.prototype.set = function(days)
{
	//format expiry date
	this.date = new Date();
	this.date.setTime(this.date.getTime() + ( days *24*60*60*1000));
	
	//store the string, replacing spaces with '#' so that leading spaces are preserved
	this.info = this.string.replace(/ /g,'#');
	
	//if the value is empty, set its expiry in the past to delete the cookie
	if(this.info == '') { this.date.setTime(0); }
	
	//create the cookie
	document.cookie = 'bodySwitcher=' + this.info
		+ '; expires=' + this.date.toGMTString() 
		+ '; path=/';
		
};


//read a cookie method
switchManager.prototype.read = function()
{
	//set null reference so we always have something to return
	this.cookie = null;
	
	//if a cookie exists
	if(document.cookie)
	{
		//if it's our cookie
		if(document.cookie.indexOf('bodySwitcher')!=-1)
		{
			//extract and store relevant information (turning '#' back into spaces)
			this.cookie = document.cookie.split('bodySwitcher=');
			this.cookie = this.cookie[1].split(';');
			this.cookie = this.cookie[0].replace(/#/g,' ');
		}
	}
	
	return this.cookie;
};


//switcher form constructor
function bodySwitcher(divid, label)
{
	//create an associate array of classnames for this option
	//so we can later iterate through and remove them from the custom classname string
	this.classes = [];

	//start counting options, because we'll need the index of each option as it's created
	//so that an option can be selected by default if necessary
	this.options = 0;
	
	//outer form
	this.attrs = { 'action' : '' };
	this.form = this.createElement('form', this.attrs);
	document.getElementById(divid).appendChild(this.form);

	//fieldset inside form
	//this.fieldset = this.createElement('fieldset');
	//this.form.appendChild(this.fieldset);

	//label inside fieldset
	this.attrs = { 'for' : 'select-' + divid , 'class' : 'visible' };
	this.label = this.createElement('label', this.attrs);
	//this.fieldset.appendChild(this.label);
	this.form.appendChild(this.label);

	//span inside label containing label text
	this.attrs = { 'text' : label };
	this.span = this.createElement('span', this.attrs);
	this.label.appendChild(this.span);

	//select inside label
	this.attrs = { 'id' : 'select-' + divid };
	this.select = this.createElement('select', this.attrs);
	this.label.appendChild(this.select);

	//create a global [within this scope] reference to 'this'
	var self = this;

	//bind onchange handler
	this.select.onchange = function () {

	    //run through classnames array
	    this.classLen = self.classes.length;
	    for (var i = 0; i < this.classLen; i++) {
	        //remove this key (custom class name) from string
	        switcher.string = switcher.string.replace(' ' + self.classes[i] + ' ', '');
	    }

	    //get new value from option
	    this.chosen = this.options[this.options.selectedIndex].value;

	    //if it isn't default then add to string
	    //we need both a leading and a trailing space to work with 
	    //to avoid confusion with identical leading or trailing substrings in classnames,
	    //such as "high" and "highcontrast" or "large-serif" and "small-serif"
	    if (this.chosen != 'default') {
	        switcher.string += ' ' + this.chosen + ' ';
	    }

	    //set new body class name
	    //switcher.body.className = switcher.initial + switcher.string;
	    switcher.body.className = switcher.string;  // GJ-20071030 : Comme on fixe les classes c?t? serveur, on a pas besoin de switcher.initial (on provoque des doublons de classe sinon)

	    //store changes to a cookie which expires a year from now
	    switcher.set(365);

	    //*** dev
	    //document.title = '<' + switcher.body.className.replace(/ /g,'+') + '>   [' + switcher.string.replace(/ /g,'+') + ']';

	};

};

//add a new class option method
bodySwitcher.prototype.defineClass = function(key, val)
{
	//option inside select
	this.attrs = { 'value' : key, 'text' : val }; 
	this.option = this.createElement('option', this.attrs);
	
	this.select.appendChild(this.option);

	//check for cookie value 
	if(switcher.cookie != null)
	{
		//if value contains this key
		if(switcher.cookie.indexOf(' ' + key + ' ')!=-1)
		{
			//select this option
			this.select.selectedIndex = this.options;
		}
	}
	
	//store the classname 
	this.classes[this.options] = key;

	//increase option count
	this.options ++;

};

//create element and attributes method -- http://www.codingforums.com/showthread.php?s=&postid=151108
bodySwitcher.prototype.createElement = function(tag, attrs)
{
	//detect support for namespaced element creation, in case we're in the XML DOM
	this.ele = (typeof document.createElementNS != 'undefined') ? document.createElementNS('http://www.w3.org/1999/xhtml',tag) : document.createElement(tag);

	//run through attributes argument
	if(typeof attrs != 'undefined')
	{
		for(var i in attrs)
		{
			switch(i)
			{
				//create a text node
				case 'text' :
					this.ele.appendChild(document.createTextNode(attrs[i]));
					break;
				
				//create a class name
				case 'class' : 
					this.ele.className = attrs[i];
					break;
				
				//create a for attribute 
				case 'for' : 
					this.ele.setAttribute('htmlFor',attrs[i]);
					break;
				
				//create a generic attribute using IE-safe attribute creation
				default : 
					this.ele.setAttribute(i,'');
					this.ele[i] = attrs[i];
					break;
			}
		}
	}
	return this.ele;
};


// [EOF] for file iotbs.js

// file: gui.js

packages.requires('BAM_ERMES_COMMON');
packages.requires('BAM_JQUERY_ALL');

// GJ-20090319-INJECTION-INFOBULLE-MENU DEBUT : ajout info-bulle contenant la description de l'entr?e (ajout de la gestion de l'attribut "title" pour les infobulles)
Ext.override(Ext.menu.Item, {
    onRender: Ext.menu.Item.prototype.onRender.createSequence(function (container, position) {
        if (typeof this.title == 'string') {
            this.el.dom.setAttribute('title', this.title);
        }
    })
});
// GJ-20090319-INJECTION-INFOBULLE-MENU FIN : ajout info-bulle contenant la description de l'entr?e (ajout de la gestion de l'attribut "title" pour les infobulles)

Ext.override(Ext.menu.Menu, {
    autoWidth: function () {
        var el = this.el, ul = this.ul;
        if (!el) {
            return;
        }
        var w = this.width;
        if (w) {
            el.setWidth(w);
        } else if (Ext.isIE && !Ext.isIE8) {
            el.setWidth(this.minWidth);
            var t = el.dom.offsetWidth; // force recalc
            el.setWidth(ul.getWidth() + el.getFrameWidth("lr"));
        }
    }
});

var ErmesGUI = (function (pub) {

    pub.CnilCookieName = "CookieBannerClosed";

    pub.constructMenu = function (e, bRoot, columnCount) {
        // Si la balise HTML contenant la structure UL>LI>A n'existe pas, on essaie pas de construire le menu ExtJS
        if (!Ext.get(e)) {
            return;
        }


        var items = [];

        // d?claration des variables utilis?es pour le remplacement des espaces encod?s (&nbps;) par des espaces conventionnels
        var espace = String.fromCharCode(160);
        var reg = new RegExp(espace, "g");

        // on retrouve tous les tags li situ?s directement sous le tag courant
        Ext.get(e).select('>li').each(function (loopItem, loopItems, loopIndex) {

            // set current item properties
            var link = this.child('a:first', true);

            // On retrouve tous les sous-menus (tags ul)
            var s = this.select('>ul');
            var currentItem = null;

            if (bRoot) {
                currentItem = Ext.select("#nav_menu_principal ul a.root-menu", true).elements[loopIndex];

                if (typeof (currentItem) != "undefined") {
                    // On affiche explicitement le menu lors du mouseover (ce n'est pas le comportement par d?faut, il faut donc le coder explicitement)
                    currentItem.on('mouseenter', function () {
                        if (this.menu) {
                            this.menu.mouseInside = true;
                            if (this.menu.hidden) {
                                this.menu.show(this);
                            }
                        }
                    });

                    currentItem.on('mouseover', function () {
                        if (this.menu) {
                            this.menu.mouseInside = true;
                            if (this.menu.hidden) {
                                this.menu.show(this);
                            }
                        }
                    });

                    currentItem.on('mouseleave', function () {
                        if (this.menu) {
                            this.menu.mouseInside = false;
                            var m = this.menu;
                            window.setTimeout(function () { ErmesGUI.callback.closeMenu(m); }, 800);
                        }
                    });
                }
            }
            else {
                if (link.innerHTML.toLowerCase() == "<span>-</span>") {
                    items.push("-");
                    return;
                }

                currentItem = {
                    title: link.title, // GJ-20090319-INJECTION-INFOBULLE-MENU : ajout info-bulle contenant la description de l'entr?e (pour les sous-niveaux)
                    text: link.innerHTML,
                    cls: link.className.replace(reg, " ") + ' ermes_main_menu_panel_item',
                    id: link.id,
                    href: link.href,
                    //GJ-20090325-DEBUT : Ajout du target dans le lien HREF construit (utile pour les ev?nements avec target _blank notamment)
                    hrefTarget: link.target,
                    target: link.target
                    // On supprime l'ancien code qui effectuait une navigation en javascript sans tenir compte de l'attribut "target"
                    //GJ-20090325-FIN : Ajout du target dans le lien HREF construit (utile pour les ev?nements avec target _blank notamment)
                };
            }

            // S'il y a des fils, on traite dans l'arbo (g?n?ration du sous-menu)
            if (s.elements.length) {
                var m = new Ext.menu.Menu({
                    cls: "ermes_main_menu_panel column_" + columnCount, // GJ-20090602 : On injecte ?galement une classe refl?tant la position ("colonne" du menu).
                    items: ErmesGUI.constructMenu(s.item(0), false, columnCount),
                    myAnchor: currentItem
                });

                // Gestion de la fermeture automatique quand la souris sort
                var autohidemenu_el = m.getEl();

                if (typeof (autohidemenu_el) != "undefined") {
                    autohidemenu_el.hover(
					function (e) {
					    //console.log("mouseenter : id=%s", m.id);
					    m.mouseInside = true;
					    return true;
					},
					function (e) {
					    //console.log("mouseleave : id=%s", m.id);
					    m.mouseInside = false;
					    window.setTimeout(function () { ErmesGUI.callback.closeMenu(m); }, 800);
					},
					this);

                    var dummy = new Ext.KeyNav(autohidemenu_el, {
                        "esc": function (e) {
                            m.myAnchor.focus();
                        }
                    });
                }
                // On associe le currentItem (le div) avec son menu (pour pouvoir le retrouver par la suite)
                currentItem.menu = m;
            }
            items.push(currentItem);

            // On augmente le num?ro de colonne car on passe sur l'entr?e de menu suivante
            if (bRoot) {
                columnCount++;
            }
        });

        return items;
    };

    pub.buildWAISwitches = function () {
        switcher = new switchManager();
        /*****************************************************************************
        Define switching controls
        *****************************************************************************/

        //create a switcher form ('container-id', 'label')
        if (document.getElementById('content-sub') !== null) {
            var screenSwitcher2 = new bodySwitcher('content-sub', s_WAI_TYPES_COLORS_LABEL);

            //add a new class option ('classname', 'label')
            screenSwitcher2.defineClass('default', '-');
            screenSwitcher2.defineClass('colors_blackwhite', s_WAI_TYPES_COLORS_OPTIONS_colors_blackwhite);
            screenSwitcher2.defineClass('colors_whiteblack', s_WAI_TYPES_COLORS_OPTIONS_colors_whiteblack);
            screenSwitcher2.defineClass('colors_blackyellow', s_WAI_TYPES_COLORS_OPTIONS_colors_blackyellow);
        }

        if (document.getElementById('content-sub') !== null) {
            var screenSwitcher3 = new bodySwitcher('content-sub', s_WAI_TYPES_FONT_FAMILY_LABEL);

            //add a new class option ('classname', 'label')
            screenSwitcher3.defineClass('default', '-');
            screenSwitcher3.defineClass('fontfamily_courier', s_WAI_TYPES_FONT_FAMILY_OPTIONS_fontfamily_courier);
            screenSwitcher3.defineClass('fontfamily_arial', s_WAI_TYPES_FONT_FAMILY_OPTIONS_fontfamily_arial);
            screenSwitcher3.defineClass('fontfamily_tahoma', s_WAI_TYPES_FONT_FAMILY_OPTIONS_fontfamily_tahoma);
            screenSwitcher3.defineClass('fontfamily_trebuchet_ms', s_WAI_TYPES_FONT_FAMILY_OPTIONS_fontfamily_trebuchet_ms);
        }

    };

    pub.restoreScenario = function () {
        var jsonCookie = {};
        jsonCookie = JSON.parse($.cookie("ErmesSearch"));
        if (typeof (jsonCookie) == "undefined" || jsonCookie == null) {
            return;
        }

        if (typeof (jsonCookie.mainScenario) != "undefined") {
            $("option[value='" + jsonCookie.mainScenario + "']", $("#globalScenario")).attr("selected", true);
        }
    };

    pub.sortSelect = function (selElem) {
        var tmpAry = new Array();
        for (var i = 0; i < selElem.options.length; i++) {
            tmpAry[i] = new Array();
            tmpAry[i][0] = selElem.options[i].text;
            tmpAry[i][1] = selElem.options[i].value;
        }
        tmpAry.sort();
        while (selElem.options.length > 0) {
            selElem.options[0] = null;
        }
        for (var i = 0; i < tmpAry.length; i++) {
            var op = new Option(tmpAry[i][0], tmpAry[i][1]);
            selElem.options[i] = op;
        }
        return;
    };

    return pub;
}(ErmesGUI || {}));

ErmesGUI.callback = (function (pub) {

    pub.saveScenario = function () {
        var jsonCookie = {};
        jsonCookie = JSON.parse($.cookie("ErmesSearch"));
        if (typeof (jsonCookie) == "undefined" || jsonCookie == null) {
            jsonCookie = {};
        }

        jsonCookie.mainScenario = $(this).val();
        jsonCookie.mainScenarioText = $(this).find(":selected").text();

        $.cookie("ErmesSearch", JSON.stringify(jsonCookie), { path: '/' });
    };

    pub.setScenario = function () {
        var form = $(".searchContainer").data("form");
        if (typeof (form) == "undefined" || form == null) {
            return;
        }

        form.Query.query.ScenarioCode = $(this).val();
        delete form.Query.query.SessionGuid;
        $(".searchContainer").data("form", form);
    };

    // Toggle boite login
    pub.toggleLoginBox = function () {

        var $div = $("#nav_menu_perso");
        $div.find("ul").toggle();
        $div.find("#perso_authentification").toggle();
        $div.find("#compte").toggle();

        var serviceDiv = $("#perso_services");
        if (serviceDiv.hasClass("ermesLoginBoxLoading")) {
            serviceDiv.load(
				"/medias/feed/UserServicesFragment.aspx?instance=" + serviceDiv.attr("data-instance"),
				function () {
				    $("#perso_services").removeClass("ermesLoginBoxLoading");
				}
			);
        }

        var $login = $div.find("#carte");
        if ($login.length > 0) {
            $login.focus();
        }

        return false;
    };

    // Fermeture menu javascript
    pub.closeMenu = function (m) {
        //console.log("closing menu %s", m.el.dom.textContent.trim());

        if (typeof (m) == "undefined") {
            //console.log("menu null");
            return;
        }

        // Si on a un fils ouvert, on ne ferme pas
        if (m.activeChild && m.activeChild.hidden == false) {
            //console.log("Fils ouvert : " + m.activeChild.id);
            return;
        }

        // Si la souris est sur le menu, on ne ferme pas (elle a pu repasser dessus durant le timeout)
        //console.log("jquery hover test on %s is %s", m.el.dom.textContent.trim(), $(m.el.dom).is(':hover'));
        if ($(m.el.dom).is(':hover')) {
            return;
        }

        // Sinon, on ferme le menu
        m.hide();

        if (m.parentMenu) {
            ErmesGUI.callback.closeMenu(m.parentMenu);
        }
    };

    // Callback appel? lors de l'activation d'une touche de navigation sur une entr?e de menu de niveau 1
    pub.onNavigate = function (e, sender, anchor) {

        if (!sender) return;
        if (!sender.menu) return;

        var k = e.keyCode;
        switch (k) {
            // Fleche du haut : on masque le menu                                                  
            case Ext.EventObject.ESC:
                sender.menu.hide();
                sender.menu.myAnchor.focus(); // On redonne le focus au menu de niveau 0 associ? pour pouvoir reprendre la navigation clavier facilement
                break;
                // Fleche du bas : on affiche le menu                                                  
            case Ext.EventObject.DOWN:
                sender.menu.show(sender);
                break;
        }
    };

    pub.onWAIOpen = function () {
        Ext.get('extDialogWaiSelector').fadeIn();
        Ext.get('extDialogWaiSelector').anchorTo(Ext.get('wai_eye'), "tr-bl", [0, 0]);
    };

    pub.onWAIClose = function () {
        $('#extDialogWaiSelector').fadeOut("fast");

        // GJ-20081119 : Rechargement des iFrames pour voir le r?sultat
        Ext.select('iframe').each(function () {
            this.dom.contentWindow.location.reload(true);
        });
    };

    pub.onAdvancedSearch = function () {
        if ($("#globalScenario").length > 0) {
            document.location.href = "/medias/form.aspx?instance=" + CFInstance + "&SC=" + $("#globalScenario").val();
        }
        return false;
    };

    pub.onSdiSubscribe = function (event) {
        var serviceName = $(this).data('id');

        jQuery.ajax(
        {
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            url: "/" + CFInstance + "/Ermes/sdiservice.svc/subscribe?ServiceName=" + serviceName,
            success: function (d) {
                if (d.success != null && !d.success) {
                    /* S'il y a eu une erreur */
                    var errorMessage = "Une erreur est survenue";
                    if (d.errors != null && d.errors.length > 0 && d.errors[0].msg != null) {
                        errorMessage = d.errors[0].msg;
                    }
                    $('#sdi-subscription-description').html(errorMessage);
                } else {
                    /* Sinon */
                    $('#sdi-subscription-description').html(s_SdiSuccessMessage);
                }
                $('#sdi-subscription-dialog').dialog();
                return;
            },
            failure: function () {
                $('#sdi-subscription-description').html(errorMessage).dialog();
                $('#sdi-subscription-dialog').dialog();
            }
        });


        return false;
    };

    pub.closeCnilBanner = function () {
        var myDate = new Date();
        //add a day to the date
        myDate.setDate(myDate.getDate() + 20 * 365);

        $.cookie(ErmesGUI.CnilCookieName, "1", { expires: myDate, path: "/" });
        $("#cnil_banner").remove();
    };

    pub.showCnilBanner = function () {
        var cnilCookieValue = $.cookie(ErmesGUI.CnilCookieName);
        if (cnilCookieValue == "1") {
            return;
        }

        var s_CnilBannerContentHtmlEncoded = $('<div/>').text(s_CnilBannerContent).html();
        var htmlContent = '&lt;div id="cnil_banner"&gt;&lt;div class="cnil_message"&gt;' + s_CnilBannerContentHtmlEncoded + '&lt;/div&gt;&lt;div class="cnil_button"&gt;&lt;a href="#" class="cnil_close btn" role="button"&gt;&lt;i class="icon-remove"&gt;&lt;/i&gt; ' + s_CnilBannerButtonClose + '&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;';
        var newDiv = $("<div />").html(htmlContent).text();
        $("body").prepend(newDiv);

        //$("body").prepend('<div id="cnil_banner"><div class="cnil_message">' + ErmesManager.labels.CnilBannerContent + '</div><div class="cnil_button"><a href="#" class="cnil_close btn" role="button"><i class="icon-remove"></i> ' + ErmesManager.labels.SelectionModalClose + '</a></div></div>');
        $("#cnil_banner .cnil_button a").click(ErmesGUI.callback.closeCnilBanner);
    };

    return pub;
}(ErmesGUI.callback || {}));

jQuery(function () {

    // On peuple la liste des sc?narios si ?a n'a pas d?j? ?t? fait cot? serveur
    if ($("#globalScenario").children().length === 0) {
        jQuery.ajax(
		{
		    type: "POST",
		    contentType: "application/json",
		    dataType: "json",

		    url: "/" + CFInstance + "/Ermes/Recherche/Search.svc/ListAllScenario",
		    success: function (json) {
		        //jQuery.tmpl('<option value="${Key}">${Value}</option>', json.d).appendTo("#globalScenario");

		        // hack temporaire pour permettre la mise "hors ligne" de senario en attendant un vrai bool?en administrable.
		        jQuery.tmpl('{{if Value.substr(0,1)!="_"}}<option value="${Key}">${Value}</option>{{/if}}', json.d).appendTo("#globalScenario");
		        ErmesGUI.sortSelect($("#globalScenario")[0]);
		        // On s?lectionne le sc?nario courant
		        ErmesGUI.restoreScenario();
		    }
		});
    }
    else if ($("#globalScenario").children()[0].value === "NONE") { //Aucun sc?nario associ? ? ce portail...
        $("#globalScenario").html("");
    }
    else {
        ErmesGUI.restoreScenario();
    }

    // Binding boite login
    jQuery("#nav_menu_perso li.focus a").click(ErmesGUI.callback.toggleLoginBox);

    // Binding boite login
    jQuery("#nav_menu_perso div#compte a").click(ErmesGUI.callback.toggleLoginBox);

    // Binding KeyPrerss boite login
    jQuery("div#perso_authentification form#authentification input.champ_texte").keyup(function (e) {
        if (e.keyCode == 13) {
            $("form#authentification").submit();
        }
    });

    // Binding : suppression des extra spaces dans le login/pwd
    jQuery("#authentification input:text, #authentification input:password").change(function () {
        var $this = $(this);
        $this.val(jQuery.trim($this.val()));
    });

    // Binding WAI (open)
    $("#wai_open_link").click(ErmesGUI.callback.onWAIOpen);

    // Binding changement de sc?nario (sauvegarde cookie)
    $("#globalScenario").change(ErmesGUI.callback.saveScenario);

    // Binding changement de sc?nario (changement sur la recherche courante)
    $("#globalScenario").change(ErmesGUI.callback.setScenario);

    // Binding WAI (close)
    $('#wai_close_link').click(ErmesGUI.callback.onWAIClose);

    // Bindig Lien "recherche avanc?e"
    $("#globalAdvancedSearchLink").live("click", ErmesGUI.callback.onAdvancedSearch);

    // Binding abonnement recherche publique
    $('a.sdi-subscribe-handler').live("click", ErmesGUI.callback.onSdiSubscribe);

    // Injection des styles WAI
    ErmesGUI.buildWAISwitches();

    // Ferme la login box 
    $('body').live('click', function (e) {
        if (!$(e.target).is('#nav_menu_perso, #nav_menu_perso *')) {
            if ($("#compte", "#nav_menu_perso").is(":visible")) {
                ErmesGUI.callback.toggleLoginBox();
            }
        }
        return true;
    });

});

Ext.onReady(function () {    // Construction du menu ExtJS
    ErmesGUI.constructMenu("ermes_main_menu", true, 0);

});

///////////////////////////////////////////////////////////////////////////////
// Code javascript de lyout "informations dossier lecteur
///////////////////////////////////////////////////////////////////////////////
var AccountSetting = { codeConfig: '', xslPath: "Services/LectorShortAccount.xslt" };
$(document).ready(function () {
    $('#my-account-top').qtip({
        content: {
            text: s_WML_ERMES20_HEADER_ACCOUNT_WIP,
            ajax: {
                url: "/" + CFInstance + "/Ermes/Services/ILSClient.svc/RetrieveShortAccount",
                type: 'POST',
                data: JSON.stringify(AccountSetting),
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                timeout: 60000, //1 min
                success: function (json, status) {

                    if (!ErmesManager.checkResponse(json)) {
                        return;
                    }

                    if (json.d == null) { return false; }
                    var content = json.d.HtmlView;
                    this.set('content.text', content);
                    return false;
                }
            }
        },
        position: { target: 'mouse', my: 'top right', at: 'bottom left', adjust: { x: -10, y: 10 } },
        style: {
            classes: 'ui-tooltip-light ui-tooltip-shadow' // Inherit from preset style
        },
        show: {
            solo: true
        },
        hide: { fixed: true }
    });

    $("#search_reset").live("click", function () {
        $("#textfield").val("");
        return false;
    });

    $("#textfield").live("keypress", function (e) { if (e.keyCode === 13) { $("#main_search_form").submit(); return false; } });
    $("#main_search_form").live("submit", function (e) {
        if ($("#textfield").val() === "") {
            return false;
        }
        else {
            return true;
        }
    });
});


// [EOF] for file gui.js

//package loaded!
packages.complete('BAM_ERMES_GUIJS');

// Served in 450 ms