if (typeof RSR != 'object')
    RSR = {};

//son deplacement a un effet sur le formulaire envoyer a un ami.. les boutons ne fonctionnent plus...
jQuery(document).ready(function() {
    RSR.ready.pageLoad();
});


RSR = {
    ready : {

        // pageLoad ////////////////////////////////////////////////////////////
        // Executed when the page is loaded (like document.ready) //////////////
        pageLoad : function(){

            // RSR audio player init
            RSR.player.init();

            //Set date and time in header.
            //THIS USES LOCAL CLIENT TIME ! IS THAT WE WANT ?
            if (navigator.userAgent.indexOf("MSIE 6.") == -1) {
                var options = {
                    format: '%A %d %B %Y > %H:%M' // 12-hour
                };
                if(jQuery("#jclock").length != 0) {
                    jQuery('.jclock').jclock(options);
                }
            }

            // initialize sendButton in sendToFriend opened lightbox
            RSR.navigation.sendToFriend();

            // mainmenu (corporate nav) is not content reloaded
            RSR.navigation.mainmenu();

        	RSR.ready.rtslibinit();

            // Common ready functions
            RSR.ready.common();

        },

        // contentUpdate ///////////////////////////////////////////////////////
        // Executed when the content is updated by hashUrl /////////////////////
        contentUpdate : function (){

            RSR.ready.common();
            RSR.player.autoPlay();

        },

        // common //////////////////////////////////////////////////////////////
        // Executed when the page is loaded and when the content is updated ////
        common : function(){

            // Load stats
            RSR.stats.doTag();

            // Load redirect
            RSR.navigation.loadRedirects();

            // Load specifics JS
            RSR.loadSpecificJS();

            // Plugins init (scrollPane, tabber, prettyCheckBox, etc.)
            RSR.plugins.init();

            // box_info selection
            jQuery(".box_info .selection").hover(function(){
                jQuery(this).removeClass("selection");
                jQuery(this).addClass("selection_selected");
            },function(){
                jQuery(this).removeClass("selection_selected");
                jQuery(this).addClass("selection");
            });

            // Liste des podcast
            jQuery('#podcastadr_form').hide();
            jQuery('#podcastadr').click(function(){
                jQuery('#podcastadr_form').slideToggle("slow", function () {
                    jQuery('#podcastadr_form_input').select();
                    jQuery('#podcastadr_form_input').focus();
                });
            });

            if(jQuery("#podcastIdToOpen").length != 0) {
                var podcastIdToOpen = jQuery("#podcastIdToOpen").val();
                jQuery("#podcastadr_form_"+podcastIdToOpen).hide();
                jQuery("#"+podcastIdToOpen+" a.head").trigger('click');
            }


            // selection-form.jsp (gallerie videos, photos)
            if(jQuery("#emissions-selection").length != 0) {
                if(jQuery("#loadedContent").size() > 0){
                    var sFormParamFilter = jQuery("#loadedContent").attr("data-filter");
                    var sFormParamEmission = jQuery("#loadedContent").attr("data-emission");
                    updateEmissionsSelect(sFormParamFilter, sFormParamEmission);
                }
            }

            jQuery("#chaines-selection").change( function() {
                var selection = jQuery("#chaines-selection").val();
                updateEmissionsSelect(selection, '');
            });
            jQuery(function() {
                jQuery("#datepicker").datepicker({
                    showOn: 'button', buttonImage: sFormStaticUrl + staticImg + 'calendrier/calendrier.gif', buttonImageOnly: true
                });
            });

            // contact form
            if(jQuery("#selectContact").size() > 0){
                // first init on ready, from querystring parameter
                setContact();
            }
            jQuery("#resetButton-contact").click( function() {
                jQuery("#cname").val("");
                jQuery("#cforname").val("");
                jQuery("#cemail").val("");
                jQuery("#csubject").val("");
                jQuery("#cmessage").val("");
            });

            //setResult();
            jQuery("#sendButton-contact").click(function(event){
                sendTheContestMail(event);
            });

            //Block onClick on images
            if (document.layers){
                document.captureEvents(Event.MOUSEDOWN);
                document.onmousedown=clickNS4;
            }
            else if (document.all&&!document.getElementById){
                document.onmousedown=clickIE4;
            }
            //document.oncontextmenu=new Function("return false")
            associateimages();

            // poll submit
            jQuery("#sendButton-vote").click( function() {
                jQuery("#pollForm").submit();
            });

            // truncate all needed strings
            RSR.strings.truncateAll();
            // channel is ready
            RSR.template.channel.initScroll();


            // rebuild extern inline rtf links
            RSR.strings.rtf.rebuildInlineLinks();
            // init topic
            RSR.template.topic.init();
            // Set page html title
            RSR.navigation.setPageTitle();
            // Display minivote results
            RSR.template.miniVote.displayResults();
            // Init addThis
            RSR.navigation.initAddThis();
            // Add the vitrine
            RSR.template.vitrine.addVitrine();
            // Breaking News Overlay
            RSR.template.bigEvent.init();
            // Shortnews preselection
            RSR.template.shortnews.init();
            // live strip & adapt texts
            RSR.strings.init();
            // thematicSearchForm
            RSR.template.thematic.init();
            //Community Engine init:
            RTS.ce.rsr.app.init();


            // program ready
            if (typeof(RSR.template.program) != "undefined"){
                RSR.template.program.ready();
            }

            // sitemap ready
            if(jQuery("#loadedContent").size() > 0){
                if(jQuery("#loadedContent").attr("data-surl") == "/pages-speciales/sitemap/"){
                    if (typeof(RSR.template.sitemap) != "undefined"){
                        RSR.template.sitemap.ready();
                    }
                }
            }

            jQuery("#removeContestFields").click(function(){
                removeContestFields();
            });

            jQuery("#sendTheContestMail").click(function(){
                sendTheContestMail();
            });

            //Captcha
            jQuery("#reloadCaptcha").click(function(){
                reloadCaptcha();
            });

            //verification de la version de flash player

            if(typeof flashVersion != 'undefined'){
                if (!swfobject.hasFlashPlayerVersion(flashVersion)) {
                    jQuery("#withoutFlashPlayer").css('display','block');
                }
            }


            // init search template (see rsrlib/recherche.js)
            jQuery("#loadedContent[data-surl='/pages-speciales/recherche/']").each(function(){
                if('recherche' in RSR.template){
                    RSR.template.recherche.ready();
                }
            });

            // JPLAYER
            if(jQuery("#rsrJPlayer").size() > 0){
                jQuery("#withoutFlashPlayer").remove();
            }

            if(jQuery(".video-player-holder").size() > 0){
                if(typeof(RTS.player != 'undefined')){
                    RTS.player.init();
                }
            }

            // Videos RTS html5
            RTS.html5.init();

        }
    },
    strings : {
        init:function(){
            var me = this;
            jQuery(".auto-adapt-text").each(function(){
                var h = jQuery(this).attr("data-height");
                me.adaptText(h, this);
            });
            jQuery(".auto-strip-text").each(function(){
                var h = jQuery(this).attr("data-height");
                me.truncateText(h, this,'');
            });
        },
        adaptText: function(height,line){
            var backValue = jQuery(line).css("font-size");
            if (backValue.search(/px/g)!=-1){
                while(jQuery(line).height() > height && jQuery(line).height() > 0){
                    var current = jQuery(line).css("font-size").replace("px","");
                    jQuery(line).css("font-size",(current-1)+"px");
                }
                if(jQuery(line).height() <= 0){
                    jQuery(line).css("font-size",backValue);
                }
            }
        },
        truncateText: function(height, line, type){
            var strOriginal = jQuery(line).text();
            var str="";
            var isValid=false;
            if(type == "neverDots"){
                if(jQuery(line).height() > height){
                    str = jQuery(line).text();
                    while(jQuery(line).height() > height && str.length > 0){
                        str = str.substr(0, str.length -1);
                        jQuery(line).text(str);
                    }
                    str = str.substr(0, str.length -3);
                    return true;
                }else{
                    return false;
                }
            }else if(type == "everDots"){
                str = jQuery(line).text()+"...logo";//...+logo = 7 carac
                jQuery(line).text(str);
                if(jQuery(line).height() > height){
                    //strip text
                    while(jQuery(line).height() > height && str.length > 0){
                        str = str.substr(0, str.length -1);
                        jQuery(line).text(str);
                    }
                    str = str.substr(0, str.length -7); //on enleve donc 7
                }else{
                    // no strip
                    str = str.substr(0, str.length -7);
                }
            }else{
                if(type == "stripInsideHyperlinks"){
                    //Availabke ONLY for filariane (in all pages) and .titrequeltitre in OM HomePage Calendar.
                    //Check and test output before applying it anywhere else.
                    //- does not work if height is set in CSS.
                    //- when calling this function, height parameter can be smaller than the height calculated by firebug
                    //  the rule to follow for the truncate to work is:
                    //    (height*2) < jQuery(line).height()
                    //  instead of:
                    //    height < jQuery(line).height()
                    isValid=true;
                    if(jQuery(line).height() >= (2*height)){
                        var a = jQuery(line).find("a");
                        for(var i=a.length-1; i>=0; i--) {
                            var text = a.eq(i).html();
                            while(jQuery(line).height() >= (2*height) && text != "..."){
                                text = text.substr(0, text.length - 5) + "...";
                                a.eq(i).html(text);
                            }
                        }
                    }else{
                        // no strip
                        str = jQuery(line).html();
                        jQuery(line).html(str);
                    }
                }else{

                    // Standard mode (If cut : 3 dots)
                    //----------------------------------------------------------

                    //alert("jQuery(line).height()= "+jQuery(line).height()+" ?? height= "+height);
                    if(jQuery(line).height() > height){
                        str = jQuery(line).text();
                        var lineHeight = jQuery(line).height();
                        while(lineHeight > height && str.length > 0){
                            str = str.substr(0, str.length -1);
                            jQuery(line).text(str);
                            lineHeight = jQuery(line).height();
                        }
                        str = str.substr(0, str.length -3)+"..."; //on enleve donc 3 et on ajoute ...
                        jQuery(line).text(str);
                    }else{
                        // no strip
                        str = str.substr(0, str.length -3);
                    }
                }
            }

            //Verification de la taille minimal du string sinon string original (sauf pour le filariane)
            if (!isValid){
                // 3 = minimum 3 petits points
                if(str.length > 3){
                    jQuery(line).text(str);
                }else{
                    jQuery(line).text(strOriginal);
                }
            }

        },
        truncateAll: function(){

            var me = this;
            // Standard mode : if cut -> 3dots
            //------------------------------------------------------------------

            // TODO: Replace these "Standard mode" calls, by automatic call with RSR.strings.init(),
            // auto-strip-text class and data-height param.

            // Gallery lightbox
            jQuery("#basicModalContent .table2Colonnes .lightboxContentTop .headerDiapo h1").each(function(){
                RSR.strings.truncateText(28, jQuery(this), "");
            });
            // Chanel Calandar
            jQuery("#calandarBarScroller").find(".box-emission-titre").each(function(){
                RSR.strings.truncateText(24, jQuery(this), "");
                jQuery(this).css("cursor", "default");
            });
            // Navigation left
            jQuery(".content .colonne_left .navigation_left #accordion li a").find(".nav_onglet_body").each(function(){
                RSR.strings.truncateText(15, jQuery(this), "");
            });
            // Vignette
            jQuery(".vignette li p .striptext").each(function(){
                RSR.strings.truncateText(56, jQuery(this), "");
            });
            // Home Info
            jQuery("#tableContentCenter .box_middle_center .home-info-meteo-chapo").each(function(){
                RSR.strings.truncateText(105, jQuery(this), "");
            });
            jQuery("#tableContentCenter .box_middle_center .home-info-dossiers-chapo").each(function(){
                RSR.strings.truncateText(135, jQuery(this), "");
            });

            // Neverdots mode
            //------------------------------------------------------------------
            // Gallery page
            jQuery(".box_body h1.galeries-striptext span").each(function(){
                RSR.strings.truncateText(38, jQuery(this), "neverDots");
            });
            // Box Right de home
            jQuery("#tableContentHome .box_right_body h1 .striptext").each(function(){
                RSR.strings.truncateText(27, jQuery(this), "neverDots");
            });
            jQuery("#tableContentHome .box_right_body h2 .striptext").each(function(){
                RSR.strings.truncateText(15, jQuery(this), "neverDots");
            });
            // Vignette
            jQuery(".vignette .nom_emission .striptext").each(function(){
                RSR.strings.truncateText(16, jQuery(this), "neverDots");
            });
            jQuery(".thematicBox1Text .event_picto a span").each(function(){
                RSR.strings.truncateText(14, jQuery(this), "neverDots");
            });
            jQuery("#tableContentHomeChaine .box_vignette h4").each(function(){
                RSR.strings.truncateText(26, jQuery(this), "neverDots");
            });
            // titre Actu en audio
            jQuery("#iframeLayerContent .actuAudioLightBox h2 span.actuAudioTitle").each(function(){
                RSR.strings.truncateText(18, jQuery(this), "neverDots");
            });
            jQuery("#tableContentCenter .box_middle_center .home-info-bloclibre1-chapo").each(function(){
                // Truncate and make place for picto "more".
                var isTruncated = RSR.strings.truncateText(97, jQuery(this), "neverDots");
                if (isTruncated){
                    jQuery(this).text((jQuery(this).text()).substr(0, (jQuery(this).text()).length -4));
                }
            });

            // Everdots mode
            //------------------------------------------------------------------
            jQuery("#tableContentHome .box_right_body p .striptext").each(function(){
                RSR.strings.truncateText(60, jQuery(this), "everDots");
            });
            jQuery("#mediumBlocTextHeightLimit").each(function(){
                RSR.strings.truncateText(98, jQuery(this), "everDots");
            });
            jQuery(".box_medium_body p span").each(function(){
                RSR.strings.truncateText(98, jQuery(this), "everDots");
            });
            jQuery(".box_center_body_list p span").each(function(){
                RSR.strings.truncateText(45, jQuery(this), "everDots");
            });

            // InsideHyperlinks mode
            //------------------------------------------------------------------
            jQuery("#loadedContent .entete .filarianne").each(function(){
                me.adaptFilariane(this);
            });
            // Infinite loop in IE with considerHtml
            jQuery("#calandarBarScroller").find(".titrequeltitre").each(function(){
                RSR.strings.truncateText(12, jQuery(this), "stripInsideHyperlinks");
            });


        },
        rtf : {
            rebuildInlineLinks : function(){
                jQuery(".rtf a").each(function(){
                    var href = jQuery(this).attr("href");
                    if((href.search(websiteUrl)==-1 && href.search('http')!=-1) || href.search("flux=rss")!=-1){
                        jQuery(this).attr("class", "noAjax");
                    }
                });
            }
        },
        googleSearchEncode: function(q){
            /* google has his own encoder.
            q = escape(q);
            q = q.replace(/\+/g, "%2B");
            q = q.replace(/%20/g, "+");
            q = q.replace("/", "%2F");*/
            return q;
        },
        adaptFilariane: function(fil){

            // log("base:"+jQuery(fil).width());
            // var logA = "base:"+jQuery(fil).width();

            var siblingW = jQuery(fil).siblings(".pictos").width();

            // fix IE7
            if(RTS.browser.IE7){
                var pictosW = 0
                jQuery(fil).siblings(".pictos").children().each(function(){
                    pictosW += jQuery(this).width();
                });
                siblingW = pictosW;
            }

            // log("pictos:"+siblingW); //(full width: 940. padding 5, secure: 15 => 920)
            // var logB = "pictos:"+siblingW;

            var filarianneW = 920 - siblingW;

            // log("new W:"+filarianneW);
            // var logC = "new W:"+filarianneW;
            // alert(logA+"\n"+logB+"\n" + "\n pictosW:"+ pictosW+"\n\n"+logC);

            jQuery(fil).width(filarianneW+"px");
            RSR.strings.truncateText(12, jQuery(fil), "stripInsideHyperlinks");
        }
    },
    template : {
        vitrine : {
            addVitrine : function(){

                if(jQuery("#loadedContent").size() > 0){
                    // html:  info (all devices), normal (mobile)
                    // flash: info (IE), normal (all other devices)
                    var a = navigator.userAgent;
                    var isMobile = (a.match(/iPhone/i) || a.match(/iPod/i) || a.match(/iPad/i) || a.match(/mobile/i) || a.match(/N95/i) )

                    if (	(!(jQuery.browser.msie && jQuery.browser.version <= 8)) &&
                            ( (isMobile) || (jQuery("#loadedContent").attr("data-surl") == "/info/") )){
                        this.initHtml();
                    }else{
                        this.initFlash();
                    }
                }
            },
            // Represent one slide in the vitrine slideShow, related to one bullet.
            slide :{
                init: function(id){

                    // init slide no more than one time
                    var channel = jQuery("#loadedContent").attr("class");
                    if (typeof(this.list[id]) == 'undefined'){
                        this.list[id] = {
                            dom		: jQuery("#vitrine-html5.normal div.slide."+id),
                            moveBox : jQuery("#vitrine-html5.normal div.slide."+id+" .move-up"),
                            links	: jQuery("#vitrine-html5.normal div.slide."+id+" .move-up .content ul"),
                            time	: parseInt(jQuery("#vitrine-html5.normal div.slide."+id).attr("data-time")) * 1000,
                            id		: id
                        };
                        this.bindEvents(this.list[id]);
                    }

                    // reset all autoNext
                    for (i in this.list){
                        clearTimeout(this.list[i].timeout);
                    }

                    // set current autoNext
                    this.list[id].autoNext = function(){
                        this.timeout = setTimeout(function(){
                            RSR.template.vitrine.frame.moveRight();
                        },this.time);
                    };

                    this.moveUp(this.list[id]);
                },
                bindEvents: function(slide){

                    var m = slide.moveBox;
                    var l = slide.links;
                    var d = slide.dom;
                    var more = jQuery(".logoMore", jQuery(d));

                    var moveLeft = 3;
                    var moveTop  = 22;
                    if (jQuery(l).length > 0){
                        var linksNb	 = jQuery("li", jQuery(l)).length;
                        moveLeft += (linksNb * 2);
                        moveTop  += (linksNb * 15);
                    }

                    var overAvailable = true;
                    var outAvailable = true;

                    jQuery(d).bind("mouseenter", function(){

                        outAvailable = true;
                        if(overAvailable){
                            overAvailable = false;

                            jQuery(m).animate({left:('-='+moveLeft),top:('-='+moveTop)},200);
                            if (jQuery(l).length > 0){
                                jQuery(l).fadeIn(200);
                            }
                            jQuery(more).fadeIn(200);

                        }
                    }).bind("mouseleave", function(){

                        overAvailable = true;
                        if(outAvailable){
                            outAvailable = false;

                            if (jQuery(l).length > 0){
                                jQuery(l).fadeOut(200);
                            }
                            jQuery(more).fadeOut(200);
                            jQuery(m).animate({left:('+='+moveLeft),top:('+='+moveTop)},200);

                        }
                    });
                },
                moveUp:function(slide){

                    var m = slide.moveBox;
                    var d = slide.dom;
                    var h = jQuery(".content p", jQuery(d)).height();
                    var moreThanOne = this.moreThanOne;

                    var nb = (h<22)? 0 : ((h<37)? 1 : ((h<52)? 2 : 3));
                    var states = {};
                    states.hide	 = {top:335, left:87};
                    states.lines  = new Array(
                        {top:192, left:55},
                        {top:178, left:53},
                        {top:164, left:51},
                        {top:150, left:49}
                    );

                    jQuery(m).css("left", states.hide.left);
                    jQuery(m).css("top", states.hide.top);
                    var destination = {left:states.lines[nb].left, top:states.lines[nb].top};
                    jQuery(m).animate(destination,600,function(){
                        if (moreThanOne){
                            slide.autoNext();
                        }
                    });
                }
            },
            frame :{
                init: function(){

                    // bind events
                    jQuery("#vitrine-html5.normal .bullets li").bind("mouseenter", function(){
                        jQuery(this).addClass("over");
                    }).bind("mouseleave", function(){
                        jQuery(this).removeClass("over");
                    });
                    jQuery("#vitrine-html5.normal .bullets li.goleft").click(function(){
                        RSR.template.vitrine.frame.moveLeft();
                    });
                    jQuery("#vitrine-html5.normal .bullets li.goright").click(function(){
                        RSR.template.vitrine.frame.moveRight();
                    });
                    jQuery("#vitrine-html5.normal .bullets li.bullet").click(function(){
                        RSR.template.vitrine.frame.moveTo(jQuery(this).attr("data-id"));
                    });
                    // init
                    jQuery("#vitrine-html5.normal .bullets li.0").addClass("actif");
                    jQuery("#vitrine-html5.normal").css("visibility", "visible");

                    RSR.template.vitrine.slide.moreThanOne = (jQuery("#vitrine-html5.normal div.slide").size() > 1);
                    for (id in RSR.template.vitrine.slide.list){
                        clearTimeout(RSR.template.vitrine.slide.list[id].timeout);
                    }
                    RSR.template.vitrine.slide.list = new Array();
                    RSR.template.vitrine.slide.init(0);
                },
                moveLeft : function(){
                    var slides	= jQuery("#vitrine-html5.normal .frame .slide");

                    var pos = 0;
                    if(typeof(jQuery(slides).css("left")) != "undefined"){
                        pos = parseInt((jQuery(slides).css("left")).replace("px",''));
                    }
                    if(pos > -540 && pos <= 0){ //(pos == 0)
                        // turn arround
                        var newId = parseInt(jQuery("#vitrine-html5.normal .bullets li.bullet").size())-1;
                    }else{
                        var newId = parseInt(jQuery("#vitrine-html5.normal .bullets li.actif").attr("data-id"))-1;
                    }
                    this.moveTo(newId);
                },
                moveRight : function (){
                    var slides	= jQuery("#vitrine-html5.normal .frame .slide");
                    var max = -((slides.size()-1) * 540);

                    var pos = 0;
                    if(typeof(jQuery(slides).css("left")) != "undefined"){
                        pos = parseInt((jQuery(slides).css("left")).replace("px",''));
                    }
                    if(pos < (max+540) && pos >= max){//pos == max
                        // turn arround
                        var newId = 0;
                    }else{
                        var newId = parseInt(jQuery("#vitrine-html5.normal .bullets li.actif").attr("data-id"))+1;
                    }
                    this.moveTo(newId);
                },
                moveTo : function(id){

                    var slides	= jQuery("#vitrine-html5.normal .frame .slide");
                    jQuery("#vitrine-html5.normal .bullets li").removeClass("actif");
                    jQuery("#vitrine-html5.normal .bullets li."+id).addClass("actif");

                    jQuery(slides).animate({left:(-(id*540))});
                    RSR.template.vitrine.slide.init(id);
                }
            },
            breaking:{
                init:function(){

                    jQuery("#vitrine-html5.breaking").css("display","block");

                    var h = jQuery("#vitrine-html5.breaking .move-up .content p").height();
                    var i = (h<24)? 0 : ((h<40)? 1 : ((h<56)? 2 : 3));
                    var pos = this.positions[i];
                    var hasLinks = jQuery("#vitrine-html5.breaking .move-up .content ul").size() > 0;

                    if (hasLinks){
                        var links = jQuery("#vitrine-html5.breaking .move-up .content ul li").size();
                        pos.left -= (links * 2);
                        pos.top  -= (links * 16);
                    }

                    jQuery("#vitrine-html5.breaking").css("visibility","visible");
                    jQuery("#vitrine-html5.breaking .move-up").animate({left:pos.left, top:pos.top}, function(){
                        if(hasLinks){
                            jQuery("#vitrine-html5.breaking .move-up .content ul").fadeIn(200);
                        }
                        jQuery("#vitrine-html5.breaking .logoMore").fadeIn(200);
                    });
                },
                positions: new Array(
                    {top:562, left:60},
                    {top:547, left:58},
                    {top:532, left:56},
                    {top:518, left:54}
                )
            },
            initHtml: function(){

                // Info - Simple animation
                if (jQuery("#loadedContent").attr("class") == "info"){
                    jQuery(".info #vitrine-html5").show(1, function(){

                        jQuery(".move-up", this).css("height", "0px").css("display", "block");
                        var h = jQuery(".title .content h2", this).height() + 56;
                        jQuery(".move-up", this).css("bottom", "-"+h+"px").css("height", h+"px");

                        setTimeout(function(){
                            jQuery(".info #vitrine-html5 .move-up").animate({bottom:0},600,function(){
                                RSR.strings.adaptText(jQuery(".title h1",this).attr("data-height"),jQuery(".title h1",this));
                            })
                        },1000);

                    });
                }else{
                    // Normal
                    var slides	= jQuery("#vitrine-html5.normal .frame .slide");
                    if (slides.size() > 0){
                        jQuery("#vitrine-html5.normal").css("display","block");
                        this.frame.init();
                    }

                    if(jQuery(".flashBreakingNews").size() > 0){
                        this.breaking.init();
                    }
                }
                jQuery("#flash_news").remove();
            },
            initFlash: function(){

                // Pour Greg: "surl", on peut virer.

                var surl = jQuery("#loadedContent").attr("data-surl");
                //alert("addVitrine, surl:"+surl+"\nFound receiver: "+jQuery("#flash_news").size()+"\nvitrineFile:"+vitrineFile);

                //dynamic, loaded in rsrlib JS

                // Header XML
                var xmlData = "<?xml version='1.0' encoding='utf-8'?><data><defaults><transition>5</transition><styles>" +
                        "<style id='standard'><![CDATA[h1{fontSize:20} p{fontSize:15}]]></style><style id='horizontal'>" +
                        "<![CDATA[h1{fontSize:20} p{fontSize:15}]]></style><style id='info'><![CDATA[h1{fontSize:26} p{fontSize:18}]]>" +
                        "</style></styles><channels imgpath='"+staticImg+"vitrine/'><channel id='couleur3' bgcolor='e74787' logo='couleur3.png'/>" +
                        "<channel id='la1ere' bgcolor='DC0031' logo='la-1ere.png'/><channel id='musique' bgcolor='D28102' logo='option-musique.png'/>" +
                        "<channel id='espace2' bgcolor='004788' logo='espace-2.png'/><channel id='rsrinfo' bgcolor='A50127' logo='info.png'/>" +
                        "<channel id='rsr' bgcolor='9C0B12' logo='rsr.png'/></channels><layout>";

                // Pour Greg: mode on peut virer.
                var mode = (jQuery("#vitrine-html5").attr("class") == "breaking")?"breakingnews":"standard";

                // Pour Greg: xmlData += "standard"
                xmlData += (surl == "/info/") ? "info" : mode;

                xmlData += "</layout></defaults><items>";

                // Items
                jQuery("#vitrine-html5 .xml-item").each(function(){
                    xmlData += jQuery(this).text();
                });

                // End XML
                xmlData += "</items></data>";
                xmlData = xmlData.replace(/%/g, "%25");
                xmlData = xmlData.replace(/\&/g, "%26");
                xmlData = xmlData.replace(/"/g, "%22");
                this.xmlData = xmlData;

                var flashvars = {};
                //flashvars.data = websiteUrlShort+surl+"?flux=vitrine"; // URL vers la configuration XML
                flashvars.data = this.xmlData;

                // static, parametres pour l'affichage du plugin Flash
                var params = {};
                params.allowScriptAccess = "always"; // autorise l'acces a Javascript
                params.bgcolor = "#000000"; // couleur du fond
                params.menu = "false"; // menu contextuel au minimum
                params.wmode = "transparent";

                jQuery("#flash_news").show();

                swfobject.embedSWF(
                    vitrineFile, // URL du fichier SWF de la vitrine
                    "flash_news",  // id du DIV qui sera remplace par le tag <OBJECT> du Flash
                    "100%", // largeur 100%
                    "100%", // hauteur 100%
                    "9.0.0", // version du plugin Flash necessaire (9.0.0 est suffisant)
                    null, // pas de mecanisme ExpressInstall
                    flashvars,
                    params
                );
            }
        },
        bigEvent: {
            options: {
                container: null,
                image: null,
                logo: null,
                timeout: 45,
                speed: {
                    down: 70,
                    up: 100
                },
                display: 10000,
                pos: null,
                width: null,
                height: null,
                enable: true,
                animateDownLaunched: false,
                animateUpLaunched: false,
                hoursToReappear: 2
            },
            init: function() {
                var me = this;
                //if (RTS.browser.mobile) return;
                if (!me.checkCookies()) return;

                // rsr ajax navigation adaptation
                if(me.options.container != null && me.options.container.length > 0){
                    me.options.animateDownLaunched=false;
                    me.options.animateUpLaunched=false;
                }

                me.options.container = jQuery('#rideau-overlay');
                this.options.display = jQuery('#rideau-overlay').attr("data-time");

                if (me.options.container.length == 0) return;

                me.options.image = me.options.container.children('img');

                me.getFormat();
                me.addClose();

                if (jQuery.browser.msie6)
                    me.convertPNG();

                if (jQuery.browser.msie) {
                    var l = document.getElementById('rideau-overlay');
                    l.onclick = function() {
                        var metoo = this;
                        setTimeout(function() {
                            if (RTS.hp.bigEvent.options.enable)
                                document.location.href = metoo.href;
                            return false;
                        },20);
                    }
                }
            },
            getFormat: function() {
                var me = this;
                var o = me.options;
                var c = o.container;
                var i = o.image;
                var d = [parseInt(i.css('width')),parseInt(i.css('height'))];

                if (d[1] > 100) {
                    o.width = d[0];
                    o.height = d[1];
                    o.pos = -d[1];
                    c.css('width', d[0]);
                    c.css('height', d[1]);
                    c.css('top', o.pos);
                    c.css('margin-left', '-'+parseInt(d[0]/2)+'px');

                    //me.options.image = me.options.container.children('.img');
                    i = me.options.image;
                    i.css('width', d[0]);
                    i.css('height', d[1]);

                        me.fixSelectIE6('none');

                        setTimeout(function() {
                            me.move();
                        },666);
                } else
                    setTimeout(function() {
                        me.getFormat();
                    },150);
            },
            checkCookies: function() {
                var me = this;
                var cookieName = 'event'+ jQuery("#loadedContent").attr("data-surl");
                var myCook = RTS.basic.getCookie(cookieName);
                if (!myCook) return true;
                else {
                    var d = new Date();
                    if (d.getDate() != myCook) return true;
                    /*var toCompare = (myCook*1 + (1000 * 60 * 60 * me.options.hoursToReappear));
                    if (d >= toCompare) return true;*/
                }
                return false;
            },
            move: function(f) {
                var me = this;
                var o = me.options;
                var c = o.container;

                if (!f) {
                    var end = 0;
                    o.pos += o.speed.down;
                    if (o.pos > end) o.pos = 0;
                } else {
                    var end = -o.height;
                    o.pos -= o.speed.up;
                }
                c.css('top', o.pos);
                if (!f && o.pos<end || f && o.pos>end) setTimeout(function() {
                    me.move(f);
                },o.timeout);
                else if (!f && !o.animateDownLaunched) {
                    o.animateDownLaunched = true;
                    setTimeout(function() {
                        //me.fixSelectIE6('');
                        me.animateEndDown(0);
                    },parseInt(o.timeout/2));
                }
                else if (o.animateDownLaunched && o.animateUpLaunched) {
                    me.fixSelectIE6('');
                }
            },
            animateEndDown: function(cpt) {
                var me = this;
                var o = me.options;
                var c = o.container;
                var tab = [8,14,18,19,18,15,9,5,2];

                if (tab[cpt]) {
                    o.pos = tab[cpt];
                    c.css('top', o.pos);
                    setTimeout(function() {
                        cpt++;
                        me.animateEndDown(cpt);
                    },o.timeout);
                } else if (!o.animateUpLaunched) {
                    o.animateUpLaunched = true;
                    setTimeout(function() {
                        if (o.enable) {
                            me.animateStartUp(0);
                        }
                    },o.display);
                }
            },
            animateStartUp: function(cpt) {
                var me = this;
                var o = me.options;
                var c = o.container;
                var tab = [7,12,15,18,19,18,13,5];
                if (tab[cpt]) {
                    o.pos = tab[cpt];
                    c.css('top', o.pos);
                    setTimeout(function() {
                        cpt++;
                        me.animateStartUp(cpt);
                    },o.timeout);
                } else
                    setTimeout(function() {
                        me.fixSelectIE6('none');
                        me.move(true);
                    },o.timeout);
            },
            close: function() {
                var me = this;
                var o = me.options;
                var c = o.container;

                o.enable = false;
                var cookieName = 'event'+ jQuery("#loadedContent").attr("data-surl");
                RTS.basic.setCookie(cookieName, new Date().getDate(), 1000 * 60 * 60 * 24, '/');
                me.animateStartUp(0);
            },
            addClose: function() {
                var me = this;
                var o = me.options;
                var c = o.container;

                //c.prepend('<span class="close" onclick="RTS.hp.bigEvent.close(); return false" onmouseover="$(this).css(\'color\',\'#ffffff\')" onmouseout="$(this).css(\'color\',\'\')">FERMER</span>');
                /*var closeButton = '<span class="close" onclick="RTS.hp.bigEvent.close();" onmouseover="$(this).children(\'.close3\').css(\'color\',\'#ef908c\')" onmouseout="$(this).children(\'.close3\').css(\'color\',\'\')">'
                       + '    <span class="close1">Fermer</span>'
                    + '    <span class="close2">Fermer</span>'
                    + '    <span class="close3">Fermer</span>'
                    + '</span>';*/
                var closeButton = '<span class="close"'
                    + ' onclick="RSR.template.bigEvent.close(); return false"'
                    + ' onmouseover="if (jQuery.browser.msie6){var ob = $(this); ob.css(\'filter\',ob.css(\'filter\').replace(\'-normal.png\',\'-hover.png\'));} else $(this).css(\'background-position\',\'left bottom\');"'
                    + ' onmouseout="if (jQuery.browser.msie6) {var ob = $(this); ob.css(\'filter\',ob.css(\'filter\').replace(\'-hover.png\',\'-normal.png\'));} else $(this).css(\'background-position\',\'left top\');"'
                    + '></span>';
                c.prepend(closeButton);
            },
            fixSelectIE6: function(prop) {
                var me = this;
                if (!prop) prop = '';
                if (jQuery.browser.msie6)
                 $('select').each(function() {
                  $(this).css('display',prop);
                 });
            },
            convertPNG: function() {
                var me = this;
                var o = me.options;
                var c = o.container;
                var i = o.image;

                var d = [
                 parseInt(i.attr('width')),
                 parseInt(i.attr('height'))
                ];

                c.append('<span class="img" style="width:'+d[0]+'px; height:'+d[1]+'px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+i.attr('src')+'\');"></span>');
                i.remove();
            }
        },
        channel : {
            initScroll : function(){
                if(jQuery('#calandarBarScroller').length == 1){
                    this.doScroll();
                }
            },
            doScroll : function(){
                // Scroll channel's calendar to "center" the current bc.

                var date = new Date();
                var now  = date.getHours().toString();
                var min  = date.getMinutes().toString();

                now = (now.length == 1) ? ("0"+now) : now;
                min = (min.length == 1) ? ("0"+min) : min;
                now += min;

                var found	 = false;
                var previous = null;
                var boxId	 = "";

                jQuery('#calandarBarScroller .box_emission:not(.queltitre)').each(function(){
                    var time = jQuery(this).attr("data-time");
                    if(!found && (time > now)){
                        if(jQuery("#loadedContent").attr("data-surl") != "/info/"){
                            jQuery(previous).attr("class", "box_emission_selected");
                        }
                        found = true;
                        boxId = jQuery(previous).attr("id");
                    }
                    previous = this;
                });

                if(boxId != "") {
                    var scrollId = "emissionBox" + (boxId.replace("emissionBox", "") - 1);
                    jQuery('#calandarBarScroller')[0].scrollTo('#'+scrollId);
                }
            }
        },
        topic:{
            init: function(){
                if(jQuery("#loadedContent > .content.topic").length > 0){
                    this.main = jQuery(".topic #topic-bottom-tabs");
                    this.bindEvents();
                }
            },
            bindEvents:function(){
                var me = this;


                jQuery(".box_right_onglet a",this.main).click(function(){
                    // prevent success of previous ajax tasks
                    if("tabRequest" in me || me.tabRequest != undefined || me.tabRequest != null){
                        me.tabRequest.abort();
                        delete me.tabRequest;
                    }
                    var tabIndex = ($(this).attr("class")).replace("tab-label-","");
                    me.updateContent(tabIndex);
                    me.updateTabselected(tabIndex);
                    return false;
                });
            },
            moveTo : function(id){
                jQuery(".box_info_body .tabcontent", this.main).hide();
                jQuery(".box_info_body #tabcontent-"+id, this.main).show();
            },
            updateTabselected:function(id){
                jQuery(".box_right_onglet li",this.main).removeClass("tabs-selected");
                jQuery(".box_right_onglet li a.tab-label-"+id,this.main).parent().addClass("tabs-selected");
            },
            updateContent:function(id){

                var me = this;
                var main = this.main;
                var url = (jQuery("#loadedContent").attr("data-surl"))+"?flux=topictab&tabIndex="+id;
                var h = jQuery(".box_info_body", main).height() - 90;

                if ( jQuery(".box_info_body #tabcontent-"+id, main).size() == 0){

                    //put waiter
                    var waiter = "<div class='waiter' style='text-align:center;padding:100px;height:"+h+"px;'>" +
                                 "<img src='"+staticImg+"spinner.gif' alt=' ' /></div>";

                    jQuery(".box_info_body", main).append(waiter);
                    jQuery(".box_info_body .tabcontent", main).hide();

                    // get new contents
                    me.tabRequest = jQuery.ajax({
                        url: url,
                        dataType:"html",
                        success: function(msg){
                            msg = msg.replace(/\n/g,' ');
                            msg = msg.replace(/\s(?=\s)/g,'');
                            msg = msg.replace(/>\s</g,'><');
                            jQuery(".box_info_body .waiter", main).replaceWith(msg);
                        },
                        complete: function(){
                            delete me.tabRequest;
                        }
                    });
                }else{
                    me.moveTo(id);
                }
            }
        },
        miniVote :{
            displayResults : function(displayId){

                // Disable me if my id is already in the client's cookie (already voted).
                jQuery(".day_vote .right_sondage form").each(function(){
                    var id = (jQuery(this).attr("id")).replace("miniVotePollForm","");
                    if(jQuery.cookie("vote")!=null && jQuery.cookie("vote").search("voted"+id)!=-1){
                        jQuery(this).remove();
                    }
                });

                // Reload specific result or all results, and display it.
                var selector = (typeof(displayId)=="undefined")?".miniVoteResultTable":"#miniVoteResultId-"+displayId;
                jQuery(selector).each(function(){

                    /* We use local url with param flux=proxy to go through cross-domain.
                     * With json data, and synchronous request. */

                    var container = jQuery(this);
                    var id = (container.attr("id")).replace("miniVoteResultId-", "");
                    var url = jQuery("#loadedContent").attr("data-surl");
                    var externUrl = "http://interactif.rsr.ch/ecepool/json.php?id=" + id;
                    var data = {
                        "flux":"proxy",
                        "url":externUrl
                    };
                    // We want up to date vote results. (To see "my vote")
                    jQuery.ajax({
                        url: url,
                        data: data,
                        dataType:"json",
                        async:false,
                        cache:false,
                        timeout:ajaxExternalTimeout,
                        error: function(jqXHR, textStatus, errorThrown){
                            log('jqXHR:'+jqXHR+' / textStatus:'+textStatus+' / errorThrown:'+errorThrown);
                        },
                        success: function(msg){

                            jQuery("#miniVoteResultId-"+msg.id+" .aime .aime-text").html(msg.pourcentLike+"&#37;");
                            jQuery("#miniVoteResultId-"+msg.id+" .aime .graphique").height(msg.pourcentLike+"px");
                            jQuery("#miniVoteResultId-"+msg.id+" .aimepas .aimepas-text").html(msg.pourcentDontLike+"&#37;");
                            jQuery("#miniVoteResultId-"+msg.id+" .aimepas .graphique").height(msg.pourcentDontLike+"px");
                            jQuery("#miniVoteResultId-"+msg.id+" .left_sondage").html(msg.total+"&nbsp;r&eacute;ponses");
                        }
                    });
                });
            },
            submitPoll : function(opt, pollId){

                // Update hidden field "vote" (storing vote value).
                jQuery("#miniVotePollForm"+pollId+" [name=vote]").attr("value", opt);

                // We dont need all hidden datas (jQuery("#miniVotePollForm"+pollId).serialize();)
                var publicationId = jQuery("#miniVotePollForm"+pollId+" [name=publicationId]").attr("value");
                var externalData =	"?mentometerId="+pollId+"&vote="+opt+"&publicationId="+publicationId;

                var externalUrl = jQuery("#miniVotePollForm"+pollId).attr("action")+externalData;

                var url = jQuery("#loadedContent").attr("data-surl");
                var data = {
                    "flux":"proxy",
                    "url":externalUrl
                };

                // cache:true, async:true. (by default)
                jQuery.ajax({
                    url: url,
                    data:data,
                    cache:false,
                    async:false,
                    success:function(){
                        // Cookie update. expire in 20 years.
                        var oldValue = jQuery.cookie("vote");
                        if(jQuery.cookie("vote")==null || jQuery.cookie("vote").search("voted"+pollId)==-1){
                            jQuery.cookie("vote",oldValue+"&voted"+pollId,{expires: 7300});
                        }
                        // Update display of this poll.
                        RSR.template.miniVote.displayResults(pollId);
                    },
                    error:function(xhr, status, e){
                        //var errorMsg = "Vote impossible en raison d'un probleme technique";
                        //alert(errorMsg);
                    },
                    complete:function(xhr, status, e){
                        //alert("Complete,\nxhr: "+xhr+"\nstatus: "+status+"\nerreur: "+e);
                    }
                });
            }
        },
        shortnews:{
            init:function(){
                if(jQuery("#loadedContent").attr("data-surl") == "/info/shortnews/" && jQuery("#loadedContent").attr("data-aurl") == ""){
                    var param = jQuery("#loadedContent #tableContentChaine .enBref").attr("data-selected");
                    if (param != ""){
                        this.openSelected(param);
                    }
                }
            },
            openSelected:function(id){
                var dom = jQuery("#loadedContent #tableContentChaine .list[data-id='"+id+"']");
                jQuery(".afficher", dom).hide();
                jQuery(".masquer", dom).show();
                jQuery(".texte.body", dom).slideToggle('slow');
            },
            closeSelected:function(id){
                var dom = jQuery("#loadedContent #tableContentChaine .list[data-id='"+id+"']");
                jQuery(".masquer", dom).hide();
                jQuery(".afficher", dom).show();
                jQuery(".texte.body", dom).slideToggle('slow');
            }
        },
        thematic:{
            kwdefault:"Mot(s) clé(s)",
            init:function(){
                if (jQuery('#thematicSearchForm').size() > 0){
                    this.form  = jQuery('#thematicSearchForm');
                    this.base  = jQuery("#quelTitre_search").attr("data-base");
                    this.input = jQuery("#thematic-keyword");

                    var val = jQuery(this.input).val();
                    if(val == '' || val == this.kwdefault){
                        jQuery(this.input).val(this.kwdefault);
                        jQuery(this.input).css("color","#A8A8A8");
                    }else{
                        jQuery(this.input).css("color","#000");
                    }

                    jQuery("#loadedContent select").selectbox();
                    this.bindEvents();
                }
            },
            bindEvents:function(){
                me = this;
                jQuery(me.form).submit(function(){
                    var uri = me.base;
                    uri += jQuery("#thematicSearchForm_select option:selected", this).attr("data-uri");
                    var q = jQuery(me.input).val();
                    if (q != "" && q != me.kwdefault){
                        uri += "?keyword="+encodeURI(q);
                    }
                    RSR.navigation.redirectTo(uri);
                    return false;
                });

                jQuery(me.input).focus(function(){
                    if(jQuery(this).val() == me.kwdefault){
                        jQuery(this).val("").css("color","#000");
                    }
                }).blur(function(){
                    if(jQuery(this).val() == ""){
                        jQuery(this).val(me.kwdefault).css("color","#A8A8A8");
                    }
                });
            }
        }
    },
    player:{
        init:function(){

            var me = this;

            // Use HTML version if RTS.browser is defined and if we userAgent is an iPhone, iPad, iPod.
            var useHtmlVersion = (typeof(RTS.browser) != 'undefined') ? RTS.browser.iOs : false;

            // htmlPlayerTest is set in head.jsp
            if(useHtmlVersion){
                // jplayer
                this.initHtmlPlayer();
            }else{
                // flash player
                this.embed_player();
            }
            jQuery("a.audio").live("click",function(){
                var id = jQuery(this).attr("data-id");
                if(null != id && "" != id && 'undefined' != id){
                    me.play(id);
                    return false;
                }
            });
        },
        // flash (& html todo)
        autoPlay: function(){
            if (this.ready){
                var chanel = "";
                chanel = jQuery("#loadedContent").attr("data-autoplay");
                if(chanel != "" && chanel != this.playing){
                    if (chanel == "la-1ere" || chanel == "espace-2" || chanel == "couleur3" || chanel == "option-musique"){
                        this.playing = chanel;
                        play(chanel);
                    }
                }
            }
        },
        // flash
        embed_player: function(){
            var attributes = {id:'rsrplayer'};
            var params = {salign:'tl', scale:'noscale', menu:'false', allowscriptaccess:'always', bgcolor:'#000000', wmode : 'transparent'};
            swfobject.embedSWF(swf_player, 'rsrplayer', "100%", "100%", "9.0.0", null, vars, params, attributes);
        },
        // html
        initHtmlPlayer: function(){
            jQuery.ajax({
                url: '/js/rsrlib/player-html.js?'+staticCacheKiller,
                dataType: 'script',
                cache:true,
                success: function(){
                    setTimeout(function(){
                        if(typeof(RSR.player.jplayer) == 'undefined'){
                            setTimeout(function(){
                                RSR.player.jplayer.init();
                            },400);
                        }else{
                            RSR.player.jplayer.init();
                        }
                    },200);
                },
                error:function(){
                    log("Did not succeed to load HTML Player's javascript");
                }
            });
        },
        play: function(url){
            jQuery.ajax({
                url: url+'?f=json/audio',
                dataType: 'json',
                success: function(o){
                    if (o.status == "ok"){
                        var url = "http://aod.rsr.ch"+o.audio.media[0].url;
                        var y = o.audio.audio_created_date.substr(0,4);
                        var m = o.audio.audio_created_date.substr(5,2);
                        var d = o.audio.audio_created_date.substr(8,2);
                        var title = o.audio.editorialTitle;
                        play(url, o.audio.duration, title, o.audio.program, d+m+y, o.audio.id, o.audio.sousCompte, o.audio.broadcastId);
                    }
                }
            });
        }
    },
    plugins:{
        init:function(){

            jQuery('.jqueryScoll').jScrollHorizontalPane({showArrows:true, scrollbarMargin:0, animateTo:true});

            // Tabber Custom
            jQuery(".tabs-container").addClass("tabs-hide");
            jQuery(".tabber_onglet li a").not("#loadedContent > .content.topic .tabber_onglet li a").each(function(i){
               i++;
               jQuery(this).addClass("link_tabber_"+i);
               jQuery(this).click(function(){
                   activateTab(i);
               });
               jQuery(this).attr("href","javascript:void(null);");
            });

            // Default
            jQuery(".tabber_onglet li.firstTab").addClass("tabs-selected");
            jQuery("#tabber-1").removeClass("tabs-hide");

            // Accordeon
            jQuery("#accordion").accordion({
                autoHeight: false,
                header:'.head'
            });

            // tabs
            jQuery('#tabber-container').tabs();
            jQuery('.input_checkbox').prettyCheckboxes();

        }
    },
    navigation : {
        setPageTitle: function() {
            if(jQuery("#loadedContent").size() > 0){
                var newTitle = jQuery("#loadedContent").attr("data-pagetitle");
                if( newTitle != null && typeof newTitle != "undefined" && newTitle != "" ){
                    if(jQuery.browser.msie){
                        document.title = newTitle;
                        if (typeof(hashUrl) != 'undefined'){
                            setTimeout(function(){
                                document.title = newTitle;
                            },hashUrl.locationBarTimer.waitTime);
                        }else if(typeof(waitTime) != 'undefined'){
                             setTimeout(function(){
                                document.title = newTitle;
                            },waitTime);
                        }
                    }
                    else{
                        jQuery('title').html(newTitle);
                    }
                }
            }
        },

        mainmenu: function(){

            jQuery(".Menu1 li").hover(function(){

                jQuery(this).find('ul:first').css({visibility: "visible",display: "none"}).show(200);
                jQuery(this).find('span.effet_hover').addClass("span_hover");

                // Truncates each [.Menu3 a] one time per [.Menu1 li]
                if (!("menu3Truncated" in this)){
                    this.menu3Truncated = true;
                    jQuery("#header .navigation_principale .menu_first .menu_deroulant .Menu3 a").each(function(){
                        RSR.strings.truncateText(20, jQuery(this), "");
                    });
                }

            },function(){
                jQuery(this).find('ul:first').css({visibility: "hidden"});
                jQuery(this).find('span.effet_hover').removeClass("span_hover");
            });
        },
        sendToFriend: function(){
            jQuery("#sendButton").click( function() {

                var form_name = jQuery("#form_name").val();
                var from = jQuery("#from").val();
                var to = jQuery("#to").val();
                var msg = jQuery("#msg").val();
                var current_url = window.location.href;
                current_url = current_url.replace(/\/#\//, "/");
                var page_title = jQuery("title").html();

                var validator = jQuery("#sendToAFriendForm").validate({
                    rules: {
                        form_name: {
                            required: true
                        },
                        from: {
                            required: true,
                            email: true
                        },
                        to: {
                            required: true,
                            email: true
                        }
                    },
                    messages: {
                        form_name:"Ce champ est obligatoire",
                        from: {
                            required: "Ce champ est obligatoire",
                            email: "Merci d'indiquer une adresse valide"
                        },
                        to: {
                            required: "Ce champ est obligatoire",
                            email: "Merci d'indiquer une adresse valide"
                        }
                    }
                });
                if(validator.form()) {
                    sendForm(form_name, from, to, msg, current_url, page_title);
                }
            });
            jQuery("#resetButton").click( function() {
                jQuery("#form_name").val("");
                jQuery("#from").val("");
                jQuery("#to").val("");
                jQuery("#msg").val("");
            });
        },
        // initialize ajax hashUrl
        ajax: {

            // Special IE7
            ie:{
                hiddenFrame: function(defaultUrlIE){
                    defaultUrlIE = (typeof(defaultUrlIE) == "undefined")?"":defaultUrlIE;
                    return jQuery("<iframe style='border: 0px; width: 1px; "
                        + "height: 1px; position: absolute; bottom: 0px; "
                        + "right: 0px; visibility: visible;' "
                        + "data-name='#/' id='hiddenHistory' src='"+defaultUrlIE+"'>"
                        + "</iframe>").appendTo(document.body).get(0);
                },
                goTo: function(url){
                    if(jQuery.browser.msie6){
                        // ie 6 is no ajax
                        document.location.href = url;
                    }else{
                        // uppers ie are ajax. Trigger the custom clic event (define in hashurl-ie7).
                        jQuery("<a href='"+url+"' class='iegoto'></a>").trigger("click");
                        var hash = (url.search(websiteUrlShort)==-1) ? url : url.substr(websiteUrlShort.length);
                        setTimeout(function(){
                            document.location.href = websiteUrl + "#" + hash;
                        }, 400);
                    }
                }
            },
            putWaiter: function(){
                var txt = "<img src='"+staticImg+"ajax-loader.gif' title='Waiting ajax' style='display:block;margin: 100px auto;'/>";
                jQuery("#content").html(txt);
                jQuery("#footer .background_events").remove();
                jQuery("#footer .ailleurs").remove();
            }
        },
        redirectTo: function(url){
            // no ajax redirection
            if(document.location.href.search(/#/) == -1 && (document.location.href != websiteUrl)){
                if(document.location.href.search(/http:/) == -1){
                    document.location = (websiteUrlShort + url);
                }else{
                    document.location = url;
                }
            // ajax redirection
            }else{
                //if(jQuery.browser.msie){
                if(RTS.browser.IE7 || RTS.browser.IE6){
                    this.ajax.ie.goTo(url);
                }else{
                    // no hash, relativ
                    if (url.search(/#/) == -1 && url.search(websiteUrl) == -1){
                        url = websiteUrl + "#" + url;
                    // no hash, absolute
                    }else if(url.search(/#/) == -1){
                        url = websiteUrl + "#/" + url.replace(websiteUrl, "");
                    }
                    // hash & absolute
                    document.location = url;
                }
            }
        },
        loadRedirects: function(){
            var urlRedirect = jQuery("#loadedContent").attr("data-redirectTo");
            if (urlRedirect != null && (typeof urlRedirect != "undefined")){
                if (urlRedirect.length > 0){
                    this.redirectTo(urlRedirect);
                }
            }
        },
        initAddThis: function(){
            var currentUrl = window.location.href;
            currentUrl = currentUrl.replace(/\/#\//, "/");
            jQuery(".addthis_button").attr("addthis:url", currentUrl);
            var currentTitle = jQuery(".addthis_button").attr("addthis:title");
            if(typeof (window.addthis_share) != 'undefined'){
                window.addthis_share.title = currentTitle;
                window.addthis_share.url = currentUrl;
            }
            jQuery(".addthis_button").mouseover(function(){
                return addthis_open(this,'');
            });
        }
    },
    loadSpecificJS: function(){

        // dynamic selection by template specification
        // See in main content template (grid, special-page, article) : div id="jsAdd"
        jQuery("#jsAdd[data-jsAdd]").each(function(){
            if(jQuery(this).attr("data-jsAdd") != undefined && jQuery(this).attr("data-jsAdd") != ""){
                // contains comma separated js names
                var allJsToAdd = jQuery(this).attr("data-jsAdd").split(",");
                for(i=0 ; i < allJsToAdd.length ; i++){
                    fileName = allJsToAdd[i];
                    if (!("loadedJs" in RSR) || (RSR.loadedJs.search(fileName) == -1)){
                        var url = staticUrl + "/js/rsrlib/" + fileName + cssjsPack + ".js?=" + cacheVersion;
                        jQuery.ajax({
                            url:url,
                            dataType:'script',
                            cache:true,
                            success: function(){
                                // init function
                                eval("RSR.template."+fileName+".init();");
                            }
                        });

                        // save loaded
                        if ("loadedJs" in RSR){
                            RSR.loadedJs += ","+fileName;
                        }else{
                            RSR.loadedJs = fileName;
                        }
                    }
                }
            }
        });
    },
    print: function(){
        /* test purpose
        var aurl = jQuery("#loadedContent").attr('data-aurl');
        var surl = jQuery("#loadedContent").attr('data-surl');
        var url = ((aurl == "") ? surl : aurl) + "?flux=print";
        var f = window.open(url,jQuery('title').html(),'',false); */
        window.print();
    },
    stats:{
        doTag: function(){

            var statsEnabled = jQuery("#tagStart").attr("data-statsenabled");
            if(statsEnabled == "true"){
                var tag = jQuery("#tagStart").attr("data-tag");
                var isFirstLoading = jQuery("#tagStart").attr("data-firstloading");
                var WEMF="http://rsr.wemfbox.ch/cgi-bin/ivw/CP"+tag;
                var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
                var content ="";
                if (isFirstLoading == "true"){
                    //alert("taggage actif");
                    if (window.document.URL.indexOf("#") != -1){
                        //alert("cas 1 : tags nothing, the page will reload");
                    }
                    else {

                        // REMP start
                        var rempTag = "<img src=\""+WEMF+"?r="+escape(document.referrer)+"&d="+(Math.random()*100000)+"\"width=\"1\" height=\"1\" border=\"0\">";
                        content = "<div id=\"rempStat\" style=\"font-size: 1px; position: absolute;\"><!-- WEMF-TAG VERSION=\"1.3\" -->"+rempTag+"<!-- /WEMF-TAG --></div>";
                        RSR.stats.test("REMP-start noajax",rempTag);
                        jQuery("#tagStart").append(content);

                        // GOOGLE (emissions populaires)
                        try {
                            var pageTracker = _gat._getTracker("UA-11135265-2");
                            pageTracker._trackPageview();
                        } catch(err) {}

                        // REMP end
                        var szmvars="rsr//CP"+tag;
                        RSR.stats.test("REMP-end noajax",szmvars);

                        // Wysistat
                        content=unescape("%3Cscript language='javaScript'%3Eif (valeur==1){stat('rsr','','','','"+tag+"');}%3C/script%3E");
                        jQuery("#tagStart").append(content);
                    }
                } else {

                    // REMP start
                    var rempTag = "<img src=\""+WEMF+"?r="+escape(document.referrer)+"&d="+(Math.random()*100000)+"\"width=\"1\" height=\"1\" border=\"0\">";
                    content = "<div id=\"rempStat\" style=\"font-size: 1px; position: absolute;\"><!-- WEMF-TAG VERSION=\"1.3\" -->"+rempTag+"<!-- /WEMF-TAG --></div>";
                    RSR.stats.test("REMP-start ajax", rempTag);
                    jQuery("#tagStart").append(content);

                    // GOOGLE (emissions populaires)
                    try {
                        var pageTracker = _gat._getTracker("UA-11135265-2");
                        pageTracker._trackPageview();
                        } catch(err) {}

                    // REMP end
                    var szmvars="rsr//CP"+tag;
                    RSR.stats.test("REMP-end ajax",szmvars);

                    // Wysistat
                    content = unescape("%3Cscript language='javaScript'%3Eif (valeur==1){stat('rsr','','','','"+tag+"');}%3C/script%3E");
                    jQuery("#tagStart").append(content);
                }
            }
        },
        test:function(type,content){
            if (typeof(testAnalyticTags) != "undefined" && testAnalyticTags){
                jQuery.ajax({
                    url: "http://www.rsr.ch",
                    data: ({"flux":"test-stats","data":"input","type":type,"content":content}),
                    dataType: "script"
                });
            }
        }
    }
};
// gallery ajax plugins

((function(w){
    // create new instance of gallery

    w.Gallery = function(rootSelector, id){
        this.dRoot = $(rootSelector);
        this.dImg = this.dRoot.find(this.opt.img);
        this.dText = this.dRoot.find(this.opt.text);
        this.dTotalImg = this.dRoot.find(this.opt.totalImg);
        this.dCurrentImg = this.dRoot.find(this.opt.currentImg);


        this.size = this.dText.attr(this.opt.size);
        this.id = id;

        //create link for next image and back image lets go !!!!
        var b = this;

        this.dNext = this.dRoot.find(this.opt.next);
        this.dBack = this.dRoot.find(this.opt.back);

        this.dNext.click(function(){
            b.next();
        });

        this.dBack.click(function(){
            b.back();
        });

        this.images = {};
    };

    w.Gallery.prototype = {

        opt:{
            img:'img',
            text:'.img-content',
            size:'data-size',
            id:'data-id',
            totalImg:'.total-img',
            currentImg:'.current-img',
            next:'.img-next',
            back:'.img-back',
            query:'?flux=gallery&id=[id]&start=[s]&end=[e]'
        },
        lastEnd:0,
        cPosition:0,
        init:function(){
            this.setTotal();
            this.loadImgs(0, 6);

            this.dBack.hide();
        },
        loadImgs:function(start, end){
            if(end > this.size){
                end = this.size;
            }
            if(this.lastEnd == end){
                this.last = true;
            }

            if(this.last){
                return;
            }


            query = this.opt.query.replace('[id]', this.id).replace('[s]', start).replace('[e]', end);

            var b = this;
            $.get(query, null, function(data){
                for(key in data){
                    b.images[key] = data[key];
                }
                b.lastEnd = end;
            }, 'json');


        },
        setTotal:function(){

            this.dTotalImg.html(this.size+'');
        },

        next:function(){
            this.changeImage(this.cPosition + 1);
        },
        back:function(){
            this.changeImage(this.cPosition - 1);

        },
        changeImage:function(key){
            this.dNext.show();
            this.dBack.show();

            if(key < 0) {
                key = 0;
                this.dBack.hide();
            }

            if(key >= this.size - 1){
                key = this.size - 1;
                this.dNext.hide();
            }


            //to do make load next 5 images
            if(!this.images[key + 2]){
                this.loadImgs(this.lastEnd, this.lastEnd + 6);
            }

            this.dCurrentImg.html(key + 1);
            //console.log(key);
            //change dom
            if(this.images[key]){

                //var host = 'http://'+window.location.hostname;
                var img = this.images[key];
                /*
                var oImg=document.createElement("img");
                oImg.setAttribute('src', img.url);
                oImg.setAttribute('alt', img.text);

                var parent = this.dImg.parent().get(0);
                var orignImg = this.dImg.get(0);

                parent.replaceChild(oImg, orignImg);
                */
                //this.opacity();
                this.dImg.attr({'src':img.url, 'alt':img.text});

                var decodeHtml = function (value){
                  return $('<div/>').html(value).text();
                };
                this.dText.html(decodeHtml(img.text));

                this.cPosition = key;
            }
        },
        opacity:function(){
            this.dImg.css('opacity',0);
            var b = this;
            var op = 0;
            window.time = function(){

                op += 0.1;

                b.dImg.css('opacity',op);


                if(op > 1){
                    clearInterval(timer);
                }
            };

            var timer = setInterval("time()", 50);


        }
    };
})(RSR));

if(typeof RSR != 'object') RSR = {};
((function(o){
    o.lightbox = {
        init: function(){
            // bind classes
            jQuery("a.rsr-lb-layer-action").live("click",function(){
                o.lightbox.layerAndAction(this);
                return false;
            });
        },
        layerAndAction: function(dom){
            var url = $(dom).attr("href") + "?flux=lightbox";
            var action = $(dom).attr("data-action");
            if(null==action || "" == action)action="carousel";

            AJAXopenLayerAndDoAction(url, action);

        }
    };
})(RSR));
RSR.lightbox.init();

