/*----------------------------------------------------------------------------//
// Javascript pour le site client
//----------------------------------------------------------------------------*/

function importJavascript(src) {
	document.write("<script type=\"text/javascript\" src=\"" + src + "\"></scr" + "ipt>");
}
function importCss(href, media) {
	document.write('<link rel="stylesheet" type="text/css" media="' + media + '" href="' + href + '" />');
}

/*----------------------------------------------------------------------------*/
// Importations de fichiers
/*----------------------------------------------------------------------------*/
importJavascript("/includes/js/plugins/abso.caroussel.js");
importJavascript("/includes/js/plugins/abso.jcarousellite.js");
importJavascript("/includes/js/plugins/jquery.watermarkinput.js");

importJavascript("/includes/js/plugins/jquery.imgpreload.min.js");

importJavascript("/includes/js/plugins/jquery.Jcrop.min.js");
importCss("/includes/js/plugins/jquery.Jcrop.css", "screen");

importJavascript("/includes/js/plugins/abso.thickbox.js");
importCss("/includes/js/plugins/abso.thickbox.css", "screen");


// importJavascript("/includes/js/plugins/jquery.plugin.js");
// importCss("/includes/js/plugins/jquery.plugin.css", "screen");

/*----------------------------------------------------------------------------*/
// Declarations jQuery
/*----------------------------------------------------------------------------*/
var filmenu    = 0;
var timeout    = 600;
var closetimer = 0;
var ddmenuitem = 0;

function mp_open() {
	mp_canceltimer();
	$('#MenuPrincipal > li > a').removeClass("Over");
	$('#MenuPrincipal > li ul').fadeOut(200);
	
	ddmenuitem = $('ul', this);
	if(ddmenuitem) {
		closetimer = window.setTimeout(function(){
			$(ddmenuitem).slideDown(200).prev("a").addClass("Over");
		}, timeout);
	}
}
function mp_close() {
	mp_canceltimer();
	
	if(ddmenuitem) {
		closetimer = window.setTimeout(function(){
			$(ddmenuitem).fadeOut(200).prev("a").removeClass("Over");
			ddmenuitem = 0;
		}, timeout * 2);
	}
}
function mp_canceltimer() {
	if(closetimer){
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

function fam_close() {
	fam_canceltimer();
	$("#FilAriane > li > div").fadeOut(200);
}
function fam_canceltimer() {
	if(filmenu){
		window.clearTimeout(filmenu);
		filmenu = null;
	}
}

$(document).ready(function(){
	
	$("#Contenu hr, #Formulaire hr").replaceWith('<div class="HR"></div>');
	$("input:text").filter("input[title]").each(function() {
		$(this).Watermark($(this).attr("title"), "#fff");
    });
	
	equalHeight( $('#PiedPage .Nav > ul > li') );

	$('#SiteMap > ul > li > ul').each(function(){

		var $count = 0, $group = null;

		$(this).children('li').each(function(){
			$count++
			$group = ($group == null) ? $(this) : $group.add(this);
			if ($count == 3) {
				equalHeight($group);
				$count = 0;
				$group = null;
			}
		});
	});
	
	
	//Menu principal
	//-------------------------------------------------------------------------------------------------//
	$('#MenuPrincipal > li').bind('mouseenter', mp_open).bind('mouseleave',  mp_close);

	//Sous-menu, Fil d'Ariane
	//-------------------------------------------------------------------------------------------------//
	$("#FilAriane > li").each(function(){
		var currLI = $(this);
		var currDIV = $("> div", this);
		var currCHILD = $("> div > ul > li", this);
		if ( currCHILD.length > 0 ) {
			$("> a", currLI).bind("click", function(){
				fam_close();
				currDIV
					.css({ left: ((currDIV.width() / 2) * -1) + ((currLI.width() / 2) + 20) })
					.slideDown(200);
				currLI
					.bind("mouseenter", fam_canceltimer)
					.bind("mouseleave", function(){
						fam_canceltimer();
						filmenu = window.setTimeout(fam_close, timeout);
					});
				return false;
			});
		}
	});
	$(document).bind("click", function(){
		fam_close();
	});

	//Caroussel en bas de page
	//-------------------------------------------------------------------------------------------------//
	$("#Caroussel div").jCarouselLite({
		btnNext: "#Caroussel .Suiv",
		btnPrev: "#Caroussel .Prec",
		speed: 800,
		visible: 3,
		scroll: 1
	});
	$("#Caroussel > div a").hover(function(){
		$("img:not(.Over)", this).css({opacity: 0.8});
	}, function(){
		$("img:not(.Over)", this).css({opacity: 1.0});
	});

	//Accueil, photos
	//-------------------------------------------------------------------------------------------------//
	AbsoCaroussel.init({
		id: 'AccPhotos',
		transition: 'fade',
		speed: 1200,
		wrap: true,
		autostart: {
			interval:7800
		}/*,
		preSwitchCallback: function(data){
			var prev = data.source.position,
				next = data.target.position,
				left = ( $(data.target.obj).hasClass('Left') ) ? '0px' : '626px',
				$AccPhotosNav = $("#AccPhotosNav"),
				$AccPhotosInfo = $("#AccPhotosInfo");
			
			$AccPhotosNav.find("a.AbsoCaroussel-AccPhotos-Item-" + prev).removeClass("On");
			$AccPhotosNav.find("a.AbsoCaroussel-AccPhotos-Item-" + next).addClass("On");
			
			$AccPhotosInfo.find("> li:nth-child(" + prev + ")").fadeOut(600);
			$AccPhotosNav.stop().animate({ left: left }, 1200, function() {
				$AccPhotosInfo.css({ left: left });
				$AccPhotosInfo.find("> li:nth-child(" + next + ")").fadeIn(600);
			});
			
		},
		postSwitchCallback: function(data){
		}*/
	});
	
	/*if ( $('#AccPhotos li:first-child').hasClass('Left') )
		$("#AccPhotosNav").css('left', '0px');*/

	//Chapitre, liste
	//-------------------------------------------------------------------------------------------------//
	$("#ChapitreListe > li").each(function(){
		var outDiv = $("div", this);
		var overDiv = $("div", this).clone().addClass("Over").css({opacity:0.0}).prepend('<img src="/images/Bg_ChapitreListe_Item.gif" width="9" height="17" alt="" />');
		outDiv.before(overDiv);
		$(this)
			.hover(
				function(){
					$(overDiv).stop().animate({opacity:1.0}, 100, function(){ $(this).removeAttr("style"); });
				},
				function(){
					$(overDiv).stop().animate({opacity:0.0}, 100);
				}
			)
			.click(function(){
				$(overDiv).stop().animate({opacity:0.0}, 100);
			})
		;
	});
	
	//Chapitre, blocs
	//-------------------------------------------------------------------------------------------------//
	$("#CategorieListe > li").each(function(){
		var overStr = '<a class="Over" href="' + $("a:first-child", this).attr("href") + '"></a>';
		$(this).prepend(overStr);
		$("a.Over", this).css({ opacity: 0.0 });
		$(this)
			.hover(
				function(){
					$("a.Over", this).stop().animate({opacity:1.0}, 100, function(){ $("a.Over", this).removeAttr("style"); });
				},
				function(){
					$("a.Over", this).stop().animate({opacity:0.0}, 100);
				}
			)
			.click(function(){
				$("a.Over", this).stop().animate({opacity:0.0}, 100);
			})
		;
	});

	//Contenu, blocs
	//-------------------------------------------------------------------------------------------------//
	$("#ContenuListe li").each(function(){
		if ($("> a", this).length > 0) {
			var curr = $(this);
			var overStr = '<a class="Over" href="' + $("a:first-child", this).attr("href") + '"></a>';
			$(this).prepend(overStr);
			$("a.Over", this).css({ opacity: 0.0 });
			$("a", this)
				.hover(
					function(){
						$("a.Over", curr).stop().animate({opacity:1.0}, 100, function(){ $("a.Over", curr).removeAttr("style"); });
					},
					function(){
						$("a.Over", curr).stop().animate({opacity:0.0}, 100);
					}
				)
				.click(function(){
					$("a.Over", curr).stop().animate({opacity:0.0}, 100);
				})
			;
		}
	});
	var colG = $("#ContenuListe ul:first", this);
	var colD = $("#ContenuListe ul:last", this);
	var equalCount = ($("li", colG).length < $("li", colD).length) ? $("li", colG) : $("li", colD);
	equalCount.each(function(i){
		var minHeight = 60;
		var itemG = $("#ContenuListe ul:first li:nth-child("+(i+1)+")");
		var itemD = $("#ContenuListe ul:last li:nth-child("+(i+1)+")");
		if (itemG.height() > itemD.height()) {
			itemD.add(itemG).css({ minHeight: (itemG.height() > minHeight) ? itemG.height() : minHeight });
		} else {
			itemG.add(itemD).css({ minHeight: (itemD.height() > minHeight) ? itemD.height() : minHeight });
		}
	});

	//Contenu, photos
	//-------------------------------------------------------------------------------------------------//
	if ($("#ContenuPhotos").length > 0) {
		if ($("#ContenuPhotosListe li:nth-child(1) > a").length > 0) {
			$("#ContenuPhotos .Zoom").attr("href", $("#ContenuPhotosListe li:nth-child(1) > a").attr("href")).show();
		} else {
			$("#ContenuPhotos .Zoom").hide();
		}
		AbsoCaroussel.init({
			id: 'ContenuPhotosListe',
			transition: 'fade',
			speed: 800,
			wrap: true,
			statusBullet: "&nbsp;",
			statusLink: true,
			autostart: {
				interval:5000
			},
			preSwitchCallback: function(){
				if ($("#ContenuPhotosListe li:nth-child(" + (this.curr + 1) + ") > a").length > 0) {
					$("#ContenuPhotos .Zoom").attr("href", $("#ContenuPhotosListe li:nth-child(" + (this.curr + 1) + ") > a").attr("href")).show();
				} else {
					$("#ContenuPhotos .Zoom").hide();
				}
			}
		});
	}

	//Détaillants
	//-------------------------------------------------------------------------------------------------//
	$("#Detaillants .Nav a").bind("click", function(){
		var curr = $(this).attr("href").substring($(this).attr("href").indexOf("#") + 1);
		$("#Detaillants div.Tab").hide();
		$("#Detaillants div." + curr).show();
		$("#Detaillants .Nav a").removeClass("On");
		$(this).addClass("On");
		return false;
	});

	//Fiche d'un vélo
	//-------------------------------------------------------------------------------------------------//
	applyBahaviors();
	initZoomLink();
	initGallery();

	$("#VeloQuickLinks .Zoom a").bind("click", function(){
		var zUrl = $(this).attr("rel").substring(0, $(this).attr("rel").indexOf("|"));
		var tzUrl = $(this).attr("rel").substring($(this).attr("rel").indexOf("|") + 1);
		showZoom(function(){
			$("#VeloZoomBig").attr("src", zUrl).css({opacity:0.0});
			$("#VeloZoomSmall").attr("src", tzUrl);
			$("#VeloZoom").fadeIn(400, function(){
				initZoom();
				$("#VeloZoomBig").animate({opacity:1.0}, 400);
			});
		});
	});
	$("#VeloZoom h3 a").bind("click", function(){
		$("#VeloZoom").fadeOut(400, hideZoom);
	});

	$("#VeloFeatures > ul a").bind("click", function(){
		$("#VeloFeatures > ul").slideUp(200);
		dataId = $(this).attr("rel");
		dataType = "spec";
		dataLang = $(this).attr("lang");
		collapseBeforeLoad(function(){
			loadXmlData();
		});
	});
	$("#VeloFeatures > h3 a").trigger('click');
	
	$("#VeloContenu .PosAnim > h3 a").bind("click", function(){
		if ($(this).hasClass("On")) {
			$("#VeloContenu .PosAnim").animate({paddingTop:"560px"}, 400);
			$("#VeloContenu .Contenu").slideUp(400);
		} else {
			$("#VeloContenu .PosAnim").animate({paddingTop:"342px"}, 400);
			$("#VeloContenu .Contenu").slideDown(400);
		}
		$(this).toggleClass("On");
	});
	
	$("#VeloAthletes li > a, #Categorie > ul li a").each(function(){
		var output = $("<span></span>").css({opacity:0.0});
		$(this).prepend(output)
			.hover(
				function(){
					$("span", this).stop().animate({opacity:1.0}, 100, function(){ $(this).removeAttr("style"); });
				}, 
				function(){
					$("span", this).stop().animate({opacity:0.0}, 100);
				}
			)
			.click(function(){
				$("span", this).stop().animate({opacity:0.0}, 100);
			})
		;
	});
	
});

// Fiche d'un vélo
//-------------------------------------------------------------------------------------------------//
var displayingSpec = false;
var displayingZoom = false;
var dataId = null;
var dataType = null;
var dataLang = null;

// Ajouter / Enlever les bahavior de navigation -------------------------------------------
function applyBahaviors() {
	$("#VeloDescription > h2 a").bind("click", function(){

		if (displayingZoom)
			$("#VeloZoom").fadeOut(200, hideZoom);

		if (displayingSpec) {
			dataId = $(this).attr("rel");
			dataType = "velo";
			dataLang = $(this).attr("lang");
			collapseBeforeLoad(function(){
				loadXmlData();
			});
		} else {
			$(this).toggleClass("On");
			$("#VeloDescription > div").slideToggle(400);
		}
	});
	$("#VeloFeatures > h3 a").bind("click", function(){
		$("#VeloFeatures > h3 a").toggleClass("On");
		$("#VeloFeatures > ul").slideToggle(200);
	});
}
function removeBahaviors() {
	$("#VeloDescription > h2 a, #VeloFeatures > h3 a").unbind("click");
}

// Fermeture avant le loading -------------------------------------------------------------
function collapseBeforeLoad(loadCallback) {
	removeBahaviors();
	
	if (displayingSpec) {
		$("#VeloContenu .PosAnim > h3 a").removeClass("On");
		$("#VeloContenu .PosAnim").animate({paddingTop:"560px"}, 400);
		$("#VeloContenu .PosAnim > h3").slideUp(400);
		$("#VeloContenu .Contenu").slideUp(400, function(){
			$("#VeloLoading").fadeIn(400, function(){
				loadCallback();
			});
		});
	} else {
		$("#VeloDescription > h2 a, #VeloFeatures > h3 a").removeClass("On");
		$("#VeloDescription > div").slideUp(400);
		$("#VeloDescripSuite").slideUp(400, function(){
			$("#VeloLoading").fadeIn(400, function(){
				loadCallback();
			});
		});
	}
}

// Ouverture après le loading -------------------------------------------------------------
function openAfterLoad() {
	if (displayingSpec) {
		$("#VeloSpecTitle, #VeloContenu").show();
		$("#VeloQuickLinks .RoadTest").hide();
		$("#VeloLoading").fadeOut(400, function () {
		    $("#VeloContenu .PosAnim > h3 a").addClass("On");
		    $("#VeloContenu .PosAnim").animate({ paddingTop: "342px" }, 400);
		    $("#VeloContenu .Contenu").removeAttr("style");
		    if ($("#VeloContenu .Contenu").height() < 116) {
		        $("#VeloContenu .Contenu").height(116);
		    }
		    $("#VeloContenu .PosAnim > h3").slideDown(400);
		    $("#VeloContenu .Contenu").slideDown(400);

		    applyBahaviors();
		});
	} else {
		$("#VeloSpecTitle, #VeloContenu").hide();
		$("#VeloQuickLinks .RoadTest").show();
		$("#VeloLoading").fadeOut(400, function(){
			$("#VeloDescription > h2 a").addClass("On");
			$("#VeloDescription > div, #VeloDescripSuite").slideDown(400);
			applyBahaviors();
		});
	}
}

// Load du XML selon le ID de vélo ou spec ------------------------------------------------
function loadXmlData() {
	$("#VeloPhotosNav, #VeloPhotos").empty();
	displayingSpec = (dataType == "spec") ? true : false;
	$.ajax({
	    type: "GET",
	    url: (displayingSpec) ? "/tools/xmlspecs.aspx?lang=" + dataLang + "&specId=" + dataId : "/tools/xmlbikes.aspx?bikeId=" + dataId,
	    //url: (displayingSpec) ? "/xml/spec.xml?bikeId=" + dataId : "/xml/velo.xml?bikeId=" + dataId,
	    dataType: "xml",
	    success: function (xml) {
	        
	        var preloadArray = [];
	        $(xml).find('Photo').each(function () {
	            var $this = $(this);

	            if ($this.attr("gUrl").toLowerCase().indexOf('.swf') == -1 && $this.attr("gUrl").toLowerCase().indexOf('.flv') == -1)
	                preloadArray.push($this.attr("gUrl"));

	            preloadArray.push($this.attr("tgUrl"));

	            if ($this.attr("zUrl") != "")
	                preloadArray.push($this.attr("zUrl"));

	            if ($this.attr("tzUrl") != "")
	                preloadArray.push($this.attr("tzUrl"));
	        });

            $.imgpreload(preloadArray, function () {

	            var photosOutput = "";
	            var photosNavOutput = "";
	            $(xml).find('Photo').each(function () {
	                var $this = $(this);
	                if ($this.attr("gUrl").toLowerCase().indexOf('.swf') != -1) {

	                    var configpath = $this.attr("gUrl").split('/');
	                    configpath.pop();
	                    configpath = configpath.join('/') + '/';

	                    photosOutput += '<li><object id="myFlash" width="950" height="560" type="application/x-shockwave-flash" name="myFlash" data="' + $this.attr("gUrl") + '">';
	                    photosOutput += '<param name="movie" value="' + $this.attr("gUrl") + '">';
	                    photosOutput += '<param name="wmode" value="transparent">';
	                    photosOutput += '<param name="scale" value="noScale">';
	                    photosOutput += '<param name="bgcolor" value="#000000">';
	                    photosOutput += '<param name="salign" value="lt">';
	                    photosOutput += '<param name="allowScriptAccess" value="always">';
	                    photosOutput += '<param name="allowFullScreen" value="true">';
	                    photosOutput += '<param name="flashvars" value="path=' + configpath + '">';
	                    photosOutput += '</object></li>';

	                } else if ($this.attr("gUrl").toLowerCase().indexOf('.flv') != -1) {

	                    photosOutput += '<li><object id="myVideo" width="950" height="560" type="application/x-shockwave-flash" name="myVideo" data="/includes/swf/videoPlayer.swf">';
	                    photosOutput += '<param name="movie" value="/includes/swf/videoPlayer.swf">';
	                    photosOutput += '<param name="wmode" value="transparent">';
	                    photosOutput += '<param name="bgcolor" value="#000000">';
	                    photosOutput += '<param name="allowScriptAccess" value="always">';
	                    photosOutput += '<param name="allowFullScreen" value="true">';
	                    photosOutput += '<param name="flashvars" value="flvPath=' + $this.attr("gUrl") + '">';
	                    photosOutput += '</object></li>';

	                } else {

	                    photosOutput += '<li><img src="' + $this.attr("gUrl") + '" width="950" height="560" alt="" /></li>';
	                    
	                }
	                
	                photosNavOutput += '<li><a href="javascript:void(0);" style="background-image:url(' + $this.attr("tgUrl") + ')" class="AbsoCaroussel-VeloPhotos-Item-' + ($this.index() + 1) + '" rel="' + $this.attr("zUrl") + '|' + $this.attr("tzUrl") + '"><img src="/images/spacer.gif" width="71" height="40" alt="" /></a></li>';
	            });
	            $("#VeloPhotos").append(photosOutput);
	            $("#VeloPhotosNav").append(photosNavOutput);
	            
	            if (displayingSpec) {
	                //$("#VeloSpecTitle").html($(xml).find('Title').text()).show();
	                $("#VeloContenu .PosAnim > h3 a").html($(xml).find('SubTitle').text()).show();
	                $("#VeloContenu .PosAnim .Contenu").html($(xml).find('Content').text() + '<div class="Clearer"></div>');
	                $("#VeloContenu").show();
	            }
	            
	            initZoomLink();
	            initGallery();
	            openAfterLoad();
                
	        });
	    },
	    error: function (e, msg) {
	    }
	});
}
function initGallery() {
	$("#VeloPhotosNav li:first-child a").addClass("On");
	AbsoCaroussel.init({
		id: 'VeloPhotos',
		transition: 'fade',
		speed: 800,
		wrap: true,
		/*autostart: {
			interval:5000
		},*/
		preSwitchCallback: function(){
			$("#VeloPhotosNav a").removeClass("On");
			$("#VeloPhotosNav a.AbsoCaroussel-VeloPhotos-Item-" + (this.curr + 1)).addClass("On");
			$("#VeloQuickLinks .Zoom a").attr("rel", $("#VeloPhotosNav a.AbsoCaroussel-VeloPhotos-Item-" + (this.curr + 1)).attr("rel"));
			( $("#VeloQuickLinks .Zoom a").attr("rel") == "|" ) ? $("#VeloQuickLinks .Zoom").hide() : $("#VeloQuickLinks .Zoom").show();
		},
		postSwitchCallback: function(){
		}
	});
}
function initZoomLink() {
	$("#VeloQuickLinks .Zoom a").attr("rel", $("#VeloPhotosNav li:first-child a").attr("rel"));
	( $("#VeloQuickLinks .Zoom a").attr("rel") == "|" ) ? $("#VeloQuickLinks .Zoom").hide() : $("#VeloQuickLinks .Zoom").show();
}

// Affichage du Zoom ----------------------------------------------------------------------
var VeloZoom;
function showZoom(callBack) {
	displayingZoom = true;
	if (displayingSpec) {
		$("#VeloContenu .PosAnim > h3 a").removeClass("On");
		$("#VeloContenu .PosAnim").animate({paddingTop:"560px"}, 400);
		$("#VeloContenu .PosAnim > h3").slideUp(400);
		$("#VeloContenu .Contenu").slideUp(400, function(){
			VeloZoom.destroy();
			callBack();
		});
	} else {
		$("#VeloDescription > h2 a, #VeloFeatures > h3 a").removeClass("On");
		$("#VeloDescription > div").slideUp(400);
		$("#VeloDescripSuite").slideUp(400, function(){
			VeloZoom.destroy();
			callBack();
		});
	}
}
function hideZoom() {
	if (displayingSpec) {
		$("#VeloContenu .PosAnim > h3").slideDown(400);
	} else {
		$("#VeloDescripSuite").slideDown(400);
	}
	displayingZoom = false;
}
function initZoom() {
	VeloZoom = $.Jcrop('#VeloZoomSmall', {
		onChange: showZoomPreview,
		onSelect: showZoomPreview,
		aspectRatio: 707 / 560,
		bgOpacity: 1,
		borderOpacity: 0,
		allowSelect: false,
		allowResize: false,
		boxWidth: 243,
		bowHeight: 182
	});
	VeloZoom.release();
	VeloZoom.setSelect([64,53,128,106]);
}
function showZoomPreview(coords) {
	if (parseInt(coords.w) > 0) {
		var rx = 707 / coords.w;
		var ry = 560 / coords.h;

		jQuery('#VeloZoomBig').css({
			width: '2600px',
			height: '1950px'
		}).stop().animate({
			marginLeft: '-' + (Math.round(rx * coords.x)) + 'px',
			marginTop: '-' + (Math.round(ry * coords.y)) + 'px'
		}, 80);
	}
}

$(window).load(function(){
	if ( $("#VeloZoom").length > 0 )
		initZoom();
});

function RenderClick(e, btnID, validationGroup) {
    if (window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    // Si Enter
    if (keynum == 13) {
        // Lancer un postback sur le bouton passé en paramètre
        if (Page_ClientValidate(validationGroup)) {
            __doPostBack(btnID, '');
        }
        return false;
    }
    return true;
}

function RenderClick(e, btnID) {
    if (window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    // Si Enter
    if (keynum == 13) {
        // Lancer un postback sur le bouton passé en paramètre
        __doPostBack(btnID, '');
        
        return false;
    }
    return true;
}

function MaxLength(obj, mlength) {
    if (obj.getAttribute) {
        if (obj.value.length > mlength) {
            obj.value = obj.value.substring(0, mlength)
        }
    }
}

function equalHeight(group) {
	tallest = 0;
	group.each(function() {
		thisHeight = jQuery(this).height();
		if (thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
		
	group.each(function() {
		jQuery(this).height(tallest + "px");
	});
}





















// switch lang on home page
$(document).ready(function() {
	
	function getCookie(c_name) {
		var i,x,y,ARRcookies=document.cookie.split(";");
		for (i=0;i<ARRcookies.length;i++) {
			x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
			y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
			x=x.replace(/^\s+|\s+$/g,"");
			if (x==c_name) {
				return unescape(y);
			}
		}
	}
	function setLang(lang) {
		lang = (lang == 'fr') ? 'fr' : 'en';
		document.cookie = 'defaultLang='+lang+';expires=' + (new Date(new Date().getTime() + 90 * 24 * 60 * 60 * 1000).toUTCString());
		return lang;
	}
	
	// get infos
	var e      = document.body.className.split(' ');
	var cLang  = e[0].split('-')[1].toLowerCase();
	var isHome = (e[1] == 'Accueil') ? true : false;


	// switch lang in force mode 
	if (isHome) {
		$('ul.Lang a').attr('href', function(){ return $(this).attr('href')+'?f'; });
	}

	// if we're sure we're not redirecting
	if (!isHome || window.location.search.substring(1) == 'f') {
		setLang(cLang);
		
	// if not
	} else {
		
		// if cookie use it or else get browser lang
		var cookie = getCookie('defaultLang');
		var lang   = setLang(
			(cookie)
				? cookie
				: ((navigator.language) ? navigator.language.split('-')[0] : navigator.userLanguage.split('-')[0]).toLowerCase()
		);
		
		// if we're not on the right page
		if (lang != cLang) {
			window.location = '/' + ((lang == 'fr') ? 'accueil' : 'homepage') + '.html?f';
		}
	}
	
});

