
/******** Initialisation des éléments du document ********/

var firstLevelSectionId  = null;
var secondLevelSectionId = null;

$(document).ready(function(){
    /**** Menus ****/
    
    // Le sélecteur CSS du lien correspondant à la rubrique de second niveau.
    var secondLevelSelector;
    if (secondLevelSectionId && secondLevelSectionId.length) {
        secondLevelSelector = 'li.'+secondLevelSectionId+'>a';
    }
    
    /** Menu principal **
     * Instanciation des éléments de premier niveau en tant que "MenuElement" et
     * définition d'une classe "actif" pour les éléments de premier ou second
     * niveaux qui correspondent à la page en cours.
     */
    $('#navigation>ul.principal>li').each(function(rank, item) {
        MenuElement.call(item);
        if ($(item).hasClass(firstLevelSectionId)) {
            $('>a', item).addClass('actif');
            if (secondLevelSelector) {
                $(secondLevelSelector, item).addClass('actif');
            }
        }
    });
    
    /** Menu contextuel **
     * Définition d'une classe "actif" pour l'élément correspondant à la page
     * en cours.
     */
    if (secondLevelSelector) {
        $('#menuContextuel'+(firstLevelSectionId == 'fonds' ? 'Fonds' : '')
            +' '+secondLevelSelector).addClass('actif');
    }
    
    
    /**** Calendrier de sélection de la date pour les fonds ****/
    
    var dateField = $('#dateFonds');
    if (dateField.length) {
        dateField.datepicker({
			changeMonth: true,
			changeYear: true
        });
        
        
        /** Persistance de la date **
         * On complète les liens du menu contextuel de façon à ce que la date
         * choisie par l'utilisateur persiste entre les pages "valeurs 
         * liquidatives" et "performances".
         */
        var search = window.location.search;
        if (search)
        {
            $(  '#menuContextuelFonds .valeurs-liquidatives a, '
              + '#menuContextuelFonds .performances         a'
            ).each(function(rank, item) {
                item = $(item);
                item.attr('href', item.attr('href')+search);
            });
        }
    }
    
    
    /**** Vidéos ****/
    $('#videos_liste>ul>li').each(VideoMenuElement);
    
	/**** Agenda ****/
	var scrollContent = $('#agenda .content');
	scrollContent.wrap('<div class="scroll-container" />');
	var scrollPane = $('#agenda .scroll-container');
	
	//build slider
	if ( scrollContent.height() > scrollPane.height() ) {
		scrollPane.append('<div class="scroll-bar" />');
		var scrollbar = $( "#agenda .scroll-bar" ).slider({
				orientation: 'vertical',
				value: 0,
				max: 0,
				min: -100,
				slide: function( event, ui ) {
					if ( scrollContent.height() > scrollPane.height() ) {
						scrollContent.css( "margin-top", Math.round(
							ui.value / -100 * ( scrollPane.height() - scrollContent.height() )
						) + "px" );
					} else {
						scrollContent.css( "margin-top", 0 );
					}
				}
			});
	}

	
    
    /**** Entête flottant des tableaux relatifs aux fonds ****/
    initFloatingHead();
});


/******** Entête flottant des tableaux relatifs aux fonds ********/

function initFloatingHead() {
    var table = $('table.tableauFonds');
    if (table.length != 1) {
        return;
    }
    
    // La valeur CSS "position: fixed" ne fonctionne pas dans IE 6 et versions
    // précédentes. Cf <http://www.howtocreate.co.uk/fixedPosition.html> pour
    // le contournement utilisé ci-après.
    var fixedPosition = !$.browser.msie || parseInt($.browser.version, 10) > 6;
    
    var floatingHeadDiv = $('<div />', document);
	
	floatingHeadDiv.append('<table />');
	
    var floatingHeadTable = floatingHeadDiv.children();
    
	floatingHeadDiv.attr({'style': fixedPosition ? 'top: 0' : "top: expression( ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) + 'px')"})
					.width(table.outerWidth())
                     .css({'display' : 'none',
                           'left'    : table.position().left,
                           'position': fixedPosition ? 'fixed' : 'absolute'});
	
    floatingHeadTable.attr({'id'   : table.attr('id')+'_enteteFlottant',
                            'class': table.attr('class')})
                     .addClass('enteteFlottant');
    //
    
    $('body').append(floatingHeadDiv);
    
    floatingHeadTable.append($('thead', table).clone());
    
    tableHeadCells = $('thead tr:last th', table);
	
	// Ancienne version qui calculait le width de chaque TH du THEAD d'origine pour l'appliqué au THEAD fixed
	// (inutile depuis rajout d'une DIV autour du TABLE fixed
	/*
    $('thead tr:last th', floatingHeadTable).each(function(rank, cell) {
        $(cell).width($(tableHeadCells.get(rank)).width());
    });*/
    
    $(window).scroll(function() {
        floatingHeadDiv.css(
            'display',
            $(document).scrollTop() <= table.position().top
                ? 'none'
                : 'block'
        );
    }).wresize(function() {
        floatingHeadDiv.css('left', table.position().left);
    });
};

/******** Menu ********/

MenuElement = function() {
    $.extend(this, MenuElement.prototype);
    $(this).mouseenter(this.onMouseEnter)
           .mouseleave(this.onMouseLeave);
};
MenuElement.prototype = {
    onMouseEnter: function() {
        this.update(true);
    },
    onMouseLeave: function() {
        this.update(false);
    },
    update: function(active) {
        var subMenu = $('ul:first', this);
        if (subMenu) {
            subMenu.css('visibility', active ? 'visible' : 'hidden');
        }
        $('>a', this)[active ? 'addClass' : 'removeClass']('hover');
    }
};


/******** Vidéos ********/

VideoMenuElement = function() {
    //console.log('VideoMenuElement()');
    
    if (!VideoMenuElement.check(this)) {
        return;
    }
    
    $.extend(this, VideoMenuElement.prototype);
    
    $(this).click(this.onClick);
};

VideoMenuElement.data = {};
VideoMenuElement.idRegExp = /(\d+)$/;

VideoMenuElement.check = function(element) {
    return VideoMenuElement.idRegExp.test(element.id);
};

VideoMenuElement.prototype = {
    onClick: function(event) {
        //console.log('VideoMenuElement.click(): '+this.getVideoId());
        event.preventDefault();
        
        if ($(this).hasClass('actif')) {
            return;
        }
        
        var activeElement = $('#videos_liste li.actif').get(0); 
        if (activeElement) {
            activeElement.deactivate();
        }
        
        this.activate();
    },
    activate: function() {
        var link = $('a:first', this).get(0);
        $(link).replaceWith(link.childNodes);
        
        var iframe = $('#videos_lecteur iframe:first').get(0);
        iframe.contentWindow.location.href = this.getVideoData().playerUrl;
        
        $(this).addClass('actif');
    },
    deactivate: function() {
        var data = this.getVideoData();
        
        $(this).wrapInner(document.createElement("a"))
               .removeClass('actif');
        //
        $('a:first', this).attr('href', data.url);
    },
    getVideoId: function() {
        return this.id.match(VideoMenuElement.idRegExp)[0];
    },
    getVideoData: function() {
        return VideoMenuElement.data[this.getVideoId()];
    }
};



/******** Actualités défilantes ********/

/**
 * Classe "SlidingNews"
 *
 * Permet de gérer le défilement vertical d'une liste de nouvelles (en fait, de
 * n'importe quelles informations qui pourraient être affichées dans des <li>).
 *
 * Doit être appliqué à un objet "<ul>" grâce à "apply".
 *
 * Requiert jQuery (testé ave la version 1.3.2).
 *
 * @param data Array Les données qui seront injectées dans les "<li>" créés lors
 *                   du défilement. Attention, "SlidingNews" ne se charge pas
 *                   d'afficher les "<li>" inialement visibles - on considère en
 *                   effet que ceux-ci sont présents sans l'aide de JavaScript.
 *
 * @param start mixed S'il faut activer le défilement. "start" peut valoir vrai
 *                    pour un démarrage immédiat ou être un nombre de
 *                    millisecondes
**/
SlidingNews = function(data, start) {
    //console.log('SlidingNews(…): ');
    
    $.extend(this, SlidingNews.prototype);
    this.data = data;
    
    var elements = this.getElements();
    this.count = elements.length;
    
    this.state = SlidingNews.STATE_STOP;
    
    if (this.isSlideNeeded()) {
        $(this).height($(this).height());
        
        var element;
        var i = this.count;
        while (--i >= 0) {
            element = elements.get(i);
            SlidingNews.Element.apply(element, [
                undefined,
                $(element).position().top
            ]); 
        }
        
        if (typeof(start) == 'number')
        {
            this.start(start);
        }
        else if (start)
        {
            this.start();
        }
    }

    return this;    
};

/**
 * Constantes d'état utilisé par les instances de SlidingNews 
**/
// Arrêté.
SlidingNews.STATE_STOP  = 0;
// Démarré.
SlidingNews.STATE_RUN   = 1;
// En pause.
SlidingNews.STATE_PAUSE = 2;

SlidingNews.prototype = {
    /**
     * Propriété "data"
     *
     * Les données à afficher dans les "<li>".
     *
     * @type Array
     * @access private
    **/
    data: undefined,
    
    /**
     * Propriété "count"
     *
     * Un compteur permettant de connaître la prochaine actualité à afficher
     * au gré du défilement.
     *
     * @type integer
     * @access private
    **/
    count: undefined,
    
    /**
     * Propriété "state"
     *
     * L'état de l'instance (cf "SlidingNews.STATE_…").
     *
     * @access private
    **/
    state: undefined,
    
    
    /**
     * Méthode "getElements"
     *
     * Retourne l'objet jQuery contenant tous les éléments "<li>" de la liste.
     *
     * @return jQuery
    **/
    getElements: function() {
        return $('>li', this);
    },
    
    /**
     * Méthode "isSlideNeeded"
     *
     * Indique si le défilement est nécessaire ou non.
     *
     * @return Boolean
    **/
    isSlideNeeded: function() {
        return  this.state != SlidingNews.STATE_STOP
             || this.data.length > this.count
    },
    
    /**
     * Méthode "start"
     *
     * Enclenche de défilement.
     *
     * @param delay Number Paramètre optionnel permettant de décaler dans le
     *                     temps (en millisecondes) le début du défilement.
    **/
    start: function(delay) {
        //console.log('SlidingNews.start('+delay+')');
        if (   this.state == SlidingNews.STATE_STOP
            && this.isSlideNeeded())
        {
            if (delay) {
                var o = this;
                setTimeout(function() {
                    o.start();
                }, delay);
            }
            else
            {
                this.start_();
            }
        }
    },
    
    /**
     * Méthode "pause"
     *
     * Met en pause le défilement.
    **/
    pause: function() {
        //console.log('SlidingNews.pause()');
        if (this.state == SlidingNews.STATE_RUN) {
            clearInterval(this.intervalId);
            this.intervalId = undefined;
        }
        this.state = SlidingNews.STATE_PAUSE;
    },
    
    /**
     * Méthode "resume"
     *
     * Ré-enclenche le défilement (lorsque celui-ci était en pause).
    **/
    resume: function() {
        //console.log('SlidingNews.resume()');
        if (this.state == SlidingNews.STATE_PAUSE) {
            this.start_();
        }
    },
    
    /**
     * Méthode "start_"
     *
     * Démarre effectivement le défilement.
     *
     * @access private
    **/
    start_: function() {
        //console.log('SlidingNews.start_()');
        this.state = SlidingNews.STATE_RUN;
        
        var o = this;
        this.intervalId = setInterval(function() {
            o.update();
        }, 80);
        this.update();
    },
    
    /**
     * Méthode "update"
     *
     * Fait défiler les éléments.
     *
     * @access private
    **/
    update: function() {
        //console.log('SlidingNews.update()');
        
        var elements = this.getElements();
        
        var element, i;
        
        element = $(elements.get(0));
        
        var top = element.position().top;
        top -= 1;
                
        /** Suppression du premier élément si nécessaire **/
        
        if (  top
            + element.outerHeight() < 0)
        {
            top += element.outerHeight();
            element.remove();
            i = 1;
        }
        else
        {
            i = 0;
        }
        
        /** Mise à jour des positions **/
        
        do {
            element = $(elements.get(i));
            element.css('top', top);
            top += element.outerHeight();
        } while (++i < elements.length)

        
        /** Ajout d'un nouvel élément si nécessaire **/
        
        if (  top < $(this).height())
        {
            var element = jQuery(this.data[this.count++], document);
            $(this).append(element);
            SlidingNews.Element.apply(element, [
                null,
                top
            ]);
            if (this.count == this.data.length) {
                this.count = 0;
            }
        }
    }
};

/**
 * Classe "SlidingNews.Element"
 *
 * Chaque élément "<li>" de "SlidingNews" est instancié sous la forme d'un
 * "Element".
 *
 * Cf "SlidingNews".
**/
SlidingNews.Element = function(data, topPosition) {
    //console.log('SlidingNews.Element(…): ');
    
    $.extend(this, SlidingNews.Element.prototype);
    
    if (data != undefined) {
        $(this).html(data);
    }
    if (topPosition != undefined) {
        this.initPosition(topPosition);
    }
    
    $(this).mouseenter(this.onMouseEnter)
           .mouseleave(this.onMouseLeave);
};
SlidingNews.Element.prototype = {
    /**
     * @access private
    **/
    initPosition: function(top) {
        $(this).css({
            'position': 'absolute',
            'top': top
        });
    },
    /**
     * @access private
    **/
    onMouseEnter: function() {
        //console.log('SlidingNews.Element.onMouseEnter()');
        this.parentNode.pause();
    },
    /**
     * @access private
    **/
    onMouseLeave: function() {
        //console.log('SlidingNews.Element.onMouseLeave()');
        this.parentNode.resume();
    }
};


/*  
===============================================================================
WResize is the jQuery plugin for fixing the IE window resize bug
...............................................................................
                                               Copyright 2007 / Andrea Ercolino
-------------------------------------------------------------------------------
LICENSE: http://www.opensource.org/licenses/mit-license.php
WEBSITE: http://noteslog.com/
===============================================================================
*/

( function( $ ) 
{
	$.fn.wresize = function( f ) 
	{
		version = '1.1';
		wresize = {fired: false, width: 0};

		function resizeOnce() 
		{
			if ( $.browser.msie )
			{
				if ( ! wresize.fired )
				{
					wresize.fired = true;
				}
				else 
				{
					var version = parseInt( $.browser.version, 10 );
					wresize.fired = false;
					if ( version < 7 )
					{
						return false;
					}
					else if ( version == 7 )
					{
						//a vertical resize is fired once, an horizontal resize twice
						var width = $( window ).width();
						if ( width != wresize.width )
						{
							wresize.width = width;
							return false;
						}
					}
				}
			}

			return true;
		}

		function handleWResize( e ) 
		{
			if ( resizeOnce() )
			{
				return f.apply(this, [e]);
			}
		}

		this.each( function() 
		{
			if ( this == window )
			{
				$( this ).resize( handleWResize );
			}
			else
			{
				$( this ).resize( f );
			}
		} );

		return this;
	};

} ) ( jQuery );




function viewScroll() {
			var xScroll, yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;	
			}
			arrayPageScroll = new Array(xScroll,yScroll);
			return arrayPageScroll;
};	


function openPage(_LINK,_WI,_HEI,_TITLE,_SCROLLING){
	
var alignPage = viewScroll();	
	$('body').prepend('<div id="overflowBG" class="REMOVING REMOVER" style="position:absolute; z-index:300; background:#000; width:100%; height:100%; top:'+alignPage[1]+'px; left:0;"></div><div class="REMOVING" id="contentOpenPage" style="width:'+_WI+'px; height:'+_HEI+'px; background:#FFF; position:absolute; z-index:301; top:50%; left:50%; margin-left:-'+Math.round(_WI*0.5)+'px; margin-top:'+Math.round((_HEI*0.5*(-1))+alignPage[1])+'px"><h3 style="background:#A21013; color:#FFF; font-weight:bold; font-size:16px; padding:0 5px; height:22px; line-height:23px;"><a href="javascript:void(0)" style="float:right; height:14px; line-height:14px; margin-top:4px; width:14px; background:#FFF; color:#F00; font-weight:bold; text-align:center; font-size:12px;" class="REMOVER">X</a>'+_TITLE+'</h3><iframe src="'+_LINK+'" style="height:'+(_HEI-22)+'px; width:'+_WI+'px" scrolling="'+_SCROLLING+'" frameborder="0"></iframe></div>');
$('#overflowBG').css({opacity:0.8});
$('#animation').css({visibility:'hidden'});




$('.REMOVER').bind('click',function(){
$('.REMOVING').remove();
$('#animation').css({visibility:'visible'});
});



$(window).scroll(function(){
alignPage = viewScroll();
$('#overflowBG').css({top:alignPage[1]+'px'});
$('#contentOpenPage').stop();
$('#contentOpenPage').animate({marginTop:Math.round((_HEI*0.5*(-1))+alignPage[1])+'px'},300);

});


	
}



