/* this dood nead refactoring since we moved the details page to the cart */


var lang = $("html").attr("lang");
if (!lang) {
    lang = "en"
}
var currency = "EUR";

$(document).ready(function(){
	loadTermsDialog();
	setupSteps();
	var giftCost = 5;
	
	var utils = new FluidFormsShopUtils();

	// This function updates the costs when the quantity changes
	var updateCosts = function(event) {
		//constrainPickup();
		
		// sum up the costs
		var subTotalExcl = 0,
			subTotalIncl = 0,
			weight = 0,
			vatTotal = 0,
			voucherVAT = 0,
			voucherSubtotal = 0,
			giftTotal = 0,
			// The shipping method, like standard or express
			shippingMethod = $('input[name="shippingMethod"]:checked').val(),
			// Get the country where the purchase should be shipped to
			countryCode = $("#shipCountryCode").val();

		if($('input[name="shippingDestination"]:checked').val() == "billingAddress"){
			countryCode = $("#billCountryCode").val();
		}
		var isGift = $("#isGift").is("input:checked");

		// for each line item do
		$("input.quantity").each(function(){
			// get quantity 
			var qty = parseInt($(this).val());
			if (isNaN(qty)) {
				qty = 0;
			}
			// sum up weight
			var itemWeight = parseAndRoundFloat($(this).siblings('input[name="weight"]').eq(0).val());
			weight += qty * itemWeight;
			if(isGift){
				giftTotal += qty * giftCost;
			}
			
			// get net price
			var priceExcl = parseFloat($(this).siblings('input[name="price"]').val());
					
			// Look for input field with vat which can override default vat calculation
			// this is because the vat has to be calculated from the shipping country
			var vat,
				isVoucher = false;
					
			if ($(this).siblings('input[name="vat"]').length == 0) {
				vat = calculateVat(countryCode, priceExcl);
			}
			else {	// vat is calculated from the shipping address of the voucher (calculated on the server side)
				isVoucher = true;			 // if a name="vat" input field exists then we have a voucher
				vat = parseFloat($(this).siblings('input[name="vat"]').val());
			}

			// calculate prices
			var priceIncl = utils.round(priceExcl + vat, 2);
			var totalExcl = utils.round(priceExcl * qty, 2);
			var totalIncl = utils.round(priceIncl * qty, 2);
					
			$(this).parents("tr").find(".perItem").html(formatPrice(priceIncl));	// show row cost per item
			$(this).parents("tr").find(".total").html(formatPrice(totalIncl));		// show row cost in total
					
			if (isVoucher) {
				voucherVAT += totalIncl - totalExcl;
				voucherSubtotal += totalExcl;
				// dont add voucher to subtotal because its not part of the VAT calculation
			} else {
				subTotalExcl += totalExcl;
				subTotalIncl += totalIncl;
			}
			vatTotal += vat;
		});
		//subTotalIncl = Math.round(subTotalIncl * 100) / 100;
		subTotalIncl += voucherSubtotal + voucherVAT;
		var giftVAT = calculateVat(countryCode, giftTotal);
		vatTotal += giftVAT;

		costs = getCosts({
			countryCode: countryCode,
			subTotalExcl: subTotalExcl,
			subTotalIncl: subTotalIncl,
			giftTotal: giftTotal,
			giftVAT: giftVAT,
			weight: weight,
			shippingMethod: shippingMethod,
			vatTotal: vatTotal,
			voucherSubtotal: voucherSubtotal,
			voucherVAT: voucherVAT
		});

		showCosts();
		$(".currencies select").change();
		
		var shipCountryCode = $("#shipCountryCode").val();
		if($('input[name="shippingDestination"]:checked').val() == "billingAddress"){
			shipCountryCode = $("#billCountryCode").val();
		}
		var vat = 1+getVatValue(countryCode);
		$(".shipping-costs-pickup").html(formatPrice(calculateShip(shipCountryCode, weight, "pickup") * vat));
		$(".shipping-costs-standard").html(formatPrice(calculateShip(shipCountryCode, weight, "standard") * vat));
		$(".shipping-costs-express").html(formatPrice(calculateShip(shipCountryCode, weight, "express") * vat));
		

	};
	/*
	var constrainPickup = function(){
		var shippingMethod = $('input[name="shippingMethod"]:checked').val();
		if(typeof shippingMethod == "undefined"){
			$("#shippingMethodStandard").attr("checked", true);
		}
		
		if(countryCode!="AT"){
			$("#shippingMethodPickup").attr("disabled", "disabled");
			if(shippingMethod=="pickup"){
				$("#shippingMethodPickup").attr("checked", false);
				$("#shippingMethodStandard").attr("checked", true);
			}
		}else{
			$("#shippingMethodPickup").removeAttr("disabled");
		}
	}
	*/
	
		
	var showCosts = function() {
		if(costs.tax){
			$(".arrivalBox .note").hide();
			$("#orderSummary .hint").hide();
		}else{
			$(".arrivalBox .note").show();
			$("#orderSummary .hint").show();
		}
		$("#subtotal").html(formatPrice(costs.subtotal));
		$(".costs_subtotal").html(formatNumber(costs.subtotal));
		$(".costs_shipping").html(formatNumber(costs.shipping));
		$(".costs_gift").html(formatNumber(costs.giftTotal+costs.giftVAT));
		$(".costs_total").html(formatNumber(costs.total));
		$(".costs_tax").html(formatNumber(costs.tax));

		var time = costs.deliveryTimes;
		if ($("#step_voucher").length == 0)
		{
			var day = 1000 * 60 * 60 * 24;
			var shippingMethod = $("input[name='shippingMethod']:checked").val();
			var now = new Date();
			var minDate = new Date(now.getTime() + fulldays(eval("time." + shippingMethod + ".min")) * day);
			var maxDate = new Date(now.getTime() + fulldays(eval("time." + shippingMethod + ".max")) * day);
			$("#estimatedArrival .min").html(formatDate(minDate));
			$("#estimatedArrival .max").html(formatDate(maxDate));
			$("#shipStandard").find(".min").html(time.standard.min).end().find(".max").html(time.standard.max);
			$("#shipPickup").find(".min").html(time.pickup.min).end().find(".max").html(time.pickup.max);
			if (time.express.min < 0) {
					$("#shipExpress").hide("slow")
			}
			else {
					$("#shipExpress").show();
					$("#shipExpress").find(".min").html(time.express.min).end().find(".max").html(time.express.max);
			}
		}
		};
	
		if ($("#step_voucher").length != 0) {

				$("#shipCountryCode").change(updateCosts);
				$("#shipCountryCode").change();
				var countChars = function(){
						var charsLength = $(this).val().length;
						var charsLeft = maxLength - charsLength;
						if (charsLeft < 0) {
								$(this).val($(this).val().substring(0, maxLength));
								charsLeft = 0
						}
						$("#charsLeft").text(charsLeft);
				};
				var maxLength = 250;
				$("#charsLeft").text(maxLength);
				$("#voucherText").bind("keyup", countChars);
				$("#voucherText").bind("blur", countChars);
				$("#voucherText").keyup();
				var shipCountryCodeChange = function(){
						var countryCode = $(this).val();
						if (isZipRequired(countryCode)) {
								$(".shipZip span.compulsory").show();
						}
						else {
								$(".shipZip span.compulsory").hide();
						}
				};
				$("#shipCountryCode").change(shipCountryCodeChange);

		} else {


		
		// Some visual effects for the shipping destination
		// either same as bill address or another address
		$("input[name='shippingDestination']").click(function(){
			if ($(this).val() == "shippingAddress") {
					$("#shippingAddress").slideDown();
					$("#shipCountryCode").change();
			}
			else {
					$("#shippingAddress").slideUp();
					$("#billCountryCode").change();
			}
		});
		
		$("input[name='shippingDestination']:checked").click();
		
		// Visual effect for gift message
		$("#isGift").click(function() {
			$("#giftMessageHolder").slideToggle();
			$("#giftSummaryHolder").toggle();
			updateCosts();
		});
		
		if ($("#isGift").is("input:checked")) {
				$("#giftMessageHolder").show();
				$("#giftSummaryHolder").show();
		}
		
		// Visual effect for note message
		$("#isNote").click(function() {
				$("#notesMessageHolder").slideToggle();
		});
		if($("#notes").html().length>0){
			$("#notesMessageHolder").show();
		}
	 
		
		// helper function to count characters
		var countChars = function(){
			var charsLength = $(this).val().length;
			var charsLeft = maxLength - charsLength;
			if (charsLeft < 0) {
					$(this).val($(this).val().substring(0, maxLength));
					charsLeft = 0
			}
			$("#charsLeft").text(charsLeft)
		};
		
		// maxLength of a gift message
		var maxLength = 300;
		$("#charsLeft").text(maxLength);
		$("#giftMessage").bind("keyup", countChars);
		$("#giftMessage").bind("blur", countChars);
		$("#giftMessage").keyup();
		
		
		$('input[name="paymentMethod"]:checked').click();

		// Move Order Summary on scroll
		var msie6 = $.browser.msie && $.browser.version < 7;
		if (!msie6) {
			var top = $("#step_cart").offset().top + $("#step_cart").height();
			var bottom = top + $("#step_bill_col_left").height();
			var formTop = $("#step_cust").offset().top;
		
			var updatePos = function(){
				var y = $(window).scrollTop() + 40;
				$("#orderSummary").css("margin-top", 0);
				if (y >= top) {
					if (y <= bottom) {
						$("#orderSummary").addClass("fixed").css({
							"left": $("#orderSummary").parent().offset().left
						});
					}
					else {
						$("#orderSummary").removeClass("fixed").css("margin-top", bottom - top);
					}
				}
				else {
					$("#orderSummary").removeClass("fixed");
				}
			}
			
			$(window).scroll(updatePos);
			updatePos();
		}
		// End  :: Move Order Summary on scroll
					
		var countryCode;
		var costs = {};
	 
				
		var countryCodeChange = function(){
				if ($(this).is("#billCountryCode") && $('input[name="shippingDestination"]:checked').val() != "billingAddress") {
						return
				}
				else {
						countryCode = $(this).val();
						updateCosts()
				}
				if (isZipRequired($("#billCountryCode").val())) {
						$(".stepBill span.compulsory").show()
				}
				else {
						$(".stepBill span.compulsory").hide()
				}
	
		};
		$("#billCountryCode").change(countryCodeChange);
		$("#shipCountryCode").change(countryCodeChange);
		$("#shipCountryCode").change();
		$("#billCountryCode").change();
		$('input[name="shippingMethod"]').click(function(){
			updateCosts()
		})
	

	
		// check if cart should be saved
		var savingCart = false;
		// at first hide the button
		$("#updateCartButton").hide();
		
		// reset save status when button is clicked
		$("#updateCartButton").click(function() { savingCart = true; })
		
		//when checking out, cart is saved automatically
		//$("#CheckoutButton").click(function(){savingCart = true;})
		$(".submit input").click(function(){savingCart = true;})
		
		// If user navigates to differente site, ask him whether he wants to save cart if necessary 
		window.onbeforeunload = function(){
			if (!savingCart && $("#updateCartButton:visible").length) {
				return strings[lang].cartSaveQuestion
			}
		}
		
		// if the quantity is updated at one line item
		$("input.quantity").keypress(function(e){
				if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
						return false
				} else {
					// make update cart button visible
					$("#updateCartButton").fadeIn("slow");
				}
		});
		
		// also update costs
		$("input.quantity").keyup(updateCosts);
		
		// make nice animation when removing cart item and update costs
		$(".remove").click(function(){
			var $remove = $(this);
			$remove.parents("tr").fadeOut("normal", function(){
				$.ajax({
					url: $remove.attr("href"), 
					data:{format:'js'},
					dataType: 'jsonp',
					jsonp: 'jsonp_callback',
					success:function(data){
						$remove.parents("tr").remove();
						updateCosts();
					}
				});
			});
			return false
		});
		
		updateCosts();
	var billCountryCode = $("#billCountryCode").val();
	var billCountryCodeChanged = false;
	$("#billCountryCode").change(function(){
		if(billCountryCodeChanged || $(this).val() != billCountryCode){
			billCountryCodeChanged = true;
			$.ajax({
					url: base + "/shop/changeCountry/?ajax=1&billCountryCode=" + $(this).val(), 
					dataType: 'jsonp',
					jsonp: 'jsonp_callback',
					success:function(data){}
			});
		}
	});
	var shipCountryCode = $("#shipCountryCode").val();
	var shipCountryCodeChanged = false;
	$("#shipCountryCode").change(function(){
		if(shipCountryCodeChanged || $(this).val() != shipCountryCode){
			shipCountryCodeChanged = true;
			$.ajax({
					url: base + "/shop/changeCountry/?ajax=1&force=1&shipCountryCode=" + $(this).val(), 
					dataType: 'jsonp',
					jsonp: 'jsonp_callback',
					success:function(data){}
			});
		}
	});

	}
	
	// START passive updates
	var updateProp = function(){
		var value = escape(this.value);
		value = value.replace("'", "\\\'");
		setTimeout("$.get('/checkout/updateProp?name="+this.name+"&value="+value+"')", 2000);
	};

	$(".stepBill :input").blur(updateProp);
	
	$(".stepShip :input:not(:radio,:checkbox)").blur(updateProp);
	$(".stepShip input:radio").change(updateProp);
	$(".stepShip input:checkbox").change(updateProp);

	$(".stepShipOpt input:radio").change(updateProp);

	$(".stepPayment input:radio").change(updateProp);
	// END passive updates

	
	$("#redeem").click(function(){
		$.getJSON(base + "/coupon/redeem", {"mycode":$("#mycode").val(), "format":"json"},
			function(data){
				if(data.status=="success"){
					window.location=window.location;
				}else{
					if($("#coupon-msg").length==0){
						$("#redeem").parent().prepend("<div id='coupon-msg'></div>");
					}
					$("#coupon-msg").html(data.message);
				}
			}
		);
		return false;
	});
	


});


function fulldays(d){
		var a = new Date();
		var b = a.getDay();
		var e = d;
		var c = Math.floor(d / 5);
		e += c * 2;
		if (6 - b <= d % 5) {
				e += 2
		}
		return e
}



function getEstimatedDelivery(countryCode, shippingMethod){
		if (!shippingMethod) {
				shippingMethod = "standard";
		}
		if (!countryCode) {
				countryCode = "NZ"; // as expensive as possible
		}
		if (deliveryTimes[shippingMethod][countryCode] != undefined) {
				time = $.extend({}, deliveryTimes[shippingMethod][countryCode])
		}
		else {
				time = {
						min: 0,
						max: 0
				};
		}
		//if (time.min > 0) {
		time.min += 5;
		time.max += 10;
		//}
		return time;
}

function getEstimatedDeliveryTimes(a){
		var b = {};
		b.pickup = getEstimatedDelivery(a, "pickup");
		b.standard = getEstimatedDelivery(a, "standard");
		b.express = getEstimatedDelivery(a, "express");
		return b
}


function calculateVat(countryCode, netPrice){
		//netPrice = Math.max(0, netPrice);
		var grossPrice = netPrice * getVatValue(countryCode);
		return grossPrice;
}

function isZipRequired(countryCode){
		return countryCode == "US" || getVatValue(countryCode) > 0
}

function getCosts(args){//countryCode, subtotal, weight, shippingMethod, voucherSubtotal, voucherVAT){
	var taxRate = getVatValue(args.countryCode);
	var shippingCosts = calculateShip(args.countryCode, args.weight, args.shippingMethod);
	shippingCosts *= 1 + taxRate;  // add tax to shipping cost
	shippingCosts = parseAndRoundFloat(shippingCosts);

	var total = args.subTotalIncl + shippingCosts + args.giftTotal + args.giftVAT;

	var deliveryTimes = getEstimatedDeliveryTimes(args.countryCode);

	return {
		shipping: shippingCosts,
		taxRate: taxRate,
		total: total,
		deliveryTimes: deliveryTimes,
		giftTotal:args.giftTotal,
		giftVAT:args.giftVAT,

		tax: args.vatTotal,
		subtotal: args.subTotalIncl,
		voucherSubtotal: args.voucherSubtotal,
		voucherVAT: args.voucherVAT
	}
};

function setupSteps(){
	if(typeof $.historyInit != "undefined"){
		$.historyInit(handleSteps);
	}
	// SETUP STEPS
	$(".gotAccountButtons a#yes").attr("href", "#chosen-yes");
	// END SETUP STEPS

	function handleSteps(){
		if(window.location.hash.indexOf("chosen")>0){
			showLogin();
		}
	}
	function showLogin(){
		hideAllSteps();
		$("#return").show();
		$(".gotAccountButtons").hide();
		
	}
	function hideAllSteps(){
		$("#return").hide();
		
	}
}




$(window).keypress(function(event){
	if (event.which == 13)
	{
		return false;
	}
});


function loadTermsDialog(){
	$("#terms-dialog").load($("#terms-link").attr("rel"));
	$("#terms-link").click(function(){
		$("#terms-dialog").dialog({width:600, height:500});
		return false;
	});
	
}