$j(document).ready(function()
{

	//shopaccordion
	$j('#more_products table').not(':first').hide();
	$j('#more_products_menu a').click(function(){
		var thisclass = $j(this).parent().attr('class');
		// alert(thisclass);
		$j('#more_products_menu a').removeClass('menuactive');
		$j(this).addClass('menuactive');
		
		$j('#more_products table:visible').hide();
		$j('#more_products table[class='+thisclass+']').show();
		return false;
	});
		
	//shop
	var totalQuantity = 0;
	var totalCostIN = 0;
	var totalCostCB = 0;
	var product_price = $j('#price_per_package').text();
	var product_package = $j('#package_contents').text();
	
	function calculatePrice(amount,price)
	{
		var priceR = price.replace(/^[^\d.]*/,'');
		var price = parseFloat(priceR);
		
		//price = isNaN(price) ? 0 : price;
		
		var quantity = parseInt(amount);
		var cost = quantity * price
		totalQuantity += quantity;
		return cost;
		
	}
	function findAsseccoire(id)
	{
		var cloneit = true;
		//$j('#table_calculation tr:gt(8)')
		$j('#table_calculation tr').each(function(){
		var thisid = this.id;
			if(thisid == id)
			{
				cloneit = false;
			}
		});
		return cloneit;
	}
	function replacePriceTxt(pricetxt)
	{
		return pricetxt.replace(/^[^\d.]*/,'').replace(/p\/st/,'')
	}
	function cloneRow(thisid,thistext)
	{
		if(thistext.length > 25 ) 
		{
			thistext = thistext.substring(0,27) + "..";
		}
		$j('#newitems').clone().attr('id',thisid).css('backgroundColor','#FFF').insertBefore('#accessoires')
		.show()
		.find('td:eq(0)')
		.text(thistext);
	}
	function removeRow(id)
	{
		$j('#table_calculation tr[id="'+id +'"]').remove();
	}
	function handleAsseccoires(thisproductlabel,thisproductid,producttext,inputvalue,productprice,cb)
	{
		var aAsseccoires = new Array();
		aAsseccoires = $j('#asseccoires_total').val().split('#');
		
		$j('#asseccoires_total').val('');
					
		if (aAsseccoires.length > 1 )
		{
			var bExists = false;
			for ( i=1; i<=aAsseccoires.length; i++ ) 
			{
				var sProduct = aAsseccoires[i];
				if (sProduct != null ) 
				{
	               
					var aProduct = sProduct.split(';');
					var sPL= aProduct[0];
					var sID = aProduct[1];
					var sTI = aProduct[2];
					var sAM = aProduct[3];
					var sPR= aProduct[4];
								
					if (sID == thisproductid && sPL == thisproductlabel) 
					{
						bExists = true;
						if(inputvalue > 0)
						{
							$j('#asseccoires_total').val($j('#asseccoires_total').val() + '#'+thisproductlabel +';'+thisproductid+';'+producttext+';'+inputvalue+';'+productprice);
						}			
					}
					else
					{
							$j('#asseccoires_total').val($j('#asseccoires_total').val() + '#'+sPL +';'+sID+';'+sTI+';'+sAM+';'+sPR);
					}
				}//sProduct
			}
			if (!bExists && inputvalue > 0 ) 
			{
				$j('#asseccoires_total').val($j('#asseccoires_total').val() + '#'+thisproductlabel +';'+thisproductid+';'+producttext+';'+inputvalue+';'+productprice);
			}
		}
		else
		{
			if(inputvalue > 0)
			{
					$j('#asseccoires_total').val('#'+thisproductlabel +';'+thisproductid+';'+producttext+';'+inputvalue+';'+productprice);
			}
						
		}
		if(inputvalue == 0 || inputvalue == '')
		{
			cb.attr('checkbox',' ');
		}
	}
	function calculateAccessoires()
	{
		 var bTotPrice = 0;
	     var aProducts = new Array();
	     aProducts = $j('#asseccoires_total').val().split('#');
	     if (aProducts.length > 1 ) 
	     {
	     	for ( i=1; i<=aProducts.length; i++ ) 
	        {
	         	var sProducts = aProducts[i];
    	        if ( sProducts != null ) 
    	        {
	                var aProduct = sProducts.split(';');
	                
					var sPL= aProduct[0];
					var sID = aProduct[1];
					var sTI = aProduct[2];
					var sAM = aProduct[3];
					var sPR= aProduct[4];
					var productid = sPL+'_'+sID;
	                var totPrice = sPR * sAM;
	                bTotPrice = bTotPrice + totPrice;
	                totPrice = totPrice.toFixed(2);
	                //alert(totPrice);
					$j('#table_calculation tr[id="'+productid +'"]').children('td:eq(2)').text(totPrice);
	             } 
	         }
			 
	     }
	     totalCostCB = bTotPrice;
		 if(totalCostCB >0)
		{
			$j('#acess_price').text(bTotPrice.toFixed(2));
		}
		else
		{
			$j('#acess_price').text('-.--');
		}
	}
	function calculateTotalPrice()
	{
		var price = totalCostIN + totalCostCB;
		if(price > 0)
		{
			$j('#total_price').text(price.toFixed(2));
		}
		else
		{
			$j('#total_price').text('-.--');
		}
	}
//	function collectCartItems()
//	{
//		var nProductId = $j('#product_id').val();
//		var nProductLabel = $j('#product_label').val();
//		var nProductQuantity = $j('#amount_pcks').val();
//		var sAssecoires = $j('#asseccoires_total').val();
//		if(nProductQuantity != '' || nProductQuantity > 0 )
//		{
//			//addToCart(nProductId,nProductLabel,nProductQuantity,sAssecoires);
//			alert('gelukt!');
//		}	
//	}
	function addToCart(nProductId,nProductLabel,nProductQuantity,sAssecoires)
	{
		$j.ajax({
						url: "/ajax/shopping_cart.php",

						type: "POST",

						data: 'id='+nProductId+'&label='+nProductLabel+'&quantity='+nProductQuantity+'&asseccoires='+sAssecoires,

						success: function(returnValue) 
						{

							if (returnValue != 'ok') 
							{
								//error handeling hier
							}
							else
							{
								//updatePayRoll();//moet nog gemaakt worden
							}
						}
		});
	}
//	$j('#addtoshoppingcart').click(function(){
//		collectCartItems();
//	})
	$j('#table_calculation input').keypress(function(event){
		if($j(this).is(':not:eq(1)'))
		{
			if(event.charCode && (event.charCode < 48 || event.charCode >57))
			{
				event.preventDefault();
			}
		}
		else
		{
			if(event.charCode && ((event.charCode < 48 && event.charCode != 46) || event.charCode >57 ))
			{
				event.preventDefault();
			}
		}
	});
	$j('#amount_pcks').keyup(function(){

		var thisvalue = $j(this).val();
		var cost = calculatePrice(thisvalue,product_price);
		//alert(cost);
		totalCostIN = 0;
		totalCostIN += cost;
		
		
		if(thisvalue != '')
		{
			var amountpackages = thisvalue * parseFloat(product_package.replace(/^[^\d.]*/,''));
			$j('#amount_necs').val(amountpackages.toFixed(2));
			$j('#subtotal_price').text(totalCostIN.toFixed(2));
			calculateTotalPrice();
		}
		else
		{
			$j('#amount_necs').val('');
			$j('#subtotal_price').text('-.--');
			calculateTotalPrice();
		}
	});//end #amount_pcks
	$j('#amount_necs').keyup(function(){
		var thisvalue = $j(this).val();
		var amountpackages = Math.ceil(thisvalue / parseFloat(product_package.replace(/^[^\d.]*/,'')));
		
		if(thisvalue > 0)
		{
			$j('#amount_pcks').val(amountpackages) ;
		}
		else
		{
			$j('#amount_pcks').val('');
			$j('#subtotal_price').text('-.--');
		}
		var price = calculatePrice($j('#amount_pcks').val(),product_price);
		totalCostIN = 0;
		totalCostIN += price;
		$j('#subtotal_price').text(price.toFixed(2));
		calculateTotalPrice();
	});
	
	$j('table:gt(1)').each(function(index){
		
		var thistable = $j(this);
		
		$j('input:checkbox',thistable).each(function(){
		
			var thischeckbox = $j(this);
			
			thischeckbox.click(function()
			{
				var thistext = thischeckbox.parent().next().text();
				var thispricetxt = thischeckbox.parent().next().next().text();
				var thisid = this.id;
				var aProductItems = thisid.split('_');
				var thisproductlabel = aProductItems[0];
				var thisproductid = aProductItems[1];
				var productprice = replacePriceTxt(thispricetxt);
				var thischeckboxinput = $j(this).parent().siblings(':last').find('input');
	
				if(this.checked)
				{
					cloneRow(this.id,thistext);
					handleAsseccoires(thisproductlabel,thisproductid,thistext,1,productprice,thischeckbox);
					thischeckboxinput.val(1);
					calculateAccessoires();
					calculateTotalPrice();
				}
				else
				{
					
					thischeckboxinput.val('');
					handleAsseccoires(thisproductlabel,thisproductid,thistext,0 ,productprice,thischeckbox);
					totalCostCB = 0;
					calculateAccessoires();
					calculateTotalPrice();
					removeRow(thisid);
					
				}//else
			});// end thischeckbox.click
		});//end $j('input:checkbox',thistable)
	
		$j(':input:not(:checkbox)',thistable).each(function(){
		
			var thisinput = $j(this);
			var thischeckbox = thisinput.parent().prev().prev().prev().find(':checkbox');
			var thisproductlabel = thisinput.parents('tr').attr('class');
			var thisproductid =thisinput.parents('tr').attr('id');
			var producttext = thisinput.parent().prev().prev().text();
			var productprice = replacePriceTxt(thisinput.parent().prev().text());
			
			var thisid = thisproductlabel+'_'+thisproductid;
			
			thisinput.keypress(function(event){
				if(event.charCode && (event.charCode < 48 || event.charCode >57))
				{
					event.preventDefault();
				}
			
			});//keypress
			
			
			thisinput.keyup(function()
			{		
				thischeckbox.attr('checked','true');
				var cost_unchecked = calculatePrice(thisinput.val(),productprice);
				var inputvalue = parseFloat(thisinput.val());
				//alert(thisid);
				
				//findAsseccoire(thisid);
				if(inputvalue > 0)
				{
					handleAsseccoires(thisproductlabel,thisproductid,producttext,inputvalue,productprice,thischeckbox);
					if(findAsseccoire(thisid) == true)
					{
						cloneRow(thisid,producttext);
					}
					calculateAccessoires();
					calculateTotalPrice();
				}	
				else
				{
					handleAsseccoires(thisproductlabel,thisproductid,producttext,0,productprice,thischeckbox);
					thischeckbox.attr('checked','');
					removeRow(thisid);
					totalCostCB = 0;
					calculateAccessoires();
					calculateTotalPrice();
				}
			});
		});
	});//end $j('table').each
});
