
(function($) {

jQuery.fn.cart = function(settings) {
	
	//SET DEFAULTS
	settings = jQuery.extend({
		prodRow: "product_row",
     	addButton: "addToCart",
		tableName: "tblProducts",
		productList: [],
		qtyList: [],
		priceList: []
	}, settings);
	
	function findCharLocation(string,findchar,offset) {
		
		/*var dividedstring=string.split("");
		var place = -1;
		var numcommas = 0;
		for (x=offset;x<=string.length-1;x++) 
		{
			if(dividedstring[x] == ",") {
				numcommas = numcommas+1;	
			}
			if(dividedstring[x]==findchar) {
				if (place==-1) {
					place = x - numcommas;
				}
			}
		}*/
		//alert(string);

		var place = -1;
		var dividedstring = string.split(",");
		for (x=0;x<=dividedstring.length-1;x++) 
		{
			if(dividedstring[x]==findchar) {
				if (place==-1) {
					place = x;
				}
			}
		}

		return place;
	}
	
	//COOKIE FUNCTIONS
	function setCookie(c_name,value,expiredays)
	{
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +value+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
	}
	
	function getCookie(c_name)
	{
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
		{ 
		c_start=c_start + c_name.length+1; 
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		} 
	  }
	return "";
	}

	$().find("#shopping_cart").append("<span style='color: #FFFFFF'><strong>Items:</strong></span> <span class='total_items'>0</span><br>");
	$().find("#shopping_cart").append("<span style='color: #FFFFFF'><strong>Total Cost:</strong></span> <span class='total_cost'>&pound;0.00</span><br><br>");
							  
	//RETRIEVE BACK EXISTING COOKIES
	
	if (getCookie('prod')!="") {
	
		settings.productList = getCookie('prod').split(",");
		settings.qtyList = getCookie('quan').split(",");
		settings.priceList = getCookie('price').split(",");
		
		settings.totalItems = settings.productList.length;
		
		for (x in settings.productList)
		{
			displayProduct(settings.productList[x],settings.qtyList[x],settings.priceList[x]);
		}
	
	}
	
	//UPDATE TOTALS
	function updateTotals() {

		var total_items = 0;
		var total_cost = 0.00;
		
		for (x in settings.productList)
		{
			total_cost = total_cost + parseFloat((parseFloat(settings.priceList[x]) * parseInt(settings.qtyList[x])));
			total_items = total_items + parseInt(settings.qtyList[x]);
		}

		total_cost = total_cost.toFixed(2);
		if (total_items<1) {
			total_items = "0";
		}
		$().find("#shopping_cart .total_cost").html("&pound;"+total_cost);
		$().find("#shopping_cart .total_items").html(total_items);
	}
	
	//GET PRODUCT FUNCTION
	function getProduct(pID)
	{
		var productRow = $.ajax({
			type: "POST",
			url: "getCartProduct.php",
			data: 'tblName='+settings.tableName+'&pID='+pID,
			async: false
		}).responseText;
		
		return productRow;
	
	}
	
	//ADD PRODUCT FUNCTION
	function addProduct(pID,num,price) {
		displayProduct(pID,num,price);
		settings.totalItems++;
		settings.productList.push(pID);
		settings.qtyList.push(num);
		settings.priceList.push(price);
		setCookie('prod',settings.productList,14);
		setCookie('quan',settings.qtyList,14);
		setCookie('price',settings.priceList,14);
		updateTotals();
	}
	
	//DISPLAY PRODUCT FUNCTION
	function displayProduct(pID,num,price) {
		
		var name = getProduct(pID);
		
		total_price = price * num;
		total_price = total_price.toFixed(2);
		
		$().find("#shopping_cart").append("<div class='cart_row' id='cart_row"+pID+"'><strong><span style='color: #FFFFFF'><span class='num_of_products'>"+num+"</span> x "+name+"</span></strong><br><span class='product_price'>&pound;"+total_price+"</span> (<span class='num_of_products'>"+num+"</span> @ &pound;"+price+")<br><a href='#' id='removeprod"+pID+"' style='color: #000000; text-decoration: none'>Remove</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='#' id='addQuan"+pID+"'><img src='images/plus.jpg' width='15px' height='15px' border='0' /></a>&nbsp;<a href='#' id='minusQuan"+pID+"'><img src='images/minus.jpg' width='15px' height='15px' border='0' /></a><div style='height: 15px'></div></div>");
		
		remove = $().find("#removeprod"+pID).click(function(){
			removeProduct(this.id.substring(10));	
			return false;
		});
		
		plus = $().find("#addQuan"+pID).click(function(){
			qtyUpdate(pID,1);	
			return false;
		});
		
		minus = $().find("#minusQuan"+pID).click(function(){
			qtyUpdate(pID,-1);	
			return false;
		});
		updateTotals();
	}
	
	//REMOVE PRODUCT 
	function removeProduct(pID) {
		$().find("#cart_row"+pID).remove();
		
		var prodString = settings.productList.join();
		var place = findCharLocation(prodString,pID,0);
		
		//var place = settings.productList.indexOf(""+pID+"");
		settings.productList.splice(place,1);
		settings.qtyList.splice(place,1);
		settings.priceList.splice(place,1);
		setCookie('prod',settings.productList,14);
		setCookie('quan',settings.qtyList,14);
		setCookie('price',settings.priceList,14);
		updateTotals();
	}
	
	//UPDATE QUANTITY
	function qtyUpdate(pID,val) {
		
		var prodString = settings.productList.join();
		var place = findCharLocation(prodString,pID,0);
		//var place = settings.productList.indexOf(pID);
		
			current_val = parseInt(settings.qtyList[place]);
			new_val = current_val + val;
		
		if (new_val>=1) {
			
			$().find("#cart_row"+pID+" .num_of_products").html(new_val);
			total_price = (new_val * settings.priceList[place]).toFixed(2);
			$().find("#cart_row"+pID+" .product_price").html("&pound;"+total_price);
			
			settings.qtyList[place] = new_val;
			setCookie('prod',settings.productList,14);
			setCookie('quan',settings.qtyList,14);
			updateTotals();
		}
	}
	
	$().find("."+settings.prodRow+" ."+settings.addButton).click(function(){
				if ($().find("#add_amount"+this.id).val()>0) {
					if(settings.productList.length == 0) {
						var place = -1;
					} else {
						var prodString = settings.productList.join();
						var place = findCharLocation(prodString,this.id,0);
					}
					if (place==-1) {
						addProduct(this.id,$().find("#add_amount"+this.id).val(),$().find("#price_amount"+this.id).val());
					} else {
						alert("This item is already in your shopping cart");
					}
				} else {
					alert("Please enter the number of items to add");
					return false;
				}
			});
		
};

})(jQuery);
