/**
 * Vypocet ceny a slevy u vyprodeje
 */

var DISCOUNTS = [
	{ 
		range 		: { low : 0, high : 10 },
		discount	: 30
	},
	
	{ 
		range 		: { low : 11, high : 50 },
		discount	: 40
	},
	
	{ 
		range 		: { low : 51, high : 1000000 },
		discount	: 50
	}
];

$(document).ready( function() {
	
	refreshTotalCost();
	
	$(".itemCount").keyup(refreshTotalCost);
	$("#shipping").change(refreshTotalCost);
});

function refreshTotalCost() {
	var totalCount = 0;
	var totalPrice = 0;
	
	jQuery.each($(".itemCount"), function() {
		var val = parseInt(this.value);
		val = isNaN(val) ? 0 : val;
		
		totalCount += val;
		totalPrice += parseFloat($(this).parent().attr("m:price")) * val;			
	});
	
	var shipping = parseFloat($("#shipping option:selected").attr("m:cost"));
	var finalPrice = (totalPrice * ((100 - computeDiscount(totalCount)) / 100)) + shipping;
	
	$("#totalPieces").text(totalCount);
	$("#total").text(finalPrice.toFixed(2));
}

function computeDiscount(count) {
	var discount = 0;
	
	if ($("#saleItems").attr("m:discountable") != "no") {
		var shippingDiscount = $("#shipping option:selected").attr("m:discount-percentage");
		discount += shippingDiscount === undefined ? 0 : parseFloat(shippingDiscount);
		
		jQuery.each(DISCOUNTS, function() {
			
			if (count >= this.range.low && count <= this.range.high) {
				discount += this.discount;
				return;
			}
		});
	}
	
	return discount;
}
