﻿/**
 * @author rpitkane
 */
$(function() {

	var systemBolagetData = {};
	
	$("input[id='postnumber']").bind("blur", function() {		
		var postcode = $(this).val(),
			searchKey = postcode.length > 1 ? postcode.substring(0, 2) : postcode;
		$.ajax({
			url: "/AltiaFormHandler/FormHandlerServlet?formType=databaseGet&postCode=" + searchKey,
			dataType: "json",
			async: true,
			contentType: "text/plain;charset=utf-8",
			timeout: 5000,
			success: function(data, textStatus, xhr) {
				systemBolagetData = data;
//				console.info(data, textStatus, xhr, data.Store0);
				var $select = $("select[name='pickup_store']"), i = 0, store = data.Store0;
				if ($select.length) {
					$select.find("option").remove();
					$select.append('<option value="">&nbsp;</option>');
					while (typeof store !== "undefined") {
						$select.append('<option value="' + store.Adresss + '_' + store.Location + '">' + store.Adresss + ' ' + store.Location + '</option>');
						i++;
						store = data["Store" + i];
					}
				}
			}
		});
	});
	
	$("button[class~='addtocart']").each(function() {
		var $this = $(this);
		if(!$this.hasClass("order")) {
			$this.closest("form").hide();
		}
	});
	
	window.altia = {};
	window.altia.shopping = (function() {
		var cart = (typeof sessvars.altia !== "undefined") ? sessvars.altia.shopping.cart : { "meta": {} },
			tooltipsSet = false;	
			
		if($("button[id='bestallning']").length){
			$("span[id='customer_name']").text(cart.meta.firstName + " " + cart.meta.lastName);
			$("span[id='postnumber']").text(cart.meta.postnumber);
			$("span[id='telefon']").text(cart.meta.phone);
			$("span[id='mobil']").text(cart.meta.mobil?cart.meta.phone:"");
			$("span[id='email']").text(cart.meta.email);
			if (cart.meta.systembolaget !== null) {
				$("span[id='address']").text(cart.meta.systembolaget.Adresss);
				$("span[id='sys_postnumber']").text(cart.meta.systembolaget.PostCode);
				$("span[id='location']").text(cart.meta.systembolaget.Location);
				$("span[id='sys_telefon']").text(cart.meta.systembolaget.Phone);
				$("span[id='vecka']").text(cart.meta.systembolaget.OpenWeekDay === null ? "" : cart.meta.systembolaget.OpenWeekDay);
				$("span[id='lordag']").text(cart.meta.systembolaget.OpenSaturday === null ? "" : cart.meta.systembolaget.OpenSaturday);
			}
		}
		
		function getSystembolagetInfo(addressLocation) {			
			var keys, address, location, store;
			if (addressLocation.indexOf("_") !== -1) { 
				keys = addressLocation.split("_");
				address = keys[0];
				location = keys[1];
	//			alert(addressLocation);
				for (store in systemBolagetData) {
					if (systemBolagetData.hasOwnProperty(store)) {
						//alert(systemBolagetData[store].Adresss + "=" + address);
						//alert(systemBolagetData[store].Location + "=" + location);
						if (systemBolagetData[store].Adresss === address && systemBolagetData[store].Location === location) {
							return systemBolagetData[store];
						}
					}
				}
				return null;
			}
			return null;
		}
				
		function Purchase(sap, title, res, sys, price, link, amount) {
			this.sap = sap;
			this.title = title;
			this.res = res;
			this.sys = sys;
			this.price = price;
			this.link = link;
			this.amount = amount;
		}
		
		function modifyPurchaseInCart(sap, step, amount) {
			if (step) {
				cart[sap].amount = cart[sap].amount + step;
			} else if (typeof amount !== "undefined") {
				cart[sap].amount = amount;
			}
						
			$("[id='total_price_"+sap+"']").text(cart[sap].amount*cart[sap].price +" kr");
			updateCart(cart);
		}
		
		function removePurchaseFromCart(sap) {
			if (typeof cart[sap] !== "undefined") {
				delete cart[sap];
				updateCart(cart);
			}
		}
		
		function setupTooltips() {
			if ($("button").filter("[data-unid]").length) {
				$("button").filter("[data-unid]").tooltip({
					delay: 0,
					fade: 300,
					track: true,
					showURL: false,
					left: -$("#content").offset().left,
					top: 25,
					bodyHandler: function() {
						var sap = parseInt($(this).attr("data-unid"), 10);
						if (typeof cart[sap] !== "undefined") {
							return "<p>Du har <strong>" + cart[sap].amount + "</strong> flaskor av denna produkt i din varukorg.</p>";
						} else {
							return "<p>Du har  <strong>0</strong> flaskor av denna produkt i din varukorg.</p>";
						}
					}
				});
				tooltipsSet = true;				
			}
		}
		
		function updateCart(cart) {
			var totalAmount = 0, totalPrice = 0, sap;
			for (sap in cart) {
				if (cart.hasOwnProperty(sap) && !isNaN(sap)) {
					totalAmount = totalAmount + cart[sap].amount;
					totalPrice = totalPrice + cart[sap].amount*cart[sap].price;
				}
			}
			cart.meta.totalAmount = totalAmount;
			cart.meta.totalPrice = totalPrice;
			$("div[id='cart']").find("em:first").text(totalAmount);
			$("[class='cart_price']").text(cart.meta.totalPrice +" kr");
			return true;
		}
		
		function showCart() {						
			var $cart = $("table[id='shoppingcart']"),
				$tbody = $cart.find("tbody"),
				$row =  $tbody.find("tr:first"),
				$aElem = null,
				sap;			
			for (sap in cart) {
				if (cart.hasOwnProperty(sap)) {
					if (!isNaN(sap)) {
						$tmpRow = $row.clone(true);
						$aElem = $tmpRow.find("td[class='first'] a");
						$aElem.text(cart[sap].title);
						$aElem.attr("href", cart[sap].link);
						if($("button[id='bestallning']").length){
							$tmpRow.find("p[class~='amount']").text(cart[sap].amount);
						} else {
							$tmpRow.find("input[name='amount']").attr("data-unid", sap).val(cart[sap].amount);
						}
						$tmpRow.find("td[class~='Systembolaget']").text(cart[sap].sys);
						$tmpRow.find("td[class~='Restaurang']").text(cart[sap].res);
						$tmpRow.find("td[class='price']").attr("id", "total_price_" + sap).text(cart[sap].price * cart[sap].amount);
						$tmpRow.find("button[class~='amount_up'], button[class~='amount_down']").attr("data-unid", sap);
						$tmpRow.find("td[class~='remove']").attr("data-unid", sap);
						$tmpRow.find("input[name='amount']").bind("blur", function(){
							var $this = $(this), amount = parseInt($this.val(), 10), sap = parseInt($this.attr("data-unid"), 10);
							modifyPurchaseInCart(sap, false, amount);
							$this.closest("tr").find("td[class='price']").text(amount * cart[sap].price);
						});
						$tbody.append($tmpRow.show());
					}
				}
			}
			$("[class='total_price']").text(cart.meta.totalPrice +" kr");
			/*if (!tooltipsSet) {
				setupTooltips();
			}*/
		}
		
		$("button[id='summary']").bind("click", function(e) {
			cart.meta.firstName = $("input[id='first_name']").val();
			cart.meta.lastName = $("input[id='last_name']").val();
			cart.meta.postnumber = $("input[id='postnumber']").val();
			cart.meta.email = $("input[id='email']").val();
			cart.meta.phone = $("input[id='phone']").val();
			cart.meta.mobil = $("input[id='mobil']").is(":checked") ? true : false;
			cart.meta.systembolaget = getSystembolagetInfo($("select[name='pickup_store']").val());
			if (!$("input[id='phone'][value]").length || $("input[id='phone']").val() === "") {
				alert("Minst ett telefonnummer måste fyllas i");
			} else if (typeof cart.meta.systembolaget === "undefined" || cart.meta.systembolaget === null) {
				alert("Du måste välja ett systembolag");
			} else {
				window.location.href = "/se/Startsida/Shopping+cart+summary"; 
//				$(this).closest("form").submit();
			}			
			e.preventDefault();
		});
		
		$("button[id='bestallning']").bind("click", function(e) {
			$("input[name='cart_data']").val(JSON.stringify(cart));
			sessvars.altia.shopping.cart = { "meta": {} };
			$(this).closest("form").submit();
		});
		
		function activateCartButton() {
			$("button").filter("[data-unid]").bind("click", function() {
				var $this = $(this),
					sap = parseInt($this.attr("data-unid"), 10),
					title = $this.attr("data-title"),
					res = $this.attr("data-res"),
					sys = $this.attr("data-sys"),
					price = $this.attr("data-price");
					link = $this.attr("data-link");
					amount = parseInt($this.closest("form").find("input[name='amount']").val(), 10);				
				if (typeof cart[sap] === "undefined") {
					purchase = new Purchase(sap, title, res, sys, price, link, amount);
					cart[purchase.sap] = purchase;
					updateCart(cart);
				} else {
					purchase = cart[sap];
					modifyPurchaseInCart(sap, amount);
				}
				/*overlayAPI.load();*/
			});
		}		
			
		$("a[id='view_cart']").bind("click", function(e) {
			var structure = {
				"shopping": {
					"cart": cart
				}
			};
			
			e.preventDefault();
			if (!cart.meta.totalAmount) {
				window.location.href = "/se/Startsida/Shopping+cart+empty";
			} else {
				sessvars.altia = structure;
				window.location.href = "/se/Startsida/Shopping+cart";
			}
		});
				
		$("button[class~='amount_up'], button[class~='amount_down']").live("click", function(e) {
			e.preventDefault();
			var $this = $(this),
				step = ($this.attr("class") === "amount_up") ? 1 : -1, 
				$amount = $this.parent().prev().find("input[name='amount']"),
				nextValue = parseInt($amount.val(), 10)+step,
				sap = $this.attr("data-unid"); 
			$amount.val(nextValue < 0 ? 0 : nextValue);			
			if ($this.parent().hasClass("modify_cart")) {
				modifyPurchaseInCart(sap, false, parseInt($amount.val(), 10));
			}
		});
		
		$("td[class='remove'] a").live("click", function() {
			var $this = $(this),
				$tmpRow = $this.closest("tr"),
				sap = $this.parent().attr("data-unid");
			removePurchaseFromCart(sap);
			$tmpRow.hide(1000, function() {
				$(this).remove();
			});
		});
		
		updateCart(cart);
		
		setupTooltips();
		
		if ($("table[id='shoppingcart']").length) {
			showCart();
		}
		
		activateCartButton();
		
		return {
			activateCartButton: function() {
				activateCartButton();
			},
			setupTooltips: function() {
				setupTooltips();
			}			
		};
	}());
});

