$('html').addClass('jsactive');

/*
** Alignement vertical
*/

(function($) {
	$.fn.vAlign = function() {
		return this.each(function(){
			$(this).css({ marginTop:($(this).parent().height() - $(this).height())/2 });
		});
	};
})(jQuery);

/*
** Marquee
*/

(function(){
	 var defaults = {
		classContainer:'.container_wrapper',
		speed:20,
		tagText:'li',
		begin:790
	 }

	 var options = {};
	function r(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector

	function addEach($elem,attributes) {
		var total = 0;
		$elem.each(function(i,item) {
			$.map(attributes, function(attr) {
				if (attr == 'width' && !isNaN($elem.eq(i).width()))
					total += $elem.eq(i).width();
				else if (attr == 'height' && !isNaN($elem.eq(i).height()))
					total += $elem.eq(i).height();
				else if ( !isNaN($elem.eq(i).attr(attr)) )
					total += $elem.eq(i).attr(attr);
			});
		})
		return total;
	}
	
	function add(value,total) {

		var newTotal = parseInt(total);
		$.map(value,function(i) {
			if (!isNaN(parseInt(i))) newTotal += parseInt(i);
		});
		return newTotal;
	}
	
	jQuery.fn.newsScroller = function(opt){
			var $this = $(this);
		options = jQuery.extend(defaults, opt);
		var heightLink = add(
			[$this.find(options.tagText).css('padding-top'),$this.find(options.tagText).css('padding-bottom')],
			$this.find(options.tagText).height()
		);
		
		var widthInsideMarquee = addEach(
			$(this).find(options.tagText),
			['padding-left','padding-right','width']
		)

		$this
			.css({width:widthInsideMarquee,position:'relative'})
			.wrap('<div class="'+r(options.classContainer)+'" style="position:relative;height:'+heightLink+'px" />'); // on encadre le newscroller d'un conteneur
		
		var pos = -parseInt(options.begin);
		setInterval(function(i) {
			widthLink = add(
				[$this.find(options.tagText).css('padding-left'),$this.find(options.tagText).css('padding-right'),$this.find(options.tagText).css('margin-left'),$this.find('a').css('margin-right')],
				$this.find(options.tagText).width()
			);
			if (pos == widthLink) {
				var newElem = $this.find(options.tagText).eq(0);
				$this.find(options.tagText).eq(0).insertAfter($this.find(options.tagText+':last'));
				pos=-0;
			}
			$this.css('left',-pos)
			pos++;
		},options.speed)
		return this;
	 };
})();


/* 
**  Plugin formManager
**  @action: action à appliquer sur l'élement du formulaire ou sur le formulaire lui-même (tempSearchText,secureForm)
             on peut appliquer plusieurs actions en les ajoutant de cette maniere : action:'tempSearchText&secureForm)
**  @classError : pour l'action secureForm, ajoute une classe sur le champs de formulaire sécurisé en cas d'erreur
*/
(function($) {
	$.fn.extend({
		formManager: function (options) {
			// Default options
			var settings = {
				action: null,
				classError:'.error',
				alertTxt:null
			};
			if(options) $.extend(settings, options);
			function c(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector
			
			function getAction(actionToTest,actionCalled) {
				return actionToTest.indexOf(actionCalled) >= 0;
			}
			function tempSearchText(elem) {
				if (!$(elem).is('input[type=text]')) return;
				var txtLabel = $(elem).prev('label').text(); // get the text of the previous label
				// if the label has a value
				if (!$(elem).attr('value').length)
					// Insertion of the label text inside the input value
					$(elem).attr('value',txtLabel);

					// Action on click
					$(elem).click(function() {
						// only if the text inside the input[value] = the label text description
						if ($(elem).attr('value') == txtLabel)
							$(elem).attr('value','');
					});
			}

			function secureForm(elem) {
				var $requiredFields = $(elem).find('.required');
				$(elem).submit(function(){
					if (
							!$requiredFields.attr('value').length ||
							$requiredFields.attr('value') == $requiredFields.prev('label').text()
					) {
						$requiredFields.addClass(c(settings.classError));
						if (settings.alertTxt)
							alert(settings.alertTxt)
						return false;
					}
				})
				$requiredFields.focus(function() {
					$(this).removeClass(c(settings.classError))
				})
			}

			if (getAction(settings.action,'tempSearchText'))
				tempSearchText($(this));
				
			if (getAction(settings.action,'secureForm'))
				return secureForm($(this))
		}
	});
})(jQuery);


/*
	Plugin addPrintLink par Olivier Gorzalka
	Permet d'insérer un lien Imprimer cette page et de lui attribuer l'action d'impression de page
	Dernière mise à jour : 6 avril 2009
*/
(function($) {
	$.fn.extend({
		addPrintLink: function (options) {
			// Default options
			var settings = {
				txt:'Imprimer la page', // texte à afficher
				tag:'p', // balise du conteneur du lien
				className:'.print', // classe du conteneur du lien
				mode:'appendTo' // mode d'insertion (insertBefore, insertAfter, appendTo)
			};
			if(options) $.extend(settings, options);
			function c(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector

			var htmlPrintLink = '<'+settings.tag+'>';
			htmlPrintLink += '<a class="'+c(settings.className)+'" href="#print" title="'+settings.txt+'">'+settings.txt+'</a>'
			htmlPrintLink += '</'+settings.tag+'>';

			if (settings.mode == 'appendTo') { $(htmlPrintLink).appendTo($(this)); }
			else if (settings.mode == 'insertBefore') { $(htmlPrintLink).insertBefore($(this)); }
			else if (settings.mode == 'insertAfter') { $(htmlPrintLink).insertBefore($(this)); }

			$(settings.className).click(function() { window.print(); });
		}
	});
})(jQuery);


// Extension CSS external: Olivier Gorzalka
// selecteur de lien externe
// utilisation $('a:external') ou tout simplement $(':external')
$.extend($.expr[':'],{
	external: function(a) {
		var url = a.href;
		var dom = window.location.hostname;
		var dom1 = dom.replace(/\./g, "\\.")
		var dom2 = dom1.replace(/\//g, "\\/")
		var pat = new RegExp("([^:]{2,6}://)?("+dom2+")?(.*)");
		var res;
		if( url && url.charAt(0) == '/' ) { return false; } // Chemin absolu avec slash ?
		res = url.match(pat);
		if( !res[1] || res[1].length == 0 ) { return false; } // Chemin relatif
		if( !res[2] || res[2].length == 0 ) { return true; } // Url externe
		if( $(a).attr("rel") == 'external') { return true; } // lien comportant déjà rel external
		return false ; // Sinon, lien interne
	}
});


/*
**  jquery.linkAnylizer.js -- jQuery plugin for anylising selected links
**  Olivier Gorzalka
**
**  Params :
**  @selectors: list of selector to retrieve (ex: selectors: ':external,:file(doc),:file(pdf)')
**  @ignore: selector of link to ignore separated by coma (ex: ignore: '.ignoreExternal, #linkId')
**  @new_window_txt: text to add in the title for external link (ex: new_window_txt: 'Open In A New Window')
**  LastChangedDate: 29 Dec 2008
*/
(function($) {
	$.fn.extend({
		linkAnylizer: function (options) {
			// Default options
			var settings = {
				selectors: null,
				ignore : '.ignoreExternal',
				new_window_txt : 'Dans une nouvelle fenêtre'
			};
			if(options) $.extend(settings, options);
			
			var $link = $(this).find('a').not(settings.ignore);
			$link.each(function(i,item) {
				if( $(item).attr('href') == undefined ) return;
				if (settings.selectors != null) {
					var listSelectors = settings.selectors.split(','); // array of files to be tested
					var matchExp = new RegExp(/\:(file\()?(\w*)\)?$/);
					// file analysis
					$(listSelectors).each(function(i,selector){
						var classElem = selector.match(matchExp); // class to apply on the link
						if($(item).is(selector)) {
							if (selector == ':external') {
								var title;
								if( $(item).attr("title") != undefined )
									title = $(item).attr("title");
								else
									title = $(item).text();
								if( $(item).hasClass('iconAfter') ){
									$(item).after('&nbsp;<span class="iconlink '+classElem[2]+'">&nbsp;</span>');
								}
								else{
									$(item).attr({
										'rel':'external',
										'title': title +" ("+settings.new_window_txt+")"
									}).addClass('iconlink '+classElem[2]); // give the class to the object
									$(item).attr('target','blank');
								}
							} else {
								if( $(item).hasClass('iconAfter') ){
									$(item).after('&nbsp;<span class="iconlink '+classElem[2]+'">&nbsp;</span>');
								}
								else
									$(item).addClass('iconlink '+classElem[2]); // give the class to the object
							}
						}
					});	
				}
			});
		}
	});
})(jQuery);


function updatetimestamp()
{
	var d = new Date();
	d.setYear($("#FromYear").val());
	d.setMonth($("#FromMonth").val()-1);
	$("#SearchTimestamp").attr("value",Math.round(d.getTime()/1000.0) );
}
var section_offset = 1
function fadeToSection(){
	if( section_offset >= $('#sectionsBloc.full ul li').length)
		section_offset = 0;
	
	var $toFade = $('#sectionsBloc.full ul li').eq(section_offset);

	$('#sectionsBloc.full ul li.active').removeClass("active").removeClass("active").find("div").fadeOut();
	$('#sectionsBloc.full ul li').eq(section_offset).find("div").fadeIn();
	$('#sectionsBloc.full ul li').eq(section_offset).addClass("active");

	section_offset++;
}


/******************* FONCTION LANCÉES AU CHARGEMENT DU DOM ********************/

$(document).ready(function () {
	
	// Alignement vertical
	$('#sectionsBloc ul h4 a span').vAlign();
		
	// Marquee
	$('.newsticker').newsScroller();


	// Rotation des rubriques en home
	var fadeToSection_tm = setInterval('fadeToSection()',5000);
		
	// Tabs
	$('#sectionsBloc.full ul li h4 a').click(function(){
		clearTimeout(fadeToSection_tm);
		if (!$(this).parent('li').hasClass('active')) {
			$(this).closest("ul").find("li.active")
				.removeClass("active")
				.find("div").fadeOut();
			$(this).closest("li").find("div").fadeIn();
			$(this).closest('li').addClass("active");
		}
		return false;
	});
	
	
	// Search Form
	$('#websiteSearch').formManager({
		action:'secureForm',
		alertTxt:'Veuillez saisir votre recherche'
	});
	
	$('#rch').formManager({
		action:'tempSearchText'
	});
	
	// Insertion du lien Imprimer cette page pour les actualités
	$('#actualite #main').addPrintLink({ txt:'Imprimer le communiqué' });
	$('.transcript').addPrintLink({ txt:'Imprimer le transcript', tag:'span' });
	
	// Gestion des liens externes
	$('#linksBloc,#footer,#blogBloc,#contenu').linkAnylizer({
		selectors: ':external'
	});
	
	if( $("#websiteSearch2").length ){
		$("#FromMonth").change(updatetimestamp);
		$("#FromYear").change(updatetimestamp);
	}
	
	// Ajout des liens RSS
	var rsslink = 'http://www.labourseetlavie.com/rss/feed/videos.rss';
	$(".rssLink").parents("li").append('<ul style="display: none"> \
	<li><a href="'+rsslink+'" title="Lire le flux RSS avec un lecteur externe"><img src="/design/cosmic/images/icons/rsslink.png" alt="yahoo"/></a></li> \
	<li><a href="http://add.my.yahoo.com/rss?url='+rsslink+'" title="Lire le flux RSS avec Yahoo"><img src="/design/cosmic/images/icons/yahoo.gif" alt="yahoo"/></a></li> \
	<li><a href="http://fusion.google.com/add?feedurl='+rsslink+'" title="Lire le flux RSS avec google"><img src="/design/cosmic/images/icons/google.gif" alt="google"/></a></li> \
	<li><a href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url='+rsslink+'" title="Lire le flux RSS avec Newsgator"><img src="/design/cosmic/images/icons/newsgator.gif" alt="newsgator"/></a></li> \
	<li><a href="http://www.netvibes.com/subscribe.php?url='+rsslink+'" title="Lire le flux RSS avec Netvibes"><img src="/design/cosmic/images/icons/netvibes.gif" alt="netvibes"/></a></li> \
	<li><a href="http://www.bloglines.com/sub/'+rsslink+'" title="Lire le flux RSS avec Bloglines"><img src="/design/cosmic/images/icons/bloglines.gif" alt="bloglines"/></a></li> \
	</ul>').find(".rssLink").click(function(e){
		$(this).parents("li").find('ul').toggle();
		return false;
	});
		
});