var products = new Array(); // Will hold an array of Product objects

//Product object
function Product() {
	this.id = 0;
	this.quantity = 0;
}

$(document).ready(function() {
	initCart();
});


// Load products into array from cookie. Should be called on domready
function initCart() {

	// Load details from cookie "shoppingcart"
	var cookieval = $.cookie("shoppingcart");
	// If there is anything inside the cookie, parse it
	if (cookieval != null && cookieval != '') {
		
		var items = cookieval.split('|');

		for(var i = 0; i < items.length; i++) {
		
			var item_detail = items[i].split(',');
			
			if (item_detail.length == 2) {
				var product = new Product();
				product.id = item_detail[0];
				product.quantity = item_detail[1];
				products.push(product);
			}
		}
		
		
		//checkForAddedItems();
	}
	updateTotals();
	$("#MailMethodDiv input[type=radio]").click(function(){
		updateTotals();
		if ($(this).attr('id') == 'mailmethod3') {
			
			$('.deliverydate').attr("disabled", 'disabled');
			$('.deliverydate').css("background-color", "#eeeeee");
			
			if ($(this).attr('checked') && products.length > 1 && (!$('#DeliverAll').attr('checked'))) {
				alert('The Express Delivery fee is charged per address. If the Red Packet Gifts should be delivered to the same address, please select "Deliver all the items to the above address".');
			}
		}
		else {
			$('.deliverydate').attr("disabled", false);
			$('.deliverydate').css("background-color", "#ffffff");
		}
	});
	
	$("#DeliverAll").click(function(){
		updateTotals();
		if (!$(this).attr('checked') && products.length > 1 && ($('#mailmethod3').attr('checked'))) {
			alert('The Express Delivery fee is charged per address. If the Red Packet Gifts should be delivered to the same address, please select "Deliver all the items to the above address".');
		}
	});
	
	updateItemsInHeader();
}


function saveEnquiryCookie() {
	var shoppingcart = '';
	
	// Loop all the products
	// cookie format: id,quantity|id,quantity,price|id,quantity
	// The delimiter is a pipe
	for (var i = 0; i < products.length; i++) {
		if (shoppingcart != '') {
			shoppingcart+= '|';
		}
		shoppingcart += ''+products[i].id+','+products[i].quantity;
	}
	
	$.cookie("shoppingcart", shoppingcart, { path: '/'});
}


// Checks the webpage (listings, or detail page + also interested in) for items that need to be marked as 'added'
function checkForAddedItems() {

	if (typeof(page_type) != 'undefined') {
		
		var id;
		for (var i = 0; i < products.length; i++) {
			id = products[i].id;

			if (page_type == 'listing') {
				// For listing page
				$('#product_listing_id_' + id).removeClass('productItem_AddBtn added_small').addClass("productItem_AddBtn added_small");
			}
			else if (page_type == 'detail') {
				// For detail page
				$('#product_detail_' + id).removeClass('ProductItemDetail_addToCartBtn added').addClass("ProductItemDetail_addToCartBtn added");
				
				// For detail page - also interested in
				$('#productItemPreview_' + id).removeClass('productItemPreview_addBtn added_small').addClass("productItemPreview_addBtn added_small");
			}
		}
	}

}


function IsNumeric(sText) {
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;
	
	if (sText == '') {
		return false;
	}
	
	for (i = 0; i < sText.length && IsNumber == true; i++) { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1)  {
			IsNumber = false;
			break;
		}
	}
	return IsNumber;
}


function addProduct(id, quantity) {

	// Validate quantity, make sure it's a number and larger than 0, otherwise it's pointless
	if (IsNumeric(quantity) && quantity > 0) { 
	
		// For listing page
		//$('#product_listing_id_' + id).removeClass('productItem_AddBtn added_small').addClass("productItem_AddBtn added_small");

		// For detail page
		//$('#product_detail_' + id).removeClass('ProductItemDetail_addToCartBtn added').addClass("ProductItemDetail_addToCartBtn added");
		
		// For detail page - also interested in
		//$('#productItemPreview_' + id).removeClass('productItemPreview_addBtn added_small').addClass("productItemPreview_addBtn added_small");

		//if (!productAlreadyInCart(id)) {
			product = new Product();
			product.id = id;
			product.quantity = quantity;
			products.push(product);
			
			// Save the stuff inside a cookie
			saveEnquiryCookie();

			updateItemsInHeader();
		//}
	}
	else {
		alert('please enter a quantity');
	}
}


// Returns true/false whether the product is already inside the cart
function productAlreadyInCart(id) {
	var result = false;

	for (var i = 0; i < products.length; i++) {
		if (products[i].id == id) {
			result = true;
			break;
		}
	}
	
	return result;
}


function updateQuantity(id, value) {

	// Find product, and update
	for (var i = 0; i < products.length; i++) {
		if (products[i].id == id) {

			// Validate value, make sure it's a number
			if (!IsNumeric(value)) {
				// Reset original value!
				$('#product_row_' + id + ' .enquiry_basket_quantity input').val(products[i].quantity);
			}
			else {
				products[i].quantity = value;
			}
			
			// Update item total
			updateItemTotal(products[i].quantity, id);
			
			saveEnquiryCookie();
			updateTotals();
			break;
		}
	}
}

function updateItemTotal(quantity, id) {
	// Update total price for this product on the form
	var price = parseFloat($('#product_row_' + id + ' .enquiry_basket_price span').text());
	price = price * quantity;
	
	var str_price = price.toFixed(2);
	$('#product_row_' + id + ' .enquiry_basket_total span').text(str_price);
}


function increaseQuantity(id) {
	// Find product, and update
	for (var i = 0; i < products.length; i++) {
		if (products[i].id == id) {
			products[i].quantity++;
			
			// Update quantity for this product on the form
			$('#product_row_' + id + ' .enquiry_basket_quantity input').val(products[i].quantity);
			updateItemTotal(products[i].quantity, id);
			break;
		}
	}
	
	saveEnquiryCookie();
	updateTotals();
}


function decreaseQuantity(id) {
	
	// Find product, and update
	for (var i = 0; i < products.length; i++) {
		if (products[i].id == id) {
			if (products[i].quantity > 1) {
				products[i].quantity--;

				// Update for this product on the form
				$('#product_row_' + id + ' .enquiry_basket_quantity input').val(products[i].quantity);
				updateItemTotal(products[i].quantity, id);
				saveEnquiryCookie();
				updateTotals();
				break;
			}
		}
	}

}


function removeProduct(id,item) {
	// Delete from array
	
	if(confirm("Are you sure you want to delete this item?")) {
		// Find product, and delete
		for (var i = 0; i < products.length; i++) {
			if (products[i].id == id) {
				// Remove item from array
				products.splice(i,1);
				// Remove row from html table
				$('#' + item).remove();
				
				saveEnquiryCookie();
				updateTotals();
				updateItemsInHeader();
				break;
			}
		}
	}

}


// Updates all the subtotals and the grand total
function updateTotals() {
	var subtotal = 0.00;
	var mailfee = parseFloat($("#MailMethodDiv input:radio:checked").val());
	
	
	if ($('#mailmethod3').attr('checked') && products.length > 1 && (!$('#DeliverAll').attr('checked'))) {
		mailfee = mailfee * products.length;
	}
	
	$('.enquiry_basket_total span').each(function(i, o){
		subtotal = subtotal += parseFloat(o.innerHTML);
	});
	
	
	
	total = subtotal + mailfee;
	$('.cartsubtotal span').text(subtotal.toFixed(2));
	$('.carttotal span').text(total.toFixed(2));
	if(subtotal == 0)
	{
		//window.location.reload();
	}	
}


// Updates the total inside the header
function updateItemsInHeader() {
	var total = products.length;
	if (total == '') {
		total = 0
	}; 
	$('#EnquiryItems_Items').html(total);
	$('.modal_totalitem').html(total);
}