

//JS Object : update the cart by ajax actions

var ajaxCart = {

	

	//override every button in the page in relation to the cart

	overrideButtonsInThePage : function(){

		//for every 'add' buttons...

		$('.ajax_add_to_cart_button').unbind('click').click(function(){

			var idProduct =  $(this).attr('rel').replace('ajax_id_product_', '');

			ajaxCart.add(idProduct, null, false, this);

			return false;

		});

		//for product page 'add' button...

		$('body#product p#add_to_cart input').unbind('click').click(function(){

			ajaxCart.add( $('#product_page_product_id').val(), $('#idCombination').val(), true, null, $('#quantity_wanted').val());

			return false;

		});

	

		//for 'delete' buttons in the cart block...

		$('.ajax_cart_block_remove_link').unbind('click').click(function(){

			//retrieve idProduct and idCombination from the displayed product in the block cart

			var firstCut =  $(this).parent().attr('id').replace('cart_block_product_', '');

			var ids = firstCut.split('_');

			//if product has attributes

			if(firstCut[1])

				ajaxCart.remove(ids[0], ids[1]);

			else

				ajaxCart.remove(ids[0]);

			return false;

		});

	},

	

	//try to expand the cart

	expand : function(){

		if ($('#cart_block #cart_block_list').hasClass('collapsed'))

		{

			$('#cart_block #cart_block_summary').slideUp(200, function(){

				$(this).addClass('collapsed').removeClass('expanded');

				$('#cart_block #cart_block_list').slideDown({

					duration: 600,

					complete: function(){$(this).addClass('expanded').removeClass('collapsed');}

				});

			});

			//toogle the button expand/collapse button

			$('#cart_block h4 span#block_cart_expand').fadeOut('slow', function(){

				$('#cart_block h4 span#block_cart_collapse').fadeIn('fast');

			});

			

			//save the expand statut in the user cookie

			$.ajax({

				type: 'GET',

				url: baseDir + 'modules/blockcart/blockcart-set-collapse.php',

				async: true,

				data: 'ajax_blockcart_display=expand' + '&rand;=' + new Date().getTime()

			});

			

			

		}

	},

	

	//try to collapse the cart

	collapse : function(){

		

		if ($('#cart_block #cart_block_list').hasClass('expanded'))

		{

			$('#cart_block #cart_block_list').slideUp('slow', function(){

				$(this).addClass('collapsed').removeClass('expanded');

				$('#cart_block #cart_block_summary').slideDown(700, function(){

					$(this).addClass('expanded').removeClass('collapsed');

				});

			});

			$('#cart_block h4 span#block_cart_collapse').fadeOut('slow', function(){

				$('#cart_block h4 span#block_cart_expand').fadeIn('fast');

			});

			

			//save the expand statut in the user cookie

			$.ajax({

				type: 'GET',

				url: baseDir + 'modules/blockcart/blockcart-set-collapse.php',

				async: true,

				data: 'ajax_blockcart_display=collapse' + '&rand;=' + new Date().getTime()

			});

		}

	},

	

	//add a product in the cart via ajax

	add : function(idProduct, idCombination, addedFromProductPage, callerElement, quantity){

		//send the ajax request to the server

		$.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 + ( (idCombination && idCombination != null) ? '&ipa=' + idCombination: ''),

			success: function(jsonData)

			{

				//apply 'transfert' effect

				var elementToTransfert = null;

				if (callerElement && callerElement != null)

					$(callerElement).parents().each( function() {

						if ($(this).is('.ajax_block_product')) elementToTransfert = $(this);

					});

				else

					elementToTransfert = $(addedFromProductPage ? 'div#image-block' : ('.ajax_block_product_id_' + idProduct) );

				elementToTransfert.TransferTo({

							to: $('#cart_block').get(0),

							className:'transferProduct',

							duration: 800,

							complete: function () {ajaxCart.updateCart(jsonData)}

				});

			},

			error: function(XMLHttpRequest, textStatus, errorThrown) {alert("TECHNICAL ERROR: unable to add the product.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);}

		});

	},

	

	//remove a product from the cart via ajax

	remove : function(idProduct, idCombination){

		//send the ajax request to the server

		$.ajax({

			type: 'GET',

			url: baseDir + 'cart.php',

			async: true,

			cache: false,

			dataType : "json",

			data: 'delete&ajax=true&qty=1&id_product=' + idProduct + '&token=' + static_token + ( (idCombination && idCombination != null) ? '&ipa=' + idCombination: ''),

			success: function(jsonData)	{ajaxCart.updateCart(jsonData)},

			error: function() {alert('ERROR : unable to delete the product');}

		});

	},

	

	//hide the products displayed in the page but no more in the json data

	hideOldProducts : function(jsonData) {

		//delete an eventually removed product of the displayed cart (only if cart is not empty!)

		if($('#cart_block #cart_block_list dl.products').length > 0)

		{

			var removedProductId = null;

			//look for a product to delete...

			$('#cart_block_list dl.products dt').each(function(){

				

				

				//retrieve idProduct and idCombination from the displayed product in the block cart

				var domIdProduct = $(this).attr('id');

				var firstCut =  domIdProduct.replace('cart_block_product_', '');

				var ids = firstCut.split('_');

				

				//try to know if the current product is still in the new list

				var stayInTheCart = false;

				for (aProduct in jsonData.products)

				{

					//we've called the variable aProduct because IE6 bug if this variable is called product

					//if product has attributes

					if (ids[1])

					{

						if (jsonData.products[aProduct]['id'] == ids[0] && jsonData.products[aProduct]['idCombination'] == ids[1]) 

							stayInTheCart = true;

					}

					else 

						if (jsonData.products[aProduct]['id'] == ids[0]) 

							stayInTheCart = true;

				

				}

				//remove product if it's no more in the cart

				if(!stayInTheCart)

				{

					removedProductId = $(this).attr('id');

				}

				

			});

			

			//if there is a removed product, delete it from the displayed block cart

			if (removedProductId != null)

			{

				var firstCut =  removedProductId.replace('cart_block_product_', '');

				var ids = firstCut.split('_');

				

				$('#'+removedProductId).addClass('strike').fadeTo('slow', 0, function(){

					$(this).slideUp('slow', function(){

						$(this).remove();

						///if the cart is now empty, show the 'no product in the cart' message

						if($('#cart_block dl.products dt').length == 0)

						{

							$('p#cart_block_no_products:hidden').slideDown('fast');

							$('div#cart_block dl.products').remove();

						}

					});

				});

				$('dd#cart_block_combination_of_' + ids[0] + (ids[1] ? '_'+ids[1] : '') ).fadeTo('fast', 0, function(){

					$(this).slideUp('fast', function(){

						$(this).remove();

					});

				});

			}

			

		}

	},

	

	//refresh display of vouchers (needed for vouchers in % of the total)

	refreshVouchers : function (jsonData) {

		$(jsonData.discounts).each(function(){

			//fix ie6 bug (one more item 'undefined' in IE6)

			if (this.id != undefined && $('#bloc_cart_voucher_' + this.id).length == 1)

			{

					$('#bloc_cart_voucher_' + this.id + ' td.price').text(this.price);

			}

		});

	},

	

	//display the products witch are in json data but no already displayed

	displayNewProducts : function(jsonData) {

		

		//add every new products or update displaying of every updated products

		$(jsonData.products).each(function(){

			//fix ie6 bug (one more item 'undefined' in IE6)

			if (this.id != undefined)

			{

				//create a container for listing the products and hide the 'no product in the cart' message (only if the cart was empty)

				if ($('div#cart_block dl.products').length == 0)

					$('p#cart_block_no_products:visible').fadeTo('fast', 0, function(){

						$(this).slideUp('fast').fadeTo(0, 1);

					}).before('<dl class="products"></dl>');

			

				//if product is not in the displayed cart, add a new product's line

				var domIdProduct = this.id + (this.idCombination ? '_' + this.idCombination : '');

				if($('#cart_block dt#cart_block_product_'+ domIdProduct ).length == 0)

				{

				

					var content =  '<dt class="hidden" id="cart_block_product_' + domIdProduct + '">';

						 content += '<span class="quantity-formated"><span class="quantity">' + this.quantity + '</span>x</span>';

						  content += '<a href="' + this.link + '" title="' + this.name + '">' + this.name + '</a>';

						  content += '<a class="ajax_cart_block_remove_link" href="' + baseDir + 'cart.php?delete&amp;id_product=' + this.id + '&amp;token=' + static_token + (this.has_attributes ? '&amp;ipa=' + this.attributes : '') + '"> </a>';

						  content += '<span class="price">' + this.priceByLine + '</span>';

						  content += '</dt>';

					if (this.hasAttributes)

						  content += '<dd id="cart_block_combination_of_' + domIdProduct + '" class="hidden"><a href="' + this.link + '" title="' + this.name + '">' + this.attributes + '</a></dd>';

					$('#cart_block dl.products').append(content);



					$('#cart_block dl.products .hidden').slideDown('slow').removeClass('hidden');

				}

				//else update the product's line

				else{

					var jsonProduct = this;

					if($('dt#cart_block_product_' + domIdProduct + ' .quantity').text() != jsonProduct.quantity)

					{

						$('dt#cart_block_product_' + domIdProduct + ' .price').text(jsonProduct.priceByLine);

						$('dt#cart_block_product_' + domIdProduct + ' .quantity').fadeTo('fast', 0, function() {

							$(this).text(jsonProduct.quantity);

							$(this).fadeTo('fast', 1, function(){

								$(this).fadeTo('fast', 0, function(){

									$(this).fadeTo('fast', 1, function(){

										$(this).fadeTo('fast', 0, function(){

											$(this).fadeTo('fast', 1);

										});

									});

								});

							});

						});

					}

				

				}

			}

		});

	},

	

	//genarally update the display of the cart

	updateCart : function(jsonData) {

		//user errors display

		if (jsonData.hasError)

		{

			var errors = '';

			for(error in jsonData.errors)

				//IE6 bug fix

				if(error != 'indexOf')

					errors += jsonData.errors[error] + "\n";

			alert(errors);

		}

		ajaxCart.expand();

		ajaxCart.updateCartEverywhere(jsonData);

		ajaxCart.hideOldProducts(jsonData);

		ajaxCart.displayNewProducts(jsonData);

		ajaxCart.refreshVouchers(jsonData);

		

		//update 'first' and 'last' item classes

		$('#cart_block dl.products dt').removeClass('first_item').removeClass('last_item').removeClass('item');

		$('#cart_block dl.products dt:first').addClass('first_item');

		$('#cart_block dl.products dt:not(:first,:last)').addClass('item');

		$('#cart_block dl.products dt:last').addClass('last_item');

		

		//reset the onlick events in relation to the cart block (it allow to bind the onclick event to the new 'delete' buttons added)

		ajaxCart.overrideButtonsInThePage();

	},

	

	//update general cart informations everywere in the page

	updateCartEverywhere : function(jsonData) {

		$('.ajax_block_cart_total').text(jsonData.total);

		$('.ajax_cart_total').text(jsonData.total);

		$('.ajax_cart_shipping_cost').text(jsonData.shippingCost);

		$('.cart_block_wrapping_cost').text(jsonData.wrappingCost);

		if(jsonData.nbTotalProducts > 0)

		{

			$('.ajax_cart_no_product:visible').hide();

			$('.ajax_cart_quantity').text(jsonData.nbTotalProducts);



			$('.ajax_cart_quantity:hidden').fadeIn('slow');

			$('.ajax_cart_total:hidden').fadeIn('slow');

			

			if(jsonData.nbTotalProducts > 1)

			{

				$('.ajax_cart_product_txt:visible').hide();

				$('.ajax_cart_product_txt_s:hidden').show();

			}

			else

			{

				$('.ajax_cart_product_txt:hidden').fadeIn('slow');

				$('.ajax_cart_product_txt_s:visible').fadeOut('slow');

			}

		}

		else

		{

			$('.ajax_cart_quantity:visible, .ajax_cart_product_txt_s:visible, .ajax_cart_product_txt:visible, .ajax_cart_total:visible').fadeOut('slow', function(){

				$('.ajax_cart_no_product:hidden').fadeIn('slow');

			});

		}

	}

}



//when document is loaded...

$(document).ready(function(){



	// expand/collapse management

	$('#block_cart_collapse').click(function(){

			ajaxCart.collapse();

	});

	$('#block_cart_expand').click(function(){

			ajaxCart.expand();		

	});

	ajaxCart.overrideButtonsInThePage();

	

});

