jQuery(function($){
	
	/******* flash *******/
	
	var flashvars = {}, params = {wmode:"transparent"}, attributes = {};
	swfobject.embedSWF(root + "/medias/swf/carte.swf", "carte", "200", "245", "8.0.0", false, flashvars, params, attributes, false);
	
	/******* lisez-le en ligne *******/
	
	$('.issuu').click(function(){
		var documentid = $(this).data('documentid');
		if (documentid != 'undefined' && documentid != ''){
			$.fancybox({
				type: 'swf',
				width: 700,
				height: 495,
				href: 'http://static.issuu.com/webembed/viewers/style1/v2/IssuuReader.swf',
				swf: {wmode:'transparent', allowfullscreen:true, menu:false, flashvars: 'mode=mini&amp;documentId=' + documentid}
			});
			return false;
		}
	});

	/******* liens externes *******/
	
	$('a.external, a[href$=".pdf"], a[href$=".doc"], a[href$=".zip"], a[href$=".dld"]').externalLinks();

	
	/******** retour haut de page ********/
	
	$('a.up').click(function(){
		$('html, body').animate({scrollTop: '0'}, 1000);
		this.blur();
		return false;
	});
	
	/******* tooltips *******/
	
	$('#col_left .tip').tooltip({
		tipClass: 'tooltip',
		opacity: 1,
		effect: 'fade',
		position: "top center",
		offset: [-8,0]
	});
	
	$('#col_right .tip').tooltip({
		tipClass: 'tooltip',
		opacity: 1,
		effect: 'fade',
		position: "top center",
		offset: [-8,0]
	});
	
	$('#content .tip').tooltip({
		tipClass: 'tooltip',
		opacity: 1,
		effect: 'fade',
		position: "center right",
		offset: [0,8]
	});
	
	/******* menu javascript *******/
	
	$("ul.sf-menu").superfish({ 
			animation: {opacity:'show', width:'show'},
			speed: 600,
			autoArrows: true,
			delay: 1000
  }); 
	
	/******* liens current *******/
	
	$('#header .nav a').each( function(idx, el) {
		if ($(this).hasClass(page))
			$(this).addClass('current'); 
 	});

	$('ul.sf-menu a').each( function(idx, el) {
		if ($(this).hasClass(page))
			$(this).add($(this).parents('ul:not(.sf-menu)').prev('a')).addClass('current'); 
 	});

	$('#reperes ul ul a').each( function(idx, el) {
		$(this).addClass('puce blue');
 	});

	$('#reperes li a').each( function(idx, el) {
		if ($(this).hasClass(page))
			$(this).addClass('current');
 	});
	
	/******* mod newsletter *******/
	
	$.initNewsletterForm();
	
	/******* mod news *******/
	
	$("#rdv .scrollable").scrollable({vertical:true, circular:true, speed:1800}).autoscroll({interval:4000});
	var rdv_api = $("#rdv .scrollable").data("scrollable");
	$("#rdv .scrollable_actions a").click(function()
	{
		if ($(this).hasClass('play'))
		{
			rdv_api.play();
			$(this).removeClass('play').attr('title','pause');
		}
		else
		{
			rdv_api.stop();
			$(this).addClass('play').attr('title','play');
		}
	});
	
	/******* mod meteo & localisation *******/
	
	$('#meteo .items').weatherfeed(['FRXX4274','FRPA0434','FRPA0444','FRPA0492','FRXX0362'], {link:false});
	$('#localisation').fancybox({type:'iframe', width:640, height:450});
	
	/******* téléchargements *******/
	
	if (page == 'outil_telechargements')
	{
		$('.conseils ul, .bulletins_archives ul').hide();
		$('a.open').toggleView();
		var open_txt = '(cliquez pour déplier)',
				close_txt = '(cliquez pour replier)';
		$('.bulletins_archives a.open').append('<span>'+ open_txt +'</span>').click(function(){
			if ($(this).hasClass('close')) $('span', this).html(close_txt);
			else $('span', this).html(open_txt);
		});
		$('.conseils a.open:first').trigger('click');
	}

});

/************************************** extends ***************************************/
/**************************************************************************************/

(function($){

	$.fn.externalLinks = function()
	{
		return $(this).live('click', function()
		{
			this.blur();
			var href = $(this).attr('href');
			window.open(href);
			return false;
		});
	}
	
	$.fn.initFormVal = function(value)
	{
		return this.each(function()
		{
			$(this).val(value)
				.focus(function() { if ($(this).val() == value) $(this).val(''); })
				.blur(function() { if ($(this).val() == '')  $(this).val(value); });
		});
	}
		
	$.fn.scrollTo = function(speed)
	{
		return this.each(function() {
			var targetOffset = $(this).offset().top;
			$('html,body').animate({scrollTop: targetOffset}, speed, 'easeOutExpo');
		});
	}


	/************** meteo **************/
	
	$.fn.weatherfeed = function(locations, options)
	{	
		var defaults = {unit:'c', image:true, highlow:true, wind:true, link:true, showerror:false, desc:false};  
		var options = $.extend(defaults, options); 

		var _callback = function(e, feed, options){
			var $e = $(e);
			var html = '<div class="weatherItem"';
			if (options.image) 
			{
				wpd = feed.item.pubDate;
				n = wpd.indexOf(":");
				tpb = _getTimeAsDate(wpd.substr(n-2,8));
				tsr = _getTimeAsDate(feed.astronomy.sunrise);
				tss = _getTimeAsDate(feed.astronomy.sunset);
				if (tpb>tsr && tpb<tss) { daynight = 'd'; } else { daynight = 'n'; }
				var img_path = feed.item.condition.code != '3200' ? 
					'http://l.yimg.com/a/i/us/nws/weather/gr/'+ feed.item.condition.code + daynight +'.png'
					: root + '/assets/images/weather_default.png';
				html += ' style="background-image:url('+ img_path +'); background-repeat:no-repeat;"';
			}
			html += '>';
			if (options.link) html += '<a class="weatherLink external" href="'+ feed.item.link +'" title="voir les prévisions sur Yahoo! Weather">';
			html += '<div class="weatherCity">'+ feed.location.city.replace(/\+/g, "'").replace(/\-/g, " ") +'</div>';
			html += '<div class="weatherTemp">'+ feed.item.condition.temp +'&deg;</div>';
			if (options.desc) html += '<div class="weatherDesc">'+ feed.item.condition.text +'</div>';
			if (options.highlow || options.wind)
			{
				html += '<div class="weatherDetails">';
				if (options.highlow)
				{
					var wf = feed.item.forecast[0];
					html += '<span class="weatherRange">Max:'+ wf.high +'&deg; Min:'+ wf.low +'&deg;</span>';
				}
				if (options.wind) 
				{
					var wd = feed.wind.direction;
					if(wd>=348.75&&wd<=360){wd="N"};if(wd>=0&&wd<11.25){wd="N"};if(wd>=11.25&&wd<33.75){wd="NNE"};if(wd>=33.75&&wd<56.25){wd="NE"};if(wd>=56.25&&wd<78.75){wd="ENE"};
					if(wd>=78.75&&wd<101.25){wd="E"};if(wd>=101.25&&wd<123.75){wd="ESE"};if(wd>=123.75&&wd<146.25){wd="SE"};if(wd>=146.25&&wd<168.75){wd="SSE"};
					if(wd>=168.75&&wd<191.25){wd="S"};if(wd>=191.25 && wd<213.75){wd="SSO"};if(wd>=213.75&&wd<236.25){wd="SO"};if(wd>=236.25&&wd<258.75){wd="OSO"};
					if(wd>=258.75 && wd<281.25){wd="O"};if(wd>=281.25&&wd<303.75){wd="ONO"};if(wd>=303.75&&wd<326.25){wd="NO"};if(wd>=326.25&&wd<348.75){wd="NNO"};
					html += '<span class="weatherWind">Vent: '+ wd +' '+ feed.wind.speed + feed.units.speed +'</span>';
				}
				html += '</div>';
			}
			if (options.link) html += '</a>';
			html += '</div>';
			$e.append(html);
		};
		
		var _getTimeAsDate = function(t) { var d = new Date(); return new Date(d.toDateString() +' '+ t);};
		
		return this.each(function(i, e)
		{
			var $e = $(e);
			if (!$e.hasClass('weatherFeed')) $e.addClass('weatherFeed');
			if (!$.isArray(locations)) return false;
			var count = locations.length;
			if (count > 10) count = 10;
			var locationid = '';
			for (var i=0; i<count; i++) {
				if (locationid != '') locationid += ',';
				locationid += "'"+ locations[i] + "'";
			}
			now = new Date();
			rnd = now.getFullYear() + now.getMonth() + now.getDay() + now.getHours();
			var query = "select * from weather.forecast where location in ("+ locationid +") and u='c'";
			var api = 'http://query.yahooapis.com/v1/public/yql?q='+ encodeURIComponent(query) +'&rnd='+ rnd +'&format=json&callback=?';
			
			$.ajax({
				type:'GET',
				url: api,
				dataType:'json',
				success: function(data) {
					if (data.query)
					{
						if (data.query.count > 1 )
							for (var i=0; i<data.query.count; i++)
								_callback(e, data.query.results.channel[i], options);
						else
							_callback(e, data.query.results.channel, options);
						$e.closest(".scrollable").slideDown().scrollable({circular:true, speed:800}).autoscroll({interval:5000});
					}
					else if (options.showerror) $e.html('<div class="weatherItem">Données météo indisponible</div>').closest(".scrollable").slideDown();
				},
				error: function(data) {
					if (options.showerror) $e.html('<div class="weatherItem">Données météo indisponible</div>').closest(".scrollable").slideDown();
				}
			});
			
		});
	}
		
	/*************** actualites **************/

	$.fn.toggleView = function()
	{
		return $(this).click(function()
		{
			this.blur();
			var target = $(this).attr('href');
			
			if (typeof target == 'undefined' || target == '' || !$(target).length)
				return false;
			
			$(this).toggleClass('close');
			$(target).slideToggle('slow');
			
			return false;
		});
	}

	/************** initNewsletterForm **************/
		
	$.initNewsletterForm = function()
	{
		var $form = $('#newsletterForm'),
				$input = $('input[name="email"]', $form),
				defaultVal = 'Entrez votre adresse email',
				$error = $('<p/>').addClass('error').hide().prependTo($form);
		
		$input.initFormVal(defaultVal);
		
		$form.submit(function(e)
		{
			$error.hide().empty();
			
			var val = $.trim($input.val()),
					email_regex = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;

			if (val == '' || val == defaultVal) e.preventDefault();
			else if (!email_regex.test(val))
			{
				$error.html('Adresse email invalide').show();
				e.preventDefault();
			}
		});
	}

})(jQuery);
