(function($){
	
	function number_format (number, decimals, dec_point, thousands_sep) {
		// Formats a number with grouped thousands
		//
		// version: 906.1806
		// discuss at: http://phpjs.org/functions/number_format
		// +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +     bugfix by: Michael White (http://getsprink.com)
		// +     bugfix by: Benjamin Lupton
		// +     bugfix by: Allan Jensen (http://www.winternet.no)
		// +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
		// +     bugfix by: Howard Yeend
		// +    revised by: Luke Smith (http://lucassmith.name)
		// +     bugfix by: Diogo Resende
		// +     bugfix by: Rival
		// +     input by: Kheang Hok Chin (http://www.distantia.ca/)
		// +     improved by: davook
		// +     improved by: Brett Zamir (http://brett-zamir.me)
		// +     input by: Jay Klehr
		// +     improved by: Brett Zamir (http://brett-zamir.me)
		// +     input by: Amir Habibi (http://www.residence-mixte.com/)
		// +     bugfix by: Brett Zamir (http://brett-zamir.me)
		// *     example 1: number_format(1234.56);
		// *     returns 1: '1,235'
		// *     example 2: number_format(1234.56, 2, ',', ' ');
		// *     returns 2: '1 234,56'
		// *     example 3: number_format(1234.5678, 2, '.', '');
		// *     returns 3: '1234.57'
		// *     example 4: number_format(67, 2, ',', '.');
		// *     returns 4: '67,00'
		// *     example 5: number_format(1000);
		// *     returns 5: '1,000'
		// *     example 6: number_format(67.311, 2);
		// *     returns 6: '67.31'
		// *     example 7: number_format(1000.55, 1);
		// *     returns 7: '1,000.6'
		// *     example 8: number_format(67000, 5, ',', '.');
		// *     returns 8: '67.000,00000'
		// *     example 9: number_format(0.9, 0);
		// *     returns 9: '1'
		// *     example 10: number_format('1.20', 2);
		// *     returns 10: '1.20'
		// *     example 11: number_format('1.20', 4);
		// *     returns 11: '1.2000'
		// *     example 12: number_format('1.2000', 3);
		// *     returns 12: '1.200'
		var n = number, prec = decimals;
	 
		var toFixedFix = function (n,prec) {
			var k = Math.pow(10,prec);
			return (Math.round(n*k)/k).toString();
		};
	 
		n = !isFinite(+n) ? 0 : +n;
		prec = !isFinite(+prec) ? 0 : Math.abs(prec);
		var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
		var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
	 
		var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
	 
		var abs = toFixedFix(Math.abs(n), prec);
		var _, i;
	 
		if (abs >= 1000) {
			_ = abs.split(/\D/);
			i = _[0].length % 3 || 3;
	 
			_[0] = s.slice(0,i + (n < 0)) +
				  _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
			s = _.join(dec);
		} else {
			s = s.replace('.', dec);
		}
	 
		var decPos = s.indexOf(dec);
		if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
			s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
		}
		else if (prec >= 1 && decPos === -1) {
			s += dec+new Array(prec).join(0)+'0';
		}
		return s;
	}
	
	function format_number(number, decimals)
	{
		if(decimals == undefined)
			decimals = true;
		var ret = '';
		if(number-Math.floor(number) > 0)
			ret = number_format(number, 2, '.', "'");
		else
		{
			if(decimals)
				ret = number_format(number, 0, '.', "'")+'.-';
			else
				ret = number_format(number, 0, '.', "'");
		}
		return ret;
	}

	$(document).ready(function(){
		
		var calculate_discount = function(){
			var discount = 0;
			
			var sum = 0;
			$('.your-bag .bag .total .price_count').each(function(){
				sum += parseFloat($(this).html().replace("'",""));
			});
			
			var post_data = $('.promotional_code').serialize();
			if(post_data != '')
				post_data += '&total='+sum;
			
			$('#promotional_infos').html('');
			
			$.ajax({
				async: false
				,type: "POST"
				,url: config_dir+"index.php?fuseaction=ajax.promotional_codes"
				,data: post_data
				,success: function(msg){
					result = msg.split('#');
					discount = parseFloat(result[0]);
					
					if($.trim($('.promotional_code:first').val()) != '')
						$('#promotional_infos').html(result[1]);
				}
			});
			return discount;
		}
		var order_rules = function(){
			var cart_total = 0;
			var cart_nitems = 0;
			var cart_weight = 0;
			$('.bag .price .price_count').each(function(){
				cart_total += parseFloat($(this).html().replace("'",""))*parseFloat($(this).parent().parent().find('.product_quantity').val());
				cart_weight += parseFloat($(this).parents('tr').find('.product_weight').val()); 
				cart_nitems++;
			});
			
			if(typeof country_taxes != 'undefined')
			{
				var cart_gift_wrapping = $('#gift').is(':checked');
				var cart_packing = 0;
				if(cart_gift_wrapping)
					cart_packing = country_taxes[$('#country_id').val()].packing;
			
				var cart_shipping = 0;
				if(parseInt($('#nr_products').val()))
					cart_shipping = country_taxes[$('#country_id').val()].shipping;
			
				$.ajax({
					async: false
					,type: "GET"
					,url: config_dir+"index.php?fuseaction=ajax.order_rules"
					,dataType: "script"
					,data: {
						vat: country_taxes[$('#country_id').val()].vat
						,shipping: cart_shipping
						,deliver_to: $('#country_id').val()
						,discount: $('#promotional_discount').val()
						,gift_wrapping: (cart_gift_wrapping)?1:0
						,packing: cart_packing
						,total: cart_total
						,nitems: cart_nitems
						,weight: cart_weight
					}
				});
				return rules;
			}
		}
		
		if($('#promotional_discount').length)
			$('#promotional_discount').val(calculate_discount());
		
		var calculate_total = function(){
			if(typeof country_taxes == 'undefined')
				return false;
			var rules = order_rules();
			var str_shipping = '';
			var str_packing = '';
			
			if(rules['shipping'] == 0)
			{
				if(parseInt($('#nr_products').val()))
					$('#shipping_price').html(_language_free.toUpperCase());
				else
					$('#shipping_price').html(_language_no.toUpperCase());
				$('#shipping_price').parent().find('.price_unit').html('');
			}
			else
			{
				$('#shipping_price').html(format_number(country_taxes[$('#country_id').val()].shipping));
				$('#shipping_price').parent().find('.price_unit').html('CHF');
			}
			
			if(rules['packing'] == 0 && rules['gift_wrapping'])
			{
				$('#packing_price').html(_language_free.toUpperCase());
				$('#packing_price').parent().find('.price_unit').html('');
			}
			else
			{
				if($('#gift').is(':checked'))
					$('#packing_price').html(format_number(country_taxes[$('#country_id').val()].packing));
				else
					$('#packing_price').html(format_number(0));
				$('#packing_price').parent().find('.price_unit').html('CHF');
			}
		
			var item_wrapper = $(this).parents('tr:first');
			var total_wrapper = $(this).parents('.your-bag');

			$('.total .price_count', item_wrapper).html( format_number(parseFloat($('.price .price_count', item_wrapper).html()) * $(this).val()) );
			
			var sum = 0;
			$('.bag .total .price_count', total_wrapper).each(function(){
				sum += parseFloat($(this).html().replace("'",""));
			});

			$('.sub-total .header .price_count', total_wrapper).html(format_number(sum));
			
			if(sum){
				if($('#gift').is(':checked') && rules['packing'] > 0)
					sum += rules['packing'];
				sum += rules['shipping'];
			}
			
			$('.subtotal-with-delivery .price_count', total_wrapper).html(format_number(sum));
			try{
				sum -= parseFloat($('#promotional_discount').val());
				if(sum < 0)
					sum = 0;
				var total = sum*(1 + (country_taxes[$('#country_id').val()].vat / 100));
				$('.grand-total .price_count', total_wrapper).html(format_number(total));
				$('#currency_convertor').change();
			} catch(e){};
		};
		
		$('.calculate_discount').click(function(){
			$('#promotional_discount').val(calculate_discount());
			calculate_total.call(this);
			return false;
		});
		
		$('#gift').click(calculate_total);
		$('.sub-total #country_id').change(function(){
			calculate_total.call(this);
			/*
			var country_id = $(this).val();
			if(typeof country_taxes == 'object')
			{
				$('#shipping_price').html(country_taxes[country_id].shipping.toFixed(2));
				$('#packing_price').html(country_taxes[country_id].packing.toFixed(2));
				calculate_total.call(this);
			}
			*/
		}).change();
		
		$('#currency_convertor').change(function(){
			var currency_id = $(this).val();
			var total = parseFloat($('.grand-total .price_count').html().replace("'",""));
			var value = currencies[currency_id].value * total;
			$('#currency_value').html(currencies[currency_id].code + ' ' + format_number(value));
		}).change();
		
		$('.input_spinner input').each(function(){
			$(this).change(calculate_total);
			calculate_total.call(this);
		});
		
		
		$('.input_spinner .minus, .input_spinner .plus').click(function(){
			calculate_total.call($('input', $(this).parent()).get(0));
		});
		
		
		plus_function = function(){
			var div = document.createElement('div');
			div.innerHTML = $('.promotion-codes .first').html() + '<a class="button plus minus" href="">-<a>';
			$('input.text', div).val('').removeClass('default_text input_default_text');
			$('.plus', div).not('.minus').click(plus_function);
			$('.minus', div).click(function(){
				$(this).parent().remove();
				return false;
			});
			$(this).parent().parent().append(div);
			$('.calculate_discount', $(this).parent().parent()).click(function(){
				$('#promotional_discount').val(calculate_discount());
				calculate_total.call(this);
				return false;
			});
			
			return false;
		};
		
		$('.promotion-codes .plus').not('.minus').click(plus_function);
		
	});
	
})(jQuery);