
//JS Object : update the bulk cart by ajax actions
var ajaxBulkCart = {
	
	//override every button in the page in relation to the cart
	overrideButtonsInThePage : function(){
		//for every 'add to bulk' buttons...
		$('.ajax_add_to_bulk_button').unbind('click').click(function(){
			var idProduct =  $(this).attr('rel').replace('ajax_id_product_', '');
			ajaxBulkCart.add(idProduct, 1, false, this);
			return false;
		});

		//for product page 'add to bulk' button...
		$('body#product p#add_to_bulk input').unbind('click').click(function(){
			ajaxBulkCart.add( $('#product_page_product_id').val(), 1, true, null);
			return false;
		});
		
		//for bulk cart 'add bulk to cart' button...
		$('#add_to_cart_bulk_product').unbind('click').click(function(){
			ajaxBulkCart.addBulkToCart();
			return false;
		});

		//for 'delete from bulk' buttons in the cart block...
		$('.ajax_bulkcart_block_remove_link').unbind('click').click(function(){
			var position =  $(this).parent().parent().parent().attr('id').replace('bulk_item', '');
			var idProduct = $('#bulkcart_block_product_'+position).attr('value');
			ajaxBulkCart.remove(idProduct,position);
			return false;
		});

		//for 'delete last product from bulk' buttons in the cart block...
		$('.ajax_bulkcart_block_remove_last_product_link').unbind('click').click(function(){
			var position = $('#nb_max_elements').val() - $('#bulkcart dl.products > dt.not_empty').size() + 1;
			var idProduct = $('#bulkcart_block_product_'+position).attr('value');
			ajaxBulkCart.remove(idProduct,position);
			return false;
		});
	},
	
	add : function(idProduct, quantity, addedFromProductPage, callerElement){
		//send the ajax request to the server
		$.ajax({
			type: 'GET',
			url: baseDir + 'bulk_cart.php',
			async: true,
			cache: false,
			dataType : "json",
			data: 'add&ajax=true&id_product=' + idProduct + '&token=' + static_token,
			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: $('#bulkcart').get(0),
							className:'transferProduct',
							duration: 800,
							complete: function () {ajaxBulkCart.updateCart(jsonData)}
				});
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {alert("TECHNICAL ERROR: unable to add the product.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);}
		});
	},
	
	addBulkToCart : function(){
		//send the ajax request to the server
		$.ajax({
			type: 'GET',
			url: baseDir + 'bulk_cart.php',
			async: true,
			cache: false,
			dataType : "json",
			data: 'add_bulk&ajax=true&token=' + static_token,
			success: function(jsonData)
			{
				//apply 'transfert' effect
				$('div#bulk_cart_block_list').TransferTo({
							to: $('#cart_block').get(0),
							className:'transferProduct',
							duration: 800,
							complete: function () { ajaxBulkCart.updateCart(jsonData); 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, position){
		//send the ajax request to the server
		$.ajax({
			type: 'GET',
			url: baseDir + 'bulk_cart.php',
			async: true,
			cache: false,
			dataType : "json",
			data: 'ajax=true&delete&id_product=' + idProduct + '&position=' + position + '&token=' + static_token,
			success: function(jsonData)	{ ajaxBulkCart.updateCart(jsonData) },
			error: function() {alert('ERROR : unable to delete the product');}
		});
	},
	
	updateDisplayProducts : function(jsonData) {
		if(jsonData.deleted_position != null){
			//a product have been deleted
			if($('#bulkcart dl.products > dt.not_empty').size() > 0)
			{
				//Il y a bien au moins un produit à supprimer
				$('#bulkcart dl.products dt#bulk_item'+jsonData.deleted_position).addClass('strike').fadeTo('slow', 0, function(){
					$(this).removeClass('strike').removeAttr('style');
					for(var i = jsonData.deleted_position; i > 1; --i){
						if($('#bulkcart dl.products #bulkcart_block_product_'+(i-1)).val() != -1){
							$('#bulkcart dl.products dt#bulk_item'+i+' span.bulkcart_block_info_product').replaceWith($('#bulkcart dl.products dt#bulk_item'+(i-1)+' span.bulkcart_block_info_product'));
							$('#bulkcart dl.products #bulkcart_block_product_'+i).val($('#bulkcart dl.products  #bulkcart_block_product_'+(i-1)).val());
							$('#bulkcart dl.products dt#bulk_item'+(i-1)).html('<input type="hidden" id="bulkcart_block_product_'+(i-1)+'" value="-1" /><span class="bulkcart_block_info_product"/>');
						}
						else{
							if($('#bulkcart dl.products #bulkcart_block_product_'+i).val() != -1){
								$('#bulkcart dl.products dt#bulk_item'+i).empty();
								$('#bulkcart dl.products dt#bulk_item'+i).html('<input type="hidden" id="bulkcart_block_product_'+i+'" value="-1" /><span class="bulkcart_block_info_product"/>');
							}
							if($('#bulkcart dl.products dt#bulk_item'+i).hasClass('not_empty')){
								$('#bulkcart dl.products dt#bulk_item'+i).removeClass('not_empty');
							}
						}
					}
					$('#bulkcart dl.products dt#bulk_item1').empty();
					$('#bulkcart dl.products dt#bulk_item1').removeClass('not_empty');
					$('#bulkcart dl.products dt#bulk_item1').html('<input type="hidden" id="bulkcart_block_product_1" value="-1" /><span class="bulkcart_block_info_product"/>');

					ajaxBulkCart.updateCartEverywhere(jsonData);	
				});
			}
		}
		else if(jsonData.add_bulk){
			var nb_products = $('#bulkcart dl.products > dt.not_empty').size();
			if(nb_products > 0)
			{
				for(var position=nb_products; position > 0; --position){
					$('#bulkcart dl.products dt#bulk_item'+position).addClass('strike').fadeTo('slow', 0, function(){
						$(this).removeClass('not_empty');
						$(this).removeClass('strike').removeAttr('style');
						$(this).empty();
						$(this).html('<input type="hidden" id="bulkcart_block_product_'+$(this).attr('id').charAt($(this).attr('id').length - 1)+'" value="-1" /><span class="bulkcart_block_info_product"/>');
						if($('#bulkcart dl.products > dt.not_empty').size() == 0){
							ajaxBulkCart.updateCartEverywhere(jsonData);
						}
					});
				}
			}
		}
		else if(jsonData.add){
			var num_elements = $('#nb_max_elements').val() - $('#bulkcart dl.products > dt.not_empty').size();
			if((jsonData.nb_more_products > 0) || (num_elements == 1)){
				var aProduct = jsonData.bulk_products[num_elements-1];
				$('#bulkcart dl.products dt#bulk_item'+num_elements).attr('style','opacity: 0;').empty().addClass('not_empty');
				$('#bulkcart dl.products dt#bulk_item'+num_elements).html(
						'<input type="hidden" id="bulkcart_block_product_'+num_elements+'" value="'+aProduct.id+'" />' +
						'<span class="bulkcart_block_info_product">' +
						'	<span class="bulkcart_block_product_name">'+aProduct.name+'</span>' +
						'	<span class="remove_link"><a class="ajax_bulkcart_block_remove_link" href="'+aProduct.delete_link+'" title="'+jsonData.delete_text+'">&nbsp;X</a></span>' +
						'	<div class="bulk_line"></div>' +
						'</span>');
				$('#bulkcart dl.products dt#bulk_item'+num_elements).fadeTo('slow',1,function(){
					ajaxBulkCart.updateCartEverywhere(jsonData);
				});
			}
		}
	},

	//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);
		}

		ajaxBulkCart.updateDisplayProducts(jsonData);
		
		//reset the onlick events in relation to the cart block (it allow to bind the onclick event to the new 'delete' buttons added)
		ajaxBulkCart.overrideButtonsInThePage();
	},
	
	//update general cart informations everywere in the page
	updateCartEverywhere : function(jsonData) {
		var num_elements = $('#bulkcart dl.products > dt.not_empty').size();
		var max_elements = $('#nb_max_elements').val();
		if(num_elements == 0){
			$('#not_empty_bulk_cart').attr('style','display:none; visibility:hidden;');
			$('#empty_bulk_cart').removeAttr('style');
		}
		else{
			$('#empty_bulk_cart').attr('style','display:none; visibility:hidden;');
			$('#not_empty_bulk_cart').removeAttr('style');
			$('#bulkcart dl.products').removeClass().addClass("products").addClass("nb_items"+jsonData.nb_bulk_products);
			$('#bulkcart_total_price').text(jsonData.total_bulk_products);
			if(jsonData.nb_more_products == 0){
				$('#add_to_cart_bulk_product').removeAttr('style');
				$('#cancel_bulk_product').removeAttr('style');
			}
			else{
				$('#cancel_bulk_product').attr('style','margin-left:47px;');
				$('#add_to_cart_bulk_product').attr('style','display:none; visibility:hidden;');
			}
		}
	}
}
//when document is loaded...
$(document).ready(function(){
	ajaxBulkCart.overrideButtonsInThePage();
	
});

