$(function(){
	$(".toolTip").toolTips();
	$('a.lightbox').lightBox({
		overlayBgColor: '#B7CB52',
		overlayOpacity: 0.95,
		txtOf: '/'
   });
	$('#logo').click(function(){
		document.location.href = './';
	});
	$("div.example-7").carousel({ autoSlide: true, loop: true});
	// utiliser maintenant .fancyboxOpenContent pour les lightbox
	$(".fancyboxOpenContent").fancybox({
		'overlayColor' : '#9aad06'
	});
	$("#identification").fancybox({
		'overlayColor' : '#9aad06'
	});
	$("#identification2").fancybox({
		'overlayColor' : '#9aad06'
	});
	/*$("#etreprevenu").fancybox({
		'overlayColor' : '#9aad06'
	});*/
	$("a#annoncedetail").fancybox({
		'overlayColor' : '#9aad06'
	});
	$(".detailLivraison").fancybox({
		'overlayColor' : '#9aad06'
	});
	$('#filtre select').selectmenu({
		menuWidth: 200,
		style:'dropdown'
	});
	// autocomplete
	$("#recherche").autocomplete('include_vel/search.php', {
		width: 268,
		multiple: false,
		matchContains: true,
		formatItem: formatItem,
		formatResult: formatResult,
		max: 15,
		scrollHeight: 250,
		selectFirst: false
	});
	function formatItem(row) {
		return row[0];
	}
	function formatResult(row) {
		return row[1].replace(/(<.+?>)/gi, '');
	}
});

var timer3;


// UTIL

function bund(id){
	if(document.getElementById(id).style.display='none')
	{document.getElementById(id).style.display='block';}
	else
	{document.getElementById(id).style.display='none';}
} 
function cache(id){
	document.getElementById(id).style.display='none';
}
function cache_by_class(classe){
	jQuery('.'+classe).hide();
}
function montre_by_class(classe){
	jQuery('.'+classe).show();
}
function rewrite(my_string) {
	if(my_string!= ""){
		var reg = new RegExp("([ -!'])", "g");
		my_string = my_string.toLowerCase().replace(reg,"+");
		var pattern_accent = new Array("é", "è", "ê", "ë", "ç", "à", "â", "ä", "î", "ï", "ù", "ô", "ó", "ö", " ");
		var pattern_replace_accent = new Array("e", "e", "e", "e", "c", "a", "a", "a", "i", "i", "u", "o", "o", "o", "+");
		for (var i=0; i<pattern_accent.length; i++) {
			my_string = my_string.replace(pattern_accent[i], pattern_replace_accent[i]);
		} 
	}
	return my_string;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}



// GENERAL

function swap(elem1, elem2, size)
{
	if(size < 1){
		document.getElementById('corps').style.height = (parseInt(document.getElementById(elem2).offsetHeight)+15)+'px';
	}
	else{
		document.getElementById('corps').style.height = size;
	}
	document.getElementById(elem1).style.visibility = "hidden";
	document.getElementById(elem1).style.position = "absolute";
	document.getElementById(elem2).style.visibility = "visible";
}
function appear(elem)
{
	document.getElementById(elem).style.visibility = "visible";
}
function diseappear(elem)
{
	document.getElementById(elem).style.visibility = "hidden";
}
function appear_theme(id){
	var time = 500;
	var idbarre = 'barrederoulante'+id;
	var idmenu = 'menuderoulant'+id;
	if(readCookie('navtheme') != null){
		time = parseInt(time)-parseInt(time);
	}
	timer = setTimeout("appear('"+idbarre+"')", time);
	timer2 = setTimeout("change_couleursmenuderoulantactif('"+idmenu+"')", time);
}
function diseappear_theme(id){
	var idbarre = 'barrederoulante'+id;
	var idmenu = 'menuderoulant'+id;
	clearTimeout(timer);
	clearTimeout(timer2);
	diseappear(idbarre);
}
function change_couleursmenuderoulant(mode){
	if(mode == 1 && timer3 != 'undefined'){
		clearTimeout(timer3);
		createCookie('navtheme','1',3600);
	}
	else if(mode == '2'){
		timer3 = setTimeout("retablie_couleursmenuderoulant()", 500);
	}
}
function change_couleursmenuderoulantactif(idmenu){
	jQuery('td.index').css({background: "#C9C8BD"});
	document.getElementById(idmenu).style.background = "#AAA798";
}
function retablie_couleursmenuderoulant(){
	jQuery('td.index').css({background: "#C9C8BD"});
	jQuery('td.indexaz').css({background: "#AAA798"});
	jQuery('td.actif').css({background: "#AAA798"});
	eraseCookie('navtheme');
}
function _recherche(){
	var chaine = document.getElementById('recherche').value;
	chaine = rewrite(chaine);
	document.getElementById('recherche2').value = chaine;
}
function change_nouveaute(id) {
	if(id == 4){ id = 0; }
	id++;
	cache_by_class('encart_nouveaute_elem');
	jQuery('#encart_nouveaute_elem_'+id).fadeIn('low');
	setTimeout("change_nouveaute("+id+")",6000);
}
function change_choixmois(id) {
	if(id == 4){ id = 0; }
	id++;
	cache_by_class('encart_choixmois_elem');
	jQuery('#encart_choixmois_elem_'+id).fadeIn('low');
	setTimeout("change_choixmois("+id+")",8000);
}
function change_cadeau(id) {
	if(id == 4){ id = 0; }
	id++;
	cache_by_class('encart_cadeau_elem');
	jQuery('#encart_cadeau_elem_'+id).fadeIn('low');
	setTimeout("change_cadeau("+id+")",7000);
}
function change_promo(id) {
	if(id == 4){ id = 0; }
	id++;
	cache_by_class('encart_promo_elem');
	jQuery('#encart_promo_elem_'+id).fadeIn('low');
	setTimeout("change_promo("+id+")",7000);
}
function change_prefere(id) {
	if(id == 4){ id = 0; }
	id++;
	cache_by_class('encart_prefere_elem');
	jQuery('#encart_prefere_elem_'+id).fadeIn('low');
	setTimeout("change_prefere("+id+")",7000);
}
function change_suggestions(id) {
	if(id == 4){ id = 0; }
	id++;
	cache_by_class('encart_suggest_elem');
	jQuery('#encart_suggest_elem_'+id).fadeIn('low');
	setTimeout("change_suggestions("+id+")",7000);
}
function montre_inscripnewsletter(){
	var content3 = "";
	content3+= "Inscrivez-vous a notre newsletter et recevez des offres privilèges !<br /><br />";
	content3+= "<form name=\"form\" method=\"post\" action=\"./\"><input autocomplete=\"off\" style=\"margin-right:5px;\" class=\"floatLeft\" type=\"text\" name=\"nl_email\" value=\"adresse e-mail\" onfocus=\"this.value='';\" />";
	content3+= "<div onclick=\"document.form.submit();\" class=\"floatLeft buttonbrin_1\">VALIDER</div></form>";
	TINY.box.show(content3,0,0,0,0,0);
}
function montre_login(url){
	var content3 = "";
	content3+= "<form name=\"form\" method=\"post\" action=\""+url+"\"><input style=\"margin-right:5px;\" class=\"floatLeft\" type=\"text\" name=\"login\" value=\"identifiant\" onfocus=\"this.value='';\" /><br /><br /><input style=\"margin-right:5px;\" class=\"floatLeft\" type=\"password\" name=\"password\" value=\"mot de passe\" onfocus=\"this.value='';\" />";
	content3+= "<br /><br /><div onclick=\"document.form.submit();\" class=\"floatLeft buttonbrin_1\">VALIDER</div></form>";
	TINY.box.show(content3,0,0,0,0,0);
}
function close_tinybox(){
	jQuery('#tinybox').fadeOut('low');
	jQuery('#tinymask').fadeOut('low');
	/*jQuery('#fancybox-overlay').fadeOut('low');
	jQuery('#fancybox-outer').fadeOut('low');
	jQuery('#fancybox-wrap').fadeOut('low');*/
	//jQuery('#fancybox-tmp').fadeOut('low');
	//jQuery('#fancybox-loading').fadeOut('low');
	
	jQuery('#fancybox-overlay').remove();
	jQuery('#fancybox-outer').remove();
	jQuery('#fancybox-wrap').remove();
	jQuery('#fancybox-tmp').remove();
	jQuery('#fancybox-loading').remove();
	jQuery('#fancybox-content').remove();
	jQuery('#fancybox-close').remove();
	jQuery('#fancybox-title').remove();
}

// INTRO
/*function change_pavehome(id){
	if(id == 3){ id = 0; }
	id++;
	$('#pavehome li').hide();
	$('#pavehome #elem'+id).fadeIn('low');
	setTimeout("change_pavehome("+id+")",6000);
}*/

// LISTE PRODUITS

function filtre(url){
	/*switch(mode){
		case 'promotion':
			url = 'index.php?lien=promotion';
			break;
		case 'categorie':
			url = 'index.php?lien=promotion';
			break;
	}*/
	var marque = jQuery('#f_marque').attr('value');
	if(marque != '' && marque != undefined) url+= '&f_marque='+marque;
	var cat = jQuery('#f_cat').attr('value');
	if(cat != '' && cat != undefined) url+= '&f_cat='+cat;
	var tr = jQuery('#f_tr').attr('value');
	if(tr != '' && tr != undefined) url+= '&f_tr='+tr;
	var theme = jQuery('#f_theme').attr('value');
	if(theme != '' && theme != undefined){
		if(theme == 10) url+= '&f_theme=5,6';
		else url+= '&f_theme='+theme;
	}
	document.location.href= url;
}
function del_filtre(){

}

// COMPTE

function montre_identification(etape, redirect){
	if(etape == 0) TINY.box.show('index.php?lien=identification&redirect='+redirect,1,620,225,1,0);
	else if(etape == 1){
		jQuery('#container_identification #etapelogin2').hide();
		jQuery('#container_identification #etapelogin1').show();
	}
}
function montre_mamansrelais_depart(cp, dep){
	TINY.box.show('index.php?lien=mamansrelais_depart&cp='+cp+'&dep='+dep,1,620,0,1,0);
}
function identifie_user(redirect){
	var login = jQuery('.login').val();
	var mdp = jQuery('.mdp').val();
	var redirect = jQuery('.redirect').val();
	jQuery.ajax({
	  url: '?lien=identification&action=checklogin&login='+login+'&mdp='+mdp,
	  success: function(data){
		if(data > 0){
			document.form.submit();
			return true;
		}
		else{
			jQuery('#container_identification #etapelogin1').hide();
			jQuery('#container_identification #etapelogin2').show();
			return false;
		}
	  }
	});
	return false;
}

// PANIER

function montre_saisietel(){
	var content3 = 'Le mode de livraison choisi requiert un numéro de téléphone portable.<br />';
	content3+= 'Cellui-ci sera utilisé afin de vous prévenir de l\'acheminement de votre colis par SMS.<br /><br />';
	content3+= 'Mon numéro <input autocomplete="off" id="tel2" value="" onkeyup="valide_choixcoli(this.value, \'index.php?lien=panier&action=modeliv&mode=2#livraison\', \'0\');" type="text" maxlength="10" name="telport" />';
	TINY.box.show(content3,0,0,0,0,0);
}
/*function valide_choixcoli(tel, action, montresaisie){
	var tel = tel.replace(' ', '');
	var tel = tel.replace('.', '');
	var tel = tel.replace('-', '');
	var tel = tel.replace('_', '');
	if(document.getElementById('tel')){ document.getElementById('tel').value = tel; }
	if(document.getElementById('tel2')){ document.getElementById('tel2').value = tel; }
	if(Verifier_Numero_Telephone(tel, 'port')){
		document.getElementById('certif').checked = true;
		document.panier.action=action;document.panier.submit();
	}
	else{
		if(montresaisie == '1'){
			montre_saisietel();
		}
	}
}*/
function valide_livraison_socolissimo(mode){
	if(mode < 4){
		document.getElementById('certif').checked = true;
		if(mode == 2){
			//TINY.box.show('index.php?lien=confirmationpanier&mode=livraisonrdv',1,0,0,1);
		}
		else{
			document.panier.action = "index.php?lien=panier&action=modeliv&mode="+mode+"#livraison";
			document.panier.submit();
		}
	}
	else document.location.href = "so_envoi.html";
}
function verifpanier()
{
if (document.panier.action!="panier.html") {
	  if (document.panier.ok.value=="no") {
		 return false;
		 };
	/*if (document.panier.tel.value == '') {
		alert("Veuillez préciser votre numéro de téléphone portable.");
		return false;
	}*/
	  if (document.panier.certif.checked==false && document.panier.action!="devis.html") {
		 alert("Merci de certifier sur l\`honneur que vous avez pris connaissance des conditions générales de vente.");
		// popup('popup_panier_cgv');
		// document.body.style.overflow = "hidden";
		 return false;
		 //document.panier.certif.focus(); return false;
		 };
	  
	  if(document.panier.choix_prodlie.value != ""){
	    if(document.panier.action.search("commandech") != -1){
			popup('popup_panier_prodlie_ch');
		}
		else{
			popup('popup_panier_prodlie_cb');
		}
		document.body.style.overflow = "hidden";
		return false;
	  }
  }
}

function certifchecked(){
	if(jQuery('#certif2').attr('checked') == true) return true;
	else{
		alert("Merci de certifier sur l'honneur que vous avez pris connaissance des conditions générales de vente.");
		return false;
	}
}

function Verifier_Numero_Telephone(num_tel, mode)
{
// Definition du motif a matcher
if(mode == 'port'){
	var regex = new RegExp(/^(06)[0-9]{8}/gi);
}
else{
	var regex = new RegExp(/^(01|02|03|04|05|06|08)[0-9]{8}/gi);
}
// Definition de la variable booleene match
var match = false;

// Test sur le motif
if(regex.test(num_tel))
{
match = true;
}
else
{
match = false;
}

// On renvoie match
return match;
}
function submit_panier(mode, ht, refcookie){
	cto_pxl();
	if(mode == 'cb'){
		document.panier.action='commandecb.html';
	}
	else if(mode == 'ch'){
		document.panier.action='commandech.html';
	}
	else if(mode == 'pp'){
		document.panier.action='commandepp.html';
	}
	else if(mode == 'bc'){
		document.panier.action='commandebc.html';
	}
	jQuery('#shoppingflux').html('<img src="http://www.shopping-flux.com/tracking/?cl=Brindilles1973&mt='+ht+'&cmd='+refcookie+'" />');
	setTimeout("document.panier.submit()", 1000);
}


// PRODUIT

function enregistre_reappro(){
	var email = jQuery('.email').val();
	var ref = jQuery('.ref').val();
	jQuery.ajax({
	  url: '?lien=reappro&action=save&email_alerte_dispo='+email+'&ref='+ref,
	  success: function(data){
		if(data){
			jQuery('#msg').html("<p>Votre demande a bien été enregistrée.<br />Vous serez prévenu par email dès que cet article sera de nouveau disponible.</p>");
			jQuery('#continuer').show();
			jQuery('#form').hide();
		}
		else{
			jQuery('#msg').html("Votre adresse e-mail est invalide");
		}
	  }
	});
}
function montre_demandereappro(ref){
	TINY.box.show('index.php?lien=reappro&ref='+ref,1,600,175,1,0);
}
function montre_preciserquantite(){
	var content3 = "Veuillez préciser une quantité.";
	TINY.box.show(content3,0,0,0,0,3);
}
function ajoutepanier(){
	if(document.getElementById('totalcmd').innerHTML=='0.00'){
		montre_preciserquantite();
	} else{
		document.ref.act.value = 'pan';document.ref.submit();
	}
}
function ajouteln(){
	if(document.getElementById('totalcmd').innerHTML=='0.00'){
		montre_preciserquantite();
	} else{
		document.ref.act.value = 'ln';document.ref.submit();
	}
}
function total_commande() {
var totalite=0;
var quantite=0;
for (i=0;i<document.ref.length;i++) if (document.ref.elements[i].name.substr(0,3)=="qte") {
    total_ligne=document.ref.elements[i].value*document.ref.elements[i+1].value;
    totalite=totalite*1+total_ligne;
    quantite=quantite*1+document.ref.elements[i].value*1;
    document.getElementById('t'+document.ref.elements[i+1].name).innerHTML=format(total_ligne);
    }
	//alert(totalite);
    document.getElementById('totalcmd').innerHTML=format(totalite);
}
function format(valeur,decimal,separateur) {
// formate un chiffre avec 'decimal' chiffres après la virgule et un separateur

    if (decimal == undefined) decimal = 2;
    if (separateur == undefined) separateur = ' ';
	
	var deci=Math.round( Math.pow(10,decimal)*(Math.abs(valeur)-Math.floor(Math.abs(valeur)))) ; 
	var val=Math.floor(Math.abs(valeur));
	if ((decimal==0)||(deci==Math.pow(10,decimal))) {val=Math.floor(Math.abs(valeur)); deci=0;}
	var val_format=val+"";
	var nb=val_format.length;
	for (var i=1;i<4;i++) {
		if (val>=Math.pow(10,(3*i))) {
			val_format=val_format.substring(0,nb-(3*i))+separateur+val_format.substring(nb-(3*i));
		}
	}
	if (decimal>0) {
		var decim=""; 
		for (var j=0;j<(decimal-deci.toString().length);j++) {decim+="0";}
		deci=decim+deci.toString();
		val_format=val_format+"."+deci;
	}
	if (parseFloat(valeur)<0) {val_format="-"+val_format;}
	return val_format;
}
function change_quantite(mode, id){
	var max = parseInt(document.getElementById('quantite-max-'+id).value);
	var courant =  parseInt(document.getElementById('quantite-input-'+id).value);
	if(mode == '+' && parseInt(courant+1) <= max){
		jQuery('#quantite-input-'+id).val(parseInt(courant+1));
		jQuery('#quantite-view-'+id).html(parseInt(courant+1));
	}
	if(mode == '-' && parseInt(courant-1) >= 0){
		jQuery('#quantite-input-'+id).val(parseInt(courant-1));
		jQuery('#quantite-view-'+id).html(parseInt(courant-1));
	}
	if(mode == '' && parseInt(courant) > max){
		jQuery('#quantite-input-'+id).val(max);
		jQuery('#quantite-view-'+id).html(max);
		alert("Cette quantité n'est pas en stock");
	}
	total_commande();
}
