
//global variables
var combinations = new Array();
var selectedCombination = new Array();
var globalQuantity = new Number;
var colors = new Array();

//add a combination of attributes in the global JS sytem
function addCombination(idCombination, arrayOfIdAttributes, quantity, price, ecotax, id_image)
{
	globalQuantity += quantity;

	var combination = new Array();
	combination['idCombination'] = idCombination;
	combination['quantity'] = quantity;
	combination['idsAttributes'] = arrayOfIdAttributes;
	combination['price'] = price;
	combination['ecotax'] = ecotax;
	combination['image'] = id_image;
	combinations.push(combination);
}

// search the combinations' case of attributes and update displaying of availability, prices, ecotax, and image
function findCombination()
{
	//create a temporary 'choice' array containing the choices of the customer
	var choice = new Array();
	$('div#attributes select').each(function(){
		choice.push($(this).val());
	});
	var nbAttributesEquals = 0;
	//testing every combination to find the conbination's attributes' case of the user
	
	for (combination in combinations)
	{
		//verify if this combinaison is the same that the user's choice
		nbAttributesEquals = 0;
		for (idAttribute in combinations[combination]['idsAttributes'])
		{
			//ie6 bug fix
			if (idAttribute != 'indexOf'){
				//if this attribute has been choose by user
				if (in_array(combinations[combination]['idsAttributes'][idAttribute], choice))
				{
					//we are in a good way to find the good combination !
					nbAttributesEquals++;
				}
			}
		}

		if (nbAttributesEquals == choice.length)
		{
			//combination of the user has been found in our specifications of combinations (created in back office)
			selectedCombination['unavailable'] = false;
			
			$('#idCombination').val(combinations[combination]['idCombination']);

			//get the data of product with these attributes
			quantityAvailable = combinations[combination]['quantity'];
			selectedCombination['price'] = combinations[combination]['price'];
			if (combinations[combination]['ecotax'])
				selectedCombination['ecotax'] = combinations[combination]['ecotax'];
			else
				selectedCombination['ecotax'] = default_eco_tax;
			
			//show the large image in relation to the selected combination
			if (combinations[combination]['image'] && combinations[combination]['image'] != -1)
				displayImage( $('#thumb_'+combinations[combination]['image']).parent() );
			
			//update the display
			updateDisplay();
			
			//leave the function because combination has been found
			return;
		}
	}
	//this combination don't exist (not created in back office)
	selectedCombination['unavailable'] = true;
	updateDisplay();
}

function updateColorSelect(id_attribute)
{
	// Visual effect
	$('#color_'+id_attribute).fadeTo('fast', 1, function(){	$(this).fadeTo('slow', 0, function(){ $(this).fadeTo('slow', 1, function(){}); }); });
	// Attribute selection
	$('#group_'+id_color_default+' option[value='+id_attribute+']').attr('selected', 'selected');
	$('#group_'+id_color_default+' option[value!='+id_attribute+']').removeAttr('selected');
	findCombination();
}

//update display of the availability of the product AND the prices of the product
function updateDisplay()
{
	if (!selectedCombination['unavailable'] && quantityAvailable > 0)
	{
		//show the choice of quantities
		$('#quantity_wanted_p:hidden').show('slow');
		
		//show the "add to cart" button ONLY if it was hidden
		$('#add_to_cart:hidden').fadeIn(600);
		//availability value management
		if (availabilityValue != '')
		{
			//update the availability statut of the product
			$('#availability_value').removeClass('warning-inline');
			$('#availability_value').text(availabilityValue);
			$('#availability_statut:hidden').show();
		}
		else
		{
			//hide the availability value
			$('#availability_statut:visible').hide();
		}
		
		//'last quantities' message management
		if (quantityAvailable <= maxQuantityToAllowDisplayOfLastQuantityMessage)
		{
			//display the 'last quantities' message
			$('#last_quantities').show('slow');
		}
		else
		{
			//hide the 'last quantities' message
			$('#last_quantities').hide('slow');
		}
	
		//display the quantities of pieces (only if allowed)
		if (quantitiesDisplayAllowed)
		{
			$('#pQuantityAvailable:hidden').show('slow');
			$('#quantityAvailable').text(quantityAvailable); 
			if(quantityAvailable < 2)
			{
				$('#quantityAvailableTxt').show();
				$('#quantityAvailableTxtMultiple').hide();
			}
			else
			{
				$('#quantityAvailableTxt').hide();
				$('#quantityAvailableTxtMultiple').show();
			}
		}
	}
	else
	{
		//hide 'last quantities' message if it was previously visible
		$('#last_quantities:visible').hide('slow');

		//hide the quantity of pieces if it was previously visible
		$('#pQuantityAvailable:visible').hide('slow');
		
		//hide the choice of quantities
		$('#quantity_wanted_p:visible').hide('slow');
		
		//display that the product is unavailable with theses attributes
		if (!selectedCombination['unavailable'])
			$('#availability_value').text(doesntExistNoMore + (globalQuantity > 0 ? ' ' + doesntExistNoMoreBut : '')).addClass('warning-inline');
		else
			$('#availability_value').text(doesntExist).addClass('warning-inline');
		$('#availability_statut:hidden').show();

		
		//show the 'add to cart' button ONLY IF it's possible to buy when out of stock AND if it was previously invisible
		if (allowBuyWhenOutOfStock && !selectedCombination['unavailable'])
		{
			$('#add_to_cart:hidden').fadeIn(600);
			$('p#availability_statut:visible').hide('slow');
		}
		else
		{
			$('#add_to_cart:visible').fadeOut(600);
			$('p#availability_statut:hidden').show('slow');
		}
	}
	
	//update display of the the prices in relation to tax, discount, ecotax, and currency criteria
	if (!selectedCombination['unavailable'])
	{
		var attribut_price_tmp = selectedCombination['price'];

		var tax = (taxRate / 100) + 1;

		if (noTaxForThisProduct)
			attribut_price_tmp /= tax;

		var productPriceWithoutReduction2 = (attribut_price_tmp + productPriceWithoutReduction) * currencyRate;
		
		if (reduction_from != reduction_to && (currentDate > reduction_to || currentDate < reduction_from))
			var priceReduct = 0;
		else
			var priceReduct = productPriceWithoutReduction2 / 100 * parseFloat(reduction_percent) + reduction_price;
		var priceProduct = productPriceWithoutReduction2 - priceReduct;
		var productPricePretaxed = (productPriceWithoutReduction2 - priceReduct) / tax;
		$('#our_price_display').text(formatCurrency(priceProduct, currencyFormat, currencySign));
		$('#pretaxe_price_display').text(formatCurrency(productPricePretaxed, currencyFormat, currencySign));
		$('#old_price_display').text(formatCurrency(productPriceWithoutReduction2, currencyFormat, currencySign));
		$('#ecotax_price_display').text(formatCurrency(selectedCombination['ecotax'], currencyFormat, currencySign));
		$('.discounted_price').each(function(){
						var type = $(this).attr('id').substr(4,1);
						var rem = $(this).attr('id').substr(5).replace(/,/,'.');
						var px;
						
						if (type == 'P')
							px = formatCurrency(priceProduct * (1 - (rem / 100)), currencyFormat, currencySign);
						else
							px = formatCurrency(priceProduct - (rem * 1), currencyFormat, currencySign);
						//alert(priceProduct+' - '+type+'_'+rem+" >> "+px);
						$(this).children(".price").text(px);
						
						});
	}
}

//update display of the large image
function displayImage(domAAroundImgThumb)
{
	if (!domAAroundImgThumb.hasClass('shown'))
	{
		if (domAAroundImgThumb.attr('href'))
		{
			var newSrc = domAAroundImgThumb.attr('href').replace('thickbox','large');
			$('#bigpic').fadeOut('fast', function(){
				$(this).attr('src', newSrc);
				$(this).fadeIn('fast');
			});
			$('#views_block li a').removeClass('shown');
			$(domAAroundImgThumb).addClass('shown');
		}
	}
}

//To do after loading HTML
$(document).ready(function(){
	
	//init the serialScroll for thumbs
	$('#thumbs_list').serialScroll({
		items:'li',
		prev:'a#view_scroll_left',
		next:'a#view_scroll_right',
		axis:'x',
		offset:0,
		start:0,
		stop:true,
		duration:700,
		step: 2,
		lock: false,
		force:false,
		cycle:false
	});

	//hover 'other views' images management
	$('#views_block li a').hover(
		function(){displayImage($(this));},
		function(){}
	);

	//add a link on the span 'view full size' and on the big image
	$('span#view_full_size, div#image-block img').click(function(){
		$('#views_block li a.shown').click();
	});

	//catch the click on the "more infos" button at the top of the page
	$('div#short_description_block p a.button').click(function(){
		$('#more_info_tab_more_info').click();
		$.scrollTo( '#more_info_tabs', 1200 );
	});

	//init the price in relation of the selected attributes
	if (typeof productHasAttributes != 'undefined' && productHasAttributes)
		findCombination();
});

function appelCompteur(nombre)
{
	var nb = nombre;
	window.alert('test');
	compteur2 ();
}


function compteur2()
{
	var nbF= nb;
	var temps = reduct_to1;						// date de fin de promo
	var dateDebut = reduct_from1;			// date de début de promo
	var tempsPromotion;								// le compteur qui affiche le temps restant
				
	tempsPromotion='';

	// on changera dynamiquement le bloc avec l'id compteur			
	var div = document.getElementById('compteur'+nbF);
	
	// on vérifie que le produit a une date de promo
	if  ( dateDebut != '0000-00-00 00:00:00')		
	{
		// on prend la date du jour
		var date = new Date();
				
		//on crée une date à partir de temps pour créer une date2() fin de promo
		var a = temps.substring(0,4);
		var m = temps.substring(5,7)-1;
		var j = temps.substring(8,10);
		var h = temps.substring(11,13);
		var min = temps.substring(14,16);
		var s = temps.substring(17,19);
						
		var date2 = new Date(a, m, j, h, min ,s);
					
		//on fait de même pour la dateDebut
		var a2 =  dateDebut.substring(0,4);
		var m2 = dateDebut.substring(5,7)-1;
		var j2 =  dateDebut.substring(8,10);
		var h2 =  dateDebut.substring(11,13);
		var min2 =  dateDebut.substring(14,16);
		var s2 = dateDebut.substring(17,19);
				
		var date3 = new Date(a2, m2, j2, h2, min2 ,s2);
					
		// si la date du jour est supérieure à la date de début et si elle est inférieure à la date de fin
		if (date > date3 && date < date2)
		{
					
			// on récupère les données de date		
			var jour = date.getDate();
			var mois = date.getMonth()+1;
			var annee = date.getFullYear();
			var heure = date.getHours();
			var minutes = date.getMinutes();
			var secondes = date.getSeconds();
						
			// on récupère les données de date2	
			var jour2 = date2.getDate();
			var mois2 = date2.getMonth()+1;
			var annee2 = date2.getFullYear();
			var heure2 = date2.getHours();
			var minutes2 = date2.getMinutes();
			var secondes2 = date2.getSeconds();
						
			// on en déduit le temps qui reste			
			var jourRestant = jour2 -jour;      						//jour
			var moisRestant =mois2 -mois;							//mois
			
			var heureRestant = heure2 -heure;					//heures
					
			if (jourRestant > 0)
			{				
				heureRestant += jourRestant*24;	
			}
						
			if (heureRestant <= 0)
			{				
				heureRestant = 0;						
			}
			
			var minutesRestant =  minutes2 -minutes;		//minutes
			if (minutesRestant <0)
			{
				if (heureRestant > 0)
				{
					minutesRestant = minutesRestant + 60;
					heureRestant = 	heureRestant-1;
				}
				else
				{
					minutesRestant = 0;
				}
			}
						
			var secondesRestant = secondes2 - secondes;	//secondes
			if (secondesRestant <0)
			{
				if (minutesRestant > 0)
				{
					secondesRestant =secondesRestant + 60;
					minutesRestant = minutesRestant-1;
				}
				else
				{
					secondesRestant = 0;
				}
			}
						
						
			// on ajoute un 0 devant les chiffres 
			secondesRestant = '' + secondesRestant;
			minutesRestant = '' + minutesRestant;
			heureRestant = ''+ heureRestant;
						
			if (heureRestant.length < 2)
			{
				heureRestant = '0'+ heureRestant;
			}
			if (minutesRestant.length < 2)
			{
				minutesRestant = '0' + minutesRestant;
			}
			if (secondesRestant.length < 2)
			{
				secondesRestant = '0' + secondesRestant;
			}
				
		
			tempsPromotion +=  '';
			
				
			// si le temps restant est nul on affiche rien
			if ( heureRestant == '00' && minutesRestant== '00' && secondesRestant== '00')
			{
				tempsPromotion = "";
			}
			// sinon on affiche le temps restant
			else
			{
				tempsPromotion += '<p class="flashTime2">H - '+heureRestant+':'+minutesRestant+':'+secondesRestant+"</p>";
			}
						
		}
	}
	div.innerHTML = tempsPromotion;
	window.setTimeout(appelCompteur(nbF),1000);
				
}


function compteur()
{
	var prix = reduction_price;
	
	//le compteur ne s'affiche que si une promotion existe
	if (prix > 0)
	{
		var temps = reduct_to;						// date de fin de promo
		var dateDebut = reduct_from;			// date de début de promo
		var tempsPromotion;								// le compteur qui affiche le temps restant
					
		tempsPromotion='';

		// on changera dynamiquement le bloc avec l'id compteur			
		var div = document.getElementById('compteur');
		
		// on vérifie que le produit a une date de promo
		if  ( dateDebut != '0000-00-00 00:00:00')		
		{
			// on prend la date du jour
			var date = new Date();
						
			//on crée une date à partir de temps pour créer une date2() fin de promo
			var a = temps.substring(0,4);
			var m = temps.substring(5,7)-1;
			var j = temps.substring(8,10);
			var h = temps.substring(11,13);
			var min = temps.substring(14,16);
			var s = temps.substring(17,19);
							
			var date2 = new Date(a, m, j, h, min ,s);
						
			//on fait de même pour la dateDebut
			var a2 =  dateDebut.substring(0,4);
			var m2 = dateDebut.substring(5,7)-1;
			var j2 =  dateDebut.substring(8,10);
			var h2 =  dateDebut.substring(11,13);
			var min2 =  dateDebut.substring(14,16);
			var s2 = dateDebut.substring(17,19);
					
			var date3 = new Date(a2, m2, j2, h2, min2 ,s2);
						
			// si la date du jour est supérieure à la date de début et si elle est inférieure à la date de fin
			if (date > date3 && date < date2)
			{
						
				// on récupère les données de date		
				var jour = date.getDate();
				var mois = date.getMonth()+1;
				var annee = date.getFullYear();
				var heure = date.getHours();
				var minutes = date.getMinutes();
				var secondes = date.getSeconds();
							
				// on récupère les données de date2	
				var jour2 = date2.getDate();
				var mois2 = date2.getMonth()+1;
				var annee2 = date2.getFullYear();
				var heure2 = date2.getHours();
				var minutes2 = date2.getMinutes();
				var secondes2 = date2.getSeconds();
							
				// on en déduit le temps qui reste			
				var jourRestant = jour2 -jour;      						//jour
				var moisRestant =mois2 -mois;							//mois
				
				var heureRestant = heure2 -heure;					//heures
						
				if (heureRestant < 0)
				{
					heureRestant = 24 + heureRestant;
				}
			
			var minutesRestant =  minutes2 -minutes;		//minutes
			if (minutesRestant <0)
			{
				if (heureRestant > 0)
				{
					minutesRestant = minutesRestant + 60;
					heureRestant = 	heureRestant-1;
				}
				else
				{
					minutesRestant = 0;
				}
			}
						
			var secondesRestant = secondes2 - secondes;	//secondes
			if (secondesRestant <0)
			{
				if (minutesRestant > 0)
				{
					secondesRestant =secondesRestant + 60;
					minutesRestant = minutesRestant-1;
				}
				else
				{
					secondesRestant = 0;
				}
			}
						
						
			// on ajoute un 0 devant les chiffres 
			secondesRestant = '' + secondesRestant;
			minutesRestant = '' + minutesRestant;
			heureRestant = ''+ heureRestant;
						
			if (heureRestant.length < 2)
			{
				heureRestant = '0'+ heureRestant;
			}
			if (minutesRestant.length < 2)
			{
				minutesRestant = '0' + minutesRestant;
			}
			if (secondesRestant.length < 2)
			{
				secondesRestant = '0' + secondesRestant;
			}
				
		
			if (jourRestant > 0)
			{
				if (jourRestant ==1 )
				{
						tempsPromotion +=  '<p class="flash">flash</p><p class="flashTime">'+jourRestant+'jour ';
				}
				else
				{
						tempsPromotion +=  '<p class="flash">flash</p><p class="flashTime">'+jourRestant+'jours ';
				 }
			}
			else
			{
				tempsPromotion +=  '<p class="flash">flash</p> <p class="flashTime">';
			}
			
				
			// si le temps restant est nul on affiche rien
			if (jourRestant==0 && heureRestant == '00' && minutesRestant== '00' && secondesRestant== '00')
			{
				tempsPromotion = "";
			}
			// sinon on affiche le temps restant
			else
			{
				tempsPromotion += '   '+heureRestant+'h '+minutesRestant+'min '+secondesRestant+"s</p>";
			}
						
		
							
			}
		}
		div.innerHTML = tempsPromotion;
		window.setTimeout(compteur,1000);
	}
				
}
		
				
			
		

