var redirect = '';
var timer_defilement = 0;
var vitesse_animation = 500;
var vitesse_defilement = 2500;

var timer_scroll;
var hauteur_defilement = 342;

var timer_alterner = 0;
var top_bulle;

$(function() {


	if ($("#bulle_univers").length > 0) {
		top_bulle = $("#bulle_univers").offset().top;
    }
    
    //bug overlay
    fix_flash();
    
	//Si moteur de recherche dans la page scroll resultat souris
	if ($(".liste_produits_recherche").length > 0) {
			
		$(".liste_produits_recherche").mousewheel(function(event, delta, deltaX, deltaY) {

			if (delta > 0) {
				scroll = 'up';
			}
			else if (delta < 0) {
				scroll = 'down';
			}
		
			lancer_recherche(scroll);
			
			return false;

		});
		
	}

	// Si accès à un produit par le moteur de recherche
	$(".liste_produits_recherche .lien_produit").live("click", function() {

		var redirection = $(this).attr("href");
		
		$.ajax({
			type: 'POST',
			url: '/produit/set_produit_publication_selectionne',
			success: function(response) {
                
				window.location.href = redirection;
			}
		});
		
		return false;
		
	});
    
    //enleve masque recherche produit
	$("*", document).click(function(evt) {

		if ($(this).get(0).tagName != "HTML") {

			if ($(evt.target).parent().attr("id") != "zone_recherche" && $(evt.target).parent().attr("id") != "champs_recherche" && $(evt.target).parent().attr("id") != "rechercher_produit" ) {
					
				if ($("#popup_gestion_extraits").is(":visible")) {

					if ($(evt.target).parent().attr("id") != "popup_gestion_extraits" && $(evt.target).parent().attr("class") != "btn_infos") {
						$(".liste_produits_recherche").hide();
					}
				}
				else {
					$(".liste_produits_recherche").hide();
				}
				
				var rel_pdt_courant;
				
				$(".infos .produit").each(function() {
					if ($(this).hasClass("produit_actif")) {
						rel_pdt_courant = $(".infos .produit_actif").attr("rel");
					}
				});
				
				clearTimeout(timer_alterner);
				//timer_alterner = setTimeout("afficher_bouton_infos_commandes(" + rel_pdt_courant + ")", 1500);
				
				if(!($.browser.msie && $.browser.version == "6.0" || $.browser.msie && $.browser.version == "7.0")) {
					$("#white_mask").stop().animate({
						opacity: 0
					}, vitesse_animation, function() {
						$("#white_mask").hide();
						$("#rechercher_un_produit").css("z-index", "1");
						$("#zone_recherche").css("z-index", "1");
					});
				}

			}
            
		}
		
	});
	
	//lance recherche produit
	$("#rechercher_un_produit, .lancer_recherche").bind('keyup click', function(e) {	
		lancer_recherche(e);     
	});
	
	$(".scroll_top").live("mouseover click", defilement_haut).mouseout(function() {
		clearTimeout(timer_scroll);
	});
	
	$(".scroll_bottom").live("mouseover click", defilement_bas).mouseout(function() {
		clearTimeout(timer_scroll);
	});
	
	// Résoud BUG IE
	// Opacité mise à 0 par défaut	
	$("#black_mask").css("opacity", 0);
	$("#white_mask").css("opacity", 0);
	
	//efface ou remet la valeur par defaut sur formulaire
	var input;
	$(".input_text").live("focus", function() {
        
		var id = $(this).attr('id');
		var rel = $(this).attr('rel');
		input = $(this).attr('value');
        if (input == "") {
            $(this).css('color', '#000');
        }
		else if (input == rel) {
			$(this).attr('value', '');
			$(this).css('color', '#000');
		}
		if (id == "date_jour" || id == "date_mois" || id == "date_annee") id = "date";
		$("div[id^=bulle_erreur_]").css("visibility", "hidden");
	}).live("blur", function() {
		var tmp_input = $(this).attr('value');
		
		if (tmp_input == "") {
			$(this).attr('value', $(this).attr('rel'));
			$(this).css('color', '#888');
		}
	});
	
	//defilement univers en haut a gauche
	timer_defilement = setTimeout("defilement_univers()", vitesse_defilement);
	
	//univers en haut à gauche
	$(".petite_bulle_univers").mouseenter(function() {
        if ($('#fermer_bulle').is(':hidden')) {
            afficher_fond_noir();
        }
	});
	
	//univers en haut à gauche
	$(".grande_bulle_univers .un_univers").live("click", function() {
	
		// Ferme la grande bulle si l'univers cliqué est externe
		if ($(this).attr("target")) {
			cacher_univers();
		}
	});
	
	//masque qui apparait lors du click sur une des bulles
	$("#black_mask").mouseenter(function() {
        if ($("#bulle_univers").length > 0) {
            cacher_univers();
        }
	});    
	
	//ferme la bulle
	$("#fermer_bulle").click(function() {
        if ($("#bulle_univers").length > 0) {
            cacher_univers();
        }
	});
    
    /*************************************************************************************/
    /*************************************************************************************/
    /* Navigateur trop vieux */
    
    $("#navigateurs .fermer").click(function() {
        
        $.ajax({
            url: '/tools/cacher_liste_navigateurs',
            success: function() {
                $("#navigateurs").remove();
            }
        });
        
    });

});

//recherche produit
function defilement_haut() {

	$(".scroll_top").die("mouseover click", defilement_haut).mouseout(function() {
		clearTimeout(timer_scroll);
	});
	
	$(".scroll_bottom").die("mouseover click", defilement_bas).mouseout(function() {
		clearTimeout(timer_scroll);
	});
	
	var nb_produits = $(".recherche_autocompletion").find('.produit').length;
	var decalage_top = $(".recherche_autocompletion").css('top');
	
	decalage_top = decalage_top.split('px'); // Split de décalage
	decalage_top = decalage_top[0]; // Récup du nombre seul
	decalage_top = Math.abs(decalage_top); // Retourne la valeur absolue
	var nb_produits_cache = decalage_top / 38; // Calcul le nombre d'éléments
	
	if (nb_produits_cache <= 0) {
		clearTimeout(timer_scroll);
		var decalage = 0;
		$(".scroll_top").hide();
	}
	else if (nb_produits_cache <= 8) {
		var decalage = parseInt(nb_produits_cache) * 38 + 38;
		$(".scroll_top").hide();
	}
	else {
		// hauteur d'une liste de 8 produits
		var decalage = 304;
	}
	
	
	if (decalage > 0) {
		$(".scroll_bottom").show();
	}
	
	// Animation
	$(".recherche_autocompletion").animate({
		top: '+=' + decalage + 'px'
	}, 1000, function() {
		
		// Activation events
		$(".scroll_top").live("mouseover click", defilement_haut).mouseout(function() {
			clearTimeout(timer_scroll);
		});
		
		$(".scroll_bottom").live("mouseover click", defilement_bas).mouseout(function() {
			clearTimeout(timer_scroll);
		});
		
	});
	
	timer_scroll = setTimeout("defilement_haut()", 2000);
		
}

//recherche produit
function defilement_bas() {

	$(".scroll_top").die("mouseover click", defilement_haut).mouseout(function() {
		clearTimeout(timer_scroll);
	});
	
	$(".scroll_bottom").die("mouseover click", defilement_bas).mouseout(function() {
		clearTimeout(timer_scroll);
	});
	
	var nb_produits = $(".recherche_autocompletion").find('.produit').length;
	var decalage_top = $(".recherche_autocompletion").css('top');
	
	decalage_top = decalage_top.split('px'); // Split de décalage
	decalage_top = decalage_top[0]; // Récup du nombre seul
	decalage_top = Math.abs(decalage_top); // Retourne la valeur absolue
	var nb_produits_cache = decalage_top / 38; // Calcul le nombre d'éléments
	
	var reste_a_afficher = nb_produits - nb_produits_cache - 8;

	if (reste_a_afficher <= 0) {
		
		clearTimeout(timer_scroll);
		var decalage = 0;
		$(".scroll_bottom").hide();
	}
	else if (reste_a_afficher <= 8) {
		
		var decalage = (parseInt(reste_a_afficher) * 38) + 38;
		$(".scroll_bottom").hide();
	}
	else {
		var decalage = 304;
	}
	
	if (decalage > 0) {
		$(".scroll_top").show();
	}

	// Animation
	$(".recherche_autocompletion").animate({
		top: '-=' + decalage + 'px'
	}, 1000, function() {
	
		// Activation events
		$(".scroll_top").live("mouseover click", defilement_haut).mouseout(function() {
			clearTimeout(timer_scroll);
		});
		
		$(".scroll_bottom").live("mouseover click", defilement_bas).mouseout(function() {
			clearTimeout(timer_scroll);
		});
	});
	
	timer_scroll = setTimeout("defilement_bas()", 2000);

}

//recherche produit
function navigation_recherche_clavier(e) {
	
	clearTimeout(timer_alterner);
	
	var prochain_produit;
	var img;
	
	// récupère l'id produit publication du produit courant
	var id_produit_publication = $(".recherche_autocompletion .produit_actif").attr("rel");
	
	// Si on clique sur la touche entrée
	if (e.which == 13) {
        // si des produits on été trouvés
        if ($(".recherche_autocompletion a").size() > 0) {
            var url_produit = $(".recherche_autocompletion .lien_produit[rel=" + id_produit_publication + "]").attr("href");
            // Redirige vers la fiche du produit sélectionné
            window.location.href = url_produit;
        }
		return false;
	}
	
	// nombre de résultats obtenus pour la recherche
	var nb_resultats = $(".recherche_autocompletion .lien_produit").length;
	
	// détermine la position du produit sélectionné
	var position_courante = 0;
	$(".recherche_autocompletion .lien_produit").each(function(i) {
        
		if ($(this).attr("rel") == id_produit_publication) {
			position_courante = i+1;
		}
	});
	
	// Si on clique sur la flèche du bas du clavier
	if (e.which == 40 || e == "down") {
        
		// Si on est au dernier produit, le suivant est le premier
		if (position_courante == nb_resultats) {
			prochain_produit = $(".recherche_autocompletion .lien_produit").first();
		}
		else {	
			// sélectionne le produit suivant
			prochain_produit = $(".recherche_autocompletion .lien_produit[rel=" + id_produit_publication + "]").next(".lien_produit");
		}
		
	}
	// Si on clique sur la flèche du haut du clavier
	else if (e.which == 38 || e == "up") {

		// Si on est au premier produit, le suivant est le dernier
		if (position_courante == 1) {
			prochain_produit = $(".recherche_autocompletion .lien_produit").last();
		}
		else {
			// sélectionne le produit précédent
			prochain_produit = $(".recherche_autocompletion .lien_produit[rel=" + id_produit_publication + "]").prev(".lien_produit");
		}
		
	}
	
	// cache l'image "infos & commandes" pour tous les produits
	$(".liste_produits_recherche .infos_commandes").each(function() {
		$(this).hide();
	});
	
	// Supprime la sélection de produit
	$(".liste_produits_recherche .produit").removeClass('produit_actif');
	
	// Sélectionne le produit que l'on survol
	prochain_produit.children(".produit").addClass('produit_actif');
	
	$(".infos_produits_recherche .un_produit").each(function() {
		if ($(this).attr("rel") == prochain_produit.attr("rel")) {
			
			img = $(this).children(".img_cachee").html();
			
			$(".liste_produits_recherche .visuel").html("<img src='" + img + "' alt='' title='' />");
			$(".liste_produits_recherche .visuel_txt").html($(this).children(".description_cachee").html());
			$(".liste_produits_recherche .boutons_produit .btn_infos").attr("href", $(this).children(".url_cachee").html());
			
		}
	});
	
	// Lance le timer sur le pdouit courant pour faire apparaitre en alternance le nom du produit et "info & commande"
	timer_alterner = setTimeout("afficher_bouton_infos_commandes(" + prochain_produit.attr("rel") + ")", 1000);
	
}

//fonction executée pour la recherche d'un produit
function lancer_recherche(e) {

	var recherche = $("#rechercher_un_produit").val();
	var scroll = "";
	
	//au bout de 3 caractères tapés, on commence la recherche
	if (recherche.length >= 3) {
        
        // Si IE6, on cache tous les select qui apparaissent par dessus le masque
        if($.browser.msie && $.browser.version == "6.0") {
            $("select").hide();
        }
		
		// Si utilisation de certaines touches de clavier
		if (e.which == 40 || e.which == 38 || e.which == 13 || e == "up" || e == "down") {
			navigation_recherche_clavier(e);
		}
		else {
			$(".scroll_top").hide();
			$(".scroll_bottom").hide();
			
			if(!($.browser.msie && $.browser.version == "6.0" || $.browser.msie && $.browser.version == "7.0")) {
                
				$("#white_mask").show();
				$("#rechercher_un_produit").css("z-index", "202");
				$("#zone_recherche").css("z-index", "202");
			}

			// Apparition du fond blanc
			$("#white_mask").stop().animate({
				opacity: 0.70
			}, vitesse_animation, function() {});
	
			$.ajax({
				type: "POST",
				url: "/chercher_produit",
				data: "recherche=" + recherche,
				dataType: "json",
				success: function(object) {
	
					// Initialisations
					$(".recherche_autocompletion").html("");
					$(".liste_produits_recherche .right .visuel").html("");
					$(".liste_produits_recherche .right .visuel_txt").html("");
					$(".message_recherche").html("").hide();
					
					$(".recherche_autocompletion").animate({
						top: '16px'
					}, 0);		
				
					if (object.nb_produits > 0) {	
					
						var s_url_produit;
						var i = 0;
						$(".infos_produits_recherche").html("");
						$(".liste_produits_recherche .boutons_produit").show();
						
						var html_kit = "<img class='img_kit_gratuit' src = '/imgs/default/etiquette_kit_gratuit.png' />";
						var kit;
                        var type_produit;
                        var id_produit_publication;
                        var infos_produits_recherche = "";
						
						$.each(object.infos_produit, function(i) {
						
							if (this.id_produits_publications_kit != 0 && this.id_produits_publications_kit != null) {
							
								kit = html_kit;
                                //id_produit_publication = this.id_produits_publications_kit;
                                type_produit = 4;
								
							} else {
							
								kit = "";
                                type_produit = 1;
								
							}
							
							id_produit_publication = this.id_produit_publication;
                            
							if (i == 0) {     
                                
								$(".liste_produits_recherche .right .visuel").html("<a class='lien_produit' href='" + this.url_production + "/" + this.url_nom_produit + "/" + this.id_produit_publication + "/produit' rel='" + id_produit_publication + '.' + type_produit + "'><img alt='' title='' src='" + this.url_image + "' /></a>");
								$(".liste_produits_recherche .right .visuel_txt").html("<a class='lien_produit' href='" + this.url_production + "/" + this.url_nom_produit + "/" + this.id_produit_publication + "/produit' rel='" + id_produit_publication + '.' + type_produit + "'>" + kit + "<p class='slogan_produit'>" + this.slogan + "</p><p class='resume_produit'>" + this.resume + "</p></div></a>");
								$(".liste_produits_recherche .boutons_produit .btn_infos").attr("href", this.url_production + "/" + this.url_nom_produit + "/" + this.id_produit_publication + "/produit");

							}
          
                            infos_produits_recherche += "<div class='un_produit' rel='" + id_produit_publication + '.' + type_produit + "'>";
                            infos_produits_recherche += "   <div class='img_cachee'>" + this.url_image + "</div>";
                            infos_produits_recherche += "   <div class='description_cachee'><a>" + kit + "<p class='slogan_produit'>" + this.slogan + "</p><p class='resume_produit'>" + this.resume + "</p></a></div>";
                            infos_produits_recherche += "   <div class='url_cachee'>" + this.url_production + "/" + this.url_nom_produit + "/" + this.id_produit_publication + "/produit" + "</div>";
                            infos_produits_recherche += "   <div class='en_vente'>" + this.en_vente + "</div>";
                            infos_produits_recherche += "</div>";
							
							$(".infos_produits_recherche").append(infos_produits_recherche);
						
							// Bouton info
							$(".recherche_autocompletion").append("<a class='lien_produit' href='" + this.url_production + "/" + this.url_nom_produit + "/" + this.id_produit_publication + "/produit' rel='" + id_produit_publication + '.' + type_produit + "'><div class='produit' rel='" + id_produit_publication + '.' + type_produit + "'>" + this.description_courte + "</div><div rel='" + this.id_produit_publication + '.' + type_produit + "' class='infos_commandes'></div></a>");
						});

						if (object.nb_produits > 8) {
							$(".scroll_bottom").show();
						}
						else {
							$(".scroll_bottom").hide();
						}
						
						//selection premier produit
						$(".liste a div:first").addClass("produit_actif");
						var rel = $(".liste a div:first").attr("rel");
                        
						survoler_produit();
						clearTimeout(timer_alterner);
						timer_alterner = setTimeout("afficher_bouton_infos_commandes(" + rel + ")", 1000);
					
					}
					else {
						$(".liste_produits_recherche .boutons_produit").hide();
						$(".message_recherche").html("Aucun résultat ne correspond à votre recherche.").show();
					}
					
					$(".liste_produits_recherche").show();
					
				}
			});
		}
	}
	else {

		if(!($.browser.msie && $.browser.version == "6.0" || $.browser.msie && $.browser.version == "7.0")) {
			// Disparition du fond blanc
			$("#white_mask").stop().animate({
				opacity: 0
			}, vitesse_animation, function() {           
				$("#white_mask").hide();
				$("#rechercher_un_produit").css("z-index", "1");
				$("#zone_recherche").css("z-index", "1");
			});
		}
        else {
            $("select").show();
        }
		
		$(".liste_produits_recherche").hide();
		
	}
}

// Fait apparaitre en alternance "infos & commandes"
function afficher_bouton_infos_commandes(rel) {

	$(".infos_commandes[rel=" + rel + "]").fadeIn(1500);
	clearTimeout(timer_alterner);
	timer_alterner = setTimeout("afficher_nom_produit(" + rel + ")", 2000);

}

// Fait apparaitre le nom du produit
function afficher_nom_produit(rel) {
	$(".infos_commandes[rel=" + rel + "]").fadeOut(1500);
	clearTimeout(timer_alterner);
	timer_alterner = setTimeout("afficher_bouton_infos_commandes(" + rel + ")", 2000);
	
}

//ajax : chargement du détail des produits
function survoler_produit() {
	$(".liste_produits_recherche .produit").mouseover(function() {
	
		var rel = $(this).attr("rel");		
		var img = $(".infos_produits_recherche .un_produit[rel=" + rel + "] .img_cachee").html();
		var url = $(".infos_produits_recherche .un_produit[rel=" + rel + "] .url_cachee").html();
        var en_vente = $(".infos_produits_recherche .un_produit[rel=" + rel + "] .en_vente").html();
		var visuel_txt = "";
		
		clearTimeout(timer_alterner);
		
		$(".recherche_autocompletion .infos_commandes").each(function() {
			if ($(this).attr("rel") != rel) {
				$(this).hide();
			}
		});
		
		if ($(".infos_produits_recherche .un_produit[rel=" + rel + "] .description_cachee").html() != "null") {
			visuel_txt = $(".infos_produits_recherche .un_produit[rel=" + rel + "] .description_cachee").html();
		}
        
		$(".liste_produits_recherche .right .visuel").html("<img src='" + img + "' alt='' title='' />");
		$(".liste_produits_recherche .right .visuel_txt").html(visuel_txt);
		$(".liste_produits_recherche .right .boutons_produit .btn_infos").attr("href", url);
		
		$(".bt_infos_commandes").each(function() {
			$(this).removeClass("bt_infos_commandes").addClass("produit").html($(this).attr("value"));
		});
		
		$(".liste_produits_recherche .produit").removeClass('produit_actif');
		$(this).addClass('produit_actif');
		
		timer_alterner = setTimeout("afficher_bouton_infos_commandes(" + rel + ")", 1000);	

	});
}

//defilement univers
function afficher_fond_noir() {

	// Afficher la grande bulle avec tous les univers
	$("#agrandir_bulle").live("click", afficher_univers);

	// Stop le défilement
	clearTimeout(timer_defilement);
	
	$("#barre_acces").css("z-index", 1);
	
	$("#black_mask").show();
	$("#agrandir_bulle").show();
	
	// Si IE6, on cache tous les select qui apparaissent par dessus le masque
	if($.browser.msie && $.browser.version == "6.0") {
		$("select").hide();
	}

	// Apparition du fond noir
	$("#black_mask").stop().animate({
		opacity: 0.50
	}, vitesse_animation);
	
	// Apparition du bouton tout voir
	$("#agrandir_bulle").stop().animate({
		opacity: 1
	}, vitesse_animation);

}

//survole initiatives bulle haut gauche
function afficher_description_initiatives() {
	$("#description_initiatives").show();
	$(this).children("img").hide();
}

function cacher_description_initiatives() {
	$("#description_initiatives").hide();
	$("#univers_logo_initiatives").children("img").show();
}

//survole univers bulle haut gauche
function afficher_description() {

	var hauteur_description = $(this).children(".description_univers").height();
	var hauteur_picto = $(this).children(".picto").height();
	var hauteur_logo = $(this).children(".logo_simplifie").height();

	// Centre verticalement la description	
	var top = (hauteur_picto + hauteur_logo) / 2 - hauteur_description / 2;
	
	$(this).children(".description_univers").css("top", top).show();
	$(this).children(".picto").hide();
	$(this).children(".logo_simplifie").hide();

}

function cacher_description() {
	$(".un_univers").children(".description_univers").hide();
	$(".un_univers").children(".picto").show();
	$(".un_univers").children(".logo_simplifie").show();
}

//animation bulle
function afficher_univers() {
	
	$("#agrandir_bulle").hide();
	
	var top = "";
	var left = "";

	$(".petite_bulle_univers").addClass("grande_bulle_univers");
    $(".grande_bulle_univers").removeClass("petite_bulle_univers");
	$("#bulle_univers").stop().animate({
		width: 483,
		height: 329,
		top: 20
	}, vitesse_animation, function() {});

	// Déplacement de tous les logos d'univers
	$("#univers_0").stop().animate({
		top: 20,
		left: 71
	}, vitesse_animation, function() {
	
		$("#univers_logo_initiatives").fadeIn();
		$("#fermer_bulle").show();
	
	});
	
	$("#univers_1").stop().animate({
		top: 20,
		left: 191
	}, vitesse_animation, function() {});
	
	$("#univers_2").stop().animate({
		top: 20,
		left: 314
	}, vitesse_animation, function() {});
	
	$("#univers_3").stop().animate({
		top: 20,
		left: 429
	}, vitesse_animation, function() {});
	
	$("#univers_4").stop().animate({
		top: 120,
		left: 71
	}, vitesse_animation, function() {});
	
	$("#univers_5").stop().animate({
		top: 120,
		left: 429
	}, vitesse_animation, function() {});
	
	$("#univers_6").stop().animate({
		top: 220,
		left: 71
	}, vitesse_animation, function() {});
	
	$("#univers_7").stop().animate({
		top: 220,
		left: 191
	}, vitesse_animation, function() {});
	
	$("#univers_8").stop().animate({
		top: 220,
		left: 314
	}, vitesse_animation, function() {});
	
	$("#univers_9").stop().animate({
		top: 220,
		left: 429
	}, vitesse_animation, function() {
		
		$("#univers_logo_initiatives").live("mouseenter", afficher_description_initiatives);
		$(".un_univers").live("mouseenter", afficher_description);
		$("#univers_logo_initiatives").live("mouseleave", cacher_description_initiatives);
		$(".un_univers").live("mouseleave", cacher_description);
	
	});

}

function cacher_univers() {

    cacher_description();

	$("#agrandir_bulle").die("click", afficher_univers);

	var a_left = new Array();
	
	// Position de tous les univers
	a_left["0"] = 15;
	a_left["1"] = 144;
	a_left["2"] = 273;
	a_left["3"] = 402;
	a_left["4"] = 531;
	a_left["5"] = 660;
	a_left["6"] = 789;
	a_left["7"] = 918;
	a_left["8"] = 1047;
	a_left["9"] = 1176;

	$("#univers_logo_initiatives").die("mouseenter", afficher_description_initiatives);
	$(".un_univers").die("mouseenter", afficher_description);
	$("#univers_logo_initiatives").die("mouseenter", cacher_description_initiatives);
	$(".un_univers").die("mouseleave", cacher_description);
	
	// Relance le défilement
	setTimeout_lancer_defilement();

	$("#fermer_bulle").hide();
	$("#univers_logo_initiatives").fadeOut("fast");
	
	// Disparition du fond noir
	$("#black_mask").stop().animate({
		opacity: 0
	}, vitesse_animation, function() {
	
		$("#black_mask").hide();
		$("#barre_acces").css("z-index", 204);
		
		// IE6: réapparition des select
		if($.browser.msie && $.browser.version == "6.0") {
			$("select").show();
		}
		
	});
	
	// Disparition du bouton tout voir
	$("#agrandir_bulle").stop().animate({
		opacity: 0
	}, vitesse_animation, function() {});
	
	// Réduction de la bulle
	$("#bulle_univers").stop().animate({
		width: 274,
		height: 104,
		top: top_bulle
	}, vitesse_animation, function() {});

	var pos;
	var nb_univers = $(".un_univers").length;
	var i = 0;
	
	// Repositionnement de chaque logo
	$(".un_univers").each(function() {
	
		pos = $(this).attr("rel");
		
		if (i != (nb_univers-1)) {
			$(this).stop().animate({
				top: 7,
				left: a_left[pos]
			}, vitesse_animation, function() {});
		}
		else {
			$(this).stop().animate({
				top: 7,
				left: a_left[pos]
			}, vitesse_animation, function() {

                $(".grande_bulle_univers").addClass("petite_bulle_univers");
                $(".petite_bulle_univers").removeClass("grande_bulle_univers");
				
			});
		}

		i++;
	});
	
}

// Défilement automatique des univers dans le header
function defilement_univers() {

	var nb_univers = $(".un_univers").length;
	var i = 0;
	var rel;
	var val;
	var clone;
	
	$(".un_univers").each(function(i) {
	
		rel = $(this).attr("rel");
		val = $(this).attr("value");
	
		$(this).animate({
			left: "-=129"
		}, 1000, function() {
		
			if (i == nb_univers-1) {
		
				// on clone l'univers en tete de liste afin qu'il soit dupliqué en fin de liste
				clone = $(".un_univers:first").clone();
				$("#liste_univers").append(clone.css("left", "1176px"));
				
				// suppression du premier univers de la liste
				$(".un_univers:first").remove();	
			
				if ($("#black_mask").css("display") == "none") {
					timer_defilement = setTimeout("defilement_univers()", vitesse_defilement);
				}
				
				i = 0;
				$(".un_univers").each(function(i) {
					$(this).attr("rel", i);
				});

			}

		});
	
	});
	
}


// Lance le défilement des logos des univers
function setTimeout_lancer_defilement() {

	// Stop défilement des logos
	clearTimeout(timer_defilement);
	
	timer_defilement = setTimeout("defilement_univers()", vitesse_defilement);
}

// Formate un nombre au format monétaire
//à refaire en php
function format(nombre) {
	var num = new Number(nombre);
	num = num.toFixed(2); // Force deux chiffres après la virgule
	num = num.replace(".", ","); // Remplace le point (.) par une virgule (,)
	return num;
}

//verifie un mail
function verifier_mail(mail) {

	var reg = new RegExp('^[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*@[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*[\.]{1}[a-z]{2,6}$', 'i');

	return(reg.test(mail));
}

/*
Cryptage Javascript
*/
function JSdecrypt(c) {
	var r = new String;
	for (var i=0;i<c.length;i+=2) {
		r += String.fromCharCode(((isNaN(c.charAt(i))?c.charCodeAt(i)-87:parseInt(c.charAt(i),10))*16+(isNaN(c.charAt(i+1))?c.charCodeAt(i+1)-87:parseInt(c.charAt(i+1),10)))-2-(i/2)%3);
	}
	return r;
}

function set_fond_erreur_champ(id) {
	$("#" + id).css('background', '#fcf8c0');
}

function clear_fond_erreur_champ(cl) {
	$("." + cl).css('background', '#ffffff');
}

// Evenement change quanaité panache
function change_panache_qte_event() {
    
    $("#popup_ajout_panier .qte").keyup(function() {
        change_panache_qte($(this));
    });
    
}

// Remplis la ville en fonction d'un code postal
function select_ville_by_cp(code_postal, ville)
{
    
	switch (ville) {
		
        // Page cordonnées -> adresse établissement
		case '#formulaire_etablissement #coordonnees_ville': 
			var div = "liste_villes_coordonnees_etablissement";
			break;
		
        // Page coordonnées -> nouvelle adresse
		case '#nouvelle_adresse #ville':
			var div = "liste_villes_coordonnees";
			break;
		
        // Popup demande de catalogue
		case '#popup_demande_catalogue #catalogue_ville':
			var div = "liste_villes_catalogue";
			break;
		
        // Popup demande de contact
		case '#popup_contact #contact_ville':
			var div = "liste_villes_contact";
			break;
            
        // Inscription concours de dessins
        case '#inscription_ville':
            var div = "liste_villes_inscription";
            break;
		
	}
    
    $("#" + div + " .une_ville").die("click", select_ville);
	
	if (code_postal.length == 5) {
		$.ajax({
			type: 'post',
			url: '/adresses/get_ville_by_code_postal',
			dataType: 'json',
			data: 'code_postal=' + code_postal,
			success: function(response) {
				
				if (response.nb_villes > 1) {
					
					$("#" + div).html("").css("visibility", "visible");
					
                    if($.browser.msie && $.browser.version == "6.0") {
                        $("#popup_adresse_contact select").hide();
                    }
                    
					$.each(response.villes, function(id, city) {
						$("#" + div).append('<div class="une_ville" rel="' + city + '" value="' + ville + '">' + city + '</div>');
					});
					
					$("#" + div + " .une_ville").live("click", select_ville);
					
					$("#" + div + " .une_ville").mouseover(function() {
						$(this).css("background", "#ccc");
					}).mouseout(function() {
						$(this).css("background", "#fff");
					});
					
				}
				
				else if (response.nb_villes == 1) {
					$(ville).attr("value", response.villes[0]).css("color", "#000");
				}
			}
		});
	}
	
	else {
		$("#" + div).html("").css("visibility", "hidden");
	}
}

function select_ville()
{
	$("#liste_villes_coordonnees_etablissement").css("visibility", "hidden");
	$("#liste_villes_coordonnees").css("visibility", "hidden");
	$("#liste_villes_catalogue").css("visibility", "hidden");
	$("#liste_villes_contact").css("visibility", "hidden");
	$("#liste_villes_inscription").css("visibility", "hidden");
	
    if($.browser.msie && $.browser.version == "6.0") {
        $("#popup_adresse_contact select").show();
    }
    
	var nom_ville = $(this).attr("rel");
	var champs = $(this).attr("value");
    
	$(champs).val(nom_ville).css("color", "#000").blur();

}

function afficher_session_expiree() {
    $("#popup_session_expiree .message_erreur").html("Il semblerait que votre panier soit vide. <br />Merci d'ajouter des produits dans votre panier afin de finaliser la commande.<br /><br />Vous allez être redirigé dans quelques secondes.");
    $("#popup_session_expiree").overlay().load();
    $("#exposeMask, #popup_session_expiree .close, #popup_session_expiree .btn_redirection").click(function() {
        window.location.href = "/panier";
    });
    window.setTimeout("location=('/panier');", 10000);
}

function trim(myString) {
    return myString.replace(/^\s+/g,'').replace(/\s+$/g,'');
}

// Cache sous les overlay les vidéos venant de youtube
function fix_flash() {
    // loop through every embed tag on the site
    var embeds = document.getElementsByTagName('embed');
    for (i = 0; i < embeds.length; i++) {
        embed = embeds[i];
        var new_embed;
        // everything but Firefox & Konqueror
        if (embed.outerHTML) {
            var html = embed.outerHTML;
            // replace an existing wmode parameter
            if (html.match(/wmode\s*=\s*('|")[a-zA-Z]+('|")/i))
                new_embed = html.replace(/wmode\s*=\s*('|")window('|")/i, "wmode='transparent'");
            // add a new wmode parameter
            else
                new_embed = html.replace(/<embed\s/i, "<embed wmode='transparent' ");
            // replace the old embed object with the fixed version
            embed.insertAdjacentHTML('beforeBegin', new_embed);
            embed.parentNode.removeChild(embed);
        } else {
            // cloneNode is buggy in some versions of Safari & Opera, but works fine in FF
            new_embed = embed.cloneNode(true);
            if (!new_embed.getAttribute('wmode') || new_embed.getAttribute('wmode').toLowerCase() == 'window')
                new_embed.setAttribute('wmode', 'transparent');
            embed.parentNode.replaceChild(new_embed, embed);
        }
    }
    // loop through every object tag on the site
    var objects = document.getElementsByTagName('object');
    for (i = 0; i < objects.length; i++) {
        object = objects[i];
        var new_object;
        // object is an IE specific tag so we can use outerHTML here
        if (object.outerHTML) {
            
            var html = object.outerHTML;
            // replace an existing wmode parameter
            if (html.match(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")[a-zA-Z]+('|")\s*\/?\>/i))
                new_object = html.replace(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")window('|")\s*\/?\>/i, "<param name='wmode' value='transparent' />");
            // add a new wmode parameter
            else
                new_object = html.replace(/<\/object\>/i, "<param name='wmode' value='transparent' />\n</object>");
            // loop through each of the param tags
            var children = object.childNodes;
            for (j = 0; j < children.length; j++) {
                try {
                    if (children[j] != null) {
                        var theName = children[j].getAttribute('name');
                        if (theName != null && theName.match(/flashvars/i)) {
                            new_object = new_object.replace(/<param\s+name\s*=\s*('|")flashvars('|")\s+value\s*=\s*('|")[^'"]*('|")\s*\/?\>/i, "<param name='flashvars' value='" + children[j].getAttribute('value') + "' />");
                        }
                    }
                }
                catch (err) {
                }
            }
            // replace the old embed object with the fixed versiony
            object.insertAdjacentHTML('beforeBegin', new_object);
            object.parentNode.removeChild(object);
        }
    }
}
