var ShoppingCart = function() {

	function GetProductById(productId)
	{
		for(var i = 0; i < that.products.length; i++)
		{
			if(that.products[i].id == productId)
			{
				return that.products[i];
			}
		}
		
		return null;
	}
	
	var subTotalPriceObj 	= null;
	var totalPriceObj 		= null;
	var deliveryPriceObj 	= null;
	
	ye.addListener(window, "load", function() { 
		subTotalPriceObj = yd.get("subTotalPrice");
		totalPriceObj = yd.get("totalPrice");
		deliveryPriceObj = yd.get("deliveryPrice");
	 } );
	
	var that = {
		deliveryPrice : 0,
		subTotalPrice : 0,
		totalPrice : 0,
		Calculate : function()
		{
			this.deliveryPrice = 0;
			this.subTotalPrice = 0;
			this.totalPrice = 0;
			
			for(var i = this.products.length - 1; i >= 0; i--)
			{
				if(this.products[i].quantity == 0)
				{
					this.products.splice(i, 1);
					continue;
				}
				this.products[i].Calculate();
				this.deliveryPrice 	+= this.products[i].deliveryCost;
				this.subTotalPrice 	+= this.products[i].subTotalPrice;
				this.totalPrice		+= this.products[i].totalPrice;
			}
			
			
			if(this.products.length == 0)
			{
				document.location = "../literatur-bestellen.php";
			}
			
			this.deliveryPrice 	= NB.Math.FormatFloat(this.deliveryPrice, 2);
			this.subTotalPrice 	= NB.Math.FormatFloat(this.subTotalPrice, 2);
			this.totalPrice 	= NB.Math.FormatFloat(this.totalPrice, 2);
		},
		DeleteSelected : function()
		{
			for(var i = 0; i < this.products.length; i++)
			{
				if(yd.get("chk_" + this.products[i].id).checked)
				{
					this.products[i].Remove();
				}
			}
			this.Calculate();
			this.RefreshPage();
		},
		InitProducts : function(products)
		{
			this.products = [];
			for(var i = 0; i < products.length; i++)
			{
				this.products[i] = new ShopProduct(products[i].id, products[i]);
			}
		},
		RefreshPage : function()
		{
			subTotalPriceObj.innerHTML = NB.Math.FormatNumber(this.subTotalPrice, 2, ",", " ")  + " &euro;";
			totalPriceObj.innerHTML = NB.Math.FormatNumber(this.totalPrice, 2, ",", " ")  + " &euro;";
			deliveryPriceObj.innerHTML = NB.Math.FormatNumber(this.deliveryPrice, 2, ",", " ") + " &euro;";
		},
		SetQuantity : function(oEvt, productId, action)
		{
			oEvt = ye.getEvent(oEvt);
			ye.stopEvent(oEvt);
			
			var product = GetProductById(productId);
			
			if(product == null)
			{
				throw "product not found";
			}
			
			switch(action)
			{
				case "plus":
					product.quantity++;
					break;
				case "minus":
					product.quantity--;
					break;
				case "none":
					var inputObj = yd.get("qty_" + productId);
					inputObj.value = NB.Math.GetFloat(inputObj.value, 0);
					product.quantity = inputObj.value;
					break;
			}
			product.AcceptChanges();
			this.Calculate();
			this.RefreshPage();
		}
	}
	
	return that;
	
}();
