var current_valNutr = 0;
var interval_valNutr;

$(document).ready(function(){
	if(($.browser.msie)&&($.browser.version < 7)) {
		$(document).pngFix();
	}
	activerSousMenu();
	activerValeurNutritive();
	activerHautPage();
	activerBullesCertifications();
	activerTopLayer();
	
	equalHeight($("#view_distribution .gauche, #view_distribution .centre, #view_distribution .droite"));
	equalHeight($("#view_produit .gauche, #view_produit .centre, #view_produit .droite"));
	//equalHeight($("#view_accueil .gauche, #view_accueil .centre, #view_accueil .droite"));
	
	Cufon.replace("h1, h2, h3, h4", {autoDetect: true, hover: true});
});

/*--------------------------------------------------------------
	TOP LAYER
--------------------------------------------------------------*/
function activerTopLayer() {
	$("a.pop-video").click(function(){
		afficherOverlay();
		initTopLayer($(this));
		$(this).blur();
		return false;
	});
}

function initTopLayer(__el) {
	if($('html').attr('lang') == 'en'){
		$("body").append("<div id=\"toplayer\" style=\"height:300px;\" class=\"" + __el.attr("class") + "\"><p id=\"bt-fermer-toplayer\"><a href=\"#\"></a></p><div id='toplayer_contenu'></div><p class=\"txt-sous-video\">This feature was produced for the TV program <a href=\"http://www.par-dessuslemarche.tv\" target=\"_blank\">Par-dessus le march&eacute;</a>. <br />(Available in French only.)</p></div>");
	} else {
		$("body").append("<div id=\"toplayer\" class=\"" + __el.attr("class") + "\"><p id=\"bt-fermer-toplayer\"><a href=\"#\"></a></p><div id='toplayer_contenu'></div><p class=\"txt-sous-video\">Ce reportage a &eacute;t&eacute; r&eacute;alis&eacute; dans le cadre de l'&eacute;mission <a href=\"http://www.par-dessuslemarche.tv\" target=\"_blank\">Par-dessus le march&eacute;</a>.</p></div>");
	}
	
	var href = __el.attr("href");
	switch (__el.attr("class")) {
		case "pop-video":
			afficherPlayerVideo(href);
			positionTopLayer();
			$("#toplayer").css({display:"block"});
			break;
			
		default: 
			// rien
			break;
	}
	
	$("#bt-fermer-toplayer").click(function(){
		$("#overlay").click();
		$(this).blur();
		return false;
	});
	
	$(document).keyup(function(event){
		if (event.keyCode == 27) {
			$("#overlay").click();
		}
	});
}

function afficherPlayerVideo(href) {
	// VIDEO
	var flashvars = {};
	flashvars.autoPlay = true;
	flashvars.path = href;
	flashvars.color = $("body").attr("class");
			
	var params = {};
	params.menu = false;
	params.wmode = "transparent";
	params.allowFullScreen = true;
	params.allowScriptAccess = "always";
			
	swfobject.embedSWF("/swf/video-player.swf", "toplayer_contenu", "480", "270", "9.0.0","/swf/expressInstall.swf", flashvars, params);
}

function positionTopLayer() {
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	var largeurToplayer = $("#toplayer").width();
	var hauteurToplayer = $("#toplayer").height();
	//var marginTop = arrayPageScroll[1] + -(hauteurToplayer/2);
	var marginTop = -(hauteurToplayer/2);
	var marginLeft = -(largeurToplayer/2);
	
	$("#toplayer").css("margin-top", marginTop);
	$("#toplayer").css("margin-left", marginLeft);
}

function cacherTopLayer() {
	$(document).unbind("keyup");
	$("#toplayer a").unbind("click");
	$("#toplayer").remove();
}

function afficherOverlay() {
	$("body").append("<div id=\"overlay\"></div>");
	var arrayPageSize = getPageSize();
	var hauteurOverlay = arrayPageSize[1];
	
	$("#overlay").css("height", hauteurOverlay);
	$("#overlay").css("opacity", "0.7");
	$("#overlay").css("display", "block");
	$("#loading").css("display", "block");
	
	$("#overlay").click(function(){
		cacherTopLayer();
		cacherOverlay();
		$(this).blur();
		return false;
	});
	
	if(($.browser.msie)&&($.browser.version < 7)) {
		visibilitySelects("hidden");
	}
}

function cacherOverlay() {
	$("#overlay").remove();
	
	if(($.browser.msie)&&($.browser.version < 7)) {
		visibilitySelects("visible");
	}
}

function visibilitySelects(visibility){
	$("select").each(function(i){
		$(this).css("visibility", visibility);
	});
}

/*-------------------------------------------------------------------
	Validation format courriel
-------------------------------------------------------------------*/
function validerCourriel(val){
	var reg =/^[_a-zA-Z0-9.\-]*@[a-zA-Z0-9]([_a-zA-Z0-9\-]+\.)+([a-zA-Z]{2,10})$/;
	if(val.match(reg)) {
		return true;
	} else {
		return false;
	}
}

/*-------------------------------------------------------------------
	Égalise la hauteur des colonnes
-------------------------------------------------------------------*/
function equalHeight(group) {
    var tallest = 0;
    group.each(function() {
        var thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

/*-------------------------------------------------------------------
	Infobulles au survol des certifications
-------------------------------------------------------------------*/
function activerBullesCertifications() {
	$("#liste_certifications li").each(function(){
		var alt = $("img", this).attr("alt");
		$(this).append("<strong>" + alt + "<span></span></strong>");
		
		var config = {    
			sensitivity: 1,
			interval: 10,
			over: afficherBulleCertification,
			timeout: 100,
			out: cacherBulleCertification
		};
		$(this).hoverIntent(config);
	});
}

function afficherBulleCertification(){
	var hImg = ($("img", this).height()/2)+15;
	$("strong", this).css("margin-top", hImg);
	if($.browser.msie) {
		$("strong", this).css("display", "block");
	} else {
		$("strong", this).fadeIn("fast");
	}
}
function cacherBulleCertification(){
	if($.browser.msie) {
		$("strong", this).css("display", "none");
	} else {
		$("strong", this).fadeOut("fast");
	}
}

/*-------------------------------------------------------------------
	Haut de page
-------------------------------------------------------------------*/
function activerHautPage() {
	var htmlHaut = "";
	if($('html').attr('lang') == "en"){
		htmlHaut = "<p class=\"haut\"><a href=\"#haut\">- top -</a></p>";
	} else {
		htmlHaut = "<p class=\"haut\"><a href=\"#haut\">- haut -</a></p>";
	}
	
	var hWindow = $(window).height();
	var hDocument = $("body").height();
	if(hDocument > hWindow) {
		$("#corps").append(htmlHaut);
		activerSmoothScroll();
	}
}

function activerSmoothScroll(){
	var elScroll = "html";
	if($.browser.safari) {
		elScroll = "body";
	}
	$(".haut a").click(function(el){
		$(elScroll).animate({scrollTop: 0}, "slow");
		$(this).blur();
		return false;
	});
}

/*-------------------------------------------------------------------
	Sous-menu
-------------------------------------------------------------------*/
function activerSousMenu() {
	$("#bt_produits>a").click(function(){
		$(this).blur();
		return false;
	});
	
	$("#bt_produits>ul>li").click(function(){
		toggleSousMenu($(this));
	});
	
	var config = {    
		sensitivity: 1,
		interval: 10,
		over: ouvrirSousMenu,
		timeout: 900,
		out: fermerSousMenu
	};
	$("#bt_produits, #bt_boulangerie").hoverIntent(config);
}

function toggleSousMenu(el) {
	$("#bt_produits>ul>li").removeClass("actif");
	el.addClass("actif");
}
function ouvrirSousMenu() {
	$(this).addClass("hover");
}
function fermerSousMenu() {
	$(this).removeClass("hover");
	$("#bt_produits li li.actif").parents("li").click();
}

/*-------------------------------------------------------------------
	Bulle valeur nutritive
-------------------------------------------------------------------*/
function activerValeurNutritive() {
	$("#valeur_nutritive .bulle").eq(current_valNutr).addClass("actif");
	$("#nutritioniste .bulle").eq(current_valNutr).addClass("actif");
	
	$("#nutritioniste .bulle").each(function(){
		$(this).append("<span></span>"); // fleche vers le haut
	});
	
	$("#valeur_nutritive .bulle").each(function(i){
		var no = i;
		$(this).mouseover(function(){
			clearInterval(interval_valNutr);
			if(no != current_valNutr) {
				toggleValeurNutritive(no);
			}
		});
		$(this).mouseout(function(){
			intervalValeurNutritive();
		});
	});
	
	intervalValeurNutritive();
}

function toggleValeurNutritive(no) {
	//alert($("#valeur_nutritive .bulle").length);
	if($("#valeur_nutritive .bulle").length > 1){
		if($.browser.msie) {
			$("#valeur_nutritive .bulle").eq(current_valNutr).removeClass("actif");
			$("#nutritioniste .bulle").eq(current_valNutr).removeClass("actif");
			$("#valeur_nutritive .bulle").eq(no).addClass("actif");
			$("#nutritioniste .bulle").eq(no).addClass("actif");
			current_valNutr = no;
		} else {
			$("#valeur_nutritive .bulle").eq(current_valNutr).removeClass("actif");
			$("#nutritioniste .bulle").eq(current_valNutr).fadeOut("fast", function(){
				$("#valeur_nutritive .bulle").eq(no).addClass("actif");
				$("#nutritioniste .bulle").eq(no).fadeIn("fast");
				current_valNutr = no;
			});
		}
	}
}

function findNextValeurNutritive() {
	if(current_valNutr == 0){
		toggleValeurNutritive(1);
	} else {
		toggleValeurNutritive(0);
	}
}

function intervalValeurNutritive() {
	interval_valNutr = setInterval("findNextValeurNutritive()",5000);
}

function bindPrintRecette(){
	$('.btn-print').bind('click', function(){
		var divToPrint = $(this).parents('.recette').html();
		var titre = $(this).next('h2').html();
		var haut = $('#haut h1').html();
		var popupWin = window.open('', '_blank', 'width=10,height=10,left=0,top=0');
		popupWin.document.open();
		popupWin.document.write('<html><head><link href="/css/impression.css" rel="stylesheet" type="text/css" media="print" /><title>'+titre+'</title></head><body><body id="view_recettes"><div id="haut"><h1>'+haut+'</h1></div><div class="recette">' + divToPrint + '</div></div></html>');
		popupWin.document.close();
		popupWin.focus();
		popupWin.print();
		popupWin.close();
		
		return false;
	});	
}


/**********************************************************************
DIMENSIONS DE L'ÉCRAN
**********************************************************************/
function getPageScroll(){
	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

/*--------------------------------------------------------------
	PROMOTIONS
--------------------------------------------------------------*/

function initPromo() {
	$('input, textarea').live('focusin', onInputFocusIn);
	$('input, textarea').live('focusout', onInputFocusOut);
	$('input, textarea').trigger('focusout');
	
	$('form').bind('submit', onFormSubmit);
	
	var math_start = Math.floor(Math.random() * (1 + 6 - 2)) + 2;
	var math_question = '(';
		math_question += math_start * 2;
		math_question += ' + ';
		math_question += 2;
		math_question += ')';
		math_question += ' / ';
		math_question += 2;
	var math_answer = (math_start * 2 + 2) / 2;
	
	$('span.math_question').html(math_question);
	$('input[name=math_answer]').val(math_answer);
}

/**
 *	Input focus in event
 */
function onInputFocusIn() {
	var value = $(this).val();
	var defaultValue = $(this).attr('title');
	
	if (value == defaultValue) {
		$(this).val('');
	}
	
	$(this).removeClass('error');
}

/**
 *	Input focus out event
 */
function onInputFocusOut() {
	var value = $(this).val();
	var defaultValue = $(this).attr('title');
	
	if (value == '') {
		$(this).val(defaultValue);
	}
}

/**
 *	Form validation
 *	@form Form jQuery object
 */
function validateForm(form) {
	var validForm = true;
	
	var email_reg = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", "g");
	var postal_reg = new RegExp("([a-z])\d([a-z])(.?)\d([a-z])\d", "g");
	
	form.find(':input').each(function() {
		var value = $(this).val();
		var validField = true;
		
		if ($(this).hasClass('requis')) {
			if (!value) {
				validField = false;
			} else if (value == $(this).attr('title')) {
				validField = false;
			} else if ($(this).hasClass('email') && !value.match(email_reg)) {
				validField = false;
			} else if ($(this).hasClass('postal') && !value.match(postal_reg)) {
				validField = false;
			} else if ($(this).is(':checkbox') && !$(this).is(':checked')) {
				validField = false;
			} else if ($(this).is(':[name=math_question]') && $(this).val() != $('input[name=math_answer]').val()) {
				validField = false;
				
			}
		}
		
		if (!validField) {
			validForm = false;
			
			$(this).addClass('error');
		} else {
			$(this).removeClass('error');
		}
	});
	
	return validForm;
}

/**
 *	Form submit
 */
function onFormSubmit() {
	if (!validateForm($(this))) {
		return false;
	}
	
	var action = $(this).attr('action');
	var method = $(this).attr('method');
	
	var data = {};
	
	// Populate data fields
	$(this).find(':input').each(function() {
		var name = $(this).attr('name')
		var value = $(this).val();
		
		if ($(this).is('[type=submit]') || $(this).is('[type=image]') || $(this).is('[type=button]')) {
			return false;
		}
		
		if (value == $(this).attr('title')) {
			return false;
		}
		
		if (name.match(/\[\]/g)) {
			name = name.replace(/\[\]/g, '');
			
			if (typeof(data[name]) == 'undefined') {
				data[name] = [];
			}
			
			data[name].push(value);
		} else {
			data[name] = value;
		}
		
	});
	
	$('p.erreur, p.merci').slideUp(250);
	
	$.ajax({
		type:method,
		url:action,
		data:data,
		success:onFormSubmitSuccess,
		error:onFormSubmitError
	});
	
	return false;
}

function onFormSubmitSuccess(data) {
	if (data.match(/error/)) {
		onFormSubmitError(data);
		return false;
	}
	
	$('p.merci').slideDown(250);
	$('form').slideUp(250);
}
	
function onFormSubmitError(data) {
	$('p.erreur').slideDown(250);
}
