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(){
			$(".basketloading").fadeIn("normal");
			var idProduct =  $(this).attr('rel').replace('ajax_id_product_', '');
			ajaxCart.add(idProduct, false, this);
			return false;
		});
		//for product page 'add' button...
		$('.buy-more .buy-key').unbind('click').click(function(){
			$(".basketloading").fadeIn("normal");
			var idProduct =  $(this).attr('rel').replace('ajax_id_product_', '');
			ajaxCart.add( idProduct, true, this, $('.buy-count').val());
			return false;
		});
		//for 'delete' buttons in the cart block...
		$('.ajax_cart_block_remove_link').unbind('click').click(function(){
			$(".basketloading").fadeIn("normal");
			var idProduct =  $(this).attr('rel').replace('ajax_id_product_', '');
			ajaxCart.remove(idProduct);
			return false;
		});
		$('.basketpage_delete').unbind('click').click(function(){
			$(".basketloading").fadeIn("normal");
			var idProduct =  $(this).attr('rel').replace('delete_basket_', '');
			ajaxCart.remove(idProduct,true);
			return false;
		});
		$('.basketpage_quantity_up').unbind('click').click(function(){
			$(".basketloading").fadeIn("normal");
			var idProduct =  $(this).attr('rel').replace('quantity_up_', '');
			ajaxCart.quantity_up(idProduct);
			return false;
		});
		$('.basketpage_quantity_down').unbind('click').click(function(){
			$(".basketloading").fadeIn("normal");
			var idProduct =  $(this).attr('rel').replace('quantity_down_', '');
			ajaxCart.quantity_down(idProduct);
			return false;
		});
		$('.clear_basket_button').unbind('click').click(function(){
			$(".basketloading").fadeIn("normal");
			ajaxCart.clear();
			return false;
		});
		
	},
	
	// cart to fix display when using back and previous browsers buttons
	refresh : function(){
		//send the ajax request to the server
		$.ajax({
			type: 'GET',
			url: '/show_basket.html',
			async: true,
			cache: false,
			dataType : "json",
			data: 'ajax=true&action=refresh',
			success: function(jsonData)
			{
				ajaxCart.updateCart(jsonData)
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert('خطا در دریافت اطلاعات \n نوع خطا :\n '+textStatus);
			}
		});
	},
	clear : function(){
		//send the ajax request to the server
		$.ajax({
			type: 'GET',
			url: '/show_basket.html',
			async: true,
			cache: false,
			dataType : "json",
			data: 'ajax=true&action=clear',
			success: function(jsonData)
			{
				$(".basketloading").fadeOut("normal");
				ajaxCart.removeall();
				ajaxCart.updateCart(jsonData);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
			}
		});
	},
	quantity_up : function(idProduct){
		$.ajax({
			type: 'GET',
			url: '/show_basket.html',
			async: true,
			cache: false,
			dataType : "json",
			data: 'ajax=true&action=quantity_up&id_product=' + idProduct,
			success: function(jsonData)
			{
				$(".basketloading").fadeOut("normal");
				var quan = "#quentity_value_"+idProduct;
				$('.total_price_basket').text(jsonData.TotalPrice).fadeTo('fast', 1, function(){
					$(this).fadeTo('fast', 0, function(){
						$(this).fadeTo('fast', 1);
					});
				});
				$(quan).text(jsonData.quantity).fadeTo('fast', 1, function(){
					$(this).fadeTo('fast', 0, function(){
						$(this).fadeTo('fast', 1);
					});
				});
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert('خطا در دریافت اطلاعات \n نوع خطا :\n '+textStatus);
			}
		});
	},
	quantity_down : function(idProduct){
		//send the ajax request to the server
		$.ajax({
			type: 'GET',
			url: '/show_basket.html',
			async: true,
			cache: false,
			dataType : "json",
			data: 'ajax=true&action=quantity_down&id_product=' + idProduct,
			success: function(jsonData)
			{
				$(".basketloading").fadeOut("normal");
				var quan = "#quentity_value_"+idProduct;
				$('.total_price_basket').text(jsonData.TotalPrice).fadeTo('fast', 1, function(){
					$(this).fadeTo('fast', 0, function(){
						$(this).fadeTo('fast', 1);
					});
				});
				$(quan).text(jsonData.quantity).fadeTo('fast', 1, function(){
					$(this).fadeTo('fast', 0, function(){
						$(this).fadeTo('fast', 1);
					});
				});
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
			}
		});
	},
	// add a product in the cart via ajax
	add : function(idProduct, addedFromProductPage, callerElement, quantity){
		//disabled the button when adding to do not double add if user double click
		if (addedFromProductPage)
			$('.buy-more .buy-key').attr('disabled', 'disabled');
		else
			$('.ajax_add_to_cart_button').attr('disabled', 'disabled');
		
		//send the ajax request to the server
		$.ajax({
			type: 'GET',
			url: '/show_basket.html',
			async: true,
			cache: false,
			dataType : "json",
			data: 'action=add&ajax=true&qty=' + ( (quantity && quantity != null) ? quantity : '1') + '&id_product=' + idProduct ,
			success: function(jsonData)
			{
				$(".basketloading").fadeOut("normal");
				//apply 'transfert' effect
				var elementToTransfert = null;
				$(callerElement).parents().each( function() {
					if ($(this).is('.ajax_block_product')) elementToTransfert = $(this);
				});
				//alert(elementToTransfert);
				var targetOffset = $('#cart_block').offset().top;
				$('html,body').animate({scrollTop: targetOffset-100}, 1200);
				elementToTransfert.effect("transfer", { to: '#cart_block' }, 1200,function(){
					ajaxCart.updateCart(jsonData);
					if (addedFromProductPage)
						$('.buy-more .buy-key').removeAttr('disabled');
					else
						$('.ajax_add_to_cart_button').removeAttr('disabled');
				});
				  
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert("خطای فنی: محصول مورد نظر به سبد اضافه نشد.\n\nوضعیت:\nدارای خطا \n" + 'متن وضعیت: ' + textStatus);
				//reactive the button when adding has finished
				if (addedFromProductPage)
					$('.buy-more .buy-key').removeAttr('disabled');
				else
					$('.ajax_add_to_cart_button').removeAttr('disabled');
			}
		});
	},

	//remove a product from the cart via ajax
	remove : function(idProduct,FromBasketPage){
		//send the ajax request to the server
		$.ajax({
			type: 'GET',
			url:  '/show_basket.html',
			async: true,
			cache: false,
			dataType : "json",
			data: 'action=delete&id_product=' + idProduct + '&ajax=true',
			success: function(jsonData)	{
				$(".basketloading").fadeOut("normal");
				if (FromBasketPage){
					$("#row_"+idProduct).fadeOut();
					$.ajax({
						type: 'GET',
						url: '/show_basket.html',
						async: true,
						cache: false,
						dataType : "json",
						data: 'ajax=true&action=refresh',
						success: function(jsonData)
							{
								if (jsonData.TotalAllProduct==0) {
									$("#norowbasket").fadeIn("slow");
									$("#Navigation").fadeOut("slow");
									$(".ostanselect").fadeOut("slow");
									}
								$('.total_price_basket').text(jsonData.TotalPrice);
							},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							}
					});
				}else
					ajaxCart.hideOldProducts(jsonData);
			ajaxCart.updateCart(jsonData) },
			error: function() {alert('خطا :  حذف محصول با خطا مواجه شد');}
		});
	},

	// Update product quantity
	updateProductQuantity : function (product, quantity) {
		$('dt#cart_block_product_' + product.id  + ' .quantity').fadeTo('fast', 0, function() {
			$(this).text(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);
						});
					});
				});
			});
		});
	},


	//display the products witch are in json data but not 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.productlist').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;
				var domIdProductAttribute = this.id ;
				if($('#cart_block dt#cart_block_product_'+ domIdProduct ).length == 0)
				{
					$("#cart_block hr").fadeIn("normal");
					$(".show_basket_button").css("display","block").fadeIn("normal");
					$(".clear_basket_button").css("display","block").fadeIn("normal");
					
					var productId = parseInt(this.id);
					var content =  '<dt class="hidden" id="cart_block_product_' + productId + '">';
						 var name = (this.name.length > 13 ? this.name.substring(0, 12) + '...' : this.name);
						  content += '<a href="' + this.link + '" title="' + this.name + '">' + name + '</a>';
						 content += '<span class="quantity-formated"><span class="quantity">' + this.quantity + '</span>x</span>';
						  content += '<span class="remove_link"><a class="ajax_cart_block_remove_link" rel="ajax_id_product_' + productId +'" href="/show_basket.html?action=delete&amp;id_product=' + productId +'"> </a></span>';
						  content += '<span class="price">' + this.price + '</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>';
					if (this.hasAttributes) content += '</dd>';

					$('.productlist').append(content);
				}
				//else update the product's line
				else{
					var jsonProduct = this;
					if($('dt#cart_block_product_' + domIdProduct + ' .quantity').text() != jsonProduct.quantity)
					{
						// Usual product
						$('dt#cart_block_product_' + domIdProduct + ' .price').text(jsonProduct.price);
						ajaxCart.updateProductQuantity(jsonProduct, jsonProduct.quantity);
					}
				}
				$('.productlist .hidden').slideDown('slow').removeClass('hidden');

			var removeLinks = $('#cart_block_product_' + domIdProduct).find('a.ajax_cart_block_remove_link');
			if (this.hasCustomizedDatas && removeLinks.length)
				$(removeLinks).each(function() {
					$(this).remove();
				});
			}
		});
	},
	//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.updateCartEverywhere(jsonData);
		ajaxCart.displayNewProducts(jsonData);
		
		//update 'first' and 'last' item classes
		$('.productlist dt').removeClass('first_item').removeClass('last_item').removeClass('item');
		$('.productlist dt:first').addClass('first_item');
		$('.productlist dt:not(:first,:last)').addClass('item');
		$('.productlist 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();
	},
	removeall : function(jsonData) {
		$("[id^='cart_block_product_']").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();
				}
			});
		});
	},
	//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 dt').length > 0)
		{
			var removedProductId = null;
			var removedProductData = null;
			var removedProductDomId = null;
			//look for a product to delete...
			$('#cart_block 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 (jsonData.Products[aProduct]['id'] == ids[0])
						stayInTheCart = true;
				}
				//remove product if it's no more in the cart
				if(!stayInTheCart)
				{
					removedProductId = $(this).attr('id');
					//return false; // Regarding that the customer can only remove products one by one, we break the loop
				}
			});
			
			//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();
						}
					});
				});
			}
			
		}
	},
	//update general cart informations everywere in the page
	updateCartEverywhere : function(jsonData) {
		if(jsonData.TotalProduct > 0)
		{
			$('.ajax_total_product:hidden').fadeIn('slow');
			$('.ajax_total_all_product:hidden').fadeIn('slow');
			$('.ajax_total_price:hidden').fadeIn('slow');
			$('.ajax_total_product').text('تعداد محصولات :'+jsonData.TotalProduct);
			$('.ajax_total_all_product').text('تعداد سفارشات :'+jsonData.TotalAllProduct);
			$('.ajax_total_price').text('جمع کل :'+jsonData.TotalPrice);
			$('.ajax_cart_no_product:visible').hide();
		}
		else
		{
			$("#Navigation").fadeOut("slow");
			$(".ostanselect").fadeOut("slow");
			
			$('.ajax_total_product:visible, .ajax_total_all_product:visible, .ajax_total_price:visible, #cart_block hr:visible,.show_basket_button:visible,.clear_basket_button:visible').fadeOut('slow', function(){
				$('.ajax_cart_no_product:hidden').fadeIn('slow');
			});
		}
	}
}
$(document).ready(function(){
	ajaxCart.overrideButtonsInThePage();
	ajaxCart.refresh();
});

