// Ajoute un fonctionalité de tri à l'objet Array ***NE PAS MODIFIER***
tfObjSort={
    init:function(){
        Array.prototype.objSort=function(){
            tfObjSort.setThings(this);
            var a=arguments;
            var x=tfObjSort;
            x.a=[];x.d=[];
            for(var i=0;i<a.length;i++){
                if(typeof a[i]=="string"){x.a.push(a[i]);x.d.push(1)};
                if(a[i]===-1){x.d[x.d.length-1]=-1}
            }
            return this.sort(tfObjSort.sorter);
        };
        Array.prototype.strSort=function(){
            tfObjSort.setThings(this);
            return this.sort(tfObjSort.charSorter)
        }
    },
    removeAccent:function(texte)
    {
        return texte.replace(/[ÂÄÀ]/g,'A').replace(/[âäà]/g,'a').replace(/[ÉÊËÈ]/g,'E').replace(/[éêëè]/g,'e').replace(/[ÎÏÌ]/g,'I').replace(/[îïì]/g,'i').replace(/[ÔÖÒ]/g,'O').replace(/[ôöò]/g,'o').replace(/[ÛÜÙ]/g,'U').replace(/[ûüù]/g,'u').replace(/[ÿ]/g,'y').replace(/[Ç]/g,'C').replace(/[ç]/g,'c');
    },
    sorter:function(x,y){
        var a=tfObjSort.a
        var d=tfObjSort.d
        var r=0
        for(var i=0;i<a.length;i++){
            if(typeof x+typeof y!="objectobject"){return typeof x=="object"?-1:1};
            var m=x[a[i]]; var n=y[a[i]];
            var t=typeof m+typeof n;
            if(t=="booleanboolean"){m*=-1;n*=-1}
            else if(t.split("string").join("").split("number").join("")!=""){continue};
            r=m-n;
            if(isNaN(r)){r=tfObjSort.charSorter(m,n)};
            if(r!=0){return r*d[i]}
        }
        return r
    },
    charSorter:function(x,y){
        if(tfObjSort.ignoreCase){x=x.toLowerCase();y=y.toLowerCase()};
        if(tfObjSort.ignoreAccent){x=tfObjSort.removeAccent(x);y=tfObjSort.removeAccent(y)};
        var s=tfObjSort.chars;
        if(!s){return x>y?1:x<y?-1:0};
        x=x.split("");y=y.split("");l=x.length>y.length?y.length:x.length;
        var p=0;
        for(var i=0;i<l;i++){
            p=s.indexOf(x[i])-s.indexOf(y[i]);
            if(p!=0){break};
        };
        if(p==0){p=x.length-y.length};
        return p
    },
    setThings:function(x){
        this.ignoreCase=x.sortIgnoreCase;
        this.ignoreAccent=x.sortIgnoreAccent;
        var s=x.sortCharOrder;
        if(!s){this.chars=false;return true};
        if(!s.sort){s=s.split(",")};
        var a="";
        for(var i=1;i<1024;i++){a+=String.fromCharCode(i)};
        for(var i=0;i<s.length;i++){
            z=s[i].split("");
            var m=z[0]; var n=z[1]; var o="";
            if(z[2]=="_"){o=n+m} else {o=m+n};
            a=a.split(m).join("").split(n).join(o);
        };
        this.chars=a
    }
};
tfObjSort.init();

// Constructeur de l'objet MenuJS ***NE PAS MODIFIER***
function MenuJS(menuId,groupId,mode)
{
    this.menuId = menuId;
    this.groupId = groupId;
    this.mode = mode;
    this.shortPageUrl = this.getPageId(document.location.href);
    this.pageCible = this.shortPageUrl;
    this.currentSelection = 0;
    this.menuRoot = 1;
    this.menu = new Array();
}

// Retourne le id d'une page en fonction de la nomenclature d'Oracle ***NE PAS MODIFIER***
MenuJS.prototype.getPageId = function(longUrl)
{
    var debut = longUrl.indexOf('_pageid=');
    if(debut < 0) return null;
    var fin = longUrl.indexOf('&',debut);
    if(fin < 0) fin = longUrl.length;
    longUrl = longUrl.substring(debut + 8,fin);
    debut = longUrl.indexOf(',');
    if(debut < 0) return null;
    return longUrl.substring(debut + 1);
}

// Permet la sauvegarde dans un cookie ***NE PAS MODIFIER***
MenuJS.prototype.writeCookie = function(Name,Value,Expiry,Path,Domaine,Secure)
{

    if (Expiry != null)

    {

        var datenow = new Date();

           datenow.setTime(datenow.getTime() + Math.round(86400000*Expiry));

           Expiry = datenow.toGMTString();

       }

        Expiry = (Expiry != null) ? '; expires='+Expiry : '';

       Path = (Path != null) ? '; path=' + Path : '';

       Domaine = (Domaine != null) ? '; domain=' + Domaine : '';

       Secure = (Secure != null) ? '; secure' : '';

       document.cookie = Name + '=' + escape(Value) + Expiry + Path + Domaine + Secure;

}

// Permet la lecture d'un cookie ***NE PAS MODIFIER***
MenuJS.prototype.readCookie = function(Name)
{

        var cookies = document.cookie;

       if (cookies.indexOf(Name + '=') == -1) return null;

       var start = cookies.indexOf(Name + '=') + (Name.length + 1);

       var finish = cookies.substring(start,cookies.length);

       finish = (finish.indexOf(';') == -1) ? cookies.length : start + finish.indexOf(';');

       return unescape(cookies.substring(start,finish));
}

// Constructeur de l'objet MenuElement ***NE PAS MODIFIER***
MenuJS.prototype.MenuElement = function(Id,DisplayName,CategoryName,Category,TypeName,Type,ParentId,MoveToId,LinkToId,OrderBy,Position,Hidden,CreationDate,ModificationDate,IsPublic)
{
    this.Id = Id;
    this.DisplayName= DisplayName;
    this.CategoryName = CategoryName;
    this.Category = Category;
    this.TypeName = TypeName;
    this.Type = Type;
    this.ParentId = ParentId;
    this.MoveToId = MoveToId;
    this.LinkToId = LinkToId;
    this.OrderBy = OrderBy;
    this.Position = Position;
    this.Hidden = (Hidden == '1') ? 1 : 0;
    this.CreationDate = CreationDate;
    this.ModificationDate = ModificationDate;
    this.IsPublic = IsPublic;
}

// Retourne les éléments ayant pour parent ou parent forcé le id de l'élément passé en paramètre ***NE PAS MODIFIER***
MenuJS.prototype.menuGetChilds = function(parentId)
{
    var retour = new Array();
    for(var x = 0; x < this.menu.length; x++) if((this.menu[x].MoveToId == '0' && this.menu[x].ParentId == parentId) || (this.menu[x].Id != 1 && this.menu[x].MoveToId == parentId)) retour.push(this.menu[x]);
    return retour; 
}

// Retourne l'élément ayant l'id spécifié ***NE PAS MODIFIER***
MenuJS.prototype.menuGetId = function(id)
{
    for(var x = 0; x < this.menu.length; x++) if(this.menu[x].Id == id) return this.menu[x]; 
}

// Retourne le id de l'elément racine du menu ***NE PAS MODIFIER***
MenuJS.prototype.getRootId = function()
{
    var menuRacine = 1;
    for(var x = 0; x < this.menu.length; x++)
        if(this.menu[x].Id == 1)
        {
            menuRacine = (this.menu[x].MoveToId > 1) ? this.menu[x].MoveToId : 1;
            break;
        }
    this.menuRoot = menuRacine; 
    return menuRacine; 
}

// Retourne l'élément ayant le linktoid spécifié ***NE PAS MODIFIER***
MenuJS.prototype.menuGetLinkToId = function(id)
{
    for(var x = 0; x < this.menu.length; x++) if(this.menu[x].LinkToId == id) return this.menu[x]; 
}

// Retourne le tri effectif pour la branche dont l'id de l'élément est mentionné  ***NE PAS MODIFIER***
MenuJS.prototype.menuGetTri = function(id)
{
   var element = this.menuGetId(id);
   var parentId = 0;
   while(element.OrderBy == '' && element.Id != '1')
   {
      parentId = (element.MoveToId == '0') ? element.ParentId : element.MoveToId;
      element = this.menuGetId(parentId);   
   }
   return (element.OrderBy == '') ? 'c_nom' : element.OrderBy;
}

// Effectue le tri mentionné sur la branche mentionnée ***NE PAS MODIFIER***
MenuJS.prototype.menuDoSort = function(branche,tri)
{
   branche.sortIgnoreCase=true;
   branche.sortIgnoreAccent=true;
   if(tri == 'c_creation') branche = branche.objSort("CreationDate","DisplayName"); 
   else if(tri == 'd_creation') branche = branche.objSort("CreationDate",-1,"DisplayName");
   else if(tri == 'c_modification') branche = branche.objSort("ModificationDate","DisplayName"); 
   else if(tri == 'd_modification') branche = branche.objSort("ModificationDate",-1,"DisplayName");  
   else if(tri == 'c_nom') branche = branche.objSort("DisplayName","ModificationDate"); 
   else if(tri == 'd_nom') branche = branche.objSort("DisplayName",-1,"ModificationDate");
   else if(tri == 'personalise_h')
   {
       for(var x = 0; x < branche.length; x++)
            if(parseInt(branche[x].Position) > 20000000000000) branche[x].Position = (parseInt(branche[x].Position) * -1);
        branche = branche.objSort("Position"); 
   }
   else if(tri == 'personalise_b') branche = branche.objSort("Position");
   for(var x = 0; x < branche.length; x++) branche[x].Position = (x + 1);
   return branche;  
}

// Retourne le premier élément html de type mentionné à partir de l'élément mentionné ***NE PAS MODIFIER***
MenuJS.prototype.getFirstTag = function(tagName, source)
{
    if(!source) return null;
    var items = source.getElementsByTagName(tagName);
    if(!items) return null;
    return items[0];
}

// Retourne le lien parent du ul ***NE PAS MODIFIER***
MenuJS.prototype.getParentNodeOfType = function(noeud,noeudType)
{
    var retour = noeud.parentNode;
    var id = (retour) ? retour.getAttribute('id') : null;
    while(retour && retour.nodeName.toUpperCase() != noeudType.toUpperCase() && this.menuId != id)
    {
        retour = retour.parentNode;
        id = (retour) ? retour.getAttribute('id') : null;
    }
    return (retour && retour.nodeName.toUpperCase() == noeudType.toUpperCase()) ? retour : null;
}

// Retourne le premier élément html de type ul répertorié à partir du lien spécifié ***NE PAS MODIFIER***
MenuJS.prototype.getLinkChildUl = function(lien)
{
    var liNode = this.getParentNodeOfType(lien,'li');
    if(!liNode) return null;
    var subMenu = this.getFirstTag('ul', liNode);
    return subMenu;
}

// Retourne l'id de l'élément html ul parent de l'ul dont le id est mentionné ***NE PAS MODIFIER***
MenuJS.prototype.getPreviousUl = function(ulId)
{
    var element = this.menuGetId(ulId.substring(ulId.indexOf('_')+1));
    if(element) element = this.menuGetId(((element.MoveToId != "0") ? element.MoveToId : element.ParentId));
    if(!element || element.Id == this.menuRoot) return null;
    return this.menuId + '_' + element.Id;
}

// Retourne le lien parent du ul ***NE PAS MODIFIER***
MenuJS.prototype.getParentLink = function(ulId)
{
    return (this.getFirstTag('a',this.getParentNodeOfType(document.getElementById(ulId),'li')));
}

// Retourne le id de la page cible ***NE PAS MODIFIER***
MenuJS.prototype.getPageCible = function(id)
{
    var item = this.menuGetId(id);
    if(!item)
    {
        item = this.menuGetLinkToId(id);
        if(item) id = item.Id;
    }
    while(item && item.Id != 1 && item.Hidden == 0)
    {
        item = this.menuGetId(((item.MoveToId > 0) ? item.MoveToId: item.ParentId));
    }
    if(item && item.Id != 1 && item.Hidden == 1) return item.Id;
    return id;
}


// Applique le style spécifié
MenuJS.prototype.setStyle = function(lien,target,style)
{
    target.style.display = style;
}

// Retourne le style à appliqué
MenuJS.prototype.getStyle = function(enfants,level,pageEnCours)
{
    if(pageEnCours) return ' class="' + this.menuId + 'Selected"';
    else return '';
}

// Ouvre toutes les branches jusqu'à l'élément mentionné
MenuJS.prototype.selectToId = function(ulId)
{
    if(("" + ulId).substring(0,(this.menuId.length + 1)) != (this.menuId + '_')) ulId = this.menuId + '_' + ulId;
    while(ulId)
    {
        var cible = document.getElementById(ulId);
        if(cible) this.setStyle(this.getParentLink(ulId),cible,'block');
        ulId = this.getPreviousUl(ulId);    
    }
}

// Ferme toutes les sous-branches de la branche mentionnée
MenuJS.prototype.closeToId = function(ulId)
{
    if(("" + ulId).substring(0,(this.menuId.length + 1)) != (this.menuId + '_')) ulId = this.menuId + '_' + ulId;
    while(ulId)
    {
        var cible = document.getElementById(ulId);
        if(cible) this.setStyle(this.getParentLink(ulId),cible,'none');
        ulId = this.getPreviousUl(ulId);    
    }
}

// Action lorsqu'un élément contenant des enfants est sélectionné
MenuJS.prototype.toggleMenu = function(lien)
{
    var stayHere = (this.getPageId(lien.href) == this.shortPageUrl) ? true : false;
    var subMenu = this.getLinkChildUl(lien);
    if(!subMenu) return false;
    if(subMenu.style.display == 'block' && this.getPageId(lien.href) == this.shortPageUrl)
    {
        this.setStyle(lien,subMenu,'none');
        return false;
    }
    else if(this.getPageId(lien.href) == this.shortPageUrl)
    {    
        this.closeToId(this.currentSelection);
        this.currentSelection = subMenu.id;
        this.selectToId(this.currentSelection);
        return false;
    }
    return true;
}

// Affiche une branche du menu
// niveau n'est pas utilisé, mais est laissé là en cas de besoin
MenuJS.prototype.menuBranche = function(source,niveau)
{
    if(!source) return false;
    var enfants = (source.Hidden == 0) ? this.menuGetChilds(source.Id) : new Array();
    var pageEnCours = false;
    if(source.Id != this.menuRoot)
    {
        var beforeLink = (source.BeforeLink) ? source.BeforeLink : '';
        var afterLink = (source.AfterLink) ? source.AfterLink : '';
        if(this.pageCible == source.Id) pageEnCours = true;
        if(enfants.length > 0)
        {
            document.write('<li>' + beforeLink + '<a href="/portal/page?_pageid=' + this.groupId + ',' + ((source.LinkToId != "0") ?  source.LinkToId : this.shortPageUrl) + '&_dad=portal&_schema=PORTAL' + ((this.mode) ? ('&_mode=' + this.mode) : '') + '" onclick="return ' + this.menuId + '.toggleMenu(this)"' + this.getStyle(enfants.length,niveau,pageEnCours) + '>' + source.DisplayName + '</a>' + afterLink);
        }
        else
        {
            document.write('<li>' + beforeLink + '<a href="/portal/page?_pageid=' + this.groupId + ',' + ((source.Hidden == 0) ? source.Id : source.LinkToId) + '&_dad=portal&_schema=PORTAL' + ((this.mode) ? ('&_mode=' + this.mode) : '') + '"' + this.getStyle(enfants.length,niveau,pageEnCours) + '>' + source.DisplayName + '</a>' + afterLink);
        }
    }
    if(enfants.length > 0)
    {
        var tri = this.menuGetTri(source.Id);
        enfants = this.menuDoSort(enfants,tri);
        document.write('<ul id="' + this.menuId + '_' + source.Id + '">');
        for(var x = 0; x < enfants.length; x++) this.menuBranche(enfants[x],niveau + 1);
            document.write('</ul>');        
    }
    document.write('</li>');
}

// Affiche une branche du plan de site
// niveau n'est pas utilisé, mais est laissé là en cas de besoin
MenuJS.prototype.menuBranchePlan = function(source,niveau)
{
    if(!source) return false;
    var enfants = (source.Hidden == 0) ? this.menuGetChilds(source.Id) : new Array();
    var pageEnCours = false;
    if(source.Id != this.menuRoot)
    {
        var beforeLink = (source.BeforeLink) ? source.BeforeLink : '';
        var afterLink = (source.AfterLink) ? source.AfterLink : '';
        if(this.pageCible == source.Id) pageEnCours = true;
        if(enfants.length > 0)
        {
            if(source.LinkToId != "0") document.write('<li>' + beforeLink + '<a href="/portal/page?_pageid=' + this.groupId + ',' + source.LinkToId + '&_dad=portal&_schema=PORTAL' + ((this.mode) ? ('&_mode=' + this.mode) : '') + '">' + source.DisplayName + '</a>' + afterLink);
            else document.write('<li>' + beforeLink + '<span>' + source.DisplayName + '</span>' + afterLink);
        }
        else
        {
            document.write('<li>' + beforeLink + '<a href="/portal/page?_pageid=' + this.groupId + ',' + ((source.Hidden == 0) ? source.Id : source.LinkToId) + '&_dad=portal&_schema=PORTAL' + ((this.mode) ? ('&_mode=' + this.mode) : '') + '">' + source.DisplayName + '</a>' + afterLink);
        }
    }
    if(enfants.length > 0)
    {
        var tri = this.menuGetTri(source.Id);
        enfants = this.menuDoSort(enfants,tri);
        document.write('<ul id="' + this.menuId + '_' + source.Id + '">');
        for(var x = 0; x < enfants.length; x++) this.menuBranchePlan(enfants[x],niveau + 1);
        document.write('</ul>');        
    }
    document.write('</li>');
}
            
// Base pour le menu vertical
MenuJS.prototype.menuVertical = function(root)
{
    document.write('<div id="' + this.menuId + '">');
    this.menuBranche(this.menuGetId(root),0);
    document.write('</div>');
}

// Base pour le plan de site
MenuJS.prototype.planSite = function(root)
{
    document.write('<div id="' + this.menuId + '">');
    this.menuBranchePlan(this.menuGetId(root),0);
    document.write('</div>');
}
            
// Base pour le menu horizontal
MenuJS.prototype.menuHorizontal = function(root)
{
    if(!this.menuGetId(root)) return;
    var niveau1 = this.menuGetChilds(root);
    niveau1 = this.menuDoSort(niveau1,this.menuGetTri(this.getRootId()));
    document.write('<div id="' + this.menuId + '">');
    document.write('<table><tr valign="top">');
    for(var x = 0; x < niveau1.length; x++)
    {
        document.write('<td><ul>');
        this.menuBranche(niveau1[x],1);
        document.write('</ul></td>');
    }
    document.write('</tr></table>')
    document.write('</div>');
}

// Point d'entré du menu
MenuJS.prototype.draw = function(option)
{
    this.pageCible = this.getPageCible(this.shortPageUrl);
    if(option == 'horizontal') this.menuHorizontal(this.getRootId());
    else if(option == 'plan') this.planSite(this.getRootId());
    else this.menuVertical(this.getRootId());
    this.selectToId(this.pageCible);
}