$(document).ready(function(){
	getTheValues(false);
	
	$('.amount').click(function(){
		getTheValues(true);
	});
	
	$('#shoppingform').submit(function(){
		// lets check if we have chosen a value if not scroll to top
		var total = getTheValues(true);
		if(total ==  0){
			$(document).scrollTop(1);
			return false;
		}
	});
	
	
	function getTheValues(dontCreateError){
		var total = 0;
		var amountItems = 0;
		$('.product').each(function(e){
			var price = $(this).find('div input.price').val();
			var amount = $(this).find('div .amount').val();
			var sub = parseFloat(price) * parseInt(amount);
			total = total + sub;
			amountItems = parseInt(amountItems) + parseInt(amount);
		});
		
		if(isInteger(total)){
			var newtotal = total + '.00';
		}
		
		var gst = roundNumber(total / 11,2);
		
		// file the field for Grand Total
		$('#grand-total').html('$' + newtotal);
		$('#amount-items').html(amountItems + ' items');


		if(gst == '0' || is_int(gst)){
			$('#gst').html('$'+gst+'.00');
		}else{
			$('#gst').html('$' + gst);
		}
		
		if(dontCreateError === true){
			if(amountItems == '0'){
				$('#pls-choose-product').slideDown('slow').text('Please choose at least one product');
			}
		}
		if(total != 0){
			$('#pls-choose-product').slideUp('slow').text('');
		}
		
		return total;
	};
	
	function roundNumber(num, dec) {
		var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
		return result;
	};
	
	function isInteger (s){
		var i;
		
		if (isEmpty(s))
		if (isInteger.arguments.length == 1) return 0;
		else return (isInteger.arguments[1] == true);
		
		for (i = 0; i < s.length; i++)
		{
			var c = s.charAt(i);
			if (!isDigit(c)) return false;
		}
		
		return true;
	}
	function isEmpty(s)	{
		return ((s == null) || (s.length == 0))
	}

	function isDigit (c){
		return ((c >= "0") && (c <= "9"))
	}
	
	function is_int(input){
		return typeof(input)=='number'&&parseInt(input)==input;
	}
	
	
	
});
