/* ------------------------------------------------------------------------
	Global document ready for stuff on all pages.
------------------------------------------------------------------------- */

	$(document).ready(function(){
		// Personalisez votre menu
		$('#personalisez .first a').click(function(){
			if($('#personalisez li:eq(1)').is(':visible')){
				$('#personalisez li:gt(0)').hide();
			}else{
				$('#personalisez li:gt(0)').show();
			};
			
			return false;
		});
		
		// init resize on load
		layout.resize();				

		// For the full screen images
		$(window).resize(function(){
			layout.resize();				
		});
		
		// Custom dropdowns
		dropdown.init();
		
		// Tabs
		tabs.init();
		
		// modal window (facebox plugin)
		$('a[rel*=facebox]').facebox({
			opacity: 0.25,
			overlay: true,
			closeText: 'Fermer',
			onReveal: function() {
				if(jQuery.support.opacity) {
					Cufon.replace('#facebox h1 span', { fontFamily: 'Seravek Basic ExtraLight' });
				} else {
					DD_belatedPNG.fix('#facebox table td.tl, #facebox .tc, #facebox .tr');						
				}				
			}
		});

		// Make sure the content and sidebar are the same height
		layout.equalHeight();
    
		var switch_content = function(selector, mode) {
			$(selector).each(function() {
				var elem = $(this);
				var current_content = elem.text();
				var alt_content = elem.attr('title');
				if (alt_content.match(new RegExp(mode + "$")))
				elem.attr('title', current_content).text(alt_content);
			});
		};
    
		$(".javascript-celcius").live('click', function() { 
			$(this).parents('li').addClass('selected').siblings().removeClass('selected');
			switch_content('.javascript-temperature', 'C');
			return false;
		});
		$(".javascript-fahrenheit").live('click', function() { 
			$(this).parents('li').addClass('selected').siblings().removeClass('selected');
			switch_content('.javascript-temperature', 'F'); 
			return false;
		});
		$(".javascript-cm").live('click', function() { 
			$(this).parents('li').addClass('selected').siblings().removeClass('selected');
			unit = ($('body').attr('id') == 'fr') ? 'cm' : 'cm';
			switch_content('.javascript-length', unit);
			return false;
		});
		$(".javascript-po").live('click', function() { 
			$(this).parents('li').addClass('selected').siblings().removeClass('selected');
			unit = ($('body').attr('id') == 'fr') ? 'po.' : 'in.';
			switch_content('.javascript-length', unit); 
			return false;
		});

		var inputEmail = $('form.newsletter input[name=email]');
		var initValue = inputEmail.val();

		$(inputEmail).focus(function(){
			if ( $(this).val() == initValue )
				$(this).val('');
		});

		$(inputEmail).blur(function(){
			if ( $(this).val() == '' )
				$(this).val(initValue);
		});
	});
	
	
/* --------------------------------------------------------------------------
	Class: layout
	Description: fix containers dimension on load and browser resize
---------------------------------------------------------------------------- */
layout = {
	resize : function() {
		if($('body').hasClass('fixed')) {
			$('#page').css('height', $(window).height());			
			$('#content-container').css('height', $(window).height() - $("#header-container").height() - $("#footer-container").height());
			$('#hub-bg-browser,.overlay-boxes').show();
		}
	},
	equalHeight : function(){
		if(!($.browser.msie && $.browser.version == 6)){
			$('#content,#sidebar').css('min-height',0);
			
			maxHeight = ($('#content').height() > $('#sidebar').height()) ? $('#content').height() : $('#sidebar').height();
			if(maxHeight < 200) maxHeight = 200;
			$('#content,#sidebar').css('min-height',maxHeight);
		}
	}
	
};


/* --------------------------------------------------------------------------
	Class: swf background
	Description: In charge of displaying and resize a flash on the background
---------------------------------------------------------------------------- */
swf_background = {	
	init : function(container) {
		dimensions = swf_background.get_dimensions();
		flashid = 'flash-player';
		var params = {
			wmode:'opaque',
			align: 'middle',
			scale: 'showall',
			menu: 'true',
			allowFullScreen: 'true',
			allowScriptAccess:'sameDomain'
		};
		var flashvars = {
			heap: heap.urlmap['api_amf'],
			lang: heap.config.current_language
		};
		var attributes = {};
		swfobject.embedSWF("/massif/static/swf/loader_massif.swf", flashid, dimensions.width, dimensions.height, "10.0.0","/massif/static/swf/expressInstall.swf",flashvars,params,attributes);
		
		this.getFlash();
		
	},
	
	getFlash : function() {
		if ( this.flash_object ) return false;
		
		if ( document[flashid] )
			this.flash_object = window.document[flashid];
		else
			this.flash_object = document.getElementById(flashid);
		
	},
	
	resize : function() {
		var dimensions = swf_background.get_dimensions();
		$('#flash-player').attr('width', dimensions.width);
		$('#flash-player').attr('height', dimensions.height);	
		$('#flash-container').attr('height', dimensions.height);							
	},
	
	get_dimensions : function() {
		dimensions = {
			width: $(window).width(),
			height: $(window).height() - $("#header").height() -2
		};
		return dimensions;
	}, 
  
  setIdle : function() {
		this.getFlash();
    if (typeof(swf_background.flash_object.setAsIdle) != 'function') return false;
    swf_background.flash_object.setAsIdle();
  }, 
  
  setActive : function() {
    this.getFlash();
		if (typeof(swf_background.flash_object.setAsActive) != 'function') return false;
    swf_background.flash_object.setAsActive();
  }
	
};



/* ------------------------------------------------------------------------
	Class: Dropdown
	Description: Used for the custom dropdowns
------------------------------------------------------------------------- */

	dropdown = {
		init : function(){
			$('.dropdown ul').each(function(){
				
				$(this).find('a:first').click(function(){
					if($(this).parents('ul:first').find('li:eq(1)').is(':visible')){ // If it's open, close it
						$(this).parents('ul:first').css('border-bottom',0).find('li:gt(0)').hide();
					}else{ // Open it
						$(this).parents('ul:first').css('border-bottom','1px #a6a3a3 solid').find('li:gt(0)').show();
					}

					return false;
				});
				
				$(this).find('a:gt(0)').click(function(i){
					$(this).parents('ul:first')
					.find('li.first a')
						.html($(this).text())
						.attr('href', $(this).attr('href'))
						.attr('rel', $(this).attr('rel')); // Set the new currently selected text

					// Sorting methods
					if( $(this).hasClass('sorting') )
					{
						var sortOpt = $(this).parents('ul:first').find('li.first a').attr('rel').split('|');
						msearch.setOption('sort', sortOpt[0]);
						msearch.setOption('sortOrder', sortOpt[1]);
						msearch.reload();
					}

					$(this).parents('ul:first').find('li.first a').trigger('click'); // Close the dropdown

					return false;
				});
				
			});
		}
	};

/* ------------------------------------------------------------------------
	Class: Tabs
	Description: In charge of the tabs toggling
------------------------------------------------------------------------- */
	
	tabs = {
		init : function(){
			hash_prefix = '#_';
			
			$('ul.javascript-tabs li a').click(function(){
				$(this).parents('ul:first').find('.selected').removeClass('selected');
				$(this).parent().addClass('selected');
				tabs.show($(this).attr('href'));
				
				hash = $(this).attr('href');
				top.location.hash = hash_prefix + hash.substring(1,hash.length);
				
				return false;
			});
			
			$('div.javascript-tab').hide();
			
			// Show the first tab of each tabs on a page
			$('ul.javascript-tabs').each(function(){
				// Check if there's an hash
				desiredTab = null;
				if(top.location.hash && top.location.hash != "#"){
					// Keep only the hash value
					desiredTab = top.location.hash;
					desiredTab = desiredTab.substring(desiredTab.indexOf(hash_prefix) + hash_prefix.length,desiredTab.length);
				}
				
				// Click the corresponding tab
				if($(this).find('a[href*='+desiredTab+']').size() > 0){
					$(this).find('a[href*='+desiredTab+']').parent().addClass('selected'); // Select the tab
					tabs.show('#' + desiredTab); // Show the tab
				}else{
					$(this).find('a:first').parent().addClass('selected'); // Select the tab
					tabs.show($(this).find('a:first').attr('href')); // Show the tab
				}
			});
		},
		show : function(which){
			Cufon.refresh('.tabs:not(.horizontal-tabs) a span');
			$(which).parent().find('div.javascript-tab').hide();
			$(which).show();
			
			// Make sure the content and sidebar are the same height
			layout.equalHeight();
		}
	};


/* ------------------------------------------------------------------------
	Class: Features
	Description: In charge of the featured items on top of the content details page
------------------------------------------------------------------------- */

	features = {
		currentPicture : 0, totalPictures : 0, itemsPerPage : 3, currentPage : 0, totalPage: 0, paused: false,
		settings : {
			animationspeed : 5000
		},
		init : function(json) {
			features.totalPictures = $(json).size();
			
			// Set the counter
			$('.features .counter').text((features.currentPicture+1) + '/' + features.totalPictures);
			
			// Set the slideshow nav
			$('.slideshow-nav .previous').click(function(){
				features.changePicture('previous',json);
				return false;
			});
			
			$('.slideshow-nav .next').click(function(){
				features.changePicture('next',json);
				return false;
			});
			
			$('.slideshow-nav .pause').click(function(){
				clearInterval(slideshow);
				features.paused=true;
				$('.slideshow-nav .play').removeClass('hide');
				$(this).addClass('hide');
				return false;
			});
			
			$('.slideshow-nav .plus').click(function(){
				$('.features .photos-nav').toggleClass('hide');
				$(this).addClass('hide');
				$('.slideshow-nav .minus').removeClass('hide');
				$('.slideshow-nav .pause:visible').trigger('click');
				return false;
			});
			
			$('.slideshow-nav .minus').click(function(){
				$('.features .photos-nav').toggleClass('hide');
				$(this).addClass('hide');
				$('.slideshow-nav .plus').removeClass('hide');
				return false;
			});
			
			$('.features .fullscreen').live('click',function(){
				if($('.features .photos-nav').is(':visible')){
					$('.features .photos-nav').addClass('hide');
					$('.slideshow-nav .plus').removeClass('hide');
					$('.slideshow-nav .minus').addClass('hide');
				}
			});
			
			$('.slideshow-nav .play').click(function(){
				slideshow = setInterval(function(){ features.changePicture('next',json); },features.settings.animationspeed);
				features.paused=false;
				$('.slideshow-nav .pause').removeClass('hide');
				$(this).addClass('hide');
				return false;
			});
			
			$('.features .infos .info').click(function(){
				$(this).next().toggleClass('hide');
				return false;
			});
			
			// Set the images in the image browser
			toInject = "";
			$(json).each(function(){
				toInject += '<li><a href="#"><img src="'+$(this)[0].sizes.thumb_photofeature+'" alt="" /></a></li>';
			});
			$('.features .photos-nav ul').html(toInject);
			$('.features .photos-nav li:first').addClass('selected');
			
			features.totalPage = Math.ceil(features.totalPictures / features.itemsPerPage) - 1;
			
			// Position the images in the image browser
			$('.features .photos-nav li').each(function(i){
				$(this).css({
					'position':'absolute',
					'left': ($(this).width() + 10) * i
				}).find('a').click(function(){
					features.changePicture(i,json);
				});
			});
			
			// Set the image browser nav
			$('.features .previous:first').click(function(){
				features.changePage('previous');
				return false;
			});
			
			$('.features .next:first').click(function(){
				features.changePage('next');
				return false;
			});
			
			// Hide the photo nav
			$('.features .photos-nav').addClass('hide');
			
			// Bring the nav back up front
			$('.features-nav').css('z-index',2);
			
			// Set the slideshow time
			slideshow = setInterval(function(){ features.changePicture('next',json); },features.settings.animationspeed);
		},
		changePicture : function(direction,json){
			if(direction == 'next'){ 
				features.currentPicture ++;
				
				if(features.currentPicture > features.totalPictures-1){
					features.currentPicture = 0;
				}
			}else if(direction == 'previous'){
				features.currentPicture --;
				if(features.currentPicture < 0){
					features.currentPicture = features.totalPictures-1;
				}
			}else{
				features.currentPicture = direction;
			}
			
			var pic = $(json)[features.currentPicture];
			if(pic['_meta'] && pic['_meta']['is_galerie'])
			  var new_url = heap.urlmap.planifier_galeries + '?doc_id=' + pic['id'];
			else
				var new_url = '#';

			// Inject the clone image (for crossfade)
			$('.features #fullscreen_link').attr('href', new_url).prepend('<img src="'+pic.sizes.full_photofeature+'" class="fullscreen" alt="" />');
			$('.features #fullscreen_link img:first').hide().fadeIn();
			$('.features #fullscreen_link img:eq(1)').fadeOut(function(){ $(this).remove(); });
			
			var is_potd = pic.tags.match(/\bmontagne.Photos du jour\b/);
			if (is_potd) $('.potd').fadeIn();
			else $('.potd').fadeOut();
			
			// Update the counter
			$('.features .counter').text((features.currentPicture+1) + '/' + features.totalPictures);
			
			// Select the proper element in the photo nav
			$('.features .photos-nav li.selected').removeClass('selected');
			$('.features .photos-nav li:eq('+features.currentPicture+')').addClass('selected');
			
			// Change the infos
			var caption = pic.description;
			var credits = pic.credits;
			var html = '';
			html += '<p><span class="dark">' + (caption ? caption : "&nbsp;") + '</span><br />';
			html += (credits ? heap.translate('photo_realized_by')+'<br /> '+credits : "&nbsp;");
			html += "</p>";
			$('.features .infos .content').html(html);
			if (credits != "")
			{
			  $('.features .infos').fadeIn();
			}
			else
			{
			  $('.features .infos').fadeOut();
			}
			
			// Reset the interval
			if(!features.paused){
				clearInterval(slideshow);
				slideshow = setInterval(function(){ features.changePicture('next',json); },features.settings.animationspeed);
			}
		},
		changePage : function(direction){
			itemWidth = $('.features .photos-nav li:first').width() + 10;
			pageWidth = features.itemsPerPage * itemWidth;
			
			if(direction=='next'){
				features.currentPage ++;
				direction = -1;

				if(features.currentPage > features.totalPage){
					features.currentPage = 0;
				}
			}else{
				features.currentPage --;
				direction = 1;
				
				if(features.currentPage < 0){
					direction = -1; // Invert the direction to go to the last page
					features.currentPage = features.totalPage;
				}
			}
			
			// Slide the pages, logic ++
			$('.features .photos-nav li').each(function(i){
				$(this).animate({
					'left': (i * itemWidth) - (pageWidth * features.currentPage)
				});
			});
		}
	};


/* ------------------------------------------------------------------------
	Class: Conversion
	Description: In charge of the length/temperature conversion
------------------------------------------------------------------------- */

	conversion = {
		init : function(){
			// Assign the length conversion
			$(".length-switcher a.cm").click(function(){
				if($(this).parent().hasClass('selected')) return;
				$(this).parents('ul:first').find('.selected').removeClass('selected');
				$(this).parent().addClass('selected');
				conversion.convertlength('cm');
				return false;
			});
			
			$(".length-switcher a.po").click(function(){
				if($(this).parent().hasClass('selected')) return;
				$(this).parents('ul:first').find('.selected').removeClass('selected');
				$(this).parent().addClass('selected');
				conversion.convertlength('po');
				return false;
			});
			
			// Assign the temp conversion
			$(".temperature-switcher a.celcius").click(function(){
				if($(this).parent().hasClass('selected')) return;
				$(this).parents('ul:first').find('.selected').removeClass('selected');
				$(this).parent().addClass('selected');
				conversion.converttemp('celcius');
				return false;
			});
			
			$(".temperature-switcher a.fahrenheit").click(function(){
				if($(this).parent().hasClass('selected')) return;
				$(this).parents('ul:first').find('.selected').removeClass('selected');
				$(this).parent().addClass('selected');
				conversion.converttemp('fahrenheit');
				return false;
			});
		},
		convertlength : function(desiredunit){
			$('.length').each(function(){
				currentval = $(this).text();
				currentval = currentval.substring(0,currentval.length-2);
				currentval = eval(currentval);

				if(desiredunit == 'po'){ // Convert to inches
				 	newval = Math.round(currentval * 0.39);
					newval += ' po';
				}else{ // Convert to cm
					newval = Math.round(currentval * 2.54);
					newval += ' cm';
				}
				
				$(this).text(newval);
			});
		},
		converttemp : function(desiredunit){
			$('.temperature').each(function(){
				currentval = $(this).text();
				currentval = currentval.substring(0,currentval.length-2);
				currentval = eval(currentval);

				if(desiredunit == 'fahrenheit'){ // Convert to celcius
				 	newval = Math.round((currentval * 1.8) + 32);
					newval += ' &deg;F';
				}else{ // Convert to fahrenheit
					newval = Math.round((currentval - 32) / 1.8);
					newval += ' &deg;C';
				}
				
				$(this).html(newval);
			});
		}
	};
	
/* ---------------------------------------------------------------------------
	Class: Backgrounds
	Description: insert background image and streching within browser viewport
------------------------------------------------------------------------------ */

	backgrounds = {			
		settings : {
			animationspeed : 10000, 
			transitioning : false
		},		
		init : function(selection) {			
			// looping through selection (ie: a[rel=hub-image])
			backgrounds.settings.browser_elements = selection;
			$(selection).each(function() {
				// using link Title and HREF attributes
				backgrounds.insert_image($(this).find('img').attr('alt'), $(this).attr('href'));															
				// we dont want that.. 
				$(this).removeAttr('href');				
				// attach on click
				$(this).click(function() {
					if(!$(this).hasClass('active')) {
						backgrounds.show(this);	
					}								
					// clear interval
					clearInterval(slideshow);							
				});				
			});						
			// start slideshow
			if ( $(selection).size() > 1 )
				slideshow = setInterval(function(){ backgrounds.changePicture(); }, backgrounds.settings.animationspeed);							
			// show first image
			$('.hub-bg-image:first').show();			
			// init current picture data, starting at 1 which is the second element
			// Show the nav
			$('#hub-bg-browser').data("current_page", 1).removeClass('hide');			
			// init resizing and position
			backgrounds.resize();
		},
		resize : function() {
			// resize backgrounds width
			var width = $('body').width();
			var height = $(window).height();
			
			// resize background
			var bg = $.find('.hub-bg-image');			
			$(bg).css('width', width).css('height', height);
			$(bg).children().css('width', width);			
		},
		insert_image : function(id, image_path) {
			// create div, append an image into it (unclean ie6 solution)
			div = $("<div/>").attr('id', id).addClass('hub-bg-image');
			img = $("<img/>").attr('src', image_path);
			$(img).appendTo(div);
			backgrounds.resize(div);
			return $(div).appendTo('body');
		},
		show: function(a) {
			if (this.settings.transitioning) return;
			this.settings.transitioning = true;
			
			// reset all
			$(backgrounds.settings.browser_elements).removeClass('active');
		
			// find associated bg image by ID + title attribute
			var old_img = $('.hub-bg-image:visible');
			var old_id = old_img.attr('id');
			var new_id = $(a).find('img').attr('alt');
			
			img = $.find("#" + new_id);
			$(a).addClass('active');
			
			//set display:block on new pic, but still hidden by old picture via z-index
			$('.hub-bg-image').css('z-index', 10);
			$(img).css('z-index', 0).show();
			
			//Let the old picture fade out, giving way to the new one
			var that = this;
			old_img.fadeOut('slow', function() { that.settings.transitioning = false; }); 
		},
		changePicture : function() {
			var currentPage = $('#hub-bg-browser').data("current_page");
			// find element
			el = $(backgrounds.settings.browser_elements).eq(currentPage);
      
			// and activate
			backgrounds.show(el);			

			// increment or reset current page
			if(currentPage < $(backgrounds.settings.browser_elements).length - 1) {				
				var nextPage = currentPage += 1;
				$('#hub-bg-browser').data("current_page", nextPage);				
			} else {
				$('#hub-bg-browser').data("current_page", 0);				
			}
		}
	};

/* ---------------------------------------------------------------------------
	Class: GMaps
	Description: various snippets for interacting with Google Maps API
------------------------------------------------------------------------------ */
	gmaps = {

		settings : {
			default_lat: 47.35185,
			default_lng: -70.549393,
			zoom_level: 10,
			container: 'map',
			markers_selection: '.markers a'
		},

		init_map : function(settings) {
			// extend settings
			jQuery.extend(gmaps.settings, settings);						

			// init map object and center to the mountain
			this.map = new GMap2(document.getElementById(gmaps.settings.container));
			this.map.addControl(new GSmallMapControl());
			this.map.addControl(new GMapTypeControl());
			this.map.enableScrollWheelZoom();

			// default position
			var leMassif = new GLatLng(this.settings.default_lat, this.settings.default_lng);
			// var marker = new GMarker(leMassif);

			// add default marker and center map
			// this.map.addOverlay(marker);			
			this.map.setCenter(leMassif, this.settings.zoom_level);

			// inject all markers
			gmaps.init_markers(gmaps.settings.markers_selection);			

			// init filtering
			gmaps.filter(gmaps.settings.markers_selection);

			// inject tooltip markup
			$("<div id='tooltip_message'></div>").appendTo(gmaps.map.getPane(G_MAP_FLOAT_SHADOW_PANE));
		},

		init_markers: function(selection) {
			// clear all markers on map
			gmaps.map.clearOverlays();

			$(selection).filter(":visible").each(function() {
				var type = this.className;
				var title = $(this).attr("title");
				var LatLng = gmaps.get_coordinates($(this).attr('rel')); // retreive lag&long from element rel attribute
				var i = gmaps.create_icon(type);
				var markerLatLng = new GLatLng(LatLng.lat, LatLng.lng);
				var marker = new GMarker(markerLatLng, {icon: i, title: title});
				var slug = this.href.substr(this.href.indexOf('#')+1,this.href.length);
				var a = $(this);

				// add marker on map
				gmaps.map.addOverlay(marker, slug);

				// register click event on marker
				GEvent.addListener(marker, "click", function() {
					gmaps.display_info_window(marker, slug, a);
				});

				GEvent.addListener(marker, "mouseover", function() {
					var markerOffset = gmaps.map.fromLatLngToDivPixel(marker.getPoint());
					$('#tooltip_message').text(title);
					$("#tooltip_message").css({ top:markerOffset.y - 50, left:markerOffset.x + 10, opacity: 0 }).show().animate({opacity: 0.9}, 150);
				});

				// hide tooltip
				GEvent.addListener(marker, "mouseout", function() {
					$('#tooltip_message').hide();
				});

				GEvent.addListener(gmaps.map, "infowindowclose", function() {
					// $('#tooltip_message').hide();
					$(a).parent().removeClass('selected');
				});

				// unbind anything and register on click event on marker link
				a.unbind('click');
				a.click(function() {
					// scroll back to #content
					var positions = $('#content').position();
					$('html,body').animate({scrollTop: positions.top}, 250);

					// display info window
					//gmaps.display_info_window(marker, url, a);
					gmaps.map.panTo(markerLatLng);		

					// prevent default click
					return false;
				});
			});
		},

		display_info_window : function(marker, slug, a) {
			//No info window; we just redirect to the actual page.
			$("#area_map").append("<div class='gmap-loader'></div>");

				heap.api.atoms.load(function(response) {
					$('.gmap-loader').remove();
					
					if (response.type != heap.SUCCESS) {
						//error occured
						alert(response.msg);
						return false;
					}
					var atom = response.data;
					
					html = "<div class='gmap_content'>";
					if(atom._documents)
						html += "<img src='"+atom._documents[0].sizes.thumb+"' class='fleft'>";

					html += "<h4>"+atom.title+"</h4>";

					if(atom.excerpt)
						html += atom.excerpt;
					
					if($('body').hasClass('en')){
						detailsText = "Details"
					}else{
						detailsText = "Détails"
					}
					
					
					if(atom.url)
						html += "<p><a href='"+atom.url+"'>"+detailsText+"</a>&nbsp;&nbsp;&nbsp;<a href='"+atom.url+"'>Directions</a></p>";
					
					html += "</div>";
					
					gmaps.map.openInfoWindowHtml(marker.getPoint(), html, { pixelOffset:new GSize(-5, -20) });
					
					//Here I can access anything
					//atom.title, atom.subtitle, atom.publish_start, etc.
				}, { slug : slug });
				
				$(a).parent().addClass('selected');
		},

		create_icon : function(type) {	
			if(type == undefined) { type = 'default'; }

			var i = new GIcon();
			i.image = "/massif/static/images/all/backgrounds/map-icn-"+type+".png";
			i.shadow = "/massif/static/images/all/backgrounds/icons-shadow.png";
			i.shadowSize = new GSize(32, 24);
	    	i.iconSize = new GSize(24, 24);
	    	i.iconAnchor = new GPoint(24, 47);
	    	i.infoWindowAnchor = new GPoint(1, 1);
			i.zIndex = 10000;
			return i;
		},

		// extrac geo-coding from a string
		// expected format : geo:lat=X.XXX,geo:lon=X.XXX
		get_coordinates : function(string) {
			raw_coordinates = string.split(',');
			LatLng = {
				lat: raw_coordinates[0].replace(/geo:lat=/, ''),
				lng: raw_coordinates[1].replace(/geo:lon=/, '')
			};
			return LatLng;
		},

		filter : function(markers_selection) {
			$(".markers-filter a").click(function() {
				var checked = $(this).hasClass('checked');
				var className = '.' + $(this).attr('name');								
				if(checked) {
					$(this).removeClass('checked');						
					$(className).each(function() {
						$(this).parent().hide();
					});					
				} else {
					$(this).addClass('checked');					
					$(className).each(function() {
						$(this).parent().show();
					});
				}

				// re-init map markers
				gmaps.init_markers(markers_selection);

				// re-color rows
				gmaps.color_rows();

				// Make sure some are visible
				if($('#ajax ol:first').find('li:visible').size() == 0){
 					$('.no-results').removeClass('hide');
				}else{
					$('.no-results').addClass('hide');
				}

				// prevent default onClick
				return false;				
			});
		},

		// re-color rows with .even or .odd className
		color_rows : function() {
			$('.markers li').filter(":visible").each(function(i) {
				$(this).removeClass('odd', 'even');
				if(i % 2) {
					$(this).addClass('even');
				} else {
					$(this).addClass('odd');
				}
			});
		}

	};

/* ---------------------------------------------------------------------------
	Class: Slider
	Description: Code for the show/hide of content, usually FAQs
------------------------------------------------------------------------------ */

	slider = {
		init : function() {
			$('.slider a').click(function(){
				if(!$(this).parent().find('div:first').is(':visible')){
					$(this).parent().find('div:first').animate({height:'show'},function(){ $(this).removeClass('hide'); });
				}else{
					$(this).parent().find('div:first').animate({height:'hide'},function(){ $(this).addClass('hide'); });
				}
				
				return false;
			});
		}
	};
	

/* ------------------------------------------------------------------------
	Class: Form
	Description: Handles the toggling in the forms
------------------------------------------------------------------------- */

	form = {
		init: function(){
			// hide all the toggles
			$('div.toggle').hide();

			// The checkboxes toggle
			$('.toggle>input').click(function(){
				if($(this).parent().find('input:checked').size() > 0){
					$(this).parent().nextAll('.toggle:first').show();
				}else{
					$(this).parent().nextAll('.toggle:first').hide();
				}
			});
			
			// The input toggle
			$('select.toggle').change(function(){
				if($(this).attr('selectedIndex') > 0){
					$(this).parent().nextAll('.toggle:first').show();
					
					$(this).parent().nextAll('.toggle:first').find('ul.tabs li').show();
					$(this).parent().nextAll('.toggle:first').find('ul.tabs li:gt('+(parseFloat($(this).attr('selectedIndex')) -1) +')').hide();
					
					/*for(var i = 0; i < $(this).attr('selectedIndex'); i++)
					{
						$(this).parent().nextAll('.toggle:first').find('div.javascript-tab.tab').eq(i).addClass('toValidate');
					};*/
					
				}else{
					$(this).parent().nextAll('.toggle:first').hide();
					//$(this).parent().nextAll('.toggle:first').find('div.javascript-tab.tab').removeClass('toValidate');
				}
			});
		}
	}
	
	form_improved = {
		init: function(){
			// hide all the toggles
			$('div.toggle').hide();

			// The checkboxes toggle
			$('.toggle>input').click(function(){
				if($(this).parent().find('input:checked').size() > 0){
					$(this).parent().nextAll('.toggle:first').show();
				}else{
					$(this).parent().nextAll('.toggle:first').hide();
				}
			});
			
			// The input toggle
			$('select.toggle').change(function(){
				if($(this).attr('selectedIndex') > 0){
					$(this).parent().nextAll('.toggle:first').show();
					
					$(this).parent().nextAll('.toggle:first').find('ul.tabs li').show();
					$(this).parent().nextAll('.toggle:first').find('ul.tabs li:gt('+(parseFloat($(this).attr('selectedIndex')) -1) +')').hide();
					$(this).parent().nextAll('.toggle:first').find('ul.tabs li:first').trigger('click');
					
					for(var i = 0; i < $(this).attr('selectedIndex'); i++)
					{
						$(this).parent().nextAll('.toggle:first').find('div.javascript-tab.tab').eq(i).find('input,select').removeAttr('disabled');
					};
					
					
				}else{
					$(this).parent().nextAll('.toggle:first').hide();
					$(this).parent().nextAll('.toggle:first').find('div.javascript-tab.tab').find('input,select').attr('disabled','disabled');
				}
			});
		}
	}



video_player = function(options)
{	
	this.playerId = options.playerId;
	this.videoUrl = options.videoUrl;
	
	var params = {
		wmode:'opaque',
		align: 'middle',
		scale: 'showall',
		menu: 'true',
		allowFullScreen: 'true',
		allowScriptAccess:'sameDomain'
	};
	var flashvars = {
		lang: 'fr',
		type: 'document',
		_slug: this.videoUrl,
		autoPlay: 'true',
		resizeToStage: 'true'
	};
	var attributes = {};
	swfobject.embedSWF("/massif/static/swf/player.swf", this.playerId, '593', '355', "10.0.0","/massif/static/swf/expressInstall.swf",flashvars,params,attributes);
	
}

/* ------------------------------------------------------------------------
	Cookie functions
------------------------------------------------------------------------- */

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}





var promoScroller = {
	interval : '',
	selector : '',
	init : function(params){
		promoScroller.selector = params.selector;
		$(params.selector).mouseenter(function(){
			window.clearInterval(promoScroller.interval);
		});
		$(params.selector).mouseleave(function(){
			promoScroller.interval = window.setInterval( promoScroller.next, 5000 );
		});
		promoScroller.interval = window.setInterval( promoScroller.next, 5000 );
	},
	next : function(){
		if ($(promoScroller.selector).find('.javascript-tabs li.selected').is(':last-child'))
			$(promoScroller.selector).find('.javascript-tabs li').eq(0).find('a').trigger('click');
		else
			$(promoScroller.selector).find('.javascript-tabs li.selected').next().find('a').trigger('click');
	}
}



/* Latest events block - Sidebar */
var cycleEvents = function(params)
{
	this.id = params.id;
	this.items = $('#' + this.id + ' .last_event_item');
	this.nbItems = $(this.items).size();
	this.refHeight = null;
	
	$('#'+this.id).css('height',this.getHeight() + 'px');
	$(this.items).eq(0).addClass('on');
	$(this.items).not('.on').hide();
	
	that = this;
	this.loopEvents = self.setInterval('that.toggleView()', 5000);
	
	$(this.items).bind('mouseenter', function(){
		that.loopEvents = window.clearInterval(that.loopEvents);
	});
	$(this.items).bind('mouseleave', function(){
		that.loopEvents = self.setInterval('that.toggleView()', 5000);
	});
	
};

cycleEvents.prototype.toggleView = function()
{
	$('#' + this.id + ' .on').fadeOut('normal', function(){
		
		if($(this).next().length <= 0 )
			$(this).parent().find(':first').addClass('on').fadeIn('normal');
		else
			$(this).next().addClass('on').fadeIn('slow');
		
		$(this).removeClass('on');
	});
};

cycleEvents.prototype.getHeight = function()
{
	for(var i = 0; i < this.nbItems; i++)
	{
		if($(this.items).eq(i).height() > this.refHeight) this.refHeight = $(this.items).eq(i).height();
	};
	return this.refHeight;
};