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.embed_player();
	
			//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();
			
			// 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) {				
				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+'/images/calendrier/calendrier.gif', buttonImageOnly: true
				});
			});
			
			// contact form
			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.doScroll();
			RSR.template.channel.queltitre();
			// rebuild extern inline rtf links
			RSR.strings.rtf.rebuildInlineLinks();
			// init topic-tabs
			RSR.template.topicTabs.init();
			// Set page html title
			RSR.navigation.setPageTitle();
			// Display minivote results
			RSR.template.miniVote.displayResults();
			// Init addThis
			RSR.navigation.initAddThis();
			
			// program ready
			if (typeof(RSR.template.program) != "undefined"){
				RSR.template.program.ready();
			}
			
			// sitemap ready
			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 (!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();
				}
			});
			
			// Add the vitrine
			RSR.template.addVitrine();
		}
	},
	strings : {
		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);
				}
			}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 enl�ve 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(){
			
			
			// Standard mode : if cut -> 3dots
			//------------------------------------------------------------------
			// 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("#tableContentHomeChaine .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), "");
			});
			jQuery(".box_right_body .home-info-chapo").each(function(){
			    RSR.strings.truncateText(90, 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");
			});
			// 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), "");
			});
			jQuery("#tableContentCenter .box_middle_center .home-info-bloclibre1-chapo").each(function(){
			    RSR.strings.truncateText(75, jQuery(this), "");
			});
			// Everdots mode
			//------------------------------------------------------------------
			jQuery("#tableContentHome .box_right_body p .striptext").each(function(){
			    RSR.strings.truncateText(45, 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(){
				RSR.strings.truncateText(12, jQuery(this), "stripInsideHyperlinks");
			});
			// 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;
		}
	},
	template : {
		addVitrine : function(){
					
			var surl = jQuery("#loadedContent").attr("data-surl");
			//alert("addVitrine, surl:"+surl+"\nFound receiver: "+jQuery("#flash_news").size()+"\nvitrineFile:"+vitrineFile);

			//dynamic, loaded in rsrlib JS
			var flashvars = {};
			flashvars.data = websiteUrlShort+surl+"?flux=vitrine"; // URL vers la configuration XML
			
			// 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";
			
			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
			);
			
		},
		channel : {
			doScroll : function(){
				// Scroll channel's calendar to "center" the current bc.
				if(jQuery('#calandarBarScroller').length == 1){
					var boxId = jQuery('#calandarBarScroller').find(".box_emission_selected").attr("id");
					if(boxId) {
						var scrollId = "emissionBox" + (boxId.replace("emissionBox", "") - 1);
						jQuery('#calandarBarScroller')[0].scrollTo('#'+scrollId);
					}
				}
			},
			queltitre : function(){
				if ( (jQuery("#loadedContent").attr("data-surl")).match(/^\/(la-1ere|espace-2|couleur3|option-musique)\/$/) ){
					if ((typeof (this.timeOut) == "undefined") || (this.timeOut == 0)){
						this.timeOut = setTimeout(function(){
							RSR.template.channel.reloadQueltitre();
						}, 180000);
					}
				}else{
					if(typeof(this.currentRequest) != "undefined"){
						this.currentRequest.abort();
					}
					clearTimeout(this.timeOut);
					this.timeOut = 0;
				}
			},
			reloadQueltitre : function(){
				
				if("currentRequest" in this && this.currentRequest != undefined && this.currentRequest != null){
					this.currentRequest.abort();
					delete this.currentRequest;
				}
				
				this.currentRequest = jQuery.ajax({
					url		 : jQuery("#loadedContent").attr("data-surl"),
					data	 : {"flux":"channel-queltitre"},
					dataType : "html",
					async	 : true,
					cache	 : false,
					success	 : function(msg){
						jQuery(".colonne_right .blocQuelTitre .blocQuelTitre-content").html(msg);
					}
				});
				this.timeOut = setTimeout(function(){
					RSR.template.channel.reloadQueltitre();
				}, 180000);
			}
		},
		topicTabs :{
			init: function(){
				// le script a exectuer
				if(jQuery(".topic").length > 0){
					RSR.template.topicTabs.uneAutreFonction();
				}
			},
			uneAutreFonction : function(){
				
			}
		},
		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://events.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,
                        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);
					}
				});
			}
		}
	},
	player:{
		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);
		},
		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);
					}
				}
			}
		}
	},
	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").each(function(i){
			   i++;
			   jQuery(this).addClass("link_tabber_"+i);
			   jQuery(this).click(function(){ 
			   		activateTab(i);
			   });	
			   jQuery(this).attr("href","javascript:void(null);");
			});
			jQuery(".tabber_onglet li.firstTab").addClass("tabs-selected");
			jQuery("#tabber-1").removeClass("tabs-hide");
			// FIN Tabber Custom
			
			// Accordeon
			jQuery("#accordion").accordion({
				autoheight: false,
				header:'.head'
			});
			
			// tabs
			jQuery('#tabber-container').tabs();
			jQuery('.input_checkbox').prettyCheckboxes();
			
			//Add only on pages that need this feature
			//$("select").selectbox();
			jQuery("#loadedContent[data-surl$='/themes/'] select").selectbox();
		}
	},
	navigation : {
        setPageTitle: function() {
	        var newTitle = jQuery("#loadedContent").attr("data-pagetitle");
	        if( newTitle != null && typeof newTitle != "undefined" && newTitle != "" ){
	            if(jQuery.browser.msie){
	                document.title = newTitle;
	            }
	            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_ie).
						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='"+staticUrl+"/images/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){
					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";
						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();
	},
	xml:{
		// Returns a XML DOM Object from an XML String (txt).
		getXMLDoc: function(xmlStr){
			// JQuery doesn't manage with xml and cdata :(
			if (window.DOMParser){
				parser=new DOMParser();
				xmlDoc=parser.parseFromString(xmlStr,"text/xml");
			}else{
				// Internet Explorer
				xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async="false";
				xmlDoc.loadXML(xmlStr);
			}
			return xmlDoc;
		}
	},
	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.");
				if (isFirstLoading == "true"){
					//alert("taggage actif");
					if (window.document.URL.indexOf("#") != -1){ 
						//alert("cas 1 : tags nothing, the page will reload");
					}
					else {

						// REMP start
						jQuery("#tagStart").append("<div id=\"rempStat\" style=\"font-size: 1px; position: absolute;\"><!-- WEMF-TAG VERSION=\"1.3\" --><img src=\""+WEMF+"?r="+escape(document.referrer)+"&d="+(Math.random()*100000)+"\"width=\"1\" height=\"1\" border=\"0\"><!-- /WEMF-TAG --></div>");
						
						// google
						try {
							var pageTracker = _gat._getTracker("UA-2056199-24");
							pageTracker._trackPageview();
							} catch(err) {}
						
						// REMP end
						var szmvars="rsr//CP"+tag;
						
						// Wysistat
						jQuery("#tagStart").append(unescape("%3Cscript language='javaScript'%3Eif (valeur==1){stat('rsr');}%3C/script%3E"));
							
					}
				}
				else {
					
					// REMP start
					jQuery("#tagStart").append("<div id=\"rempStat\" style=\"font-size: 1px; position: absolute;\"><!-- WEMF-TAG VERSION=\"1.3\" --><img src=\""+WEMF+"?r="+escape(document.referrer)+"&d="+(Math.random()*100000)+"\"width=\"1\" height=\"1\" border=\"0\"><!-- /WEMF-TAG --></div>");
					
					// google
					try {
						var pageTracker = _gat._getTracker("UA-2056199-24");
						pageTracker._trackPageview();
						} catch(err) {}
					
					// REMP end
					var szmvars="rsr//CP"+tag;
					
					// Wysistat
					jQuery("#tagStart").append(unescape("%3Cscript language='javaScript'%3Eif (valeur==1){stat('rsr');}%3C/script%3E"));
						
				}
			}
		}
	}
};