Shop = (function(){
	this.ids = new Array();
	this.num = new Array();
	this.price = new Array();

	this.updateInfo = function()
	{
		var sum = 0;
		for ( var i = 0; i < this.ids.length; i++) {
			sum = sum + this.num[i] * this.price[i];  			
		}		

		$('#shop-cart-info').text(' ( ' + this.ids.length + ' articles: ' + parseInt(sum) + ' SEK )');
	};

	
	// Get stored cart
	if($.jStorage.storageAvailable())
	{
		if($.jStorage.get("shop.array.id", null) != null)
		{
			this.ids = new Array();
			this.num = new Array();
			this.price = new Array();
			//try {
				var _ids = $.jStorage.get("shop.array.id", ""); //localStorage["shop.array.id"].split(',');
				var _num = $.jStorage.get("shop.array.num", ""); //localStorage["shop.array.num"].split(',');
				var _price = $.jStorage.get("shop.array.price", ""); //localStorage["shop.array.num"].split(',');				
			//} catch (e) {
			//}			
			for ( var i = 0; i < _ids.length; i++) {
				var n = parseInt(_num[i]);
				if(n > 0)
				{
					this.ids.push(_ids[i]);
					this.num.push(_num[i]);
					this.price.push(_price[i]);
				}
			}
		}
	}
	
	this.Store = function()
	{
		if($.jStorage.storageAvailable())
		{
			// Store
			//try {
				$.jStorage.set("shop.array.id", this.ids); //localStorage["shop.array.id"] = this.ids;
				$.jStorage.set("shop.array.num", this.num); //localStorage["shop.array.num"] = this.num;
				$.jStorage.set("shop.array.price", this.price); //localStorage["shop.array.price"] = this.price;				
			//} catch (e) {
			//}
		}		
	};
	
	this.add = function(id,p)
	{
		// check if already in cart.
		var found = false;
		for ( var i = 0; i < this.ids.length; i++) {
			if(this.ids[i]==id)
			{
				found = true;
				this.num[i] = parseInt(this.num[i]) + 1;
			}
		}
		// Append if not in cart already
		if(!found)
		{
			this.ids.push(id);
			this.num.push(1);
			this.price.push(p);
		}
		
		this.Store();
		this.updateInfo();
		
	};
	
	this.set = function(i,v){
		this.num[i]=v;
		try{
		$.jStorage.set("shop.array.num", this.num);
		//localStorage["shop.array.num"] = this.num;
		}catch(e){
		}
	};
	
	this.updateTot = function()
	{
		var tot = 0;
		for ( var i = 0; i < this.ids.length; i++) {
			tot += this.price[i]*this.num[i];
		}		
		$('td#shop-tot-cost').text(parseInt(tot)+" SEK");
		this.updateInfo();
	}
	
	this.post = function(element, form){
		var cart_data = new Array();
		var f = form.attr('id');
		for ( var i = 0; i < this.ids.length; i++) {
			var id = this.ids[i];
			var n = this.num[i];
			var price = this.price[i];
			cart_data.push([id, n, price]);
		}
		//element.html(cart_data.toString());
		$.post('shop/buy.php',{'cart[]':cart_data,'key':this.key,'form':form.serialize()},function(data){
			element.append('Your order number is : ' + data.order_number);
			$('#' + f + ' input').each(function(){
				var v = $(this).attr('value');
				$(this).after($('<td>').text(v));
				$(this).hide();
			});
		});
	}
	
	this.clear = function(){
		this.ids= new Array();
		this.num = new Array();
		this.price = new Array();
		this.Store();
		/*
		localStorage["shop.array.id"] = this.ids;
		localStorage["shop.array.num"] = this.num;
		localStorage["shop.array.price"] = this.price;
		*/
		this.updateTot();
	};
	
	this.getList = function(settings)
	{
		$.ajax({
			url: 'api/rest.php?q=/productarr&p='+this.ids.toString(),
			cache : true,
			success: function(indata) {
				//var data = indata.data;
				//th.key = indata.key;
				settings.success(indata);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				settings.error(textStatus);
			}
		});
	};
	
	this.list = function(element)
	{
		var _ids = this.ids;
		var _num = this.num;
		var _price = this.price;
		var th = this;
		$.ajax({
			url: 'api/rest.php?q=/productarr&p='+this.ids.toString(),
			cache : false,
			success: function(indata) {
				var data = indata.data;
				th.key = indata.key;
				element.html("");
				if(indata.data.length == 0)
				{
					element.append(
							$('<tr>')
							.append($('<th>').text('No products in shopping cart.'))
						);
					
					return;
				}
				element.append(
					$('<tr>')
					.append($('<th>').text('#'))
					.append($('<th>').text('Product'))
					.append($('<th>').text('Price'))
				);
				$totCost = 0;
				for ( var j = 0; j < _ids.length; j++) {
					var id = _ids[j];
					for ( var i = 0; i < data.length; i++) {
						var d = data[i];
						if(d.Index == id)
						{
							element.append(
								$('<tr>')
								//.append($('<td>').text(id))
								.append(
										$('<td>').append(
											$('<input>',{'value':_num[j],'size':4,'price':_price[j],'c':j}).change(function(){
												var pr = parseInt($(this).attr('value'));
												if(pr == 0)
												{
													$(this).parent().siblings().addClass('removed');
												} else {
													$(this).parent().siblings().removeClass('removed');
												}
												$(this).parent().nextAll('#price')
													.text(parseInt(parseFloat($(this).attr('price')) * $(this).attr('value')));
												th.set($(this).attr('c'),$(this).attr('value'));
												th.updateTot();
											}
									))
								)
								.append($('<td>').append(
										$('<a>',{'href':'/#products.php?pid='+d.Index+'&cath='+d.category}).append($('<b>').text(d.pid))
									).append(
										$('<p>').text(d.heading)
								))
								.append($('<td>',{'id':'price'}).text(parseInt(_price[j]*_num[j])))
							);
							$totCost += parseInt( _price[j]*_num[j]);
						}
					}
				}
				element.append(
						$('<tr>')
						.append($('<td>').text(''))
						.append($('<td>').text('Total'))
						.append($('<td>',{'id':'shop-tot-cost'}).text($totCost+ " SEK"))
					);

			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				$('.result').append(textStatus);
			}
		});
	};
	
});

