
/////Cookie content change

function qtyChange (ID, qty, add)
{
	//if (add=NULL) add=false;
	var cookie = $.cookie('shopCartHS');
	if (cookie)
	{
		var product = decodeURIComponent(cookie);
		
		prod_arr = product.split('#');
		if (typeof(prod_arr)=='string')
			prod_arr = [prod_arr];
		old_qty = 0;
		for(var i=0; i<prod_arr.length; i++)
		{
			prod = prod_arr[i];
			prod = prod.split('&');
			if (prod[0] == 'ID=' + ID)
			{
				old_qty += parseInt(prod[1].split('=')[1]);
				prod_arr.splice(i, 1);
			}
			
		}
		
		if (qty)
		{
			if (add) {
				qty = parseInt(qty);
				qty += parseInt(old_qty);
			}
			if(prod_arr.length>=1)
				product = prod_arr.join("#") + "#" + "ID=" + ID + "&qty=" + qty;
			else
				product = "ID=" + ID + "&qty=" + qty;
		} 
		else
		{
			product = prod_arr.join("#");
		}
		
	} else {
			var product = "ID=" + ID + "&qty=" + qty;
	}	
			
	$.cookie('shopCartHS', product, {expires: 1, path:'/'});
	
	return product;	
}

//Set Cookie for Gift Basket Flavors
function giftTypesCookie (ID, types, read)
{
	//if (add=NULL) add=false;
	var type_txt = '';
	var cookie = $.cookie('giftTypesHS'+ID);
	if (cookie != '')
	{
		if (read)
		{
			var giftTypes = decodeURIComponent(cookie);
			
			type_array = giftTypes.split('&');
			
			var types_arr = [];
			if (type_array[0] == 'ID=' + ID)
			{
				types_arr = type_array[1].split('#');
			}
			
			return types_arr;
		}
		else
		{
			var type_str = '';
			for(var i=0; i<types.length; i++)
			{
				if (i < types.length -1)
				{
					type_str += types[i] + '#';
				}
				else
				{
					type_str += types[i];
				}
			}
			type_txt = "ID=" + ID + "&" +  type_str;
		}
	}
	else
	{
		var type_str = '';
		for(var i=0; i<types.length; i++)
		{
			if (i < types.length -1)
			{
				type_str += types[i] + '#';
			}
			else
			{
				type_str += types[i];
			}
		}
		type_txt = "ID=" + ID + "&" +  type_str;
	}
			
	$.cookie('giftTypesHS'+ID, type_txt, {expires: 1, path:'/'});
	
	return type_txt;	
}

function getQty(ID)
{
	var cookie = $.cookie('shopCartHS');
	var allQty = 0;
	if (cookie)
	{
		var product = decodeURIComponent(cookie);
		
		prod_arr = product.split('#');
	
		for(var i=0; i<prod_arr.length; i++)
		{
			prod = prod_arr[i];
			prod = prod.split('&');
			if (ID)
			{
				if (prod[0] == 'ID=' + ID)
				{
					a = prod[1].split('=');
					return a[1];
				}
			}
			else
			{
				a = prod[1].split('=');
				allQty += parseInt(a[1]);
			}
		}
		
		if  (!ID)
			return allQty;
	}
}

$(document).ready(function(){

//	$('form[id^=addProduct]').each(function(index){
//			
//			var formID = $(this).attr('id');
//			var ID = $('#' + formID + ' > [name=ID]').val();
//			
//			/////////////////////Saving gifts types in cookie
//			if ($('#giftTypes' + ID).length != 0)
//			{
//				var giftTypes = giftTypesCookie(ID, null, true);
//			}
//			///////////////////////////
//	});
	
	if ($('#productRight').length != 0)
	{
		var IDstatus = $('[name=IDstatus]').val();
		var prodName = $('[name=giftCat]').val();
		$.post (
				
				'files/shoppingCart.php',
				{action: 'getStatusValue', ID: IDstatus},
				function(data) {
					if (data)
					{
						$('#addProduct').remove();
						$('#statusText').html('<div style="color:#c00;font-weight:bold;">SOLD OUT</div>');
					}
				},
				"json"
		);
		if ($('#giftTypes').length!= 0)
		{
			$.post (
					
					'files/shoppingCart.php',
					{action: 'getGiftTypes', ID: IDstatus, name: prodName},
					function(data) {
						if (data)
						{
							var output = '';
							for (var i = 0; i < data.length; i++)
							{
								output += data[i];
							}
							$('#giftTypes').html(output);
						}
					},
					"json"
			);
			
		}
	}
	
	$('form[id^=addProduct]').each(function(index){
		
			var formID = $(this).attr('id');
			var ID = $('#' + formID + ' > [name=ID]').val();
			var prodName = $('[name=giftCat' + ID + ']').val();
			
			$.post (
					
					'files/shoppingCart.php',
					{action: 'getGiftTypes', ID: ID, name: prodName},
					function(data) {
						if (data)
						{
								var output = '';
								for (var i = 0; i < data.length; i++)
								{
									output += data[i];
								}
								$('#giftTypes' + ID).html(output);
						}
					},
					"json"
				);
	});

	
		if ($('#shipForm').length != 0)
		{
			$('#shipForm').validate({
				rules: {
							field: "required",
							firstname: "required",
							lastname: "required",
							company: "required",
							address: "required",
							city: "required",
							state: "required",
							zip: "required",
							country: "required"								
			  }
			});

		}
	
		if ($('.qty'))
		{
			if ($('#shoppingCartTable').length == 0)
			{
				if ($('[name=ID]').length > 1)
				{
					$('[name=ID]').each(function(){
						singleID = $(this).val();
						$('#addProduct'+singleID + ' > .qty').val(getQty(singleID));
					})
				}
				else
				{
					singleID = $('[name=ID]').val();
					//getQty(singleID);
					$('.qty').val(getQty(singleID));
				}
			}
			
			$('.qty').bind('change', function() {
				
				var qty = $(this).val();
				if (qty.search(/^[0-9]+$/) != 0)
				{
			         alert("Enter correct quantity.");
			         return;
			    }
			
				if ($('#shoppingCartTable').length != 0)
				{
					var parentId = $(this).parents('tr').attr('id');
					var ID = parentId.substring(8);
					var price = $('#' + parentId + ' .pPrice span').text();
					
					qtyChange (ID, qty);
					$.post (
							
							'files/shoppingCart.php',
							{action: 'getAmount', ID: ID},
							function(data) {
								if (data)
								{
									var prodTotal = parseFloat(qty * data["price"]).toFixed(2);
									$('#' + parentId + ' .pTotal span').text(prodTotal);
									$('#merch').text(data["merch"]);
									$('#shipPrice').text(data["shipprice"]);
									$('#totalAmount').text(data["amount"]);
								}
							},
							"json"
					);
					var quant = getQty(); //parseInt($('#totalQuant').text()) - qty;
					if (quant != 0)
					{
						$("#totalQuant").text(quant);
					}
					else
					{
						$("#totalQuant").text('');
					}
				}				
			});
			

			if ($('#shoppingCartTable').length != 0)
			{
				var prodIds = [];
				$('[id^=product_]').each(function(index){
					prodIds[index] = $(this).attr('id');
				});
				if (prodIds.length != 0)
				{
					for (var k = 0; k < prodIds.length; k++)
					{
						var prodID = prodIds[k].substring(8);
						
						var typeCookie = $.cookie('giftTypesHS'+prodID);
						
						if (typeCookie)
						{
							var type_arr = typeCookie.split('&');							
							var types = type_arr[1].replace(/#/gi, ', ');
							
							$('#' + prodIds[k] + ' td.pName').append('<br /><div id="types_' + prodID + '">' + types + '</div>');
						}
					}
				}
				
				$('.deleteP').click(function() {
					
					var parentId = $(this).parents('tr').attr('id');					
					var ID = parentId.substring(8);
					
					var qty = $('#' + parentId + ' .qty').val();
					var quant = parseInt($('#totalQuant').text()) - qty;
					
					$(this).parents('tr').remove();
					qtyChange(ID, 0);
					
					var typeCookie = $.cookie('giftTypesHS'+ID);
					if (typeCookie)
					{
						$.cookie('giftTypesHS'+ID, null, {expires: -1, path:'/'});
					}
					
					if ($('#shoppingCartTable').find('tr').length > 1) {
					
						$.post (
								
								'files/shoppingCart.php',
								{action: 'getAmount', ID: ID},
								function(data) {
									if (data)
									{
										$('#merch').text(data["merch"]);
										$('#shipPrice').text(data["shipprice"]);
										$('#totalAmount').text(data["amount"]);
									}
								},
								"json"
						);
					} else {
						$.post (
								
								'files/shoppingCart.php',
								{action: 'getEmptyMsg'},
								function(data) {
									$('#shoppingCartTable').remove();
									$('.content').html('<div style="text-align: center;">' + data + "</div>");
								},
								"text"
						);	
					}
					if (quant != 0)
					{
						$("#totalQuant").text(quant);
					}
					else
					{
						$("#totalQuant").text('');
					}
				});
				
				$("#buyNowBtn").click(function(){
					
					$.post (
							
							'files/shoppingCart.php',
							{action: 'checkout'},
							function(data) {
							
								if (data)
								{
									$('#buyNowForm').prepend(data);
									$('#buyNowForm').submit();
								}
							},
							"html"
					);
					
				});
			}
		}
		
		
		$("#addProduct").submit(function(){
			
				var ID = $('[name=ID]').val();
				var qty = $('.qty').val();
				
				/////////////////////Saving gifts types in cookie
				var types = [];
				$('[name^=type]').each(function(index){types[index] = $(this).val();});
				giftTypesCookie(ID, types, false);
				///////////////////////////
				
				var cookieText = qtyChange (ID, qty, true);
				
				var len = cookieText.split('#').length;				
				cookieText = cookieText.split('#');
				var quant = 0;				
				for(var i=0; i<len; i++)
				{
					quant += parseInt(cookieText[i].substr (parseInt(cookieText[i].indexOf('qty=')) + 4));
				}
				$.post (
						
						'files/shoppingCart.php',
						{action: 'getName', ID: ID},
						function(data) {
							if (data)
							{
								$('#toShopCart').html("<p><br />" + data + " is currently available. It has been added to your basket.</p>" +
								"<div style='height:20px;'>" +
									"<div class='cartLink'>" +
										"<a href='http://www.harvestsongventures.com/en/shopping-cart/'>Shopping Cart </a>" +
										"<span id='totalQuant2'></span>" +
									"</div>" +
									"<div class='cartIcon'>" +
										"<img src='img/cart.gif' />" +
									"</div>" +
									"<br clear='all'>" +
								"</div>");
								$("#totalQuant2").text(quant);
							}
						},
						"text"
				);
				$("#totalQuant").text(quant);
				//$("#added").html("Product is added to Your shopping cart.");
				//$("#toShopCart").html(prodName + " is currently available. It has been added to your basket.<br />" +
				//		"<a href='http://www.harvestsongventures.com/en/shopping-cart/'>Click here</a> to view the contents of your shopping basket.");
		});
		
		if ($("#totalQuant").length != 0)
		{
			var coo = $.cookie('shopCartHS');
			var quant = 0;
			if (coo)
			{
				var product = decodeURIComponent(coo);
				
				var len = coo.split('#').length;				
				coo = coo.split('#');
				
								
				for(var i=0; i<len; i++)
				{
					quant += parseInt(coo[i].substr (parseInt(coo[i].indexOf('qty=')) + 4));
				}
			}
			
			if (quant != 0)
			{
				$("#totalQuant").text(quant);
			}
			else
			{
				$("#totalQuant").text('');
			}
		}
		
		if ($('#productList').length != 0)
		{
			var IDstatus = '';
			var data = {};
			$('[name=IDstatus]').each(function(){
				IDstatus = $(this).val();
				$.post (
						'files/shoppingCart.php',
						{action: 'getStatusValue',ID : IDstatus},
						function(data) {							
							if (data)
							{
								$('#addProduct' + data['prodID']).remove();
								$('#statusText' + data['prodID']).html('<div style="color:#c00;font-weight:bold;">SOLD OUT</div>');
							}
						},
						"json"
				);	
			});
			
			
				
			$('form[id^=addProduct]').each(function(index){
										$(this).submit(function(){
											
											var formID = $(this).attr('id');
											var ID = $('#' + formID + ' > [name=ID]').val();
											var qty = $('#' + formID + ' > .qty').val();
											
											/////////////////////Saving gifts types in cookie
											if ($('#giftTypes' + ID).length != 0)
											{
												var types = [];											
												$('#giftTypes' + ID + ' > [name^=type]').each(function(index){types[index] = $(this).val();});
												giftTypesCookie(ID, types, false);
											}
											///////////////////////////
											
											var cookieText = qtyChange (ID, qty, true);
											
											var len = cookieText.split('#').length;				
											cookieText = cookieText.split('#');
											var quant = 0;				
											for(var i=0; i<len; i++)
											{
												quant += parseInt(cookieText[i].substr (parseInt(cookieText[i].indexOf('qty=')) + 4));
											}
											$.post (
													
													'files/shoppingCart.php',
													{action: 'getName', ID: ID},
													function(data) {
														if (data)
														{
															$('[id^=toShopCart]').empty();
															$('#toShopCart'+ID).html("<p><br />" + data + " is currently available. It has been added to your basket.</p>" +
															"<div style='height:20px;'>" +
																"<div class='cartLink'>" +
																	"<a href='http://www.harvestsongventures.com/en/shopping-cart/'>Shopping Cart </a>" +
																	"<span id='totalQuant2"+ID+"'></span>" +
																"</div>" +
																"<div class='cartIcon'>" +
																	"<img src='img/cart.gif' />" +
																"</div>" +
																"<br clear='all'>" +
															"</div>");
															$("#totalQuant2"+ID).text(quant);
														}
													},
													"text"
											);
											$("#totalQuant").text(quant);
											
									});
						});
		}
			
});
