//recuepratio de parametres supplementaire: exp proix total des commandes
function addParam(resume_recherche,_class,param_supp,param_supp_1)
{
	//alert(resume_recherche+','+param_supp+','+_class);
	//prix total des commandes
	if(_class=='Orders')
	{		
		$('#total_commandes').html('Total des commandes en TTC : <b>' + param_supp+ ' €</b>');
		if(param_supp_1) 
		{
			$('#total_commandes').append('<br>Total des commandes (avec Frais de livraison) en TTC : <b>' + param_supp_1+ ' €</b>');
		}	
		$('#resume_recherche').html(resume_recherche);	
		//alert(resume_recherche);
		$('#search_3').show();
		
		//$('#search_3').animate({height:1,animated: 'easeslide'}).animate({height:200,animated: 'easeslide'});
	}	
}
/********************************************************************************************/
					/*Fonctions du generateur*/
/********************************************************************************************/
function loadFormGenerator()
{
	// bind 'myForm' and provide a simple callback function
	var options = {        
        beforeSubmit:  check_modele,  // pre-submit callback 
        success:   showResponse  // post-submit callback 
 
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }; 
 
    // bind form using 'ajaxForm' 
    $('#myFormGenerator').ajaxForm(options); 
}
// pre-submit callback 
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
    alert('About to submit: \n\n' + queryString); 
 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true; 
} 
 
// post-submit callback 
function showResponse(responseText, statusText)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 

	if(responseText=='modeleExiste')
	{
		$('#err').html('Le modèle que vous voulez créer existe déjà');		
	}
	else
	{		
		alert_simple('Le modèle a été créé');
		//$.prompt('Le modèle a été créé',{ buttons:{Ok:true}, prefix:'cleanblue',show:'slideDown'});
	}
} 
function check_modele(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
	$('#err').empty();	
	nom_table  = $('#nom_table').val();
	_nom_modele = $('#nom_modele').val();
	if(nom_table=='') 
	{		
		$('#err').html('Veuillez choisir une table');
		return false;
	}
	if(_nom_modele=='') 
	{		
		$('#err').html('Veuillez saisir le nom du modèle à créer');
		return false;
	}
	return true;	
}
/*
	Charger les attributs d'une table 
	Utilisée dans la generation des modeles
*/	

function charger_attributs(_nom_table)
{		
	nom_modele = firstCharToUpperCase(_nom_table) ;
	$('#nom_modele').val(nom_modele);
	$.get(
		"gestion/charger_attributs.php", 
		{nom_table:_nom_table}, 
		function(_html) 
		{						
			$('#liste_attributs').html(_html); 			
			//alert(_html);
		}
	);	
}
/********************************************************************************************/
					/*Gestion du menu*/
/********************************************************************************************/	
function loadMenuSoreted()
{	
	$('#ajax-response1').NestedSortableWidget({
		loadUrl: "gestion/gestion_menu.php?getAllMenu",
		onLoad: list_loaded_callback, 
		onLoadError: function() {
			alert('pb au chargement');
		}, 
		saveUrl:  "gestion/gestion_menu.php",
		onSave : function(callback) {
			$.prompt('La mise à jour c\'est bien effectuée',
			{ 
				buttons:{Ok:true}, 
				prefix:'cleanblue',
				show:'slideDown',
				callback: redirct
			});					
		},
		onSaveError : function(callback) {
			alert('Pb à la sauvegarde');
		},
		text: {
			saveButton: "Save"
		}
	});
}
	
function list_loaded_callback() 
{ 			
	//alert(this.);		
	$(".nsw-item").dblclick(function() 
	{ 
		liId = this.id; 		
		id  = liId.substr(9);			
		//alert($('#'+liId+' div:eq(1)').html())
		getTotemMenu(id);		
		return false; 
	}); 		
} 	
function redirct()
{
	document.location = 'login.php';
}

/*******************************/
  /*gestion du totem menu*/
/*******************************/
var etatTotemMenu = 0;
function getTotemMenu(_id)
{		
	 $.ajax({   
		type: "GET",   
		url: "gestion/gestion_menu.php",   
		data: "idMenu="+_id,   
		success: function(_html)
		{     
			//alert(_html);
			//$("#divTotemMenu").html(_html);
			//document.getElementById("divTotemMenu").innerHTML = _html;						
			var totem = new Totem('divTotemMenu','Menu','Menu',_html);							
			$("#divTotemMenu").show();			
			//mettre à jour les valeurs des fk_pere et fk_path			
			$('#fk_pere').val($('#value_fk_pere').val());
			$('#fk_path').val($('#value_fk_path').val());	 
		} 
	});	
}
function sendTotemMenu()
{
	if(checkTotemMenu())
	{
		id = $('#id').val();		
		//var param = $("input","#form1").serialize();
		var param = $('#form1').formSerialize();  			
		$("#divTotemMenu").hide();	
		$.ajax({   
			type: "GET",   
			url: "gestion/gestion_menu.php",   
			data: param,   
			success: function(nomMenu)
			{    
				if($('#mode').val()=='update')
				{
					/*$.prompt('La mise à jour c\'est bien effectuée',
					{ buttons:{Ok:true}, prefix:'cleanblue',show:'slideDown'});*/
					alert_simple('La mise à jour c\'est bien effectuée');
					//maj du nom du Menu qui vient d'etre modifié
					//alert(nomMenu);
					liId = 'nsw-item-'+id;
					$('#'+liId+' div:eq(1)').html(nomMenu);				
				}
				else
				{
					$.prompt('Le menu a été créé',
						{ buttons:{Ok:true}, prefix:'cleanblue',show:'slideDown',callback: reloadMenu});
				}
			} 
		});
	}
}
function checkTotemMenu()
{		
	if($('#nom').val() == '')
	{		
		//$.prompt('Veuillez indiquer le nom',{ buttons:{Ok:true}, prefix:'cleanblue',show:'slideDown'});
		alert_simple('Veuillez indiquer le nom');
		return false;
	}
	if($('#width_pos').val() == '')
	{
		//alert('Veuillez indiquer la largeur du menu');
		//$.prompt('Veuillez indiquer la largeur du menu',{ buttons:{Ok:true}, prefix:'cleanblue',show:'slideDown'});
		alert_simple('Veuillez indiquer la largeur du menu');
		return false;
	}
	if($('#top_pos').val() == '')
	{
		//alert('Veuillez indiquer la position Top du menu');
		//$.prompt('Veuillez indiquer la position Top du menu',{ buttons:{Ok:true}, prefix:'cleanblue',show:'slideDown'});
		alert_simple('Veuillez indiquer la position Top du menu');
		return false;
	}
	if($('#left_pos').val() == '')
	{
		//alert('Veuillez indiquer la position Left du menu');
		//$.prompt('Veuillez indiquer la position Left du menu',{ buttons:{Ok:true}, prefix:'cleanblue',show:'slideDown'});
		alert_simple('Veuillez indiquer la position Left du menu');
		return false;
	}	
	return true;
}
function reloadMenu()
{
	document.location = 'gestion_menu.php';
}

/********************************************************************************************/
					/*GESTION DU LISTING*/
/********************************************************************************************/
//parametres du flexi grid : util dans le cas du retour de la page de creation ou de maj
var flex_width;//largeur
var flex_height;//hauteur
var flex_sortorder;//ordre de tri
var flexsortname; //clé de tri
var	flex_page;//numero de la page
var flex_rp;//nombre d'elements par page

//Recherche dans le listing*************
function recherche(_class,url_read)
{ 	
	var params = $('#fb0').formSerialize();
	//alert(params);	
	jQuery('#flex_'+_class).flexOptions({newp:1, url: url_read+'?'+getTime()+'&'+params});
	jQuery('#flex_'+_class).flexReload();
	
	return false;	
}
//Recherche des affilés il existe deux mode : complet - resumé*****************
var MODE_COMPLET = 'non_active';
function recherche_Orders_affiliate(url_read)
{ 			
	if(document.forms['fb0'].elements['mode_1'][0].checked) mode = 'resume';		
	else mode = 'complet';
	
	var params = $('#fb0').formSerialize();  
	
	//mode complet des affiliés	
	if(mode == 'complet')
	{
		//mode complet pas encore activé
		if(MODE_COMPLET == 'non_active')
		{
			activer_mode_complet(params+'&mode='+mode);
			MODE_COMPLET = 'active';
		}
		else
		{		
			jQuery('#flex_Orders_affiliate_complet').flexOptions({newp:1, 											
										url: url_read+'?'+getTime()+'&'+params+'&mode='+mode});
			jQuery('#flex_Orders_affiliate_complet').flexReload();					
		}
		$('#div_resume').hide();
		$('#div_complet').show();
	}
	else
	{		
		jQuery('#flex_Orders_affiliate_resume').flexOptions({newp:1, 											
										url: url_read+'?'+getTime()+'&'+params+'&mode='+mode
										});
		jQuery('#flex_Orders_affiliate_resume').flexReload();
		$('#div_complet').hide();
		$('#div_resume').show();		
	}	
	
	return false;	
}

function recherche_Orders_statistique(url_read)
{	
	var param = $('#fb0').formSerialize();  
	jQuery('#recherche_Orders_statistique').flexOptions({newp:1, 											
										url: url_read+'?from_recherche=1&'+getTime()+'&'+param});
			
	jQuery('#recherche_Orders_statistique').flexReload(); 
	jQuery('#recherche_Orders_statistique').flexOptions({newp:1, 											
										url: url_read+'?'+getTime()});
	return false;
}

function recherche_Taille_statistique(url_read)
{	
	var param = $('#fb0').formSerialize();  
	jQuery('#recherche_Taille_statistique').flexOptions({newp:1, 											
										url: url_read+'?from_recherche=1&'+getTime()+'&'+param});
			
	jQuery('#recherche_Taille_statistique').flexReload(); 
	jQuery('#recherche_Taille_statistique').flexOptions({newp:1, 											
										url: url_read+'?'+getTime()});
	return false;
}

//passage du mode resumé au mode complet pour un afilié
//maj du champ affilié et du mode complet
//relancer la recherche
function switchToModeComplet(id_affiliate)
{
	$('#fk_affiliate').val(id_affiliate);
	fb0.mode_1[1].checked = 'checked';
	recherche_Orders_affiliate();
}
//maj du resumé de la rechrche dans la page des affiliés et des commandes
function updateInfosRecherche(fk_affiliate,dateofb1,dateofb2,fk_meansofpayment,
								 fk_state_1,fk_state_2,fk_state_3,fk_state_4,fk_state_5,fk_state_6,
								 fk_state_7,fk_state_8,fk_state_9,fk_state_10,fk_state_11,fk_state_12,fk_state_13)
{
	infos_date = '';
	if(dateofb2=='') dateofb2 = "13/08/2008";
	if(dateofb1=='')
	{
		infos_date = 'jusqu\'au '+dateofb2; 
	}else
	{
		infos_date = 'du '+dateofb1+' au '+dateofb2;
	}
	$('#date_commande_selected').html(infos_date);
}
//suppresison d'un element du listing*************
function validate_delete(className,id)
{	
	//si c'est une couleur on verifie si elle n'est pas associée à un produit
	if(className=='Couleur')
	{
		$.ajax({
		   type: "POST",
		   dataType: "html",
		   url: "existAssociateProduct.php",
		   data: "id="+id,
		   success: function(exist)
		   {
				if(exist==true)
				{
					alert_simple("Cette couleur est associée à un produit.\nVous ne pouvez pas la supprimer.");
				}
				else
				{
					var txt  = 'Confirmez vous la suppression de cet élément ?';
					txt += '<input type="hidden" id="className" name="className" value="'+className+'" />';
					txt += '<input type="hidden" id="id" name="id" value="'+id+'" />';
					$.prompt(txt,{callback: delete_element,  buttons: { Oui: 'oui', Non: 'non'},prefix:'cleanblue',show:'slideDown'});
				}
		   }
		});	
	}
	else
	{	
		var txt  = 'Confirmez vous la suppression de cet élément ?';
		txt += '<input type="hidden" id="className" name="className" value="'+className+'" />';
		txt += '<input type="hidden" id="id" name="id" value="'+id+'" />';
		$.prompt(txt,{callback: delete_element,  buttons: { Oui: 'oui', Non: 'non'},prefix:'cleanblue',show:'slideDown'});
	}
}
function delete_element(action,m)
{
	if(action=='oui')
	{
		className =  m.children('#className').val();	
		id =  m.children('#id').val();	
		$.ajax({
		   type: "POST",
		   dataType: "html",
		   url: "delete_ajax.php",
		   data: "id="+id+"&className="+className,
		   success: function(data){			
		   $('#flex_'+className).flexReload();
		   }
		});	
	}    
}
//create ou udpate d'un element du listing*************
var etatTotemElement = 0;
function getTotemElement(_id,page,name,_defaultWidth,_defaultHeight,_minWidth,_minHeight,_maxWidth,_maxHeight)
{
	//alert(_id+','+page+','+name+','+_defaultWidth+','+_defaultHeight+','+_minWidth+','+_minHeight+','+_maxWidth+','+_maxHeight);
	//page = "category_create.php";
	$.ajax({
		type: "GET",
		url: ""+page,
		data: "id="+_id+"&"+getTime(),
		success: function(_html)
		{
			/*
			initGestionTotem('divTotemElement','Element',name,_html,
												_defaultWidth,_defaultHeight,_minWidth,_minHeight,_maxWidth,_maxHeight);
			*/
			var totem = new Totem('divTotemElement','Element',name,_html,
												_defaultWidth,_defaultHeight,_minWidth,_minHeight,_maxWidth,_maxHeight);
			//positionner un div au milieu de la page
			centerDiv($("#divTotemElement"));
			$("#divTotemElement").show('slow');
			//optionsLoad();
			//charger les valeurs des intervalles de tailles et de de couleurs
			if(page=='product_update.php' && $('#fk_intervalle_taille').val()!='' && $('#fk_intervalle_couleur').val()!='')
			{
				//generateOptions(_id,totem);
				/*keepstate_orders_colors();
				$('#fk_order_3').val(3);
				alert($('#fk_order_3').val());
				*/
			}
		}
	});
}
function sendTotemElement(_id,_class,page,mode)
{		
	//recuepration des categories et themes associés
	if(_class=='Product')
	{
		var IdsCategories 	= catsSend(); 	
		$('#IdsCategories').val(IdsCategories);
		//var IdsTopic 		= topicSend();	
		//$('#IdsTopic').val(IdsTopic);
	}	
	
	var param = $('#form_'+_class).formSerialize();  
	
	$('#form_'+_class).ajaxForm({ 
		url: ""+page,
        success: function(_html) 
		{			
			retourTpln = $(_html);
			//
			val = $('#div_err_form_'+_class,retourTpln).html();	
			//si val==null cad que le serveur a envoyer un message d'erreur=>CATALOGUE BLOQUE 
			if(val==null)
			{					
				$('#totemElementContent').html(_html);	
				return;
			}			
			//verifier si le serveur n'a pas envoyer d'erreurs
			if(val!='')
			{			
				$('#div_err_form_'+_class).html(val);
			}				
			else
			{
				$("#divTotemElement").hide();
				$('#flex_'+_class).flexReload();								
			}
			
			if(_class=='Product') 
			{
				catsLoad();
				//topicLoad();				
			}
			
        }
    });
	//
	$('#form_'+_class).submit();	
}

function flexReload(_class,m)
{
	$('#flex_'+_class).flexReload();
}
//redirection vers la page de creation des elements
function create_elmt(page_create,redirect)
{
	window.location = page_create+'?redirect='+redirect+'&fw='+flex_width+'&fh='+flex_height
					+'&fo='+flex_sortorder+'&fn='+flexsortname+'&fp='+flex_page+'&fr='+flex_rp;
}
//redirection vers la page de mise à jour des produits
function update_elmt(page_update,id,redirect,id_search)
{
	search = $("#"+id_search).val();
	new_page = page_update+'?id='+id+'&redirect='+redirect+'&fw='+flex_width+'&fh='+flex_height
					+'&fo='+flex_sortorder+'&fn='+flexsortname+'&fp='+flex_page+'&fr='+flex_rp+'&search='+search;
	if(id_search=='search_Product')
	{
		fk_category1 = $("#fk_category1").val();
		fk_category2 = $("#fk_category2").val();
		fk_category3 = $("#fk_category3").val();
		fk_trade = $("#fk_trade").val();
		new_page += '&s_cat1='+fk_category1+'&s_cat2='+fk_category2+'&s_cat3='+fk_category3+'&s_trade='+fk_trade;
	}
	if(id_search=='search_Orders')
	{
		dateofb1 = $('#dateofb1').val();
		dateofb2 = $('#dateofb2').val();
		fk_meansofpayment = $('#fk_meansofpayment').val();
		new_page += '&dateofb1='+dateofb1+'&dateofb2='+dateofb2+'&fk_meansofpayment='+fk_meansofpayment;
		
		//les etats de la commande				
		for(var i=1;i<=20;i++)
		{
			if(document.getElementById('fk_state_'+i)) 
			{
				if(document.getElementById('fk_state_'+i).checked) 
				{
					new_page += '&fk_state_'+i+'='+$('#fk_state_'+i).val();
				}
				else new_page += '&fk_state_'+i+'=';
			}			
		}
		
	}
	window.location = new_page;
}
//redirection du bouton annuler de la page de create/maj vers le read
/*function retour_read(page_redirect,sortname,sortorder,width_flex,height_flex,rp_flex,page_flex,search)
{
	window.location = page_redirect+'?fw='+width_flex+'&fh='+height_flex
								+'&fo='+sortorder+'&fn='+sortname+'&fp='+page_flex+'&fr='+rp_flex+'&search='+search;
}*/
function retour_read(page_redirect,add_url)
{	
	window.location = page_redirect+'?'+add_url;
}
//envoie du formulaire d'une page en ajax
//function sendPageElement(_id,_class,page,page_redirect,sortname,sortorder,width_flex,height_flex,rp_flex,page_flex,search)
function sendPageElement(_id,_class,page,page_redirect,add_url)
{
	//recuepration des categories et themes associés
	if(_class=='Product')
	{
		var IdsCategories 	= catsSend(); 	
		$('#IdsCategories').val(IdsCategories);
		//var IdsTopic 		= topicSend();	
		//$('#IdsTopic').val(IdsTopic);
	}
	
	var param = $('#form_'+_class).formSerialize();
	
	$('#form_'+_class).ajaxForm({
		url: page,
        success: function(_html)
		{
			var resultat = _html.indexOf('redirect'); 			
			//alert(Resultat);
			if(resultat!=-1)
			{				
				//redirection
				/*window.location = page_redirect+'?fw='+width_flex+'&fh='+height_flex
									+'&fo='+sortorder+'&fn='+sortname+'&fp='+page_flex+'&fr='+rp_flex+'&search='+search;*/
				//alert(add_url);
				window.location = page_redirect+'?'+add_url;
				return;
			}
			retourTpln = $(_html);
			//
			val = $('#div_err_form_'+_class,retourTpln).html();	
			//si val==null cad que le serveur a envoyer un message d'erreur=>CATALOGUE BLOQUE 
			if(val==null)
			{					
				$('#div_contenu').html(_html);	
				return;
			}			
			//verifier si le serveur n'a pas envoyer d'erreurs
			if(val!='')
			{					
				$('#div_err_form_'+_class).html(val);
			}							
			if(_class=='Product') 
			{
				catsLoad();			
				//topicLoad();
			}
        }
    });
	//
	$('#form_'+_class).submit();	
}
/********************************************************************************************/
					/*Affiliate Category*/
/********************************************************************************************/
function loadAffiliateCategory(id_affiliate)
{	
	//tout effacer
	$('input:checkbox').attr('checked',false);
	if(id_affiliate=='tous' || id_affiliate=='-1') return;
	$.ajax({
	   type: "POST",
	   dataType: "script",
	   url: "get_affiliate_category.php",
	   data: "id="+id_affiliate,
	   success: function(data){}
	});	
}
//affirmation de la creation des fichiers CSV pour les affiliés*************
function validate_create_csv()
{	
	_data = $("select[@id=fk_affiliate]").serialize();	
	$.ajax({
	   type: "POST",
	   dataType: "html",
	   url: "get_name_affiliate.php",
	   data: _data,
	   success: function(name_affiliate)
	   {
			var txt  = 'Type de fichier à générer pour '+name_affiliate+' :</br>';	
			txt += '<table border="0" width="70%">';
			txt += '<tr><td width="20"></td><td>XML et CSV</td><td><input type="radio" name="type_fichier" value="tous" checked ';
			txt += '	onClick="$(\'#type_fichier_val\').val(this.value);"/></td></tr>';
			txt += '<tr><td></td><td>CSV</td><td><input type="radio" name="type_fichier" value="csv" ';
			txt += '	onClick="$(\'#type_fichier_val\').val(this.value);"/></td></tr>';
			txt += '<tr><td></td><td>XML</td><td><input type="radio" name="type_fichier" value="xml" ';
			txt += '	onClick="$(\'#type_fichier_val\').val(this.value);"/></td></tr>';
			txt += '</table>';
			txt += '<input type="hidden" id="type_fichier_val" value="tous" />';
			
			$.prompt(txt,
						{
							callback: create_csv,  
							buttons: { Oui: 'oui', Non: 'non'},
							prefix:'cleanblue',show:'slideDown'
						});
	   }
	});	
}
function create_csv(action,m)
{
	if(action=='oui')
	{		
		type_fichier = m.children('#type_fichier_val').val();		
		//alert('affiliate_export_read.php?upload&type_fichier='+type_fichier);
		document.getElementById('fb0').action='affiliate_export_read.php?drawer=24&upload&type_fichier='+type_fichier;		
		document.getElementById('fb0').submit();    
	}    
}
function openDivXML(nom)
{	
	$.ajax({
		type: "POST",
		url: "get_affiliate_file_xml.php",
		data: "nom="+nom,
		success: function(_html)
		{
			retour  = "<table width='100%' border='0'><tr><td colspan='2' height='20px'></td></tr>";
			retour += "<tr><td width='10'></td><td>"+_html+"</td></tr></table>";

			//initGestionTotem('divTotemXML','Element','Export XML pour l\'affilié '+nom,retour,900,800,100,40);
			var totem = new Totem('divTotemXML','Element','Export XML pour l\'affilié '+nom,retour,900,800,100,40,1500,1500);
			$("#divTotemXML").show();
		} 
	});	
	
}
/**********************************************************************************************/
/*****************************affectation de plusieurs categorie à un produit**************************/
/**********************************************************************************************/
var CategoriesSecondaires =  new Array();
	
function catsLoad()
{
	// on efface tout		
	while(document.getElementById('CatsC').options.length > 0)
		document.getElementById('CatsC').options[0] = null;
	
	// on recharge		
	for(i=0; i <  CategoriesSecondaires.length; i++)
	{			
		tab = CategoriesSecondaires[i];
		new_el = new Option(tab[1], tab[0]);
		document.getElementById('CatsC').options[document.getElementById('CatsC').length] = new_el;
	}		
}

function catsAdd()
{
	// on vérifie qu'il y a une selection		
	if(document.getElementById('CatsP').value=='')
	{
		alert("Vous devez choisir une catégorie");
		return;
	}
	
	// on regarde si la valeur est présente
	if(catsExits())
	{
		alert("Cette catégorie est déjà sélectionnée");
		return;			
	}
	
	//la nouvelle categorie	
	index = document.getElementById('CatsP').options.selectedIndex;		
	
	_value = document.getElementById('CatsP').options[index].value;		
	_text  = document.getElementById('CatsP').options[index].text;				
	
	document.getElementById('CatsP').options.selectedIndex = -1;	
	arg 	= new Array();
	arg[0] 	= _value;	
	//qq = _text.replace(/(\r\n|\n|\r|\s)/g, 'q');
	arg[1] 	= $.trim(_text);		
	CategoriesSecondaires[CategoriesSecondaires.length] = arg;	
	//maj du delai de livraison du produit	
	$.ajax({   
		type: "GET",   
		url: "get_category_delivery.php",   
		data:'id='+_value,   		
		success: function(delivery)
		{
			$('#delivery').val(delivery);
		} 
	});	  
	//recharge
	catsLoad();				
}

function catsExits()
{		
	for(i=0; i <  CategoriesSecondaires.length; i++)
	{
		tab   = CategoriesSecondaires[i];
		id 	  = tab[0];
		if(document.getElementById('CatsP').value == id)
			return true;
	}
	
	return false;
}

function catsDel()
{
	// on vérifie qu'il y a une selection		
	if(document.getElementById('CatsC').value=='')
	{
		alert("Vous devez choisir une catégorie");
		return;
	}
	
	// on supprime la valeur
	value_del = document.getElementById('CatsC').value;
	tmp      = CategoriesSecondaires;
	CategoriesSecondaires =  new Array();		
	for(i=0; i <  tmp.length; i++)
	{			
		if(value_del != tmp[i][0])
		{	
			CategoriesSecondaires[CategoriesSecondaires.length] = tmp[i];				
		}
	}
			
	catsLoad();
}
function catsSend()
{
	var content = '';
	
	for(i=0; i <  CategoriesSecondaires.length; i++)
	{			
		if(i!=0) content += ',';
		content += CategoriesSecondaires[i][0];						
	}		
	return content;
}
/**********************************************************************************************/
/*****************************affectation de plusieurs themes à un produit**************************/
/**********************************************************************************************/
var Themes =  new Array();
	
function topicLoad()
{
	// on efface tout		
	while(document.getElementById('TopicC').options.length > 0)
		document.getElementById('TopicC').options[0] = null;
	
	// on recharge		
	for(i=0; i <  Themes.length; i++)
	{			
		tab = Themes[i];
		new_el = new Option(tab[1], tab[0]);		
		document.getElementById('TopicC').options[document.getElementById('TopicC').length] = new_el;
	}	
}

function topicAdd()
{
	// on vérifie qu'il y a une selection		
	if(document.getElementById('TopicP').value=='')
	{
		alert("Vous devez choisir un thème");
		return;
	}
	
	// on regarde si la valeur est présente
	if(topicExits())
	{
		alert("Ce thème est déjà sélectionné");
		return;			
	}
	
	//le nouveau theme
	index = document.getElementById('TopicP').options.selectedIndex;		
	
	_value = document.getElementById('TopicP').options[index].value;		
	_text  = document.getElementById('TopicP').options[index].text;				
	
	document.getElementById('TopicP').options.selectedIndex = -1;	
	arg 	= new Array();
	arg[0] 	= _value;	
	//qq = _text.replace(/(\r\n|\n|\r|\s)/g, 'q');
	arg[1] 	= $.trim(_text);
	//alert($.trim(_text));
	Themes[Themes.length] = arg;	
	//recharge
	topicLoad();				
}

function topicExits()
{		
	for(i=0; i <  Themes.length; i++)
	{
		tab   = Themes[i];		
		id 	  = tab[0];
		if(document.getElementById('TopicP').value == id)
			return true;
	}
	
	return false;
}

function topicDel()
{
	// on vérifie qu'il y a une selection		
	if(document.getElementById('TopicC').value=='')
	{
		alert("Vous devez choisir un thème");
		return;
	}
	
	// on supprime la valeur
	value_del = document.getElementById('TopicC').value;
	tmp       = Themes;
	Themes    =  new Array();		
	for(i=0; i <  tmp.length; i++)
	{			
		if(value_del != tmp[i][0])
		{	
			Themes[Themes.length] = tmp[i];				
		}
	}
			
	topicLoad();
}
function topicSend()
{
	var content = '';
	
	for(i=0; i <  Themes.length; i++)
	{			
		if(i!=0) content += ',';
		content += Themes[i][0];						
	}		
	return content;
}
/***********************************************************************************************************/
						/*gestion des options associées aux produits*/
/**********************************************************************************************************/
//generer les options(taille/couleur) d'un produit apres le choix des intervalles de couleurs et de tailles
function generateOptions(setColor)
{
	taille = $('#fk_intervalle_taille').val();
	couleur = $('#fk_couleur').val();
	id_produit = $('#id').val();
	//alert(couleur);
	//apres une modification de l'intervalle de couleur il faut maj tous les listing	
	if(couleur!='' && setColor) setColors();
	
	if(taille=='')		
	{
		//alert('Veuillez choisir un intervalle de tailles');
		return;
	}
	if(couleur=='')		
	{
		//alert('Veuillez choisir un intervalle de couleurs');
		return;
	}
	
	$.ajax({   
		type: "POST",   
		url: "get_options_intervalle.php",   
		data: "couleur="+couleur+"&taille="+taille+"&id_produit="+id_produit,  
		//dataType: "script", 
		beforeSend: function()
		{   			
			$('#optionsProduct').html('<table width="100%"><tr><td width="35%"></td><td><img src= "images/ajax-loader.gif"></center></td></tr></table>');			
		},
		success: function(_html)
		{   			
			//keepstate_options();			
			$("#optionsProduct").html(_html);
		} 
	});	
}

var ProductOptions =  new Array();

function optionsLoad()
{
	// on recharge		
	for(i=0; i <  ProductOptions.length; i++)
	{			
		tab = ProductOptions[i];		
		$('#'+tab[0]).val(tab[1]);				
	}		
}

/***********************************************************************************************************/
						/*gestion des produits associés*/
/**********************************************************************************************************/
function addProductAssociate(id,name,_defaultWidth,_defaultHeight,_minWidth,_minHeight,_maxWidth,_maxHeight)
{
	$.ajax({
		type: "POST",
		url: "get_associate_product.php",
		data: "id="+id+'&action=get_totem',
		success: function(_html)
		{
			var totem = new Totem('divTotemProduct','Element',name,_html,
												_defaultWidth,_defaultHeight,_minWidth,_minHeight,_maxWidth,_maxHeight);
			$("#divTotemProduct").show();
		}
	});
}
function associateProduct(id)
{		
	var param = $('#form_associate_product').formSerialize();  
	
	$('#form_associate_product').ajaxForm({ 
		url: "get_associate_product.php",
        success: function(_html) 
		{			
			$('#tr_last_assoc').before(_html);
			$("#divTotemProduct").hide();
        }
    });
	//
	$('#form_associate_product').submit();	
}
//supp d'un prod assoc
function deleteAssociateProduct(id_prod)
{
	$('#'+id_prod).hide({animated: 'easeslide'}).remove();
}
/***********************************************************************************************************/
						/*gestion des stickers associés aux produits*/
/**********************************************************************************************************/
function addProductSticker(id,name,_defaultWidth,_defaultHeight,_minWidth,_minHeight,_maxWidth,_maxHeight)
{
	$.ajax({
		type: "POST",
		url: "get_associate_sticker.php",
		data: "id="+id+'&action=get_totem',
		success: function(_html)
		{
			var totem = new Totem('divTotemProduct','Element',name,_html,
												_defaultWidth,_defaultHeight,_minWidth,_minHeight,_maxWidth,_maxHeight);
			$("#divTotemProduct").show();
		}
	});
}
//recuperer l'image d'un sticker
function refreshImageSticker(id_sticker)
{
	$.ajax({
		type: "POST",
		url: "get_associate_sticker.php",
		data: "id="+id_sticker+'&action=get_image_sticker',
		success: function(image)
		{
			$('#image_sticker').html(image);
		}
	});
	
}
function associateSticker(id)
{		
	var param = $('#form_associate_sticker').formSerialize();  
	
	$('#form_associate_sticker').ajaxForm({ 
		url: "get_associate_sticker.php",
		data: "id="+id+'&action=add_sticker',
        success: function(_html) 
		{			
			$('#tr_last_assoc_sticker').before(_html);
			$("#divTotemProduct").hide();
        }
    });
	//
	$('#form_associate_sticker').submit();	
}
//supp d'un sticker assoc
function deleteAssociateSticker(id_prod)
{
	$('#'+id_prod).hide({animated: 'easeslide'}).remove();
}
/***********************************************************************************************************/
						/*gestion des images associées aux produits*/
/**********************************************************************************************************/
function addProductImage()
{	
	var cpt = parseInt($('#cpt_images').val());
	$('#cpt_images').val(cpt+1);
	var nb = parseInt($('#nb_images').val());
	$('#nb_images').val(nb+1);
	ordre = nb+1;
	num = cpt+1;
	//alternance des couleur
	tmp = nb % 2;
	if(tmp==0) tmp=2;
	color = "bc_normal_"+tmp;	
	//ajout
	txt  = '<tr id="tr_'+num+'" class="'+color+'" onmouseover="TrBgColorate(this,\'over\',\''+color+'\');" ';
	txt += '	onmouseout="TrBgColorate(this,\'out\',\''+color+'\');"> ';
	txt += '    <td align="center"><div id="val_fk_ordre_'+num+'"> '+ordre+'</div></td>';
	txt += '    <td colspan="1"><div id="div_'+num+'"  selected_div><table width="100%" cellspacing="1" cellpadding="0">';	
	txt += '<td width="200"><table><tr>';
	txt += '<td><input type="hidden" size="2" name="fk_ordre_'+num+'" id="fk_ordre_'+num+'" value="'+ordre+'">';
	txt += '<input type="file" name="upload_image_'+num+'" id="upload_image_'+num+'" size="35"/></td>';
	txt += '<td></td></tr></table></td>';
	/*txt += '<td align="left" width="150"><select name="fk_couleur_'+num+'" id="fk_couleur_'+num+'" ></select></td>';*/
	txt += '</table></div></td>';
	txt += '<td align="center"><a href="javascript:changePosition('+num+','+ordre+',\'haut\');">haut</a>';	
	txt += '<br><a href="javascript:changePosition('+num+','+ordre+',\'bas\');">bas</a></td>';
	txt += '<td  align="center"><a href="javascript:deleteImage('+num+');">supp</a></td>';
	txt += '</tr>';
	
	$('#tr_last').before(txt);
	//maj des autre listing des ordre des images
	//leur ajouter une position
	//setOrdrers('add');
	//récupérer la liste des couleurs rattachées à l'intervalle de couleurs choisit
	getColors('fk_couleur_'+num);
}
//supp une image
function deleteImage(id_image)
{	
	var nb = parseInt($('#nb_images').val());
	$('#nb_images').val(nb-1);
	porder = $('#fk_ordre_'+id_image).val();
	var nb = parseInt($('#cpt_images').val());
	//alert(porder+' : ' +nb);
	if(porder!=nb)
	{
		//for(i=porder;i<=nb;i++)
		for(i=2;i<=nb;i++)
		{		
			ord = parseInt($('#fk_ordre_'+i).val());
			if(i!=id_image && ord>porder)
			{
				$('#fk_ordre_'+i).val(ord-1);
				$('#val_fk_ordre_'+i).html(ord-1);
			}	
		}
	}
	//$('#tr_'+id_image).hide({animated: 'easeslide'}).empty();
	//table_parent = 
	$('#tr_'+id_image).hide({animated: 'easeslide'}).remove();
	
	//$('#'+delete_image).val(1);
	//setOrdrers('delete');
}
//changer la position d'une ligne
function changePosition(old_num,old_ordre,sens)
{	
	//recuperer 
	if(sens == 'haut')
	{
		new_tr  = $("#tr_"+old_num).prev();					
	}
	else
	{			
		new_tr  = $("#tr_"+old_num).next();				
	}	
	//id de la ligne
	id_new_tr = new_tr.attr("id");	
	new_num   = id_new_tr.substring(3,id_new_tr.lenght);
	new_ordre = $('#fk_ordre_'+new_num).val();
	//alert(new_num);
	old_div  	= $("#div_"+old_num);
	old_contenu = old_div.html();	
	new_div  	= $("#div_"+new_num);	
	new_contenu = new_div.html();		
	//changement de l'ordre
	//alert(old_ordre+':'+new_ordre);	
	old_div.html(new_contenu);
	new_div.html(old_contenu);	
	$('#fk_ordre_'+new_num).val(old_ordre);
	$('#fk_ordre_'+old_num).val(new_ordre);
}
//récupérer la liste des couleurs rattachées à l'intervalle de couleurs choisit
function getColors(id_ligne)
{
	couleur = $('#fk_intervalle_couleur').val();
	
	$.ajax({
		type: "POST",
		url: "get_intervalle_couleurs.php",
		data: "couleur="+couleur,
		success: function(_html)
		{
			$('#'+id_ligne).append(_html);
		}
	});
}
//apres une modification de l'intervalle de couleur il faut maj tous les listing
function setColors()
{			
	couleur = $('#fk_couleur').val();	
	$.ajax({   
		type: "POST",   
		url: "get_intervalle_couleurs.php",   
		data: "couleur="+couleur,  		
		success: function(_html)
		{   
			var nb = parseInt($('#cpt_images').val());				
			for(i=1;i<=nb;i++)
			{		
				$('#fk_couleur_'+i).empty();
				$('#fk_couleur_'+i).append(_html);
			}
		} 
	});	
}
//recueprer une liste d'ordre des images
function getOrdrer_old()
{	
	var nb = parseInt($('#nb_images').val());	
	txt = '';
	for(i=1;i<nb;i++)
	{		
		txt += '<option value="'+i+'">'+i+'</option>';		
	}
	//la mettre en derniere position		
	txt += '<option value="'+nb+'" selected>'+i+'</option>';		
	return txt;
}
//maj des autre listing des ordre des images
//leur ajouter une position
function setOrdrers_old(action)
{	
	var cpt = parseInt($('#cpt_images').val());
	var nb = parseInt($('#nb_images').val());
	if(action=='add')
	{
		txt = '<option value="'+nb+'">'+nb+'</option>';
		for(i=1;i<cpt;i++)
		{
			$('#fk_ordre_'+i).append(txt);
		}
	}
	else
	{
		//la nouvelle liste d'ordre des images
		txt = '';		
		for(i=1;i<=nb;i++)
		{		
			txt += '<option value="'+i+'">'+i+'</option>';		
		}
		//supp : enlever le derniere ordre
		for(i=1;i<=cpt;i++)
		{		
			_val = $('#fk_ordre_'+i).val();
			$('#fk_ordre_'+i).empty();
			$('#fk_ordre_'+i).append(txt);
			$('#fk_ordre_'+i).val(_val);				
			
		}
	}
}
//maj de l'ordre des images
function updateOrdrers_old(id_image)
{
	//recuperer l'ancienne valeur de l'ordre de l'image		
	old_porder = getOldOrder();
	
	porder = $('#fk_ordre_'+id_image).val();
	//alert(old_porder+' : '+porder);
	if(porder < old_porder)
	{		
		for(i=porder;i<old_porder;i++)
		{		
			ord = parseInt($('#fk_ordre_'+i).val());
			if(i!=id_image)
			{
				$('#fk_ordre_'+i).val(ord+1);
			}	
		}
		return;		
	}
	if(porder > old_porder)
	{
		for(i=old_porder;i<=porder;i++)
		{		
			ord = parseInt($('#fk_ordre_'+i).val());
			if(i!=id_image)
			{
				$('#fk_ordre_'+i).val(ord-1);
			}	
		}
		return;
	}
}
function deleteImage_old(id_image,delete_image)
{	
	var nb = parseInt($('#nb_images').val());
	$('#nb_images').val(nb-1);
	porder = $('#fk_ordre_'+id_image).val();
	var nb = parseInt($('#cpt_images').val());
	for(i=porder;i<=nb;i++)
	{		
		ord = parseInt($('#fk_ordre_'+i).val());
		if(i!=id_image)
		{
			$('#fk_ordre_'+i).val(ord-1);
		}	
	}
	$('#tr_'+id_image).hide({animated: 'easeslide'}).empty();
	$('#'+delete_image).val(1);
	setOrdrers('delete');
}
//recuperer l'ancien ordre
function getOldOrder_old()
{
	array2 = new Array();
	var nb = parseInt($('#cpt_images').val());	
	for(i=1;i<=nb;i++)
	{
		//alert($('#fk_ordre_'+i).val());
		array2[i-1] = $('#fk_ordre_'+i).val();
	}		
	array2.sort(sortByCroissant); 
	var array2 = Doublons(array2);
	//alert(array2.toString());
	for(i=1;i<=nb;i++)
    {
		//alert('valeur '+array2[i-1]);
		if(array2[i-1]!=i) return i;
    }
	return 1;
}
/********************************************************************************************/
					/*gestion des oprions taille et couleur*/
/********************************************************************************************/
function showDivCreate()
{
	$('#div_form_create').show({animated: 'easeslide'});
}
function hideDivCreate()
{
	$('#div_form_create').hide({animated: 'easeslide'});
}
function addIntervalle(page)
{	
	if($('#new_intervalle').val()=='')
	{
		alert('Veuillez saisir le libellé de l’intervalle de taille');
		return;
	}
	document.getElementById('form_option').action=page+'.php?create';
	document.getElementById('form_option').submit();
}		
function updateAllIntervalles(page)
{
	document.getElementById('form_option').action=page+'.php?submit';
	document.getElementById('form_option').submit();
}		

function addOption(id_intervalle,type)
{
	var nb = parseInt($('#nb_options_'+id_intervalle).val());		
	$('#nb_options_'+id_intervalle).val(nb+1);
	//alternance des couleur
	tmp = nb % 2;
	if(tmp==0) tmp=2;
	color = "bc_normal_"+tmp;	
	//ajout		
	txt  = '<div id="div_'+type+'_new_'+nb+'_'+id_intervalle+'"><table width="100%" cellspacing="1" cellpadding="1">';	
	txt += '<tr  class="'+color+'" onmouseover="TrBgColorate(this,\'over\',\''+color+'\');" ';
	txt += ' onmouseout="TrBgColorate(this,\'out\',\''+color+'\');">';	
	txt += '<td align="center"><input type="text" name="'+type+'_'+id_intervalle+'[]" id="'+type+'_'+id_intervalle+'[]" value=""></td>';
	txt += '<td><a href="#" onclick="deleteOption(\'div_'+type+'_new_'+nb+'_'+id_intervalle+'\');">del</a></td>';
	txt += '</tr></table></div>';
	
	$("#div_options_"+id_intervalle).append(txt);
}
function addCouleur()
{
	var nb = parseInt($('#nb_couleurs').val());
	$('#nb_couleurs').val(nb+1);
	//alternance des couleur
	tmp = nb % 2;
	if(tmp==0) tmp=2;
	color = "bc_normal_"+tmp;	
	
	//ajout	
	txt  = '<div id="div_couleur_new_'+nb+'"><table width="100%" cellspacing="1" cellpadding="1">';								
	txt += '<tr  class="'+color+'" onmouseover="TrBgColorate(this,\'over\',\''+color+'\');" ';
	txt += ' onmouseout="TrBgColorate(this,\'out\',\''+color+'\');">';	
	txt += '<td align="center"><input type="text" name="couleur_new_'+nb+'" id="couleur_new_'+nb+'" value=""></td>';
	txt += '<td><a href="#" onclick="deleteOption(\'div_couleur_new_'+nb+'\');">del</a></td>';
	txt += '</tr></table></div>';
	
	$("#div_couleurs").append(txt);
}
function deleteOption(id_ligne)
{		
	$('#'+id_ligne).hide({animated: 'easeslide'}).remove();	
}

/********************************************************************************************/
					/*bon de reduction avec le panier*/
/********************************************************************************************/
function check_code_reduction()
{
	$('#img_envoyer_promo').attr('src','images/ajax-loader.gif');
	libelle = $('#libelle_promo').val();
	if(libelle=='')
	{
		//$.prompt('Aucun code de réduction n\'a été saisi.',{ buttons:{Ok:true}, prefix:'cleanblue',show:'slideDown'});
		txt = 'Aucun code de réduction n\'a été saisi.';
		$.prompt(txt,{
						callback: resetImage,  
						buttons: { Ok:true},
						prefix:'cleanblue',show:'slideDown'
					});
		
	}
	else
	{
		$.ajax({
			type    : "GET",
			url     : "ajax_check_code_reduction.php",
			data    : "libelle="+libelle,
			dataType: "script",
			success : function(script)
			{
				if(erreur!='')
				{					
					$.prompt(erreur,{
						callback: resetImage,  
						buttons: { Ok:true},
						prefix:'cleanblue',show:'slideDown'
					});				
				}
				else
				{					
					$("#div_reduction1,#div_total,#div_reduction2").show();
					//
					$("#div_reduction1").html(reduction);					
					$("#div_total_avant").html(total_avant+' €');
					$("#div_amount_reduction").html(amount_reduction+' €');
					$("#div_total_apres").html(total_apres+' €');
					//remettre l'mage du ok*******
					resetImage();
					//mettre à jour le bloc panier*****
					updatePanierBloc();
				}
			}
		});
	}
}
//remettre l'image du bouton envoyer
function resetImage()
{
	$('#img_envoyer_promo').attr('src','images/ok.gif');
}
/*********************************************************************************************************/
		/*****************************carousel Vignette****************************************/
/*********************************************************************************************************/
var NB_ELEMENT_CAROUSEL_VIGNETTE = 2;
//vignettes en carousel
function initProductVignette()
{
       //alert("ee");
    jQuery('#productVignette').jcarousel({
        itemLoadCallback: productVignette_itemLoadCallback,
		scroll: NB_ELEMENT_CAROUSEL_VIGNETTE
    });
}
//var product_id;
function productVignette_itemLoadCallback(carousel, state)
{
    // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) 
	{
        return;
    }
    
	//var id_product = $('#id').val();
    jQuery.get(
        'carousel_product_vignette.php',
        {
            id_product : $('#id').val(),
			time	   : getTime(),
			action	   :'allVignettes',
            first	   : carousel.first,
            last	   : carousel.last
        },
        function(xml) {
            productVignette_itemAddCallback(carousel, carousel.first, carousel.last, xml);
        },
        'xml'
    );
};

function productVignette_itemAddCallback(carousel, first, last, xml)
{
    // Set the size of the carousel
    carousel.size(parseInt(jQuery('total', xml).text()));
	cpt = 0;
    jQuery('image', xml).each(function(i) 
	{
		elmt = jQuery(this);
		src = jQuery('src',elmt).text();
		id_img  = jQuery('id', elmt).text();
		reference_libelle   = jQuery('reference_libelle', elmt).text();
		carousel.add(first + i, productVignette_getItemHTML(id_img,src,reference_libelle));
		cpt++;
    });
	//replacer les case qui ne contiennent pas d'images par des vide
	if(cpt<NB_ELEMENT_CAROUSEL_VIGNETTE) 
	{
		for(var j=cpt;j<NB_ELEMENT_CAROUSEL_VIGNETTE;j++)
		{
			carousel.add(first + j, '');      
		}	
	}
};
//Item html creation helper.
function productVignette_getItemHTML(id_img,src,reference_libelle)
{    
	return '<div id="a_vignette_produit"><a href="javascript:changeImageFiche(\''+id_img+'\');" title="'+
			reference_libelle+'"><img onmouseover="changeImageFiche(\''+id_img+'\');" src="' + src + '" title="'+reference_libelle+'"/></a></div>';

};/*
function product_getItemHTML(src,id_prd,trade,fr,prix,reference,reference_libelle)
{
	txt  = '';
	txt  = '<div class="cross_vignette">';
	txt += '<a href="product_fiche.php?id='+id_prd+'&reference='+reference+'&reference_libelle='+reference_libelle+'" title="'+reference_libelle+'"><img src="' + src + '"  alt="'+reference_libelle+'"/></a>';
	txt += '</div>';
	txt += '<a href="product_fiche.php?id='+id_prd+'&reference='+reference+'&reference_libelle='+reference_libelle+'" title="'+
			reference_libelle+'">';
	txt += '<span class="titre_nouveaute">'+trade+'</span><span class="prix">'+prix+'  ?</span>';
	txt += '</a>';

	//alert(txt);

	return txt;
};*/
//changer la qty du produit dans la fiche
function changeQty(action)
{
	qty = $('#qty').val();
	//verifer si le prdoduit est un entier positif
	if(verif_numeric(qty))
	{
		if(action=='-' && qty>1) $('#qty').val(parseInt(qty)-1);
		if(action=='+') $('#qty').val(parseInt(qty)+1);
	}
}

//verifer si le prdoduit est un entier positif
function checkQty(qty)
{
	if(!verif_numeric(qty))
	{
		alert_simple('La quantité doit être positive');
	}
}
//changer l'image principale de la fiche produit**
function changeImageFiche(name_img)
{	
	$.ajax({
	   type		: "GET",
	   dataType : "script",
	   url      : "product_vignette.php",
	   data     : "name_img="+name_img,
	   success  : function(data){}
	});
}
//tableau des option disponibles (couleur dispo pour une taille/ tailles dispo pour une couleur)**
var options_dispo_color = new Array();
var options_dispo_taille = new Array();
//le produit est en promos
var is_promos = false;

function changeImageFicheByColor(fk_color, fk_taille, isUpdated)
{
	var id_product  = $('#id').val();
	var old_taille  = $('#select_taille').val();
	var new_couleur = $('#select_couleur').val();
	
	$.ajax({
	   type: "GET",
	   dataType : "script",
	   url      : "carousel_product_vignette.php",
	   data     : "action=color&id_product="+id_product+"&fk_color="+fk_color+"&fk_taille="+fk_taille,
	   success  : function(retour)
	   {			
		   	document.getElementById('select_taille').value  = old_taille;
		   	document.getElementById('select_couleur').value = new_couleur;
			
			/*//si le produit n'est dispo on remplace bouton ajouter au panier par l'alerte sms	
			if((isDispoOptionTaille(old_taille)==false) )			
			{
				$('#ajouter_panier').html(getButtonAddCart('alert',isUpdated));					
				$('#epuise').show();
				$('#promos').hide(); 				
			}
			else
			{
				$('#ajouter_panier').html(getButtonAddCart('cart',isUpdated));				
				$('#epuise').hide();
				if(is_promos == true) $('#promos').show(); 
				else $('#promos').hide(); 
			}*/	
	   }
	});		
}
//gestion des tailles et couleurs
function initGestionSize()
{
	//modification de taille
	$('.not_selected_taille').click(function() 
	{ 
		id_taille = this.id;
		//deselectionner toutes les autres tailles
		jQuery('.selected_taille').each(function(i){			
			$('#'+this.id).removeClass('selected_taille');
			$('#'+this.id).addClass('not_selected_taille');
		});	
		$('#'+id_taille).removeClass('not_selected_taille');
		$('#'+id_taille).addClass('selected_taille');
		$('#select_taille').val(id_taille);
		//afficher la qte disponible pour la taille selectionnée
		setQteTaille(id_taille);		
		//changeColorByTaille(id_taille, $('#select_couleur').val(),null);		
		//return false; 
	});
	/*$/('.not_selected_taille').hover(function() 
	{ 
		id_taille = this.id;
		//deselectionner toutes les autres tailles
		//deselectionner toutes les autres tailles
		
		$('#'+id_taille).removeClass('not_selected_taille');
		$('#'+id_taille).addClass('selected_taille');
		$('#select_taille').val(id_taille);
		//recueprer la liste des couleurs dispo pour cette taille
		//return false; 
	});*/
	/*$('.not_selected_taille').toggle(function(){   
		$(this).addClass("selected_taille"); 
		},
		function(){   
			$(this).removeClass("selected_taille"); 
	});*/
	//modification de couleur
	/*$('.not_selected_color').click(function() 
	{ 
		id_color = this.id;
		//deselectionner toutes les autres tailles
		jQuery('.selected_color').each(function(i){			
			$('#'+this.id).removeClass('selected_color');
			$('#'+this.id).addClass('not_selected_color');
		});	
		$('#'+id_color).removeClass('not_selected_color');
		$('#'+id_color).addClass('selected_color');
		//maj de la couleur
		$('#select_couleur').val(id_color);
		//recuperer la vignette (si elle existe)  qui corresond à la couleur choisit
		//et recueprer la liste des tailles dispo pour cette couleur
		changeImageFicheByColor(id_color, $('#select_taille').val(), null);
		//return false; 
	});*/
}
//afficher la qte disponible pour la taille selectionnée
function setQteTaille(id_taille)
{		
	if(id_taille=='')  return true;
	for(i=0; i < options_dispo_taille.length; i++)
	{			
		tab = options_dispo_taille[i];			
		if(tab[0]==id_taille)
		{				
			//afficher la qte restante si elle ne depasse pas 5
			qte = parseInt(tab[2]);
			mess_qte = "";
			if(qte<6) mess_qte = " - Plus que "+qte;			
			$('#taille_selectionnee').html("Taille sélectionnée : "+tab[1]+mess_qte);
			return;
		}
	}
	$('#taille_selectionnee').html("Choisissez une taille");
}
//S’il existe une seul couleur => vérifier la dispo des tailles
//ou s’il existe une seul taille => vérifier la dispo des couleurs
function checkTailleAndColors(action)
{
	var id_product  = $('#id').val();
	var fk_color 	= $('#select_couleur').val();
	var fk_taille   = $('#select_taille').val();
	//alert(old_taille);
	
	$.ajax({
	   type		: "GET",
	   dataType : "script",
	   url      : "carousel_product_vignette.php",
	   data     : "action="+action+"&id_product="+id_product+"&fk_color="+fk_color+"&fk_taille="+fk_taille,
	   success  : function(data)
	   {
			document.getElementById('select_couleur').value = fk_color;
			document.getElementById('select_taille').value  = fk_taille;			
	   }
	});	
}
function changeColorByTaille(fk_taille, fk_color,isUpdated)
{
	var id_product  = $('#id').val();
	var old_couleur = $('#select_couleur').val();
	var new_taille  = $('#select_taille').val();
	
	$.ajax({
	   type		: "GET",
	   dataType : "script",
	   url      : "carousel_product_vignette.php",
	   data     : "action=taille&id_product="+id_product+"&fk_color="+fk_color+"&fk_taille="+fk_taille,
	   success  : function(data)
	   {
			document.getElementById('select_couleur').value = old_couleur;
			document.getElementById('select_taille').value  = new_taille;
			
			//$('#select_taille').val(106);
			//si le produit est dispo on remplace bouton ajouter au panier par l'alerte sms			
			/*
			if(isDispoOptionColor(old_couleur)==false)			
			{
				$('#ajouter_panier').html(getButtonAddCart('alert', isUpdated));		
				$('#epuise').show();
				$('#promos').hide();
			}
			else
			{
				$('#ajouter_panier').html(getButtonAddCart('cart', isUpdated));
				$('#epuise').hide();
				if(is_promos == true) $('#promos').show(); 
				else $('#promos').hide(); 
			}	*/		
	   }
	});	
}
function isDispoOptionColor(id_option)
{	
	if(id_option=='')  return true;
	for(i=0; i <  options_dispo_color.length; i++)
	{		
		if(options_dispo_color[i]==id_option) return true;
	}
	return false;
}

function isDispoOptionTaille(id_option)
{		
	if(id_option=='')  return true;
	for(i=0; i <  options_dispo_taille.length; i++)
	{		
		if(options_dispo_taille[i]==id_option) return true;
	}
	return false;
}
function getButtonAddCart(type, isUpdated)
{
	if(type=='cart')
	{
		txt  = '<input type="image" ';
		if(isUpdated)
			txt += 'src="images/boutons/bt_update_panier.gif" alt="Modifier le panier" class="right" />';
		else
			txt += 'src="images/boutons/bt_ajouter_panier.gif" alt="Ajouter ce produit au panier" class="right" />';
	}
	else
	{
		txt  = '<img src="images/boutons/bt_alerte_produit.gif" style="cursor:hand;" alt="Alerte produit" class="right" ';
		txt += ' onclick="checkAlert(true);"/>';		
	}
	return txt;
}
//contenu de la popup d'alert
/*
function getContentAlert(email,mobile)
{
	var txt  = 'Pour être alerté par email :<br />';
	txt += '<input type="text" size ="40" id="mail_alert" name="mail_alert" value="'+email+'"/><br />';
	txt  += 'Pour être alerté par sms :<br />';
	txt += '<input type="text" size ="40" id="mobile_alert" name="mobile_alert" value="'+mobile+'"/><br />';
	return txt;
}*/
//enregistrer une alerte pour un utilisateur
function checkAlert(first,txt_1)
{
	if(txt_1 == null) txt_1 = '';
	if(first)
	{
		_data = "type_redirection=alertez_moi&" + "first&" + "txt_1=" + txt_1 + "&"+getTime();
	}
	else
	{
		email  = $('#mail_alert').val();
		mobile = $('#mobile_alert').val();
		fk_product    = $('#id').val();
		fk_option_1   = $('#select_taille').val();
		fk_option_2   = $('#select_couleur').val();
		_data 		  = "type_redirection=alertez_moi&"+"mobile="+mobile+"&email="+email+"&fk_product="+
						fk_product+"&fk_option_1="+fk_option_1+"&fk_option_2=" + fk_option_2 + '&txt_1=' + txt_1 + '&'+ getTime();
	}
	
	//var error = '';
	$.ajax({   
		type: "GET",   
		url: "popup.php",   
		data: _data,   
		success: function(_html)
		{     
			//alert(_html);
			if(_html=='') 
			{
				txt  = 'Visley surveille les arrivages pour toi !\n';
				txt += 'Dés que ce produit est disponible nous t\'enverrons un mail ou un sms pour te prévenir.';
				alert_simple(txt);
			}
			else 
			{				
				$.promptWest(_html, {prefix:'popvisleyAlert',show:'slideDown'});
			}
		} 
	});		
	//
	/*
	if(txt_1==null) txt_1 = '';
	email = '';
	//adresse mail de l'utilisateur si il est conecté
	$.ajax({
	   type		: "GET",	  
	   url      : "get_email_account_session.php",	
	   dataType : "script",
	   success  : function(script)
	   {
			//contenu de la popup d'alert
			var txt  = txt_1 + getContentAlert(email,mobile);
			$.prompt(txt,
				{
					callback: saveAlert,  
					buttons: { Envoyer: 'Envoyer'},					
					prefix:'cleanblue',show:'slideDown'
				});
	   }
	});		
	*/	
}
/*
//reafficher la pop up de l'alert avec l'erreur : mail ou portable
function errorAlert(error,email,mobile)
{	
	var style = 'font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; ';
	style 	 += 'font-size: 10px; ';
	style 	 += 'color:#FF0000; ';
	var txt   = '<font style="'+style+'">'+error+'</font><br />';
	//contenu de la popup d'alert
	txt  += getContentAlert(email,mobile);
	$.prompt(txt,
		{
			callback: saveAlert,  
			buttons: { Envoyer: 'Envoyer'},					
			prefix:'cleanblue',show:'slideDown'
		});
}*/
/*
function saveAlert(v,m)
{
	if(v=='Envoyer')
	{		
		var email 		  = m.children('#mail_alert').val();
		var mobile 		  = m.children('#mobile_alert').val();		
		var fk_product    = $('#id').val();
		var fk_option_1   = $('#select_taille').val();
		var fk_option_2   = $('#select_couleur').val();
		//var error 		= '';
		//associer l'alert au client
		$.ajax({
		   type		: "POST",
		   dataType : "script",
		   url      : "save_alert.php",
		   data     : "mobile="+mobile+"&email="+email+"&fk_product="+fk_product+"&fk_option_1="+
					   fk_option_1+"&fk_option_2="+fk_option_2+'&'+getTime(),
		   success  : function(data)
		   {
				if(data!='')
				{
					//reafficher la pop up de l'alert avec l'erreur : mail ou portable
					errorAlert(error,email,mobile);
				}
				else
				{
					txt  = 'Visley surveille les arrivages pour toi !\n';
					txt += 'Dés que ce produit est disponible nous t\'enverrons un mail ou un sms pour te prévenir.';
					alert_simple(txt);
				}		
		   }		   
		});			
	}	
}*/
function saveAlert()
{			
	var email 		  = $('#mail_alert').val();
	var mobile 		  = $('#mobile_alert').val();		
	var fk_product    = $('#id').val();
	var fk_option_1   = $('#select_taille').val();
	var fk_option_2   = $('#select_couleur').val();
	//var error 		= '';
	//associer l'alert au client
	$.ajax({
	   type		: "POST",
	   dataType : "script",
	   url      : "save_alert.php",
	   data     : "mobile="+mobile+"&email="+email+"&fk_product="+fk_product+"&fk_option_1="+
				   fk_option_1+"&fk_option_2="+fk_option_2+'&'+getTime(),
	   success  : function(data)
	   {
			if(data!='')
			{
				//reafficher la pop up de l'alert avec l'erreur : mail ou portable
				errorAlert(error,email,mobile);
			}
			else
			{
				txt  = 'Visley surveille les arrivages pour toi !\n';
				txt += 'Dés que ce produit est disponible nous t\'enverrons un mail ou un sms pour te prévenir.';
				alert_simple(txt);
			}		
	   }		   
	});		
}
/*********************************************************************************************************/
		/*****************************Produits associés****************************************/
/*********************************************************************************************************/
var NB_ELEMENT_CAROUSEL_HORIZONTAL = 3;
var NB_ELEMENT_CAROUSEL_ASSOCIATE  = 3;
function initAssociateProduct()
{
	jQuery('#associateProduct').jcarousel({       		
		itemLoadCallback: associateProduct_itemLoadCallback,
		scroll: NB_ELEMENT_CAROUSEL_ASSOCIATE,
		vertical: true
    })
};
function associateProduct_itemLoadCallback(carousel, state)
{	
    // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) 
	{
        return;
    }	
    jQuery.get(
        'carousel_associate_product.php',
        {
			id_product:$('#id').val(),
			time:getTime(),
            first: carousel.first,
            last: carousel.last
        },
        function(xml) {
            product_itemAddCallback(carousel, carousel.first, carousel.last, xml);
        },
        'xml'
    );
};

function product_itemAddCallback(carousel, first, last, xml)
{    
	
	// Set the size of the carousel
    carousel.size(parseInt(jQuery('total', xml).text()));	
	cpt = 0;
    jQuery('image', xml).each(function(i){			
		//alert(first +' : '+ i);
		src 		= jQuery('src',this).text();
		id_prd  	= jQuery('id', this).text();
		trade		= jQuery('trade', this).text();
		fr			= jQuery('fr', this).text();		
		prix		= jQuery('prix', this).text();	
		reference	= jQuery('reference', this).text();
		reference_libelle	= jQuery('reference_libelle', this).text();
		carousel.add(first + i, product_getItemHTML(src,id_prd,trade,fr,prix,reference,reference_libelle));       
		cpt ++;
    });	
	//replacer les case qui ne contiennent pas d'images par des vide
	if(cpt<NB_ELEMENT_CAROUSEL_HORIZONTAL) 
	{
		for(var j=cpt;j<NB_ELEMENT_CAROUSEL_HORIZONTAL;j++)
		{
			carousel.add(first + j, '');      
		}	
	}	
};
//Item html creation helper.
function product_getItemHTML(src,id_prd,trade,fr,prix,reference,reference_libelle)
{   	
	txt  = '';
	//txt  = '<div class="cross_vignette">'; 
	txt += '<a href="product_fiche.php?id='+ id_prd +'&reference='+ reference +'&reference_libelle='+ reference_libelle +'" title="'+ reference_libelle +'"><img src="' + src + '"  alt="'+ reference_libelle +'"/></a>'; 
	//alert(txt);
	return txt;
	
};
/*********************************************************************************************************/
		/*****************************Articles deja vus****************************************/
/*********************************************************************************************************/
function initProductView()
{
	jQuery('#productView').jcarousel({       		
		itemLoadCallback: productView_itemLoadCallback,
		scroll: 2
    });	
}
function productView_itemLoadCallback(carousel, state)
{	
    // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) 
	{
        return;
    }	
    jQuery.get(
        'carousel_product_view.php',
        {			
            first: carousel.first,
            last: carousel.last
        },
        function(xml) 
		{
            product_itemAddCallback(carousel, carousel.first, carousel.last, xml);
        },
        'xml'
    );
};
/*
function productView_itemAddCallback(carousel, first, last, xml)
{    
	// Set the size of the carousel
    carousel.size(parseInt(jQuery('total', xml).text()));

    jQuery('image', xml).each(function(i){		
	
		src 		= jQuery('src',this).text();
		id_prd  	= jQuery('id', this).text();
		trade		= jQuery('trade', this).text();
		fr			= jQuery('fr', this).text();		
		prix		= jQuery('prix', this).text();	
		carousel.add(first + i, productView_getItemHTML(src,id_prd,trade,fr,prix));       
    });	
};
//Item html creation helper.
function productView_getItemHTML(src,id_prd,trade,fr,prix)
{    
	txt  = '';
	txt  = '<div class="cross_vignette">'; 
	txt += '<a href="product_fiche.php?id='+id_prd+'" title="'+fr+'"><img src="' + src + '"  alt=""/></a>'; 
	txt += '</div>';
	txt += '<a href="product_fiche.php?id='+id_prd+'" title="'+fr+'">';
	txt += '<span class="titre_nouveaute">'+trade+'</span><span class="prix">'+prix+'  €</span>';
	txt += '</a>';

	return txt;
};*/
/*********************************************************************************************************/
	/*****************************carousel produits de la meme marque****************************************/
/*********************************************************************************************************/
function initSameTrade()
{
	jQuery('#sameTrade').jcarousel({       		
		itemLoadCallback: sameTrade_itemLoadCallback,
		scroll: 2
    });	
}
function sameTrade_itemLoadCallback(carousel, state)
{	
    // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) 
	{
        return;
    }	        
    jQuery.get(
        'carousel_same_trade.php',
        {
            id_product:$('#id').val(),
			time:getTime(),
            first: carousel.first,
            last: carousel.last
        },
        function(xml) {
            product_itemAddCallback(carousel, carousel.first, carousel.last, xml);
        },
        'xml'
    );
}
/*********************************************************************************************************/
		/*****************************les bons plans en carousel****************************************/
/*********************************************************************************************************/
function initTopDealCart()
{
	jQuery('#liste_plans').jcarousel({       		
		itemLoadCallback: topDealCart_itemLoadCallback,
		scroll: 6
    });	
}
function topDealCart_itemLoadCallback(carousel, state)
{	
    // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) 
	{
        return;
    }	
    jQuery.get(
        'carousel_top_deal_cart.php',
        {
            first: carousel.first,
            last: carousel.last
        },
        function(xml) {
            topDealCart_itemAddCallback(carousel, carousel.first, carousel.last, xml);
        },
        'xml'
    );
};

function topDealCart_itemAddCallback(carousel, first, last, xml)
{    
	// Set the size of the carousel
    carousel.size(parseInt(jQuery('total', xml).text()));

    jQuery('image', xml).each(function(i){		
	
		src 				= jQuery('src',this).text();
		id_prd  			= jQuery('id', this).text();
		trade				= jQuery('trade', this).text();
		fr					= jQuery('fr', this).text();		
		prix				= jQuery('prix', this).text();
		reference			= jQuery('reference', this).text();
		reference_libelle	= jQuery('reference_libelle', this).text();
		carousel.add(first + i, topDealCart_getItemHTML(src,id_prd,trade,fr,prix,reference,reference_libelle));       
    });	
};
//Item html creation helper.
function topDealCart_getItemHTML(src,id_prd,trade,fr,prix,reference)
{  
	txt  = '<div class="center">';
	txt += '<a href="product_fiche.php?id='+id_prd+'&reference='+reference+'&reference_libelle='+reference_libelle+'" title="'+reference_libelle+'">';
	txt += '<img src="' + src + '" alt="'+reference_libelle+'"/></a>';
	txt += '</div>';
	txt += '<p> <span class="desc">'+trade+'</span> <span class="prix">'+prix+'  €</span> </p>';
	txt += '<a href="product_fiche.php?id='+id_prd+'&reference='+reference+'&reference_libelle='+reference_libelle+
			'" title="'+reference_libelle+'">';
	txt += '<img src="images/boutons/pa_ajouter.gif" alt="Ajouter dans le panier" /></a>';
		
	return txt;
};
/****************************************/
//GESTION DU LAYER Contact******
/**************************************/
/****************************************/
//GESTION DU LAYER Contact******
/**************************************/
//positionner le layer Newsletter************
function initPosLayerContact()
{	
	//position de l'image compte****	
	var pos = $('#gestion_compte').position();
	var newY   = parseInt(pos.top)+20;
	var newX   = parseInt(pos.left)-190;
	//alert(newX + ' ' + newY);
	document.getElementById("layer_contact").style.left = newX+'px';
	document.getElementById("layer_contact").style.top 	= newY+'px';
}
//recuperer les infos le layer du Contact***
function getContactLayer()
{	
	$.ajax({   
		type: "POST",   
		url: "ajax_contact.php",   		
		data:"action=getLayer",
		success: function(_html)
		{			
			$('#layer_contact').html(_html);
			//afficher le layer du compte***
			showContactLayer();
		} 
	});
}
//afficher le layer du Contact***
function showContactLayer()
{	
	$('#layer_contact').show();
}
//cacher le layer du Contact***
function hideContactLayer()
{	
	$('#layer_contact').hide();
}
function contactFromLayer()
{	
	var param = $('#form_layer_contact').formSerialize();	
	$.ajax({   
		type: "POST",
		url: "ajax_contact.php",   		
		data:"action=send&"+param,
		success: function(_html)
		{			
			$('#layer_contact').html(_html);
			showContactLayer();
		} 
	});
}
/****************************************/
//GESTION DU LAYER NEWSLETTER******
/**************************************/
//positionner le layer Newsletter************
function initPosLayerNewsletter()
{
	//position de l'image compte****	
	/*var pos = $('#gestion_compte').position();
	var newY   = parseInt(pos.top)+20;
	var newX   = parseInt(pos.left)-200;
	//alert(newX + ' ' + newY);
	document.getElementById("layer_compte").style.left = newX+'px';
	document.getElementById("layer_compte").style.top 	= newY+'px';*/
}
//recuperer les infos le layer du Newsletter***
function initPosLayerNewsletter()
{
	//position de l'image compte****	
	var pos = $('#gestion_compte').position();
	var newY   = parseInt(pos.top)+20;
	var newX   = parseInt(pos.left)-230;
	//alert(newX + ' ' + newY);
	document.getElementById("layer_newsletter").style.left = newX+'px';
	document.getElementById("layer_newsletter").style.top 	= newY+'px';
}
function getNewsletterLayer()
{	
	$.ajax({   
		type: "POST",   
		url: "ajax_newsletter.php",   		
		data:"action=getLayer",
		success: function(_html)
		{			
			$('#layer_newsletter').html(_html);
			//afficher le layer du compte***
			showNewsletterLayer();
		} 
	});		
}
//afficher le layer du Newsletter***
function showNewsletterLayer()
{	
	$('#layer_newsletter').show();
	
}
//cacher le layer du Newsletter***
function hideNewsletterLayer()
{	
	$('#layer_newsletter').hide();
}

function newsletterFromLayer()
{	
	var param = $('#form_layer_newsletter').formSerialize();	
	$.ajax({   
		type: "POST",
		url: "ajax_newsletter.php",   		
		data:"action=insert&"+param,
		success: function(_html)
		{			
			$('#layer_newsletter').html(_html);
			showNewsletterLayer();
		} 
	});
}

/*************************************/
//GESTION DU LAYER DU COMPTE******
/***********************************/
//positionner le layer compte************
function closeFiltre(){
		$('#div_taille').hide('high');
		$('#div_couleur').hide('high');
		$('#div_tri').hide('high');
	}


function initPosLayerCompte()
{
	//position de l'image compte****	
	var pos = $('#gestion_compte').position();
	var newY   = parseInt(pos.top)+20;
	var newX   = parseInt(pos.left)-230;
	//alert(newX + ' ' + newY);
	document.getElementById("layer_compte").style.left = newX+'px';
	document.getElementById("layer_compte").style.top 	= newY+'px';
}

//recuperer les infos le layer du compte***
function getCompteLayer()
{	
	$.ajax({   
		type: "POST",   
		url: "ajax_compte.php",   		
		data:"action=getLayer",
		success: function(_html)
		{		
			$('#layer_compte').html(_html);
			//afficher le layer du compte***
			showCompteLayer();
		} 
	});		
}

//afficher le layer du compte***
function showCompteLayer()
{	
	hideCartLayer();
	$('#layer_compte').show();
	$('#gestion_compte').addClass('gestion_compte_on');
	//changer la classe du div 'gestion_compte	
	//$('#gestion_compte').attr('src','images/compte_over.gif');
}
//cacher le layer du compte***
function hideCompteLayer()
{	
	$('#layer_compte').hide('normal');
	$('#gestion_compte').removeClass('gestion_compte_on');
	//changer la classe du div 'gestion compte		
	//$('#gestion_compte').attr('src','images/compte.gif');
}
//connexion
function connectFromLayer()
{	
	var param = $('#form_layer_compte').formSerialize();	
	$.ajax({   
		type: "POST",
		url: "ajax_compte.php",   		
		data:"action=connect&"+param,
		success: function(_html)
		{			
			$('#layer_compte').html(_html);
			//afficher le layer du compte***
			//showCompteLayer();
		} 
	});
}
//mot de passe oublié
function mdpOublie()
{
	var param = $('#form_layer_compte').formSerialize();
	$.ajax({
		type: "POST",
		url: "ajax_compte.php",
		data:"action=mdp&"+param,
		success: function(_html)
		{               
            //mail envoyé
            if(_html=="mail_envoye")
            {
                //cacher le layer du compte***
                hideCompteLayer();
                alert_simple("Votre mot de passe a été envoyé");
            }
            else
                $('#layer_compte').html(_html);
			//afficher le layer du compte***
			//showCompteLayer();
		}
	});
}
function toggleDiv(id_div)
{
    $('#'+id_div).toggle({animated: 'easeslide'});
}
/***********************************************/
//GESTION DU LAYER DU ACHAT EXPRESS********
/*********************************************/
function showLayerExpress(layerExpress, layerImage)
{
	//alert(layerExpress);
	//position de l'image compte****	
	var pos = $('#'+layerImage).position();
	var newY   = parseInt(pos.top)+120;
	var newX   = parseInt(pos.left);
	document.getElementById(layerExpress).style.left = newX+'px';
	document.getElementById(layerExpress).style.top 	= newY+'px';
	$('#'+layerExpress).show();
	
}
function hideLayerExpress(layerExpress)
{
	//position de l'image compte****	
	$('#'+layerExpress).hide('');
}
/*************************************/
//GESTION DU LAYER DU PANIER******
/***********************************/
//recuperer les infos le layer du panier***
function addToCart(){
	if(checkInfosFiche())
	{
	var param = $('#ajax_addcart').formSerialize();
	$.ajax({   
			type: "GET",   
			url: "cart_add.php",   
			data: param,   
			success: function(_html)
			{   				
				if(_html!="") alert_simple(_html);
				else getInfosCart(true);
			} 
		});
	}
	return false;
	}
	/*
function getInfosCartAdd(){
	$.ajax({   
		type: "POST",   
		url: "ajax_cart.php",   		
		success: function(_html)
		{
            //on rempli le panier uniquement s'il n'st pas vide
            if(_html!="")
            {
                $('#detail_panier').html(_html);
				 showCartLayer();
                $('#detail_panier').slideUp('12000');
            }
		} 
	});	
}	
	*/

function getInfosCart(from_layer)
{
	var pos = $('#recap_panier').position();
	var newY   = parseInt(pos.top)+25;
	var newX   = parseInt(pos.left) - 200;
	document.getElementById('detail_panier').style.left = newX+'px';
	document.getElementById('detail_panier').style.top 	= newY+'px';
	if(from_layer!=null){
	if( $('#zoom_produit')[0] ) {
		var pos2 = $('#zoom_produit').position();
		var newY2   = parseInt(pos2.top)+250;
		var newX2   = parseInt(pos2.left)+200;
		document.getElementById('detail_panier').style.left = newX2+'px';
		document.getElementById('detail_panier').style.top 	= newY2+'px';
		}
	}
	$.ajax({   
		type: "POST",   
		url: "ajax_cart.php",   		
		success: function(_html)
		{
            //on rempli le panier uniquement s'il n'st pas vide
            if(_html!="")
            {
                $('#detail_panier').html(_html);
                //afficher le layer du panier***
               if(from_layer!=null) showCartLayer(true,true);
               else showCartLayer(false,true);
				//$('#detail_panier').show();
				//mettre à jour le bloc panier***
				updatePanierBloc();
            }
		} 
	});		
}
//afficher le layer du panier***
function showCartLayer(from_layer,from_cadenas)
{		
	hideCompteLayer();
	if(from_layer) 
	{
		$('#detail_panier').slideDown('slow');
		$('#detail_panier').slideUp(2500);
	}
	else  
	{
		if(from_cadenas!=null) $('#detail_panier').slideDown('slow');
		else $('#detail_panier').show();
	}
	//changer la classe du div 'recap_panier
   	//$('#recap_panier').addClass('recap_panier_on');
}


//afficher le layer du panier***
function hideCartLayer()
{	
	$('#detail_panier').slideUp(2500);
	//changer la classe du div 'recap_panier	
	//$('#recap_panier').removeClass('recap_panier_on');
}
//mettre à jour le bloc panier***
function updatePanierBloc()
{
	$.ajax({
		type: "POST",
		url: "ajax_nb_prd_cart.php",
		success: function(_html)
		{			
			$('#recap_panier').html(_html);
			//remplir le layer panier
			//getInfosCart();			
		} 
	});	
}
/*************************************/
//GESTION DU LAYER DU PRODUIT****
/***********************************/
//afficher le layer du prod***
function showProductLayer(id,event)
{
	$.ajax({   
		type: "GET",   
		url: "ajax_product.php",
		data: "id="+id,
		success: function(_html)
		{	
			$('#zoom_produit').html(_html);
			//posiotionner le div du zoom			
			/*var initX  = document.getElementById('txt_listing_'+id).offsetLeft;
			var initY  = document.getElementById('txt_listing_'+id).offsetTop;
			document.getElementById(id_layer).style.left  = (initX+160) +'px';
			document.getElementById(id_layer).style.top   = (initY-60)+'px';*/				
			//$('#_produit').show('slideDown');
			//positionner un div au milieu de la page
			centerDiv($("#zoom_produit"));
			//positionNearMouse($("#zoom_produit"),event);
			$("#zoom_produit").fadeIn("slow");
			//fermeture avec la touche ESC
			$("#zoom_produit").attr('tabindex', -1).css('outline', 0).keydown(function(ev) {
				var ESC = 27;		
				if(ev.keyCode && ev.keyCode == ESC)
				{
					hideProductLayer();
				}
			})
			//zoom du produit
            //initZoom('photoMedium','zoom_produit');
		} 
	});		
}
//afficher le layer du prod***
function initProductLayer(id_product,id_img)
{	
	$('#'+id_img).mousemove(function(e)
	{		
		//alert(e.pageX + " : " +   e.pageY);
		positionX = e.pageX-initX ;
		positionY = e.pageY-initY ;
		
	}); 	
	$.ajax({   
		type: "GET",   
		url: "ajax_product.php",
		data: "id="+id,
		success: function(_html)
		{	
			$('#zoom_produit').html(_html);
			//posiotionner le div du zoom			
			/*var initX  = document.getElementById('txt_listing_'+id).offsetLeft;
			var initY  = document.getElementById('txt_listing_'+id).offsetTop;
			document.getElementById(id_layer).style.left  = (initX+160) +'px';
			document.getElementById(id_layer).style.top   = (initY-60)+'px';*/				
			//$('#_produit').show('slideDown');
			//positionner un div au milieu de la page
			centerDiv($("#zoom_produit"));
			//positionNearMouse($("#zoom_produit"),event);
			$("#zoom_produit").fadeIn("slow");
			//fermeture avec la touche ESC
			$("#zoom_produit").attr('tabindex', -1).css('outline', 0).keydown(function(ev) {
				var ESC = 27;		
				if(ev.keyCode && ev.keyCode == ESC)
				{
					hideProductLayer();
				}
			})
			//zoom du produit
            initZoom('photoMedium','zoom_produit');
		} 
	});		
}


function hideProductLayer()
{	
	$('#zoom_produit').fadeOut("slow");
}

/********************************************************************************************/
					/*FCTS DIVERS*/
/********************************************************************************************/
//chargement d'une liste deroulante (ou 2 liste eventuelement)
//key 	    		  : permet de savoir le type de la liste exp : " produits liés à une categorie"
//valeur_key  		  : l'id du type, exp : l'id de la categorie dont on cherche les produits
//id_child 	    		  : l'id de la liste a remplir en html, exp : "fk_product"
//key2,id_child2	    	  : le cas de deux liste deroulante qui change de valeur
//si la la valeur_key == '' : la 2eme liste doit reprendre les valeurs associé a id_parent

//exemple si on a : categorie, ss_categie et marque
//si on remet a zero la liste des la ss_categorie, la liste des marques se reinitialise 

//le cas de deux liste deroulante qui change de valeur
function refreshSelect(key,valeur_key,id_child,key2,id_child2,id_parent)
{	
	_data = 'key='+key+'&valeur_key='+valeur_key+'&id_child='+id_child;
	//le cas de deux liste deroulante qui change de valeur
	if(key2!=null) 
	{	
		_data += '&key2='+key2+'&id_child2='+id_child2;
		//si la la valeur_key == '' : la 2eme liste doit reprendre les valeurs associé a id_parent
		if(id_parent!=null)
		{			
			_data += '&val_parent='+$('#'+id_parent).val();
		}
	}	
	//alert(_data);
	$.ajax({   
		type: "GET",   
		url: "../backoffice/refresh_liste.php",   
		data: _data,   
		dataType: "script",
		success: function(script){} 
	});
}
//le cas de deux liste deroulante qui change de valeur
function refreshSelectSizeColor(key,fk_trade,id_size,id_color,fk_category)
{	
	_data = 'key='+key+'&fk_trade='+fk_trade+'&id_size='+id_size+'&id_color='+id_color+'&fk_category='+fk_category;	
	$.ajax({   
		type: "GET",   
		url: "../backoffice/refresh_liste.php",   
		data: _data,   
		dataType: "script",
		success: function(script){} 
	});
}
//
function update_means_of_payment_and_unset_cart()
{	
	//Les conditions générales de vente doivent être validées
	if(!$('#conditions').is(':checked')) 
	{
		alert_simple('Les conditions générales de vente doivent être validées');
	}
	else
	{		
		//id_orders = $('#id_orders').val();
		//meansofpayment = $('#meansofpayment').val();
		var param = $('#fb0').formSerialize();		
		$.ajax({   
			type: "POST",   
			url: "update_means_of_payment_and_unset_cart.php",   
			data: param,   
			success: function(_html)
			{   				
				//document.getElementById('fb0').action = '/cgi-bin/modulev2.cgi';
				document.getElementById('fb0').submit();
			} 
		});
	}
}
//alert avec jQuery
function alert_simple(txt)
{
	$.prompt(txt,{			
		buttons: { Ok:true},
		prefix:'cleanblue',show:'slideDown'
	});	
}
//confrmation de la redirection*************
function alert_redirection(type_redirection,page_redirection,id,select_couleur,select_taille)
{
	//alert('ee');
	/*
	//id du produit
	var id 				= $("#id").val();
	//alert('id :'+id);
	//var reference 			= $("#reference").val();	
	var select_couleur 	= $("#select_couleur").val();
	var select_taille 	= $("#select_taille").val();*/
	//recuperation le contenu html a afficher comme alerte****
	$.ajax({
		  type: "GET",
		  url: "popup.php", 
		  data:{id_product:id,				
				select_couleur:select_couleur,
				select_taille:select_taille,
				page_redirection:page_redirection,
				type_redirection:type_redirection}, 
		  async:true,
		  success: function(_html){
			if(_html!='')
				$.promptWest(_html,	{show:'slideDown'});
		}
	});
	/*
	$.ajax({
		   type: "POST",
		   dataType: "html",
		   url: "delete_ajax.php",
		   data: "id="+id+"&className="+className,
		   success: function(data){			
		   $('#flex_'+className).flexReload();
		   }
		});	
	/*
	var txt  = message_redirection;
	txt += '<input type="hidden" id="page_redirection" name="page_redirection" value="'+page_redirection+'" />';
	$.promptWest(txt,
		{show:'slideDown'});
		*/
}
function dd(action,m)
{
	if(action=='oui')
	{
		window.location = m.children('#page_redirection').val();	
	} 
	  
}
function alert_valider_achat()
{	
	//id du produit
	var id = $("#id").val();	
	//recuperation le contenu html a afficher comme alerte
	/*$.ajax({
		  type: "GET",
		  url: "popup/valider_achat.php", 
		  data:{id_product:id}, 
		  async:true,
		  success: function(_html){			
			$.promptWest(_html,
				show:'slideDown'});
		  }
	});	*/
}

function alert_prix_public()
{
	txt = 'Qu\'est-ce que le "Prix public constaté?"<br>'+
			'C\'est le prix catalogue de la marque habituellement conseillé.<br>'+
			'Lorsque celui-ci est indisponible, il s\'agit du prix de vente relevé dans la distribution. ';
	$.prompt(txt,{			
		buttons: { Ok:true},
		prefix:'cleanblue',show:'slideDown'
	});	

}
/*
function validate_delete(className,id)
{
	var txt  = 'Confirmez vous la suppression de cet élément ?';
	txt += '<input type="hidden" id="className" name="className" value="'+className+'" />';
	txt += '<input type="hidden" id="id" name="id" value="'+id+'" />';	
	$.prompt(txt,{callback: delete_element,  buttons: { Oui: 'oui', Non: 'non'},prefix:'cleanblue',show:'slideDown'});

}
function delete_element(action,m)
{
	if(action=='oui')
	{
		className =  m.children('#className').val();	
		id =  m.children('#id').val();	
		$.ajax({
		   type: "POST",
		   dataType: "html",
		   url: "delete_ajax.php",
		   data: "id="+id+"&className="+className,
		   success: function(data){			
		   $('#flex_'+className).flexReload();
		   }
		});	
	}    
}
*/












//rec la lsite des parametres sous forme de tableau JSON
function chaineToJson(chaine) 
{
	var retour = "";
	//var array_retour = new array();	
	var tmp = chaine.split("&");
	
	for(var i=0;i<tmp.length;i++)
	{
		var tmp1 	 = tmp[i].split("=");		
		retour		+= "{name:'"+tmp1[0]+"', value: '"+tmp1[1]+"'}";
		if(i<tmp.length-1)  retour		+= ",";
	}
	return retour;
}
//export des commandes : pour la poste ou le suivi des commandes
function exportOrders(mode)
{
	var param = $('#fb0').formSerialize();
	if(mode==null) mode = 'poste';
	//alert(param);
	$.ajax({   
			type: "POST",   
			url: "export_commande_read.php",   
			data: param+"&action=create&mode="+mode,   
			success: function(file_csv)
			{   				
				window.location='export_commande_read.php?action=get&file_csv='+file_csv;
			} 
		});
}
//export des stat
function exportStat()
{
	//var param = $('#fb0').formSerialize();
	//alert(param);
	$.ajax({   
			type: "POST",   
			url: "export_stat_read.php",   
			data: "&action=create",   
			success: function(file_csv)
			{   				
				window.location='export_stat_read.php?action=get&file_csv='+file_csv;
			} 
		});
}
function exportStatTaille()
{	
	$.ajax({   
			type: "POST",   
			url: "export_stat_taille_read.php",   
			data: "&action=create",   
			success: function(file_csv)
			{   				
				window.location='export_stat_taille_read.php?action=get&file_csv='+file_csv;
			} 
		});
}

//export du Stock
function exportStock()
{
	var param = $('#fb0').formSerialize();
	//alert(param);
	$.ajax({   
			type: "POST",   
			url: "export_stock_read.php",   
			data: param+"&action=create",   
			success: function(file_csv)
			{   				
				window.location='export_stock_read.php?action=get&file_csv='+file_csv;
			} 
		});
}
//import des commandes : pour la poste
function importOrders()
{
	$('#form_import_orders').ajaxForm({ 
		url: "import_orders.php",
        success: function(_html) 
		{			
			retourTpln = $(_html);
			//
			val = $('#div_err_form_import_poste',retourTpln).html();	
			//si val==null cad que le serveur a envoyer un message d'erreur=>CATALOGUE BLOQUE 
			if(val==null)
			{					
				$('#totemElementContent').html(_html);	
				return;
			}			
			//verifier si le serveur n'a pas envoyer d'erreurs
			if(val!='')
			{			
				$('#div_err_form_import_poste').html(val);
			}				
			else
			{
				$("#divTotemElement").hide();				
			}						
        }
    });
	//
	$('#form_import_orders').submit();
}
/**************************************************/
	/*Fonctions pour l'autocompletion*/
/**************************************************/
//maj a jour du champ 'fk_account'
function updateValue(li) 
{
	if( li == null ) 
	{		
		document.getElementById('fk_account').value = '';
		//verifier si l'utilisateur a saisi le nom d'un client qui n'existe pas
		if($("#name_account").val()!='')
		{
			alert_simple('Le client saisit n\'existe pas');
			return false;
		}
	}
	else
	{
		// if coming from an AJAX call, let's use the CityId as the value
		if( !!li.extra ) var sValue = li.extra[0];

		// otherwise, let's just display the value in the text box
		else var sValue = li.selectValue;

		//alert(sValue);
		$('#fk_account').val(sValue);
	}
	//envoie du formulaire****
	name_form = $('#name_form').val();
	$('#'+name_form).submit();	
	return false;
}
//formatage des données recu en ajax
function formatItem(row) 
{
	//return row[0] + " (email: " + row[1] + ")";	
	return row[0];	
}
//recuperer la valeur de l'id du client au moment du submit
function lookupAjax()
{	
	var oSuggest = $("#name_account")[0].autocompleter;	
	return oSuggest.findValue();	
}

/***********************************************************************************************************/
				/*gestion des conditions associées aux promos(bon d'achat et bon de reduction)*/
/**********************************************************************************************************/
function addPromosCondition()
{	
	var cpt = parseInt($('#cpt_conditions').val());
	$('#cpt_conditions').val(cpt+1);
	var nb = parseInt($('#nb_conditions').val());
	$('#nb_conditions').val(nb+1);
	num = cpt+1;
	//alternance des couleur
	tmp = nb % 2;
	if(tmp==0) tmp=2;
	color = "bc_normal_"+tmp;	
	//ajout
	txt  = '<tr id="tr_'+num+'" class="'+color+'" onmouseover="TrBgColorate(this,\'over\',\''+color+'\');" ';
	txt += '	onmouseout="TrBgColorate(this,\'out\',\''+color+'\');"> ';
	txt += '	<td colspan="2">';
	txt += '		<div id="div_'+num+'"  class="seleceted_div">';
	txt += '			<table width="100%" cellspacing="1" cellpadding="0">';
	txt += '				<tr>';
	txt += '					<td align="center"><select name="fk_condition_'+num+'" id="fk_condition_'+num+'" ';
	txt += '						onchange="loadConditionValues('+num+');">';
	txt += '							<option value="">choisissez</option>';
	txt += '							</select>';
	txt += '					</td>';
	txt += '					<td id="td_cdt_'+num+'"></td>';
	txt += '				</tr>';
	txt += '			</table>';
	txt += '		</div>';
	txt += '	</td>';
	txt += '	<td align="center">';
	txt += '		<a href="javascript:deleteCondition('+num+');"><img src="images/remove.gif"/></a>';
	txt += '	</td>';
	txt += '</tr>';
	
	$('#tr_last').before(txt);
	//récupérer la liste des conditions d'une promos
	getConditons('fk_condition_'+num);
}
//supp une cdt
function deleteCondition(num)
{	
	var nb = parseInt($('#nb_conditions').val());
	$('#nb_conditions').val(nb-1);
	var nb = parseInt($('#cpt_conditions').val());
	$('#tr_'+num).hide({animated: 'easeslide'}).remove();
}

//récupérer la liste des conditions d'une promos
function getConditons(id_cond)
{
	$.ajax({
		type: "POST",
		url: "ajax_get_conditions.php",
		success: function(_html)
		{
			$('#'+id_cond).html(_html);
		}
	});
}
//charger els valeurs possibles  d'une condition : champs texte, arbre des categories....
function loadConditionValues(id_line)
{
	id_cdt = $('#fk_condition_'+id_line).val();
	if(id_cdt==null || id_cdt=='') return;
	$.ajax({
		type: "POST",
		url: "ajax_get_values_condition.php",
		data:"id_cdt="+id_cdt+"&id_line="+id_line,
		success: function(_html)
		{
			$('#td_cdt_'+id_line).html(_html);
		}
	});
}
//fermer et ouvrir la liste des valeurs des conditons
function initToggleCondition(id_toggle,id_values_cdt)
{
	$("#"+id_toggle).toggle(
		function()
		{   
			$('#'+id_values_cdt).animate({height:280,animated: 'easeslide'});
					$(this).html("Réduire&nbsp;&nbsp;&nbsp;-");								
		},
		function()
		{   
			$('#'+id_values_cdt).animate({height:80,animated: 'easeslide'});
					$(this).html("Agrandir&nbsp;&nbsp;&nbsp;+");
		}
	);
}
//maj des valeurs du filtre de recherche
function updateValueFiltre()
{
	//alert(document.getElementById('fk_size').value);
	if($('#fk_size').val()!='')
	{
		$('#div_taille').hide();
		$('#div_fleche_taille').hide();
		$('#div_croix_taille').show();
		$('#div_val_taille').html('Taille '+$('#libelle_size').val());
	}
	if($('#price_ecart').val()!='')
	{
		$('#div_prix').hide();
		$('#div_fleche_prix').hide();
		$('#div_croix_prix').show();
		$('#div_val_prix').html('Prix '+$('#libelle_price_ecart').val());
	}
	if($('#fk_color').val()!='')
	{
		$('#div_couleur').hide();
		$('#div_fleche_couleur').hide();
		$('#div_croix_couleur').show();
		$('#div_val_couleur').html('Couleur '+$('#libelle_color').val());
	}
	if($('#libelle_tri').val()!='')
	{
		$('#div_val_tri').html($('#libelle_tri').val());
	}
}