/************************ VARIABLE PSEUDO-GLOBALE  *************************/

var GA_CODE = 'UA-10774326-1'; // code google analytics

var BASE_HREF = $('base').attr('href'); // base href du site
var LANG = $('html').attr('lang'); // récupère la langue en cours

function _(string) { return translate[string][LANG]; } // function to translate

if(typeof Shadowbox != 'undefined'){
	Shadowbox.loadSkin('classic', BASE_HREF+'assets/templates/grospiron/scripts/plugins/skin');
	Shadowbox.loadLanguage(LANG, BASE_HREF+'assets/templates/grospiron/scripts/plugins/lang');
	Shadowbox.loadPlayer(['iframe', 'html', 'img'], BASE_HREF+'assets/templates/grospiron/scripts/plugins/player');
}

/*
 * --------------------------------------------------------------------
 * jQuery-Plugin - accessibleUISlider - creates a UI slider component from a select element(s)
 * by Scott Jehl, scott@filamentgroup.com
 * http://www.filamentgroup.com
 * reference article: http://www.filamentgroup.com/lab/progressive_enhancement_convert_select_box_to_accessible_jquery_ui_slider
 * demo page: http://www.filamentgroup.com/examples/slider/demo.html
 * 
 * Copyright (c) 2008 Filament Group, Inc
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 *
 * Usage Notes: please refer to our article above for documentation
 *  
 * Version: 1.0, 08.12.08
 * Changelog: 
 * 	
 * --------------------------------------------------------------------
 */


jQuery.fn.accessibleUISlider = function(settings){
	var selects = jQuery(this);

	//id attrs - selects need ids for this feature to work - links handles to original select menus
	var elIds = (function(){
		var tempArr = [];
		selects.each(function(){
			tempArr.push(jQuery(this).attr('id'));
		});
		return tempArr;
	})();
	
	//array of all option elements in select element
	var options = (function(){
		var opts = [];
		selects.eq(0).find('option').each(function(i){
			opts.push({
				value: jQuery(this).attr('value'),
				text: jQuery(this).text()
			});
		});
		return opts;
	})();
	
	//presets by selected indexes
	var presets = (function(){
		var indexes = [];
		selects.each(function(){
			var thisIndex = jQuery(this).find('option:selected').get(0).index;
			var thisPercentage = Math.round((thisIndex / (options.length-1)) *100);
			indexes.push(thisPercentage);
		});
		return indexes;
	})();
	
	//set up slider options API
	var sliderAPI = jQuery.extend({
		labels: 3,
		inject: true,
		rangeOpacity: 0.7,
		width: selects.parent().width(),
		range: selects.length > 1,//boolean for whether it's a range or not
		steps: options.length-1,
		stepping: 0,
		handles: function(){//set starting locations to selected index, if applicable
				var tempArr = [];
				selects.each(function(i){
					tempArr[i] = {
						start: presets[i],
						min: 0,
						max: 100,
						id: 'handle_'+i
					};
				});
				return tempArr;
			}(),
		change: function(e, ui) {//slide function
				var that = jQuery(this);
				var currValue = ui.value;
				var currIndex = Math.round(currValue / 100 * (options.length-1));
				var currValue = options[currIndex].value;
				var currText = options[currIndex].text;
				//handle feedback tooltip and aria attrs
				
				//var feedback = ui.handle.find('.ui-slider-tooltip'); 
				///feedback.html(currText).parent().attr('aria-valuetext', currValue).attr('aria-valuenow', currValue);
				//control original select menu

				
				$(selects).find('option[value='+currValue+']').attr('selected', 'selected');
				//console.log($(selects).find('option:selected').attr('value'))
			}
	}, settings);
		
	selects.change(function(){
		var thisIndex = jQuery(this).find('option:selected').get(0).index;
		var thisLeft = Math.ceil((thisIndex / (options.length-1))* 100);
		var thisIndex = jQuery('#handle_'+ jQuery(this).attr('id')).parent().prev('a').size();
		jQuery('#handle_'+ jQuery(this).attr('id')).parents('.ui-slider:eq(0)').slider("moveTo", thisLeft,thisIndex);
	});
	
	//opt groups if present
	var groups = (function(){
		if(selects.eq(0).find('optgroup').size()>0){
			var groupedData = [];
			selects.eq(0).find('optgroup').each(function(i){
				groupedData[i] = {};
				groupedData[i].label = jQuery(this).attr('label');
				groupedData[i].options = [];
				jQuery(this).find('option').each(function(){
					groupedData[i].options.push({text: jQuery(this).text(), value: jQuery(this).attr('value')});
				});
			});
			return groupedData;
		}
		else return false;
	})();	

	//create slider component div
	var sliderComponent = jQuery('<div class="sliderComponent"></div>');
	
	//CREATE HANDLES
	selects.each(function(i){
		sliderComponent.append('<div id="handle_'+elIds[i]+'" tabindex="'+ i+1 +'" class="ui-slider-handle ui-default-state" role="slider" aria-valuemin="'+ sliderAPI.minValue +'" aria-valuemax="'+  sliderAPI.maxValue +'"><span class="ui-slider-tooltip ui-component-content"></span></div>');
	});
	
	//CREATE SCALE AND TICS
	sliderComponent.width(sliderAPI.width);
	
	//write dl if there are optgroups
	if(groups) {
		var scale = sliderComponent.append('<dl class="ui-slider-scale"></dl>').find('.ui-slider-scale:eq(0)');
		jQuery(groups).each(function(){
			scale.append('<dt><span>'+this.label+'</span></dt>');//class name becomes camelCased label
			var groupOpts = this.options;
			jQuery(this.options).each(function(i){
				scale.append('<dd><span class="ui-slider-label">'+ groupOpts[i].text +'</span><span class="ui-slider-tic ui-component-content"></span></dd>');
			});
		});
	}
	//write ol
	else {
		var scale = sliderComponent.append('<ol class="ui-slider-scale"></ol>').find('.ui-slider-scale:eq(0)');
		jQuery(options).each(function(){
			scale.append('<li><span class="ui-slider-label">'+this.text+'</span><span class="ui-slider-tic ui-component-content"></span></li>');
		});
	}
	
	//style the li's or dd's
	sliderComponent.find('.ui-slider-scale li, .ui-slider-scale dd').each(function(i){
		jQuery(this).css({
			'left': ((100 /( options.length-1))*i).toFixed(2) + '%'
		});
	});
	
	//first and last classes, and right align the last li/dd
	sliderComponent.find('.ui-slider-scale li:first, .ui-slider-scale dd:first').addClass('first');
	sliderComponent.find('.ui-slider-scale li:last, .ui-slider-scale dd:last').addClass('last').each(function(){ 
		jQuery(this).css({'right': 0, 'left':'auto'});
	});
	
	//show and hide labels depending on showLabels pref
	//show the last one if there are more than 1 specified
	if(sliderAPI.labels > 1) sliderComponent.find('.ui-slider-scale li:last span.ui-slider-label, .ui-slider-scale dd:last span.ui-slider-label').css('text-indent', 0).addClass('ui-slider-label-show');
	//set increment
	var increm = Math.round(options.length / sliderAPI.labels);
	//show em based on inc
	for(var j=0; j<options.length; j+=increm){
		if((options.length - j) > increm){//don't show if it's too close to the end label
			sliderComponent.find('.ui-slider-scale li:eq('+ j +') span.ui-slider-label, .ui-slider-scale dd:eq('+ j +') span.ui-slider-label').addClass('ui-slider-label-show');
		}
	}

	//style the dt's
	sliderComponent.find('.ui-slider-scale dt').each(function(i){
		var aPixel = ((3 / sliderAPI.width) * 100).toFixed(2);
		jQuery(this).css({
			'left': ((100 /( groups.length))*i).toFixed(2) + '%',
			'width': (((sliderAPI.width / groups.length) / sliderAPI.width) * 100).toFixed(2)- aPixel +'%'
		});
	});
	
	sliderAPI.markup = sliderComponent;
	
	//port slider function to pass api in.
	sliderAPI.markup.slider = function(settings){
		var sliderAPI_port = jQuery.extend(sliderAPI, settings);		
		jQuery(this).slider(sliderAPI_port).find('.ui-slider-range').css('opacity', sliderAPI_port.rangeOpacity);
		return this;
	}
	
	//if inject is true, inject slider after last select element and init, otherwise return api including markup
	if(sliderAPI.inject){
		sliderAPI.markup.insertAfter(jQuery(this).eq(this.length-1)).slider(sliderAPI).find('.ui-slider-range').css('opacity', sliderAPI.rangeOpacity);
		return this;
	}
	else{
		return sliderAPI;
	}

}


// Extension CSS external: Olivier Gorzalka
// selecteur de lien externe
// utilisation $('a:external') ou tout simplement $(':external')
$.extend($.expr[':'],{
	external: function(a) {
		if(!a.href) { 
			return false;
		}
		return a.hostname && a.hostname !== window.location.hostname;
	}
});


// Extension CSS file: Sunny Ripert & Olivier Gorzalka
// selecteur de type de fichier (img et a)
// utilisation $('a:file(pdf)') > récupère tout les liens vers des fichiers pdf
// utilisation $(':file(jpg)') > récupère tout les images de type jpg
$.extend($.expr[':'],{	
	file: function(a,i,m) {
		var type = m[3];
		var types = {
			image: '\\.(png|gif|jpe?g|bmp|tiff|psd|psp|svg|xcf|ico)$',
			music: '\\.(mp3|ogg|flac|wav|aif|aiff|aifc|cda|m3u|mid|mod|mp2|snd|voc|wma)$',
			archive: '\\.(zip|rar)$',
			video: '\\.(avi|wmv|qt|mkv|flv|mpg|ram)$',
			email: '^(mailto:)'
		} // types of file
		if (types[type])
			var match = new RegExp(types[type]); // if the type is in the array
		else
			var match = new RegExp('\\.'+type+'$'); // else herit of the filetype defined by the user

		if (a.href)
			return a.href.match(match);

		if (a.src)
			return a.src.match(match);

		return false;
	}
});


/*
**  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);



/*
	tabGenerator plugin for jQuery
	created by Cosmic Communication
	parameters: @separator : element which define the différent panels of content
					             a header tag (h2,h3,hr) can be choosen as delimiter > a div wraps each section beginning by this tag
	            @navigation : element which contains the tabs
*/

(function($) {
	$.fn.tabGenerator = function(options) {
		// Default options
		var settings = {
			separator : 'h4', // separator
			navigation: '.nav', // tab links class or id
			tabClassName: '.tabApplied',
			callbackOnClick:function() {} // callback on click
		};
		if(options) $.extend(settings, options);
		function c(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector
		// Element to exclude from the creation of wrapper div
		var arr = [ 'div' , 'dl' , 'ul' , 'li' ];
		
		$(this).addClass(c(settings.tabClassName));
		return $(this).each(function(i, elem) {
			// if object exists
			if ($(elem).length) {
				// initialize variables
				var div = false;
				var linkNavigTab = new Array();
				var idConteneur = null;
				var createWrappers = null;
				if (jQuery.inArray(options.separator, arr) < 0) {
					createWrappers = true
				}

				var wrapperElement = options.separator;
				/* Each elements delimited by the 
				 separator is wrapped by a div */
				
				// if element is not in the exclusion list to wrap with a div
				if (createWrappers) {
					$(elem).children().each(function(){
						if( $(this).is(options.separator) ){
							div = document.createElement("div");
							$(div).insertBefore(this);
							$(div).append(this);
							return;
						}
						if( div != false ){
							$(div).append(this);
						}
					});
					wrapperElement = 'div';
				}
				
				/* Id attribute of each created div */
				var parentElement = $(elem).find(wrapperElement).not(options.navigation);
				if (wrapperElement == 'li' && $(elem).find('ul').length == 2) {
					parentElement = $(elem).find('ul:eq(1)').find(wrapperElement).not(options.navigation);
				}

				parentElement.each(function(i,item) {
					var idConteneur;
					if (createWrappers) {
						idConteneur = $(this).find(options.separator).attr('id');
						$(this).attr('id',idConteneur+'_wrapper').addClass('panel').hide();	
						idConteneur = $(this).find(options.separator).attr('id',idConteneur+'_title');
					} else {
						idConteneur = $(this).attr('id');
						$(this).attr('id',idConteneur+'_wrapper').addClass('panel').hide();	
					}
				})

				/* If a url hash is present in the URL */

				if (window.location.hash) {
					var offsetElem = $(settings.tabClassName).offset().top
					$('html,body').animate({ scrollTop: offsetElem }, 0)
					var navigTabHash = window.location.hash; // hash variable
					if ($(elem).find(navigTabHash+'_wrapper').length) {
						$(elem).find(navigTabHash+'_wrapper').show(); // show !!!
						$(options.navigation).find("a[href$='"+navigTabHash+"']").closest('li').addClass('active'); // give the 'active' class to the active tab
					}
					// else we show the first element
					else {
						$(elem).find('.panel:first').show(); // show !!!
					}
				} else {
					$(elem).find('.panel:first').show();
				}
				
				// when the user click on a tab
				$(options.navigation).bind('click', function (e){	

					var $target = $(e.target);
					if ($target.is('a')) { 
						targetLink = $target;
					} else if ($target.parents().is('a')) {
						targetLink = $target.parents('a')[0]
					} else { return; }

					if ($(targetLink).is("a[href*='#']")) {
						if ($(targetLink).closest('li').hasClass('active')) { return; }
						$(options.navigation).find("a").closest('li.active').removeClass('active'); // remove the 'active' class
						$(targetLink).closest('li').addClass('active'); // give the 'active' class to the active tab
						var hashValue = $(targetLink).attr("href"); // 'href' attribute of the clicked tab
						var lengthHref = $(targetLink).attr("href").length; // size of the url
						var checkhashValue = hashValue.lastIndexOf('#'); // search for the last # in the url
						if (checkhashValue > -1) {
							var targetHash = hashValue.substr(checkhashValue,lengthHref); // give the real hash value
							if ($(elem).find(targetHash)) {
								$(elem).find('.panel:visible').hide(); // hide the previous panel
								$(elem).find(targetHash+'_wrapper').fadeIn('slow',settings.callbackOnClick); // show the called panel by the tab link
							}
						}
					}
				});
			}
		});
	}
})(jQuery);


/**
 * Equal Heights Plugin
 * Equalize the heights of elements. Great for columns or any elements
 * that need to be the same size (floats, etc).
 * 
 * Example 1: $(".cols").equalHeights(); Sets all columns to the same height.
 * Example 2: $(".cols").equalHeights(400); Sets all cols to at least 400px tall.
 * Example 3: $(".cols").equalHeights(100,300); Cols are at least 100 but no more
 * than 300 pixels tall. Elements with too much content will gain a scrollbar.
 * 
 */

(function($) {
	$.fn.equalHeights = function(minHeight, maxHeight) {
		var tallest = (minHeight) ? minHeight : 0;	
		function addSize(elem,baseHeight,operation) {
			var border_top = parseInt(elem.css('border-top-width'));
			var border_bottom = parseInt(elem.css('border-bottom-width'));
			var padding_top = parseInt(elem.css('padding-top'));
			var padding_bottom = parseInt(elem.css('padding-bottom'));
			if (operation == 'subtract') {
				if (!isNaN(padding_top)) baseHeight -= padding_top;
				if (!isNaN(padding_bottom)) baseHeight -= padding_bottom;
				if (!isNaN(border_top)) baseHeight -= border_top;
				if (!isNaN(border_bottom)) baseHeight -= border_bottom;
			} else {
				if (!isNaN(padding_top)) baseHeight += padding_top;
				if (!isNaN(padding_bottom)) baseHeight += padding_bottom;
				if (!isNaN(border_top)) baseHeight += border_top;
				if (!isNaN(border_bottom)) baseHeight += border_bottom;
			}
			return baseHeight;
		}	
		this.each(function() {
			var height = $(this).height();
			height = addSize($(this),height);
			if (height > tallest) tallest = height;
		});
		if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
		return this.each(function() {
			tallest2 = addSize($(this),tallest,'subtract')
			$(this).height(tallest2);
		});
	}
})(jQuery);

// Converti une liste en formulaire de téléchargement de PDF
function pseudoSelect(elem) {
	var attribute = new Array();
	$(elem).each(function() {
		var selectObject = '<select class="jSelect chp_text">';
		
		var select_country = "Imprimez le guide dont vous avez besoin";
		// Quelle langue ?
		if( $('html').attr('lang') == 'en' )
			select_country = "Print the guide you need";
			
		selectObject += '<option value="#">'+select_country+'</option>';
		$this = $(this).find('a');
		$this.each(function(i,item) {
			attribute[i] = {
				txt:$(this).text(),
				url:$(this).attr('href')
			};
			selectObject += '<option value="'+attribute[i].url+'">'+attribute[i].txt+'</option>';
		})
		selectObject += '</select>';
		$(this).replaceWith(selectObject);
	})
	$('.jSelect').change( function () {
		//document.location.href=$(this).attr('value');
		window.open(BASE_HREF+$(this).val()); 
 	});
}

// ajoute un joli effet hover au passage de la souris
function menuEffects(colorBefore,colorAfter,delay) {
	$('#mainmenu li:not([class=active]) a').hover(function() {
		$(this).parent('li').stop().animate({
			backgroundColor:colorAfter
		},300)
	}, function() {
		$(this).parent('li').stop().animate({
			backgroundColor:colorBefore
		},delay)
	})
}

// ajoute un effet au passage de la souris
function blockHome() {
	$('#mainsections li').each(function() {
		$('<div></div>').insertBefore($(this).find('a')).css('opacity',0)
	})
	
	$('#mainsections a').hover(function() {
		$(this).prev('div').stop().animate({'opacity':0.5},300)
	}, function() {
		$(this).prev('div').stop().animate({'opacity':0},300)
	});
}

// position le bloc gris subtil en fonction de la dimension des éléments
function bgPosition(elem) {
	bgPosBodyY = Math.round(700-($(elem).height()+$(elem).offset().top));
	bgPosContentX = Math.round(656-($(elem).offset().left-$('#content').offset().left));
	$('body')
		.css('background-position','0 -'+bgPosBodyY+'px')
		.find('#content')
		.css('background-position','-'+bgPosContentX+'px -'+bgPosBodyY+'px')
}


// texte sur fond noir opacité avec effet d'apparition cool au passage de la souris :)
function movingText(elem,heightDiv,widthDiv) {
	$(elem).find('p').wrapInner('<span></span>');
	$(elem).find('p span').css('opacity',0);
	
	$('<div class="overlayBlock"></div>').insertAfter($(elem).find('li div')).css({
		height:heightDiv,
		marginTop:-(heightDiv),
		'opacity':0
	});
	
	$(elem).find('li div').find('p')
		.appendTo($(this).parent('li'))
		.css({
			height:heightDiv,
			marginTop:-(heightDiv+16),
			'position':'relative',
			'top':0,
			'left':20
		});
	
	$(elem).find('li div').css({
		height:heightDiv,
		width:widthDiv
	});
	

	$(elem).find('li').hover(function() {
			$(this).find('p').css({zIndex:4});
			$(this).find('span').stop().animate({
				top:10,
				left:0,
				opacity:1
			});
			$(this).find('div:eq(1)').stop().animate({'opacity':0.7},300)
	}, function() {
			$(this).find('p').css({zIndex:5})
			$(this).find('span').stop().animate({
				top:-130,
				left:0,
				opacity:0
			});
			$(this).find('div:eq(1)').stop().animate({'opacity':0},300)
	});

}

// durant le chargement du DOM

function collapseZone(elems,duration,callback) {
	$('h4 > input')
	.addClass('hitarea')
	.click(function () {
	  $(this)
	  	.toggleClass('active')
		.parent()
		.next('fieldset')
		.slideToggle(duration,callback);
	});
}

function jMap(elem,imgProperties) {
	/* Carte Grospiron Europe */
	$(elem)
		.find('a')
			.click(function() { return false; }) // le lien ne doit pas être cliquable
			.append('<span id="ctrlBtn"></span>') // on ajoute le bouton qui permettra d'agrandir la carte et de la réduire
		.find('img').css({
			'display':'block',
			'opacity':0
		}); // on affiche l'image mais en opacité 0, on l'affichera ensuite au clic sur la france
	
	$('#ctrlBtn')
		// Au passage sur le span créé précédemment
		.hover(function() {
			if (!$(this).hasClass('closeBtn')) // seulement si le bouton n'a pas la classe closeBtn (donc s'il s'agit de la zone permettant de zoomer)
				$(this).closest(elem).addClass('hover'); // on ajoute la classe hover au conteneur .grospiron_europeSteps (carte de france devient jaune)
		}, function() {
			$(this).closest(elem).removeClass('hover'); // on retire la classe hover au conteneur .grospiron_europeSteps (carte de france redevient grise)
		})
		// Au clic sur le span créé précédemment
		.click(function() {
			if ($(this).hasClass('closeBtn')) {
				$(this).animate({opacity:0}) // opacité 0 sur le bouton fermer
				.closest(elem) // réduction de l'image de la carte
					.find('img').animate(imgProperties.normal, function() {
						$(this).animate({
							opacity:0
						}, function() { $('#ctrlBtn').removeClass('closeBtn').css({'opacity':1}); });
					});
			} else {
				$(this)
					.css({opacity:0})
					.addClass('closeBtn')
					.animate({opacity:1}) // on affiche le bouton pour fermer l'aggrandissement de l'image
				.closest(elem) // agrandissement de l'image de la carte
					.find('img').animate({
						opacity:1
					}, function() {
						$(this).animate(imgProperties.zoomed);
					});
			}
		});
}

$(document).ready(function(){
	
	// gestion du formulaire de devis
	if ($('.devis').length) {
		var elemToShow = ''; // liste des élements à afficher
	 	var actionLists = (window.location.search.replace('?','')).split('&'); // on récupère la liste des actions à effectuer

	$('.collapsable').prev('h4').find('input:checked').each(function() {
		elemToShow += '.formulaire_'+$(this).attr('name').replace('_activate','')+',';
	});
	
	if (actionLists != "") {
		$(actionLists).each(function(i,item) {
			elemToShow += '.formulaire_'+item.substring(0,item.length-2)+',';
		})
	}
		$('.collapsable').prev('h4').find('input').attr('checked','checked');
		$('.collapsable').not(elemToShow).addClass('hidden').hide().prev('h4').find('input').removeAttr('checked');
		collapseZone(
			".devis fieldset:eq(1),.devis fieldset:eq(2),.devis fieldset:eq(3),.devis fieldset:eq(4)",
			300,
			function() { 
				$('#footer')
					.css({
						'position':'relative',
						'bottom':'-9999px'
					})
					.css({
						'position':'absolute',
						'bottom':'0'
					}); 
			});
	}

	// Guides PDF
	pseudoSelect('ul#guides,ul#douane');
	
	// texte sur fond noir opacité avec effet d'apparition cool au passage de la souris :)
		//movingText('.demenagementSteps',117,222);
		//movingText('.fine_artsSteps',117,222);
		//movingText('.mondeSteps',135,139);
		$('.mondeSteps').find('li:nth-child(4n),li:last').addClass('last');
	
	var widthLi = $('.mondeSteps').find('li:first').width();
	
	// Carte de l'europe
	jMap('.grospiron_europeSteps', { // Propriétés de l'image zoomée et non-zoomée
			zoomed : {
				left:-167,
				top:-312,
				width:1000,
				height:821
			},
			normal : {
				left:-16,
				top:-1,
				width:419,
				height:318
			}
	});

	// analyse des différents type de liens de fichiers
	$('#text').linkAnylizer({
		selectors: ':external', // list of selector to retrieve
		new_window_txt: 'dans une nouvelle fenêtre' // "Open in a new window" text for external link
	});
	
	$('#chapo').linkAnylizer({
		selectors: ':external', // list of selector to retrieve
		new_window_txt: _('newWindow') // "Open in a new window" text for external link
	});

	$('body').addClass('jsactive');
	blockHome();
	menuEffects('#fff','#fbd100',300); 

	
	$('.makeMeTab').tabGenerator({
			separator : 'h5', // separator
			navigation: '.liste_mobilite', // tab links class or id
			tabClassName: '.tabApplied',
			callbackOnClick:function() { 
				$('#footer')
					.css({
						'position':'relative',
						'bottom':'-9999px'
					})
					.css({
						'position':'absolute',
						'bottom':'0'
					}); 
			}
	});

	var biggestHeight = 0;
	var imgIllustr = new Array();
	var idParent;
	$('.liste_mobilite')
	.find('h4').each(function(i) {
		idParent = $(this).closest('li').attr('id');
		imgIllustr[i] = $(this).css('background-image');

	})
	.find('span').each(function() {
		var heightSpan = $(this).height()-1;
		if (heightSpan > biggestHeight) biggestHeight = heightSpan;
	})
	.closest('.liste_mobilite').eq(0)
	.next('.tabApplied')
	.find('.panel:not(:first)').each(function(i) {
		$('<span class="illustr"></span>')
			.prependTo($(this).find('p').eq(0))
			.css({
				width:220,
				height:147,
				margin:'0 0 10px 10px',
				backgroundImage:imgIllustr[i],
				float:'right'
			})
		$('<p style="clear:both"></p>').appendTo(this)
	})
	if (window.location.hash) {
		if (!$('.resized').length) {
			$('.liste_mobilite').addClass('resized')
			.find('span,a').css({height:biggestHeight});
		}
	}
	
	$('.liste_mobilite').click(function() {	
		if (!$('.resized').length) {
			$(this)
				.addClass('resized')
				.find('span,a')
				.animate({
					height:biggestHeight
				},500);
		}
 	});
 	
	// activation des shadowboxs 	
	if(typeof Shadowbox != 'undefined'){
		Shadowbox.init({
			animateFade: false,
			animate : false,
			overlayOpacity : 0,
			fadeDuration: 0,
			displayNav: false,
			displayCounter: false
		});
	}
	
	$('a[rel^=shadowbox]').click(function(){
		Shadowbox.open({
				player:     'iframe',
				title:      $(this).attr("title"),
				content:    $(this).attr("href"),
				height:     427,
				width:      410
			
		})
		return false;
	});

	if ($('select#satisfaction').length) {
		$('select#satisfaction').accessibleUISlider({labels: 10}).find('option:eq(10)').attr('selected','selected');
		if (!$('select#satisfaction').find('option:selected').length) {
			$('select#satisfaction').find('option:eq(10)').attr('selected','selected');
		}


		$('#handle_satisfaction').css('left', Math.round($('select#satisfaction').find('option:selected').val()/($('select#satisfaction option').length-1)*100)+'%' );
	}
	
	$.datepicker.setDefaults($.extend({constrainInput: false}, $.datepicker.regional['fr']));
	
	$(".datepicker").click(function() {
		if ($(this).attr('value') == 'jj/mm/aaaa') {
			$(this).attr('value','');
		}
	}).datepicker();

	/*
	{
		dateFormat:'dd/mm/yy',
		monthNames:['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
		monthNamesShort:['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
		dayNames:['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
		dayNamesShort:['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
		dayNamesMin:['D', 'L', 'M', 'M', 'J', 'V', 'S'],
		
	}
	
	*/
	$('map').wrap('<div id="wrapper_map"/>')
	
	function ucfirst( str ) {
	    str += '';
	    var f = str.charAt(0).toUpperCase();
	    return f + str.substr(1);
	}
	
	// on construit les conteneurs des tooltips
	var htmlTooltip = ''; // init du code html
	var posDebTown,lengthHref;
	var tooltip = new Array();
	$('#carte_france_map area').each(function(i,item){
		lengthHref = $(this).attr('href').length;
		posDebTown = $(this).attr('href').lastIndexOf('coordonnees_');
		if (posDebTown > 0) {
			idTown = $(this).attr('href').substr(posDebTown+12,lengthHref)
		}
		contactInfo = '<dl><dt>Contact '+ucfirst(idTown)+'</dt>';
		contactInfo += '<dd>'+$('#coordonnees_'+idTown+' .contact_tel').text()+'</dd>';
		contactInfo += '<dd>'+$('#coordonnees_'+idTown+' .contact_fax').text()+'</dd></dl>';
		$(this).attr('id','area_'+i);
		htmlTooltip += '<div rel="area_'+i+'">'+contactInfo+'</div>';
	});

	$(htmlTooltip).appendTo('#wrapper_map'); // on insère le code html construit précédemment dans le wrapper de la carte
	$('div[rel^=area_]').css({opacity:0});
		
	$('#carte_france_map area').hover(function(e) {
		$('div[rel='+$(this).attr('id')+']').css('z-index',80).stop().animate({opacity:1});
	}, function() {
		$('div[rel='+$(this).attr('id')+']').css('z-index',1).stop().animate({opacity:0});
	});
	
	$('#slideimg').cycle({ 
	    fx:    'fade', 
	    random:  1 
	 });});

// une fois le DOM chargé
$(window).load(function(){
    
    $.gaTracker(GA_CODE);
	
	$('.genericblock.custom').equalHeights(); // uniformise la hauteur de blocs
	
	bgPosition('.firstblock :first');	
	
	
	
})



