var cl = "ajaxccart";

function ccartClick(id_product, index, is_ete)
{
	var div = $('#'+cl+'-id'+id_product);
	div.ccartdata = '';

	ccartClose();
	if (div.css('display') == 'block')
		return false;
	else
	{
		hlToProduct(id_product);
		ccartCallAjax(id_product, div, index, is_ete);
	}
	return false;
}

function ccartCallAjax(id_product, div, index, is_ete)
{
	ccartDisp(1, div, index);
	if (div.ccartstop != true)
	{
		$.ajax({
			url: url+'?come=product',
			type: 'POST',
			data: 'id_product='+parseInt(id_product)+'&id_category='+id_category_main+(is_ete ? '&ete=1' : ''),
			dataType: 'json',
			success: function (data, status) {
				if (data.error != '')
					div.ccartdata = 'Error: '.data.error;
				else
				{
					div.ccartdata = data.data;
					div.ccartstop = true;
				}
				ccartAjaxDisp(div);
			},
			error: function (status, data) {
				div.ccartdata = 'Ajax error: '.data;
			}
		});
	}
	else
		ccartAjaxDisp(div);
}

function ccartClose()
{
	closeAll();
	return false;
}

function ccartDisp(action, div, index)
{
	$('.ajaxccart').stop(true, true);
	if (action == 1)
	{
		$('.ajaxccart-ajax').hide();
		$('.ajaxccart-def').show();
		$('.ajaxccart').hide();
		if ((index + 1) % 4 == 0 && parseInt(div.css('left')) > 0)
			div.css('left', (parseInt(div.css('left')) - div.width() - 160)+'px');
		div.show('slow');
	}
	else
		div.hide();
}

function ccartAjaxDisp(div)
{
	$('.ajaxccart').stop(true, true);
	var id = div.attr('id');
	$('#'+id+' .ajaxccart-def').hide();
	$('#'+id+' .ajaxccart-ajax').html(div.ccartdata);
	$('#'+id+' .ajaxccart-ajax').show();
	setTimeout('loadajaxcart("'+id+'");', 50);
}

function loadajaxcart(id_div)
{
	//$('a.available').unbind('click');
	$('#'+id_div+' a.available').click(function() {

		var pid = $(this).attr('alt');

		var pr = $(this).attr('rel').split(';');

		var id_category_main = $('#id_category_main_'+pid).attr('value');

		switch(currency_format) {
			case 1:
			case 3:
				$('#price_'+pid).html(currency_sign + parseFloat(pr[0]).toFixed(2));
				$('#old_price_'+pid).html(currency_sign + parseFloat(pr[1]).toFixed(2));
				break;
			default:
				$('#price_'+pid).html(parseFloat(pr[0]).toFixed(2) + ' ' + currency_sign);
				$('#old_price_'+pid).html(parseFloat(pr[1]).toFixed(2) + ' ' + currency_sign);
				break;
		}

		$('#ajax_ipa_'+pid).val($(this).attr('href'));
		// $(this).removeClass('available');
		// $('div.select-size a.selected_'+parseInt(id_category_main)).addClass('available');
			// $('div.select-size a').removeClass('selected_'+parseInt(id_category_main));
		// $(this).addClass('selected_'+parseInt(id_category_main));

		return false;
	});

	$('#'+id_div+' .ajax_add_cart').submit(function() {
			one_size = $('p.one-size-'+$(this.id_product).attr('value'));
			if (($(this.id_product_attribute).attr('value') == '' || $(this.id_product_attribute).attr('value') == 0) && (one_size.length == 0 || !one_size))
			{
				$('a#inline').fancybox().trigger('click');
				return false;
			}
			else
				ajax_cart($(this.id_product).attr('value'), $(this.id_product_attribute).attr('value'), $(this.quantity).attr('value'), id_div);
			return false;
		});

}

function showTab(id_tab, id_tab_hidden, id_product)
{
	$('div.product-'+parseInt(id_tab_hidden)+'-'+parseInt(id_product)).css('background-image', 'url(http://img2.melijoe.com/bg-product-info-tab'+parseInt(id_tab_hidden)+'-off.jpg)');
	$('div.product-'+parseInt(id_tab)+'-'+parseInt(id_product)).css('background-image', 'url(http://img2.melijoe.com/bg-product-info-tab'+parseInt(id_tab)+'-on.jpg)');
	$('div.product-content-'+parseInt(id_tab_hidden)+'-'+parseInt(id_product)).css('display', 'none');
	$('div.product-content-'+parseInt(id_tab)+'-'+parseInt(id_product)).css('display', 'block');
}

function ajax_cart(idProduct, idCombination, quantity, form)
{
	var addedFromProductPage = true;

	undercart = true;
	$.ajax({
		type: 'GET',
		url: baseDir + 'cart.php',
		async: true,
		cache: false,
		dataType : "json",
		data: 'add&ajax=true&qty=' + ( (quantity && quantity != null) ? quantity : '1') + '&id_product=' + idProduct + '&token=' + static_token + ( (parseInt(idCombination) && idCombination != null) ? '&ipa=' + parseInt(idCombination): ''),
		success: function(jsonData)
		{
			//apply 'transfert' effect
			$(form).find('input.add_to_cart').TransferTo({
				to: 'header-cart',
				className:'transferProduct',
				duration: 1000,
				complete: function () {
					if (jsonData.hasError)
					{
						var errors = '';
						for(error in jsonData.errors)
							//IE6 bug fix
							if(error != 'indexOf')
								errors += jsonData.errors[error] + "\n";
						alert(errors);
					} else {
						var total = jsonData.total;
						var ntotal = jsonData.nbTotalProducts;
						$('#header-cart').html('<a href="'+baseDir+'order.php">'+ ntotal +' '+article_trad+(ntotal > 1 ? 's' : '')+'</a><br /><a href="'+baseDir+'order.php">'+total+'</a>');
					}
				}
			});
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("TECHNICAL ERROR: unable to add the product.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
			//reactive the button when adding has finished
			if (addedFromProductPage)
				$('body#product p#add_to_cart input').removeAttr('disabled').addClass('exclusive').removeClass('exclusive_disabled');
			else
				$('.ajax_add_to_cart_button').removeAttr('disabled');
		}
	});
}

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

//check if a function exists
function function_exists(function_name)
{
	if (typeof function_name == 'string')
		return (typeof window[function_name] == 'function');
	return (function_name instanceof Function);
}

//execute oosHook js code
function oosHookJsCode()
{
	for (var i = 0; i < oosHookJsCodeFunctions.length; i++)
	{
		if (function_exists(oosHookJsCodeFunctions[i]))
		setTimeout(oosHookJsCodeFunctions[i]+'()', 0);
	}	
}

//add a combination of attributes in the global JS sytem
function addCombination(idCombination, arrayOfIdAttributes, quantity, price, sold_out, product_id)
{
	var combination = new Array();
	combination['id_product'] = product_id;
	combination['idCombination'] = idCombination;
	combination['idsAttributes'] = arrayOfIdAttributes;
	combination['quantity'] = quantity;
	combination['price'] = price;
	combination['sold_out'] = sold_out;
	combinations.push(combination);
}

// search the combinations' case of attributes and update displaying of availability, prices, ecotax, and image
function findCombination(elt)
{
	if (!isNaN(elt))
		var product_id = elt;
	else
	{
		var product_id = elt.attr('alt');
		$('form#add_ajax_cart_'+product_id+' #btn-return-link').css('margin-top', '10px');
	}
	//create a temporary 'choice' array containing the choices of the customer
	var choice = new Array();
	$('form#add_ajax_cart_'+product_id+' div.select-size a.selected').each(function(){
		choice.push($(this).attr('href'));
	});
	var nbAttributesEquals = 0;
	//testing every combination to find the conbination's attributes' case of the user

	for (combination in combinations)
	{
		if (combinations[combination]['id_product'] == product_id)
		{
			var 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;
				$('form#add_ajax_cart_'+product_id+' #idCombination').val(combinations[combination]['idCombination']);
				$('form#add_ajax_cart_'+product_id+' span.selected_size').text('');
				$('form#add_ajax_cart_'+product_id+' span.selected_size').text($('form#add_ajax_cart_'+product_id+' div.select-size a.selected').text());

				//get the data of product with these attributes
				quantityAvailable = combinations[combination]['quantity'];
				selectedCombination['price'] = combinations[combination]['price'];
				//update the display
				updateDisplay(product_id);
				/* Zed */
				//refreshProductImages(combinations[combination]['idCombination']);
				/* End */
				//leave the function because combination has been found
				return;
			}
		}
	}
	//this combination doesn't exist (not created in back office)
	selectedCombination['unavailable'] = true;
	updateDisplay(product_id);
}

//update display of the availability of the product AND the prices of the product
function updateDisplay(product_id)
{
	//alert(product_id);
	if($('form#add_ajax_cart_'+product_id+' div.select-size').size() != 0 && $('form#add_ajax_cart_'+product_id+' div.select-size a.selected').attr('href') != '-1')
	{
		var pr = $('form#add_ajax_cart_'+product_id+' div.select-size a.selected').attr('rel').split(';');
		switch(currency_format) {
			case 1:
			case 3:
				$('div#product-info #price_'+product_id).html(currency_sign + parseFloat(pr[0]).toFixed(2));
				$('#old_price_'+product_id).html(currency_sign + parseFloat(pr[1]).toFixed(2));
				break;
			default:
				$('#price_'+product_id).html(parseFloat(pr[0]).toFixed(2) + ' ' + currency_sign);
				$('#old_price_'+product_id).html(parseFloat(pr[1]).toFixed(2) + ' ' + currency_sign);
				break;
		}
	}
	else if ($('p#one-size').size() != 0)
		$('form#add_ajax_cart_'+product_id+' #btn-return-link').css('margin-top', '10px');
	
	if (!selectedCombination['unavailable'] && quantityAvailable > 0)
	{
		// show the "add to cart" button ONLY if it was hidden
		$('form#add_ajax_cart_'+product_id+' .select-quantity:hidden').fadeIn('fast');
		$('form#add_ajax_cart_'+product_id+' #btn-return-link').css('padding-left', '58px');
		
		//hide the hook out of stock
		// Z - test if module mailalerts is active
		if(typeof oosHookJsCodeMailAlert == 'function') 
			oosHookJsCodeMailAlert(true, product_id);
		else $('form#add_ajax_cart_'+product_id+' #oosHook').hide();
	}
	else if (allowBuyWhenOutOfStock && availableLaterValue != '')
	{
		//hide the hook out of stock
		// Z - test if module mailalerts is active
		if(typeof oosHookJsCodeMailAlert == 'function') 
			oosHookJsCodeMailAlert(true, product_id);
		else $('form#add_ajax_cart_'+product_id+' #oosHook').hide();
	}
	else
	{
		//show the hook out of stock
		if ($('form#add_ajax_cart_'+product_id+' #oosHook').length > 0 && typeof oosHookJsCodeMailAlert == 'function') 
			oosHookJsCodeMailAlert(false, product_id);
		else
			$('form#add_ajax_cart_'+product_id+' #oosHook').show();
		
		if (allowBuyWhenOutOfStock && !selectedCombination['unavailable'])
		{
			$('form#add_ajax_cart_'+product_id+' .select-quantity:hidden').fadeIn('fast');
		}
		else
		{
			$('form#add_ajax_cart_'+product_id+' .select-quantity:visible').fadeOut('fast');
			$('form#add_ajax_cart_'+product_id+' #btn-return-link').css('padding-left', '0');
		}
	}
}

//To do after loading HTML
$(document).ready(function(){
	$('img.jqzoom').jqueryzoom({
		xzoom: 370, //zooming div default width(default width value is 200)
		yzoom: 430, //zooming div default width(default height value is 200)
		offset: 10 //zooming div default offset(default offset value is 10)
	});
	$('#centralpics').attr('alt', $('#centralpics').attr('alt').replace('-jqzoom', ''));
	$('img.minihover').click(function(){
//		return;

		var img_list = {};
		
		img_list = {
			'central' : $(this).attr('rel'),
			'fancy' : $(this).attr('src').replace('-mediumpack', '-thickbox').replace('-medium', '-thickbox'),
			'thickbox': $(this).attr('src').replace('-mediumpack', '').replace('-medium', '')
		};

		$('#centralpics').attr('src', img_list.central);		
		$('#centralpics').attr('alt', img_list.thickbox);

		$('#fancy').attr('href', img_list.fancy);

		return false;
	});
	$('#fancy').attr('href', $('#centralpics').attr('src').replace('-largepack/', '-thickbox/'));
	$('#fancy').attr('href', $('#centralpics').attr('src').replace('-large/', '-thickbox/'));
	$('#fancy').fancybox({
		'zoomOpacity': true,
 		'zoomSpeedIn': 500, 
 		'zoomSpeedOut': 500,
 		'overlayShow': false
	});
	
	$('.add_to_cart')
		.bind('click', function() {
			one_size = $('p.one-size-'+$(this).parents('form').find('input#product_page_product_id').val());
			if (($(this).parents('form').find('input#idCombination').val() == ''
				|| $(this).parents('form').find('input#idCombination').val() == 0)
				&& (one_size.length == 0 || !one_size))
			{
				$('a#inline').fancybox().trigger('click');
				return false;
			}
			else
			{
				ajax_cart(
					$(this).parents('form').find('input#product_page_product_id').val(), 
					$(this).parents('form').find('input#idCombination').val(), 
					$(this).parents('form').find('div.select-quantity select').val(),
					$(this).parents('form'));
				return false;
			}
		})
		.addClass('toto');
	
	//init the price in relation of the selected attributes
	if (typeof productHasAttributes != 'undefined' && productHasAttributes)
		findCombination();
});

function saveCustomization()
{
	$('#quantityBackup').val($('#quantity_wanted').val());
	$('body select[@id^="group_"]').each(function() {
		$('#customizationForm').attr('action', $('#customizationForm').attr('action') + '&' + this.id + '=' + parseInt(this.value));
	});
	$('#customizationForm').submit();
}

function imagebox(id_prod, index, src)
{
	$('.imagebox-div').stop(true, true);
	var div = $('#imagebox-id'+id_prod);
	imageboxClose();
	if (div.css('display') == 'block')
		return false;
	hlToProduct(id_prod);
	if ((index) % 5 >= 2 && parseInt(div.css('left')) > 0) {
		div.css('left', (parseInt(div.css('left')) - div.width() - 180)+'px');
	}
	div.css({'top': '-150px'});
	var img = loadimage(src);
	div.show('slow');
	img.onload = function() {
			$('#imagebox-id'+id_prod+' img.prod_img').attr('src', src);
			$('#imagebox-id'+id_prod+' img.prod_img').show('slow');
		};
	return false;
}

function imageboxClose()
{
	closeAll();
	return false;
}

function closeAll()
{
	$('.imagebox-div').stop(true, true);
	$('.imagebox-div').hide('slow');
	$('.ajaxccart').stop(true, true);
	$('.ajaxccart').hide();
	$('.to-product-page').removeClass('hl');
	return false;
}

function hlToProduct(id)
{
	$('#to-product-page-id'+id).addClass('hl');
}

function loadimage(url)
{
	var img = new Image();
	img.src = url;
	return img;
}