/**
 * utilisé depuis la colorbox ajout de produit 
 * pour afficher le total d'article dans le panier
 */
function setTotalArticlePanier($total){
	$('.account .qt').text($total);
        $('.account .last').show();
        $('.account .lien_noborder').removeClass("lien_noborder");
}


/**
 * fonctions du moteur de recherche
 */

//Lorsque le visiteur quitte le champ du moteur de recherche
function blurSearchField(){
	setTimeout(function(){
            if($('#searchEngineField').val() == ''){
                    $('#searchEngineField').val('Recherchez un produit');
            }
            else{
                    $('#zone_suggestions').hide();
            }
        }, 800);
}

//Lorsque le visiteur clique dans le champ du moteur de recherche
function clickSearchField(){
	if($('#searchEngineField').val() == 'Recherchez un produit'){
		$('#searchEngineField').val('');
	}
	else{
		autocompleteSearchField();
	}
}


//Lorsque le visiteur écrit dans le champ du moteur de recherche
function autocompleteSearchField(){
	var keywords = $('#searchEngineField').val();
	//var arr_keywords = keywords.split(' ');
	//var last_keyword = arr_keywords[(arr_keywords.length -1)];
	//if(last_keyword.length > 2){
	if(true){

		//On lance l'autocomplétion
		$.ajax({
			type: "POST",
			url: "/suggestions-recherche",
			data: "keywords="+encodeURIComponent(keywords),
			success: function(xmldoc){
				
				//On vide la zone de résultats
				$(document).find('#zone_suggestions').html('<div class="cale_zone"></div>');

				if($(xmldoc).find('suggestion').length > 0){
					
					//on affiche la zone de rsultats, au-cas-où
					$(document).find('#zone_suggestions').show();

					//On a trouvé toutes les suggestions, on les affiche dans le champ de suggestions
					$(xmldoc).find('suggestions').find('suggestion[type=produit]').each(function(){
						$(document).find('#zone_suggestions')
									.append('<div class="suggestion_row"><span class="lien_direct"><a href="'+$(this).attr('url')+'">'+$(this).text()+'</a></span></div>');
					});
					$(xmldoc).find('suggestions').find('suggestion[type=titre], suggestion[type=keyword]').each(function(){
						if($(this).attr('type') == 'titre'){
							$(document).find('#zone_suggestions')
									.append('<div class="suggestion_row"><span class="titre">'+$(this).text()+'</span></div>');
						}
						else{
							$(document).find('#zone_suggestions')
									.append('<div class="suggestion_row"><span class="suggestion" onclick="selectSuggestion(this)">'+$(this).text()+'</span></div>');
						}
					});
				}
			}
		});

	}
}
function remplace(expr,a,b) {
  var i=0
  while (i!=-1) {
     i=expr.indexOf(a,i);
     if (i>=0) {
        expr=expr.substring(0,i)+b+expr.substring(i+a.length);
        i+=b.length;
     }
  }
  return expr
}

function submitSearchField(){
    var keywords = $('#searchEngineField').val();
    keywords = remplace(keywords,' ','+');
    _gaq.push(['_trackPageview',keywords]);
    location.href = '/resultats-de-la-recherche='+keywords;
}

//Au clic sur une suggestion de l'autocompleter
function selectSuggestion(element){
	var keywords = $('#searchEngineField').val();
	var arr_keywords = keywords.split(' ');
	var nb_keywords = arr_keywords.length;
	arr_keywords[nb_keywords-1] = html_entity_decode($(element).html());

	$('#searchEngineField').val(arr_keywords.join(' '))

        $('#searchEngineForm').submit();
}

//Fonctionne comme la fonction PHP homonyme
function html_entity_decode(string){
	return string.replace('&amp;', '&')
				 .replace('&lt;', '<')
				 .replace('&gt;', '>')
				 .replace('&quot;', '"')
				 .replace('&apos;', "'");
}


function toggle_filters_container(){
	if($('#filters_container').is(':hidden')){
		var rayon_id = $('input[name=rayon_creation_filtres]').val();
		$.ajax({
			type: "POST",
			data: 'rayon='+rayon_id,
			url: "/ajax-box-filtrage",
			success: function(result){
				$('#filters_container').html(result);
				$('#filters_container').fadeIn(500);
			}
		});
	}
	else{
		$('#filters_container').fadeOut(500);
	}
}

function fillFilterBar(){
	if($('#bloc_criteres_recherche').is(':hidden')){
		showFilterBar();
	}
	else{
		$('#bloc_criteres_recherche').slideUp(250, function(){
			showFilterBar();
		});
	}
}

function showFilterBar(){
	$.ajax({
		type: "POST",
		url: "/ajax-barre-filtrage",
		success: function(result){
			if(result && result != '0'){
				$('#bloc_criteres_recherche').html(result);
				$('#filters_link').hide();
				$('#filters_link2').show();
				$('#bloc_criteres_recherche').slideDown(function(){
					document.location.reload();
				});
			}
			else if(result == '0'){
				document.location.reload();
			}
		}
	});
}



function reinit_filters(){
	$.ajax({
		type: "POST",
		url: "/ajax-reinitialise-filtrage",
		success: function(result){
			$('#filters_link2').hide();
			$('#filters_link').show();
			$('#bloc_criteres_recherche').slideUp(250, function(){
				window.location.reload();
			});
		}
	});
}


/******************************************************************************/
/****************Includes a specific CSS for wide screens**********************/
/******************************************************************************/

if (screen.height >= 1024) {
	document.write('<link rel="stylesheet" id="main_style_wide" media="all" type="text/css" href="/style/main_wide.css" />');
}


/**
 * Colorboxes
 */
 $('.lien_cbox').live('click', function(e){ //la pose de l'ecouteur par colorbox ne marche pas.
        e.preventDefault();
        var myHref = $(this).attr('href');
        $.colorbox({
                href: myHref,
                iframe: true,
                innerWidth: '850px',
                innerHeight: '550px'
    });
});



/*********************Other functions (need documentation)*********************/

var resizeThem  = function () {
	h = screen.height;
	paddingtop = Math.round($(window).height() * 0.0313253012);
	
	if(paddingtop > 26) paddingtop=26;
	$('#page').css("padding-top", (h >= 1024) ? paddingtop : 0)

	marginbottom = Math.round($(window).height() * 0.0578313);
	if(marginbottom > 45) marginbottom = 45;
	$('#header').css('height', (h >= 1024) ? Math.round(marginbottom+78) : 0)
	$('#header_head').css('margin-bottom', (h >= 1024) ? marginbottom : 0);

	total = paddingtop+marginbottom;
	$(document.body).css("background-position", (h >= 1024) ? "0px "+total+"px" : 0);
};

var collectionSwitchEffect = {
	lock:false,
	elements:null,
	el:null,
	curr:0,
	fetching:'',
	state:'',
	start: function (name) {
		if(this.lock) return false;
		if(this.state == name) return false;
		
		this.lock=true;
		divShowLoading($('.collections_right')[0], 0.35);

		if($('.collections_right img.big_image').length > 0){

			var img=null;
			img = document.createElement('img');
			img.src = (name == 'homme') ? '/collection/homme_2.jpg' : '/collection/femme_1.jpg';/*TODO corriger TF*/
			$(img).addClass('big_image')
			$(img).fadeTo(0, 0.5);
			$(img).load (function() {
				$('.collections_right img.big_image').fadeTo(500, 1)
				setTimeout("divHideLoading($('.collections_right')[0]);", 500);

			});
			$('.collections_right img.big_image').remove();
			$('.collections_right').eq(0).append(img);

		}


		if($.browser.msie && $('.collections_right img.big_image').get(0).complete) {
			$('.collections_right img.big_image').fadeTo(500, 1);
			setTimeout("divHideLoading($('.collections_right')[0]);", 500);
		}
		


		this.elements = $('.liste_niveau1 li.'+((name == 'homme') ? 'femme' : 'homme'));
		this.fetching = name;
		
		this.curr=this.elements.length-1;
		this.run(1);
		
	},

	run: function(step) {
		switch(step) {
			case 1:
				if(this.curr == -1) {
					this.run(2);
				} else {
					/*alert("Running on "+this.curr)*/
					
					this.el=this.elements[this.curr];
					$(this.el).fadeOut(500);
					this.curr--;
					this.el = this.elements[this.curr];
					
					setTimeout("collectionSwitchEffect.run(1)", 50);
				}
				break;

			case 2:
					/*$('.choix_hf .selected').fadeOut(500);*/
					setTimeout("$('.choix_g').fadeOut(125);", 100);
					
					setTimeout("collectionSwitchEffect.keepOnRight();", 110);
					setTimeout("$('.choix_d').fadeOut(125);", 200);
					
					setTimeout("collectionSwitchEffect.run(3);", 450);
					break;

			case 3:
					tmp = $('.choix_g')[0].innerHTML;
					
					$('.choix_g')[0].innerHTML = $('.choix_d')[0].innerHTML;
					$('.choix_d')[0].innerHTML = tmp;
					collectionSwitchEffect.backToLeft();
					
					setTimeout("$('.choix_g').fadeIn(125);", 100);
					setTimeout("$('.choix_d').fadeIn(1000);", 450);
					setTimeout("collectionSwitchEffect.run(4);", 375)
					break;

			case 4:
					
					if(this.fetching == 'homme') {
						this.elements = $('.liste_niveau1 li.homme');
						
						setTimeout("$('.liste_niveau1').removeClass('niveau1_femme');", 15000);
						setTimeout("$('.liste_niveau1').delay(300000000).addClass('niveau1_homme');", 15000);
						$('#nom_collection_accolade').html('Collection homme');
						$('#arianne_nav_collection').html('Collection homme');
						$('#arianne_nav_collection').attr('href', 'collection_homme.php');
					}
					else {
						this.elements = $('.liste_niveau1 li.femme');
						setTimeout("$('.liste_niveau1').removeClass('niveau1_homme');", 15000);
						setTimeout("$('.liste_niveau1').delay(300000000).addClass('niveau1_femme');", 15000);
						$('#nom_collection_accolade').html('Collection femme');
						$('#arianne_nav_collection').html('Collection femme');
						$('#arianne_nav_collection').attr('href', 'collection_femme.php');
					}

					this.curr=0;
					this.run(5);
					break;

			case 5:
					if(this.curr == this.elements.length) {
						this.lock=false;
						this.state=this.fetching;

						
						return false;
					} else {
						this.el=this.elements[this.curr];
						$(this.el).fadeIn(250);
						this.curr++;
						this.el = this.elements[this.curr];
						setTimeout("collectionSwitchEffect.run(5)", 25);
					}
					
					
					break;
		}
	},
	keepOnRight: function() {
		$('.choix_d').css('float', 'right');
	},
	backToLeft: function() {
		$('.choix_d').css('float', 'left');
	}
};

var divShowLoading = function (div, opac) {
	
	$(div).css('position', 'relative');
	
	
	loader = $('#loading_div')[0].cloneNode(true);
	loader.id=null;
	
	$(div).append(loader);
	$(loader).css({'width': $(div).width(), 'height': $(div).height(), 'display': 'block'});
	
	num = ($.browser.msie) ? 0 : 1;
	$(loader.childNodes[num]).css(
		'margin-top',
		Math.round(
			($(div).height())/2 - ($(loader.childNodes[num]).height())/2
		)
	);
	
	$(loader).fadeTo(0, opac);
};

/*
 * @function divHideLoading : Cette fonction cache le voile blanc de chargement contenant l'image de chargement
 * @param HTMLDivElement : div sur lequel porte le voile à supprimer
 * @param bool transition : supprimer le voile par transition ou non
 * [@param int duration : durée de la transition de suppression (s'il y a) en millisecondes]
 * @return void, ou false en cas d'erreur sur le HTMLDivElement ou le div de chargement à attraper
 */
var divHideLoading = function (div, transition, duration) {
	
	var node = null;
	node = $(div).find('.loading_div').get(0);
	
	
	if(transition && typeof(duration) != 'undefined') {
		
		$(node).fadeOut(duration);
		//alert($(node).parents("li").eq(0).prevAll().size());
	} else {
		if(node) {
			node.parentNode.removeChild(node);
		}
		else {
			return false;
		}
	}
	
};

/*
 * @function loadIt : Cette fonction sert à lancer le chargement d'une image contenue dans le jCarousel mais n'étant pas encore visible (s'éxécute au moment où elle devient visible, événement lancé par jCarousel). Ses deux paramètres sont des paramètres standards passés aux fontions triggers du jCarousel
 * @param carousel : instance de jCarousel
 * @param state : état courant du jCarousel
 * @return void
 */
 var loadIt = function (carousel, state) {
	 /*
	 for (var i = carousel.first; i <= carousel.last; i++) {
			$('#carousel-image-item-'+i).trigger('appear');
	}*/
};

 


/*
 * @function showHidePrices : Show or hide prices on the website. A cookie is set by the function in order to adjust the display when loading another page
 * @param a [bool] : true = hide, false = show
 * @return false
 */
var showHidePrices = function (a) {
	
	$.cookie('hide_prices', a);
	$('.jq-price_visible, .jq-price_hidden').toggle();
	$('.jq-price_visible, .jq-price_hidden').toggleClass('dispnone');
	$('.jq-price_visible, .jq-price_hidden').trigger('showHidePrices', [ a ]);

	if(a == true){
		$('input[name=hide_price}').attr('checked', true);
	}
	else{
		$('input[name=hide_price]').attr('checked', false);
	}

	return false;
};


/*
 * @funtion showHideFilters : Show or hide the filters panel
 * @param obj [EventObject]
 * @return void
 */
var showHideFilters = function (obj) {
	obj.preventDefault();
	obj.stopPropagation();

	 // Cas où le panel de filtres n'est pas encore affiché
	if($('.filters_container').css('display') == 'none') {
		$('.filters_container').fadeIn(500);
		$('.filters_container').find('.filters_close').bind('click', showHideFilters);
		

		$('.filters_link').unbind('click');
	} else {
		$('.filters_container').fadeOut(500);

		$('.filters_link').bind('click', function (obj) {
			showHideFilters(obj);
		});
		$('.filters_container').find('.filters_close').unbind('click');
	}
};

/******************************************************************************/
/**
 *une serie de variable globale : bouh que c est pas beau
 *
 */

var nbDecal;
var myvPreloader = 7;
var myPreloader = 6;
var myNextLoad = 1;
var myLastVisible = 0;
var myFirstVisible = 1;
var theFirstVisible = 1;
var enableStartLoader = 0;
var totalProduitRayon = 0;
var moveforopen = false;
var objEventForMove = null;


/******************************************************************************/

/**
 * fonction de chargemet en différé des images dans le carousel produit
 */
function myLazyLoader(){
	//
	//
	//
	//alert(totalProduitRayon);
	enableStartLoader++;
	var _this = null;
	//console.log(myLastVisible);
	for(i = myFirstVisible; i < (myFirstVisible + 1); i++){
		_this = $('#carousel-image-item-'+i);


		if ($(_this).hasClass('true') && !$(_this).hasClass('isloader')){//c'est une image deja charge'
		
			if (myFirstVisible + 1 <= myLastVisible && myFirstVisible + 1 <= totalProduitRayon){
					myFirstVisible += 1;
					myLazyLoader();
				}				
		}else if (!$(_this).hasClass('true')){
				
			$(_this).addClass('true');						//je marque l image comme en chargement
			$(_this).attr('src', $(_this).attr('original')); //je met l'image en charge
			$(_this).removeAttr('original');
			$(_this).load(function(){							//je place l'ecouteur de chargement
				$(this).removeClass('isloader');
				$(this).prev('.imgLoader').remove();
				//retrait du loader
				$(this).show();		//affichage
				
				if (myFirstVisible + 1 <= myLastVisible && myFirstVisible + 1 <= totalProduitRayon){
					myFirstVisible += 1;
					myLazyLoader();
				}				
			});
		}	
	}	
	myNextLoad = (myNextLoad + myvPreloader) - 1;
	myvPreloader = 4;
}

/******************************************************************************/



/**
 * fonction utiliser post initialisation jcarousel dans les produits
 */
function postInit(myCarousel){
	
	totalProduitRayon = $('#totalProduitRayon').val();	
	
	

	/** evite la selection des produits*/
	$('.fleche_g_visuel, .fleche_d_visuel').live('dblclick',function(e){		
			disableSelection(this);
			
		});

	$('li').live('mousedown', function(){
		disableSelection(this);

	});

}


function disableSelection(la_target){
	if (typeof la_target.onselectstart!="undefined") //IE route
		la_target.onselectstart=function(){return false}
	else if (typeof la_target.style.MozUserSelect!="undefined") //Firefox route
		la_target.style.MozUserSelect="none"
	else //All other route (ie: Opera)
		la_target.onmousedown=function(){return false}
	la_target.style.cursor = "default"
}



/******************************************************************************/
$(document).ready(function(){

	$('.tooltip').each(function(){
		$(this).easyTooltip({
			tooltipId: "tooltip",
			xOffset: 15,
			yOffset: -18,
			content: '<div class="tooltiptop"></div><div class="tooltipcontent">' + $(this).attr('title') + '</div><div class="tooltipbottom"></div>'
		});
	});
	
	$('.no-tooltip').live('hover', function(){
		$('#tooltip').hide();
	});
	$('.no-tooltip').live('mouseleave', function(){
		$('#tooltip').show();
	});



	$('#searchEngineForm').submit(function(e){
            e.preventDefault();
            if($('#searchEngineField').val() == '' || $('#searchEngineField').val() == 'Recherchez un produit'){
                   submitSearchField();
            }
	});

	// si la fiche detail est ouverte on force l'affichage des btn rotations et zoom'
	$('.the_visuel_container').mouseleave(function(e){
		
		e.preventDefault();
		if($(this).next().is(':visible') && $(this).next().width() > 0  ){

			$(this).find('.actions_fiche_produit').addClass("dBlock");

		}

	});


	$('.lien_cgv').colorbox({
			width: 900,
			height: 550,
			iframe: true
	});

	$('.lien_credits').colorbox({
			width: 650,
			height: 550,
			iframe: true
	});

	$('.lien_mentions').colorbox({
			width: 750,
			height: 600,
			iframe: true
	});

	$('.lien_contact').colorbox({
			width: 750,
			height: 750,
			iframe: true
	});


	$('.lien_newsletter').colorbox({
			width: 400,
			height: 600,
			iframe: true
	});


	$('#filters_link, #filters_link2').click(function(){
		toggle_filters_container();
	});

	$('.marques_container').show();

	//Initialisation du comportement de la zone d'infos de survol des produits du rayon
	$('.header_visuel').css('height', '39px');
	$('.header_visuel').click(function(){
		$(this).parents('.the_visuel').find('.actions_fiche_produit').click();
	});

	$('.lien_afficher_prix').click(function(e){
		e.stopPropagation();
		showHidePrices(false);
	});
});

