var products = new Array(); // Will hold an array of Product objects
var last_added_product = '';

//Product object
function Product() {
	this.id = 0;
	this.quantity = 0;
	this.pp = 0; // promotion products parent
	this.pap = 0; // promotion additional products parent
}

$(document).ready(function() {
	initBasket();
});


// Load products into array from cookie. Should be called on domready
function initBasket() {

	// Load details from cookie "yourbasket"
	var cookieval = $.cookie("yourbasket");

	// 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 == 4) {
				var product = new Product();
				product.id = item_detail[0];
				product.quantity = item_detail[1];
				product.pp = item_detail[2];
				product.pap = item_detail[3];
				products.push(product);
			}
		}

		updateItemsInHeader();
	}
}


function saveBasketCookie() {
	var yourbasket = '';
	
	// 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 (yourbasket != '') {
			yourbasket+= '|';
		}
		yourbasket += ''+products[i].id+','+products[i].quantity+','+products[i].pp+','+products[i].pap;
	}
	
	$.cookie("yourbasket", yourbasket, { path: '/'});
}


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 updatePromotionCosts() {
	$('.promotion_type_a .item_radio_options').each(function(ii, oo){

		$('#'+oo.id+' .radio').each(function(i, o){
			var promotion_id = 0;
			if (o.checked) {
				// Get the promotion_id
				promotion_id = $('#'+o.id).parent().parent('.promotion_detail_box').attr('id').substr(10);

				// Get the price for this selected item
				var original_price = parseInt($('#promotion_'+promotion_id+'_price').val());
				var price = parseInt($('#'+o.id+'_price').val());
				var new_price = original_price + price;
				
				// Update the price field
				$('#promotion_'+promotion_id+' .product_action .quantity_cost span').text(new_price);
				return false;
			}
		});
	});
}


function openPromotionBasketSummary() {
	$('#promotion_added').trigger('click');
}

function addPromotionProductTypeA(promotion_id) {
	var quantity = parseInt($('#quantity_'+promotion_id).val());
	var pp = parseInt($('#'+promotion_id+'_pp').val());
	var pap = parseInt($('#'+promotion_id+'_pap').val());
	
	
	// Check first if this promotion isn't in the cart yet
	if (!promotionAlreadyInCart(pp)) {
		// Get the products that belong to this promotion and add them
		$('#'+promotion_id+' .promotion_products').each(function(i, o){
			addProduct(o.value, quantity, pp, 0);
		});
	
		// Check for any additional products
		$('#'+promotion_id+' .item_radio_options .radio').each(function(i, o){
			if (o.checked && o.value != 0) {
				// Add the additional product to the cart
				addProduct(o.value, quantity, pp, pap);
			}
		});
		
		//alert('The promotion has successfully been added to your cart');
		openPromotionBasketSummary();

	}
	else {
		alert('This promotion is already inside your basket');
	}
	
}


function addPromotionProductTypeB(promotion_id) {
	// Get the selected products
	var selected_products = new Array();
	var quantity = $('#quantity_promotion_'+promotion_id).val();
	var pp = $('#promotion_' + promotion_id + '_pp').val();

	$('#item_checkbox_options_' + promotion_id +' input.checkbox').each(function(i, o){
		if (o.checked) {
			// Add to the selected items list
			selected_products.push(o.value);
		}
	});
	
	if (selected_products.length != 3) {
		alert('Please select 3 items');
	}
	else {
		// Make sure the promotion isn't inside the cart yet
		if (!promotionAlreadyInCart(pp)) {
			for(var i = 0; i < selected_products.length; i++) {
				addProduct(selected_products[i], quantity, pp);
			}
			//alert('The promotion has successfully been added to your cart');
			openPromotionBasketSummary();
		}
		else {
			alert('This promotion is already in your basket');
		}
		

	}
}

function addPromotionProductTypeC(product_id) {
	var quantity = $('#quantity_product_' + product_id).val();
	if (addProduct(product_id, quantity)) {
		openPromotionBasketSummary();
	}
}


function addProduct(id, quantity, pp, pap) {
	//alert('addProduct'+' id:'+id+' '+'quantity:'+quantity+' '+'pp:'+pp+' '+'pap:'+pap+' ');
	//return;
	if (pp == undefined) {
		pp = 0;
	}
	
	if (pap == undefined) {
		pap = 0;
	}
	
	// Validate quantity, make sure it's a number and larger than 0, otherwise it's pointless
	if (IsNumeric(quantity) && quantity > 0) { 
	
		if (!productAlreadyInCart(id)) {
			product = new Product();
			product.id = id;
			product.quantity = quantity;
			product.pp = pp;
			product.pap = pap;
			products.push(product);
			
			// Save the stuff inside a cookie
			saveBasketCookie();
			updateItemsInHeader();
		}
		else {
			// Change the quantity of this item as it exists already
			updateQuantity(id, quantity)
		}
		
		return true;
	}
	else {
		alert('please enter a quantity');
		return false;
	}
}

function removePromotion(pp) {
	// Delete from array
	
	if(confirm("Are you sure you want to remove this promotion from your basket?")) {
		var items_to_delete = new Array();
		
		// Find promotion and related products, and delete
		for (var i = 0; i < products.length; i++) {
			if (products[i].pp == pp) {
				// Save array indexes to the list that need to be removed
				items_to_delete.push(i);
			}
		}

		// Reverse the order otherwise the array gets corrupted if we remove items
		items_to_delete.reverse();
		
		// Remove the products one by one
		for (var i = 0; i < items_to_delete.length; i++) {
			// Remove from the html table first
			$('#item_row_' + products[items_to_delete[i]].id).remove();
			
			// Remove from products array
			products.splice(items_to_delete[i],1);
		}
		
		saveBasketCookie();
		updateTotals();
		updateItemsInHeader();
	}
}


//Returns true/false if the promotion is already inside the cart
function promotionAlreadyInCart(promotion_id) {
	var result = false;

	for (var i = 0; i < products.length; i++) {
		if (products[i].pp == promotion_id) {
			result = true;
			break;
		}
	}
	
	return result;
}

// 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 increaseValue(inputbox) {
	var value = $('#'+inputbox).val();
	
	if (IsNumeric(value) && value >= 1) {
		value++;
	}
	else {
		value = 1;
	}
	
	$('#'+inputbox).val(value);
	return false;
}

function decreaseValue(inputbox) {
	var value = $('#'+inputbox).val();
	
	if (IsNumeric(value) && value > 1) {
		value--;
	}
	else {
		value = 1;
	}
	
	$('#'+inputbox).val(value);
	return false;
}

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)) {
				products[i].quantity = value;
			}
			
			// Update item total
			updateItemTotal(products[i].quantity, id);
			
			saveBasketCookie();
			updateTotals();
			break;
		}
	}
}

function updateItemTotal(quantity, id) {
	// Update total price for this product on the form
	var price = parseFloat($('#item_price_' + id).text());
	price = price * quantity;
	
	var str_price = price.toFixed(0); // price.toFixed(2);
	$('#item_total_price_' + id).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 the total price for this product on the form
			updateItemTotal(products[i].quantity, id);
			break;
		}
	}
	
	saveBasketCookie();
	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
				updateItemTotal(products[i].quantity, id);
				break;
			}
		}
	}
	
	saveBasketCookie();
	updateTotals();
}


function removeProduct(id) {
	// 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_row_' + id).remove();
				
				saveBasketCookie();
				updateTotals();
				updateItemsInHeader();
				break;
			}
		}
	}
}


// Updates all the subtotals and the grand total
function updateTotals() {
	var total = 0.00;
	var delivery_fee = 0.00;
	
	// Get product rows
	$('.total_prices').each(function(i, o){
		total = total += parseFloat(o.innerHTML);
	});


	// Set total price
	$('#order_total_price').text(total); // total.toFixed(2)

	// Check for any delivery free
	if (total < 500) {
		delivery_fee = parseFloat($('#delivery_fee').text());
	}
	
	// Set delivery fee or not
	if (delivery_fee == 0) {
		$('#free_delivery_row').show();
		$('#delivery_fee_row').hide();
		$('.qualify_info').hide();
	}
	else {
		$('#free_delivery_row').hide();
		$('#delivery_fee_row').show();
		$('.qualify_info').show();
	}
	
	// Set subtotal
	$('#order_subtotal_price').text(total + delivery_fee); // total.toFixed(2)
	
	if (getTotalItemsInBasket() == 0) {
		$('.basket_content').hide();
		$('#empty_basket').show();
	}
}


// Updates the total inside the header
function updateItemsInHeader() {
	var total = getTotalItemsInBasket();
	$('#items_count').text(total);
}

function getTotalItemsInBasket() {
	return products.length;
}

function setLastAddedProduct(name) {
	last_added_product = name;
}

function getLastAddedProduct() {
	return last_added_product;
}
