/**
 * flowplayer.playlist.js 3.0.5. Flowplayer JavaScript plugin.
 * 
 * This file is part of Flowplayer, http://flowplayer.org
 *
 * Author: Tero Piirainen, <support@flowplayer.org>
 * Copyright (c) 2008 Flowplayer Ltd
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * SEE: http://www.opensource.org/licenses
 * 
 * Version: 3.0.5 - Tue Feb 24 2009 11:42:25 GMT-0000 (GMT+00:00)
 */
 /* Configuration Flowplayer */
/**************** init onload */
$(function(){
		   
	// Modifie la liste
	$('#playlist ul li').flowPlaylist();
	// Configuration Flowplayer
	// Langue
	page_lang = $("html").attr("lang")
	var flowplayerPlay = (page_lang == "fr")? "Rejouer" : "Play again";
	
	// Établir si sur preprod avant
	$f("player", {src:dossierRacine+"flowplayer/flowplayer.commercial.swf"}, {
	   key: '#$27f91807f584e2d91c8',

		clip: {
		   baseUrl: dossierRacine+dossierVideo, 
		   scaling:'orig'
		},
		
		play: {
			replayLabel: flowplayerPlay
		},
		canvas: {
			backgroundColor: '#000000',
			backgroundGradient: 'none'
		},
		
		contextMenu: [ 
        'Hydro-Québec',  
    	],
		plugins: { 
			controls: { 
				url: dossierRacine+'flowplayer/flowplayer.controls-tube.swf',
				backgroundGradient: [0.1,0],
				border: '1px solid #333333',
				volumeSliderGradient: 'low',
				backgroundColor: '#0a0a0a',
				buttonColor: '#ffffff',
				sliderColor: '#333333',
				buttonOverColor: '#eeeeee',
				volumeSliderColor: '#ffffff',
				bufferColor: '#cee0f1',
				progressColor: '#eef4fa',
				durationColor: '#ffffff',
				height:34,
				scrubberHeightRatio: 0.6,
				scrubberBarHeightRatio: 0.3,
				volumeSliderHeightRatio:0.4,
				volumeBarHeightRatio: 0.3
			},
			logo2: {
				url: dossierRacine+'flowplayer/hq_flowplayer_logo_blanc.swf',
				width: '14%',
				height: '7%',
				opacity: 0.3,
				bottom:40,
				right:10,
				fullscreenOnly: false,
				displayTime: 0
			}
		}
	}).playlist("#playlist ul li");
	
}); 	


(function($) { 
		  
	var chemin = window.location.pathname; //recupere le chemin
	var dossieractuel = chemin.replace('\/dpcomm',''); //enleve le premier repertoire   
	
	$f.addPlugin("playlist", function(wrap, options) {
		
		var self = this;	
		var init_wrap = wrap;
		
		var opts = {
			playingClass: 'playing',
			pausedClass: 'paused',
			progressClass:'progress',
			template: '<a href="${url}">${title}</a>',
			loop: false,
			playOnClick: true,
			manual: false
		};		
		
		$.extend(opts, options);
		wrap = $(wrap);		
		var manual = self.getPlaylist().length <= 1 || opts.manual; 
		var els = null;
		
		wrap = $(init_wrap);
		/* setup playlists with onClick handlers */ 
		
		// template based playlist
		if (!manual) {
			
			
		// HTML based playlist
		} else {
			var elExt;
			els = wrap.children('h5').children('a');
			
			// allows dynamic addition of elements - jquery 1.3+
			// Dont use live because we use the trigger
			if ($.isFunction(els.live)) {
				//$(wrap.selector + "> a").live("click", function() {
				$(wrap.selector + "> h5 a").each( function(i) {
					elP = $(this);
					// Clique on title
					elP.bind("click", function(i) {
						el = $(this);
						//alert(el.attr("href"));
						return play(el.parents('li'), el.attr("href"));
					});
					// Click on image
					elP.parents('li').children('div').bind("click", function() {
						$(this).parent().children('h5').children('a').trigger("click");
					});
				});
			}
						 
					
			// setup player to play first clip
			 startClipInUrl();
			
		}
		
		function updateClipJS(clip) {
			// Bug ajouter setTimeout, comme si le call du update était fait trop vite ???
			clip_href = cleanHref(els.filter("[class=first]").attr("href"));
			setTimeout(function(){clip.update({url: clip_href})},500);
		}
		
		function cleanHref(href) {
			return href;
		}
		
		function play(el, clip)  {
			if (el.hasClass(opts.playingClass) || el.hasClass(opts.pausedClass)) {
				self.toggle();
			} else {
				el.addClass(opts.progressClass);
				self.play(clip); 							


			}			
			
			return false;
		}	
		
		
		function clearCSS() {
			if (manual) { }
			els.parents('li').removeClass(opts.playingClass);
			els.parents('li').removeClass(opts.pausedClass);
			els.parents('li').removeClass(opts.progressClass);
		}
		
		function getEl(clip) {	
			clipRef = (manual) ? els.filter("[href=" + clip.url + "]") : els.eq(clip.index);
			return clipRef;
		}
		
		//GOOGLE ANALYTICS remember to change this tracking code to yours 
		//var _tracker = _gat._getTracker("UA-11513402-1"); // PRE-PROD
		var _tracker = _gat._getTracker("UA-6552177-1");// LIVE
		//_tracker._trackPageview(); //_trackPageview not needed as it's called within the footer
		
		// onBegin
		self.onBegin(function(clip) {
			clearCSS();		
			getEl(clip).parents('li').addClass(opts.playingClass);//W
			afficheInfos(getEl(clip).parents('li'));
			openCollapse(getEl(clip).parents('li'));
			_tracker._trackEvent("Videos", "Affichage", dossieractuel+'\/'+clip.url);
		});	
		
		// onPlay	
		self.onStart(function(clip) {
			_tracker._trackEvent("Videos", "Play", dossieractuel+'\/'+clip.url);	
		});	
		
		// onPause	
		self.onPause(function(clip) {
			getEl(clip).parents('li').removeClass(opts.playingClass).addClass(opts.pausedClass);
			_tracker._trackEvent("Videos", "Pause", dossieractuel+'\/'+clip.url);
		});	
		
		// onResume
		self.onResume(function(clip) {
			getEl(clip).parents('li').removeClass(opts.pausedClass).addClass(opts.playingClass);
			_tracker._trackEvent("Videos", "Resume", dossieractuel+'\\'+clip.url);
		});		
		
		// onStop
		self.onStop(function(clip) {
			getEl(clip).parents('li').find("dd").children("div").trigger("click");
		});	
		
		// onFinish	
		self.onFinish(function(clip) {
			_tracker._trackEvent("Videos", "Complet", dossieractuel+'\/'+clip.url);	
		});	
		
		// what happens when clip ends ?
		if (!opts.loop && !manual) {
			// stop the playback exept on the last clip, which is stopped by default
			self.onBeforeFinish(function(clip) {
				if (clip.index < els.length -1) {
					return false;
				}
			}); 
		}
		
		// on manual setups perform looping here
		if (manual && opts.loop) {
			self.onBeforeFinish(function(clip) {
				var el = getEl(clip);
				if (el.next().length) {
					el.next().click();	 		
				} else {
					els.eq(0).click();	
				} 
				return false;				
			}); 
		}
		
		// onUnload
		self.onUnload(function() {
			clearCSS();		
		});
		
		function afficheInfos(el) {
			// Affiche le contenu de la description et du titre sous le player 
			var titre = el.find(".titre").text();
			titre = '<h4>'+titre+'</h4>';
			var description="";
			// Si pas de description longue prend description courte
			if (el.find('.description-longue').html() != null) {
				description = el.find('.description-longue')
			} else {
				description = el.find('dd').clone();
				// Élimine le bouton Fermer
				description.find('.btn-fermer').remove();
			}
			description = '<p>'+description.html()+'</p>';
			$("#player-description").html(titre + description);
		}
		
		function openCollapse(el) {
			// Trigger the Plus info button
			$(el).find("dt").trigger("click");
		}
		
		function startClipInUrl() {
			wLocation = (document.location + "").split("?");
			if(wLocation[1]) {
				key="p"
				param = wLocation[1].split(key+"=");
				
				/* ##################################
				debut changement 
				################################## */
				
				if(isNaN(param[1])){
					// Remove trailing args
					trimmed = param[1].split("&");
					// Trigger to start video and open collapse using video file name as a parameter (exemple: p=la_fondation)
					$("#playlist ul li a[href*='"+trimmed[0]+"']").trigger('click');
					// scrollTo
					var $target = $("#playlist ul li a[href*='"+trimmed[0]+"']").parent().parent();
					$("#playlist ul").stop().scrollTo( $target , 0 );
				}else{
					value = parseInt(param[1]);
					value -= 1;
					// Trigger to start video and open collapse using list value (ex: 2nd video = p=2)
					$('#playlist').children('ul').children('li').eq(value).find('a').trigger('click');
				}
				
				/* ##################################
				fin changement 
				################################## */
				
				/*
				anciennement comme ceci : 
				value = parseInt(param[1]);
				value -= 1;
				// Trigger to start video and open collapse
				$('#playlist').children('ul').children('li').eq(value).find('a').trigger('click');
				*/
				
				
			} else {
				var clip = self.getClip(0);
				if (!clip.url && opts.playOnClick)
					updateClipJS(clip)	
				
			} 
		}
		
		
		return self;
		
	});
		
})(jQuery);		

(function($) { 
	$.fn.flowPlaylist = function(options){

	$(this).each(function(i) {
		el = $(this);
		buildItemList(el,i);
	});
	
	function buildItemList(el, row) {

		row+=1
		// Capture les infos
		tmp_desc1 = el.find(".description-courte").html();
		tmp_desc2 = el.find(".description-longue").html();
		//Efface les description avant la reconstruction du collapse
		el.find(".description-courte").remove();
		// Reconstruit l'item de la liste
		add_class = (row%2) ? "clearfix" : "clearfix odd";
		el.addClass(add_class);
		
		// Construit le collapse si description
		if ((tmp_desc1!=null) && (tmp_desc1!='')) {

			var alt_plus = (page_lang == "fr")? "Plus d\'informations" : "More information";
			var alt_fermer = (page_lang == "fr")? "Fermer" : "Close";
			
			collapse = $('<dl class="clearfix"></dl>');
			i_dt = $('<dt><img src="'+dossierRacine+'images/hq_flowplayer_btn_ouvrir.png" alt="'+alt_plus+'" /></dt>').click( function() {
				 $(this).next("dd").slideDown("fast"); 
				 $(this).addClass("opened"); 
			});
			i_dd = $('<dd>'+tmp_desc1+'</dd>');
			i_dd_btn = $('<div class="btn-fermer"><img src="'+dossierRacine+'images/hq_flowplayer_btn_fermer.png" alt="'+alt_fermer+'" /></div>').click( function() {
				 $(this).parent().slideUp("fast"); 
				 $(this).parent().prev().removeClass("opened"); 
			});
			
			collapse.append (
				i_dt,
				i_dd.append (
					i_dd_btn
				)
			);
			// Ajoute le collapse
			el.append(collapse);
		}
	}
	// Fill the description
	var titre = (page_lang == "fr")? "Cliquez dans le menu de droite pour choisir une vidéo &raquo;" : "Click on the menu to the right to select a video &raquo;";
	titre = '<h4>'+titre+'</h4>';
	$("#player-description").html(titre);
}
})(jQuery);		


/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
