﻿$.preferCulture("da-DK");

function OpenAlertPopup(buttonId) {
    Boxy.load("/Templates/CreatePopup.aspx", {
        fixed: true,
        modal: true,
        center: true,
        unloadOnHide: true,
        title: null,
        afterShow: function() {
            $("link").hide();
            $("title").hide();
            $("#confirmButton").click(function() {
                WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(buttonId, "", true, "Order", "", false, true));
            });
        }
    });
   }

   function OpenBoxyWindow(success_param) {
   	var url = "/Templates/BoxyWindow.aspx";
   	if (success_param != null && success_param != "") {
   		url += "?go=" + success_param;
   	}
   	Boxy.load(url, {
   		fixed: false,
   		modal: true,
   		center: true,
   		unloadOnHide: true,
   		title: null,
   		afterShow: function() {
   			$("link").hide();
   			$("title").hide();
   			//this.resize(450,350);
   			$("#confirmButton").click(function() {
   				
   			});
   		}
   	});
   }

function createXMLHttpRequest() {
  var request;
  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = false;
      }
    }
  }

  if (!request)
      jAlert("Error initializing XMLHttpRequest!");
  else
	return request;
}

function closeBoxy() {	
	if (PageMode == "0") {
		// store selected values in cookies
		var DeliveryMode = "2";
		var ShopID = "00";
		if ("" + $("#rbDeliveryHome").attr("checked") == "true") {
			// Delivery to home
			var PriceText = "" + $("#DeliveryPriceText").html();
			
			if (PriceText == "Kr. 0,00" ||
				PriceText == "") {
			    jAlert("Indtast et gyldigt postnummer");
				return false;
			}
			
			DeliveryMode = "1";
			ShopID = "" + $("#txtPostCode").val();
		} else {
			// Delivery to home
			DeliveryMode = "2";
			ShopID = "" + $("#ddlShops").val();
		}

		document.cookie = DelModeCookieName + "=" + DeliveryMode + "; path=/";
		document.cookie = DelShopIDCookieName + "=" + ShopID + "; path=/";
		
		return true;	
	}
}

function getDeliveryPrice(objTxt) {
  if ($.cookie(DelModeCookieName) == "1" && objTxt.value.length == 4) {
    request = createXMLHttpRequest();
    var postcode = $("#tbPostCode").val();
    if (objTxt) postcode = objTxt.value;

    //alert(postcode);
    var url = "/Templates/CalculateDeliveryPrice.aspx?pc=" + postcode;
    request.open("GET", url, true);
    request.onreadystatechange = updatePage;
    request.send(null);
  }
}

function updatePage() {
  if (request.readyState == 4) {
    if (request.status == 200) {
      var response = request.responseText.split("|");
      // fill out the delivery price
      var postcode = "";
      if (response[0] != "" && response[0] != "Kr. 0,00") {
        postcode = response[1];
        AddShipPrice(response[0]);
      }
      $("#DeliveryPriceText").html("" + response[0]);
      $.cookie(DelModeCookieName, "1", { path: '/' });
      $.cookie(DelShopIDCookieName, postcode, { path: '/' });
    } else
        jAlert("status is " + request.status);
  }
}

function getDeliveryPriceAddress(objTxt) {
    var objTxtId = objTxt.id;
    var postcode = $("#tbPostCode").val();
    if (objTxt) postcode = objTxt.value;
    
  var onlineonly = $.cookie("userOnlineOnlyOrder");
  if (onlineonly == "True") {
      $.cookie(DelModeCookieName, "1", { path: '/' });
      $.cookie(DelShopIDCookieName, postcode, { path: '/' });
  }
  else if ($.cookie(DelModeCookieName) == "1" && 
  (($.cookie(ShowReceiverCookieName) != "true" && objTxtId.match('tbPayerMobile')) || objTxtId.match('tbReceiverMobile'))) {
    request = createXMLHttpRequest();
    //alert(postcode);
    var url = "/Templates/CalculateDeliveryPrice.aspx?pc=" + postcode;
    request.open("GET", url, true);
    request.onreadystatechange = updatePageAddress;
    request.send(null);
  }
}

function updatePageAddress() {
	if (request.readyState == 4) {
		if (request.status == 200) {
			var response = request.responseText.split("|");
			// fill out the delivery price
			
			var freeDeliveryAmount = $.cookie(FreeDeliveryAmount);
			var isFreeDelivery = $.cookie(IsFreeDelivery);
			if (freeDeliveryAmount != "0" && isFreeDelivery == "0") {
			  $("#DeliveryPriceText").html("" + response[0]);
			}
			
			var postcode = "";
			if (response[0] != "" && response[0] != "Kr. 0,00") {
			  postcode =  response[1];
			}
			$.cookie(DelModeCookieName, "1", { path: '/' });
			$.cookie(DelShopIDCookieName, postcode, { path: '/' });

			if (postcode != "" && btnFillDeliveryTime != null) {
			  $("#" + btnFillDeliveryTime).click();
			}
		} else
		    jAlert("status is " + request.status);
	}}

function updateShoppingCartPrices() {
  if (request.readyState == 4) {
    if (request.status == 200) {
      var response = request.responseText.split("|");
      // fill out the delivery price
      $("#DeliveryPriceText").html("" + response[0]);
    } else
        jAlert("status is " + request.status);
  }
}

function calculatePriceOnAddress(postCode) {
  request = createXMLHttpRequest();
  var url = "/Templates/CalculateDeliveryPrice.aspx?pc=" + postCode;
  request.open("GET", url, true);
  request.onreadystatechange = updateShoppingCartPrices;
  request.send(null);
}

function AddShipPrice(newShipPrice) {
  var isFreeDelivery = $.cookie(IsFreeDelivery);
  var oldShipPrice = $("#deliveryPrice").html();
  if (oldShipPrice == "") {
    oldShipPrice = "0";
  }
  oldShipPrice = oldShipPrice.replace("Kr. ", "");
  oldShipPrice = oldShipPrice.replace(",", ".");
  oldShipPrice = parseFloat(oldShipPrice);

  var newShipPriceVal = newShipPrice.replace("Kr. ", "");
  newShipPriceVal = newShipPriceVal.replace(",", ".");
  newShipPriceVal = parseFloat(newShipPriceVal);

  var oldFinalPrice = $("#finalPrice").html().replace("Kr. ", "");
  oldFinalPrice = oldFinalPrice.replace(",", ".");
  oldFinalPrice = parseFloat(oldFinalPrice);
  oldFinalPrice = oldFinalPrice - oldShipPrice;
  
  var priceWithoutShip = oldFinalPrice;
  var newFinalPrice = oldFinalPrice + newShipPriceVal;

  FreeDeliveryLimit = FreeDeliveryLimit.toString();
  FreeDeliveryLimit = FreeDeliveryLimit.replace(",", ".");
  FreeDeliveryLimit = parseFloat(FreeDeliveryLimit);

  if (priceWithoutShip >= FreeDeliveryLimit || isFreeDelivery == "1") {
    $("#finalPrice").html($.format(priceWithoutShip, "c"));
    $("#deliveryPrice").html("Kr. 0,00");
  }
  else {
    $("#finalPrice").html($.format(newFinalPrice, "c"));
    $("#DeliveryPriceText").html("" + newShipPrice);
    $("#deliveryPrice").html("" + newShipPrice);
  }
}

function RemoveShipPrice() {
  var oldShipPrice = $("#deliveryPrice").html().replace("Kr. ", "");
  oldShipPrice = oldShipPrice.replace(",", ".");
  oldShipPrice = parseFloat(oldShipPrice);
 
  var oldFinalPrice = $("#finalPrice").html().replace("Kr. ", "");
  oldFinalPrice = oldFinalPrice.replace(",", ".");
  oldFinalPrice = parseFloat(oldFinalPrice);

  var newFinalPrice = oldFinalPrice - oldShipPrice;

  $("#finalPrice").html($.format(newFinalPrice, "c"));
  $("#DeliveryPriceText").html("");
  //$("#DeliveryPriceText").html("Kr. 0,00");
  $("#deliveryPrice").html("Kr. 0,00");
}

function UpdateCentralDiscount(operation) {
    if (parseFloat(CentralDiscount) > 0) {
        var shipPrice = $("#deliveryPrice").html().replace("Kr. ", "");
        shipPrice = shipPrice.replace(",", ".");
        if (shipPrice != "")
            shipPrice = parseFloat(shipPrice);
        else
            shipPrice = 0;

        var shipPriceHidden = $("#DeliveryPriceText").html().replace("Kr. ", "");
        shipPriceHidden = shipPriceHidden.replace(",", ".");
        if (shipPriceHidden != "")
            shipPriceHidden = parseFloat(shipPriceHidden);
        else
            shipPriceHidden = 0;

        var oldFinalPrice = $("#finalPrice").html().replace("Kr. ", "");
        oldFinalPrice = oldFinalPrice.replace(",", ".");
        oldFinalPrice = parseFloat(oldFinalPrice);
        oldFinalPrice = oldFinalPrice - shipPrice;

        var newFinalPriceWithoutShip = oldFinalPrice;        
        if (operation == 'True' && DiscountApplied == 'False') {            
                newFinalPriceWithoutShip = oldFinalPrice - (oldFinalPrice * CentralDiscount / 100);
                DiscountApplied = 'True';
        }
        else if(operation == 'False' && DiscountApplied == 'True'){
            newFinalPriceWithoutShip = oldFinalPrice / (1 - (CentralDiscount / 100));
            DiscountApplied = 'False';
        }
        var newFinalPrice = newFinalPriceWithoutShip + shipPriceHidden;

        $("#finalPrice").html($.format(newFinalPrice, "c"));
    }
}

function UpdateCentralDiscountCookie(operation) {
    if (parseFloat(CentralDiscount) > 0) {
        var shipPrice = parseFloat($.cookie(DeliveryPriceCookieName));
        
        var oldFinalPrice = parseFloat($.cookie(TotlaAmountCookieName));
        oldFinalPrice = oldFinalPrice - shipPrice;

        var newFinalPriceWithoutShip = oldFinalPrice;
        if (operation == 'True' && DiscountApplied == 'False') {
            newFinalPriceWithoutShip = oldFinalPrice - (oldFinalPrice * CentralDiscount / 100);
            DiscountApplied = 'True';
        }
        else if (operation == 'False' && DiscountApplied == 'True') {
            newFinalPriceWithoutShip = oldFinalPrice / (1 - (CentralDiscount / 100));
            DiscountApplied = 'False';
        }
        var newFinalPrice = newFinalPriceWithoutShip + shipPrice;

        $.cookie(TotlaAmountCookieName, newFinalPrice, { path: '/' });
    }
}

function UpdateProductsPrice(singlePriceId, singleCountPriceId, productsCount) {
  var isFreeDelivery = $.cookie(IsFreeDelivery);
  var postcode = $.cookie(DelShopIDCookieName);
  request = createXMLHttpRequest();
  var url = "/Templates/CalculateDeliveryPrice.aspx?pc=" + postcode;
  request.open("GET", url, true);
  request.onreadystatechange = updateShoppingCartPrices;
  request.send(null);

  
  var shipPrice = $("#deliveryPrice").html().replace("Kr. ", "");
  shipPrice = shipPrice.replace(",", ".");
  if (shipPrice != "")
      shipPrice = parseFloat(shipPrice);
  else
      shipPrice = 0;


  var deliveryTextHidden = $("#DeliveryPriceText");
  if (deliveryTextHidden != null && deliveryTextHidden.html() != null) {
      var shipPriceHidden = deliveryTextHidden.html().replace("Kr. ", "");
      shipPriceHidden = shipPriceHidden.replace(",", ".");
      if (shipPriceHidden != "")
          shipPriceHidden = parseFloat(shipPriceHidden);
      else
          shipPriceHidden = 0;      
  }
  
  var singlePrice = $("#" + singlePriceId).html().replace("Kr. ", "");
  singlePrice = singlePrice.replace(",", ".");
  singlePrice = parseFloat(singlePrice);

  var oldFinalPrice = $("#finalPrice").html().replace("Kr. ", "");
  oldFinalPrice = oldFinalPrice.replace(",", ".");
  oldFinalPrice = parseFloat(oldFinalPrice);  
  oldFinalPrice = oldFinalPrice - shipPrice;

  var singleCountPrice = $("#" + singleCountPriceId).html().replace("Kr. ", "");
  singleCountPrice = singleCountPrice.replace(",", ".");
  singleCountPrice = parseFloat(singleCountPrice);
  
  productsCount = parseInt(productsCount);

  FreeDeliveryLimit = FreeDeliveryLimit.toString();
  FreeDeliveryLimit = FreeDeliveryLimit.replace(",", ".");
  FreeDeliveryLimit = parseFloat(FreeDeliveryLimit);

  
  var newSingleCountPrice = productsCount * singlePrice;
  var newFinalPriceWithoutShip = (oldFinalPrice - singleCountPrice) + newSingleCountPrice;

  var newFinalPrice;
  if (deliveryTextHidden != null && deliveryTextHidden.html() != null) {
      newFinalPrice = newFinalPriceWithoutShip + shipPriceHidden;
  }
  else {
      newFinalPrice = newFinalPriceWithoutShip + shipPrice;
  }

  if (newFinalPriceWithoutShip >= FreeDeliveryLimit || isFreeDelivery == "1") {
    $("#finalPrice").html($.format(newFinalPriceWithoutShip, "c"));
    $("#deliveryPrice").html("Kr. 0,00");
  }
  else {
      $("#finalPrice").html($.format(newFinalPrice, "c"));
      if (deliveryTextHidden != null && deliveryTextHidden.html() != null) {
          $("#deliveryPrice").html($("#DeliveryPriceText").html());
      }
      else {
          $("#deliveryPrice").html($.format(shipPrice, "c"));
      }
  }
  $("#" + singleCountPriceId).html($.format(newSingleCountPrice, "c"));
}

function UpdateShippingPrice(shippingPrice) {

    var deliveryText = $("#DeliveryPriceGreenland");
    if (deliveryText != null && deliveryText.html() != null) {
        $("#DeliveryPriceGreenland").html($.format(shippingPrice, "c"));
    }
    else {
        var shipPrice = $("#deliveryPrice").html().replace("Kr. ", "");
        shipPrice = shipPrice.replace(",", ".");
        if (shipPrice != "")
            shipPrice = parseFloat(shipPrice);
        else
            shipPrice = 0;

        var oldFinalPrice = $("#finalPrice").html().replace("Kr. ", "");
        oldFinalPrice = oldFinalPrice.replace(",", ".");
        oldFinalPrice = parseFloat(oldFinalPrice);
        oldFinalPrice = oldFinalPrice - shipPrice;

        var newFinalPrice = oldFinalPrice + shippingPrice;
        $("#finalPrice").html($.format(newFinalPrice, "c"));
        $("#deliveryPrice").html($.format(shippingPrice, "c"));
    }
}

function UpdateAccessoryPrice(priceId, singlePriceValue, productsCount) {
    var singlePrice = parseFloat(singlePriceValue.replace("Kr. ", "").replace(",", "."));
    productsCount = parseInt(productsCount);
    var newPrice = productsCount * singlePrice;    
    
    $("#" + priceId).html($.format(newPrice, "c").replace("Kr. ", ""));
}

function suppressEnter(e) {
	e = e || window.event;
	if (e.keyCode == 13) {
		return false;
	}
	else {
		return true;
	}}

function Watermark(id, text) {
  $(function() {
    SetWatermark(id, text);
  });
  $("#" + id).blur(function() {
    $(this).filter(function() {
      return $(this).val() == ""
    }).val(text);
  });
}

function SetWatermark(id, text) {
  $("#" + id).val(text);
  $("#" + id).focus(function() {
    $(this).filter(function() {
      return $(this).val() == "" || $(this).val() == text
    }).val("");
  });
  $("#" + id).blur(function() {
    $(this).filter(function() {
      return $(this).val() == ""
    }).val(text);
  });
}

function ValidateAddress() {
  var DeliveryMode = $.cookie(DelModeCookieName);
  var ShopID = $.cookie(DelShopIDCookieName);
  var customized = parseFloat($.cookie("userCustomizedOrderCookie"));

  var errorMsg = "";
  
  //validate payer
  if (tbPayerFirstName != null && $("#" + tbPayerFirstName).val() == "") {
    errorMsg += "- Indtast betalers fornavn.\r\n";
  }
  if (tbPayerLastName != null && $("#" + tbPayerLastName).val() == "") {
    errorMsg += "- Indtast betalers efternavn.\r\n";
  }

  if (tbPayerStreet != null && $("#" + tbPayerStreet).val() == "") {
    errorMsg += "- Indtast betalers adresse.\r\n";
  }
  if (tbPayerPostOrCity != null && $("#" + tbPayerPostOrCity).val() == "") {
    errorMsg += "- Indtast betalers postnummer eller by.\r\n";
  }
  if (tbPayerMobile != null) {
    var payerMobile = $("#" + tbPayerMobile).val();
    if (payerMobile == "") {
      errorMsg += "- Indtast betalers postnummer.\r\n";
    }
    else {
      var re = RegExp("^\\d{4}$");
      if (!re.test(payerMobile)) {
        errorMsg += "- Indtast det korrekte betalers postnummer.\r\n"
      }
    }
  }
  if (tbPayerEmail != null) {
    var payerEmail = $("#" + tbPayerEmail).val();
    if (payerEmail == "") {
      errorMsg += "- Indtast betalers email.\r\n";
    }
    else {
      var re = RegExp("^\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
      if (!re.test(payerEmail)) {
        errorMsg += "- Indtast korrekt email.\r\n"
      }
    }
  }
  if (tbConfirmPayerEmail != null) {
    var confirmPayerEmail = $("#" + tbConfirmPayerEmail).val();
    if (confirmPayerEmail == "") {
      errorMsg += "- Bekræft betalers email.\r\n";
    }
    else {
      var re = RegExp("^\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
      if (!re.test(confirmPayerEmail)) {
        errorMsg += "- Indtast korrekt email.\r\n";
      }
      if ($("#" + tbPayerEmail).val() != confirmPayerEmail) {
        errorMsg += "- Betalers emails er ikke ens.\r\n";
      }
    }
  }
  if (tbPayerTelephone != null) {
    var payerTelephone = $("#" + tbPayerTelephone).val();
    if (payerTelephone == "") {
      errorMsg += "- Indtast betalers telefon.\r\n";
    }
    else {
      var re = RegExp("^\\d+$");
      if (!re.test(payerTelephone)) {
        errorMsg += "- Indtast det korrekte telefon.\r\n";
      }
    }
  }
  
  //validate receiver
  if (((showReceiver != null && $("#" + showReceiver).is(':checked')) || $.cookie(ShowReceiverCookieName) == "true")
        && (rbDeliveryHome != null && $("#" + rbDeliveryHome).attr("checked") == true)) {
    if (tbReceiverFirstName != null && $("#" + tbReceiverFirstName).val() == "") {
      errorMsg += "- Indtast modtagers fornavn.\r\n";
    }
    if (tbReceiverLastName != null && $("#" + tbReceiverLastName).val() == "") {
      errorMsg += "- Indtast modtagers efternavn.\r\n";
    }

    if (tbReceiverStreet != null && $("#" + tbReceiverStreet).val() == "") {
      errorMsg += "- Indtast modtagers adresse.\r\n";
    }
    if (tbReceiverPostOrCity != null && $("#" + tbReceiverPostOrCity).val() == "") {
      errorMsg += "- Indtast modtagers postnummer eller by.\r\n";
    }
    if (tbReceiverMobile != null) {
      var receiverMobile = $("#" + tbReceiverMobile).val();
      if (receiverMobile == "") {
        errorMsg += "- Indtast modtagers postnummer.\r\n";
      }
      else {
        var re = RegExp("^\\d{4}$");
        if (!re.test(receiverMobile)) {
          errorMsg += "- Indtast det korrekte modtagers postnummer.\r\n"
        }
      }
    }
    if (tbReceiverEmail != null) {
      var receiverEmail = $("#" + tbReceiverEmail).val();
      if (receiverEmail == "") {
        errorMsg += "- Indtast modtagers email.\r\n";
      }
      else {
        var re = RegExp("^\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
        if (!re.test(receiverEmail)) {
          errorMsg += "- Indtast korrekt email.\r\n"
        }
      }
    }
    if (tbConfirmReceiverEmail != null) {
      var confirmReceiverEmail = $("#" + tbConfirmReceiverEmail).val();
      if (confirmReceiverEmail == "") {
        errorMsg += "- Bekræft modtagers email.\r\n";
      }
      else {
        var re = RegExp("^\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
        if (!re.test(confirmReceiverEmail)) {
          errorMsg += "- Indtast korrekt email.\r\n";
        }
        if ($("#" + tbReceiverEmail).val() != confirmReceiverEmail) {
          errorMsg += "- Modtagers emails er ikke ens.\r\n";
        }
      }
    }
    if (tbReceiverTelephone != null) {
      var receiverTelephone = $("#" + tbReceiverTelephone).val();
      if (receiverTelephone == "") {
        errorMsg += "- Indtast modtagers telefon.\r\n";
      }
      else {
        var re = RegExp("^\\d+$");
        if (!re.test(receiverTelephone)) {
          errorMsg += "- Indtast det korrekte telefon.\r\n";
        }
      }
    }
  }

  if (rbDeliveryHome != null && $("#" + rbDeliveryHome).attr("checked") == true) {
    if (ddlPickupTime != null && $("#" + ddlPickupTime).val() == "0") {
      errorMsg += "- Vælge adresse leveringsdato \r\n";
    }
  }

  if (rbDeliveryShop != null && $("#" + rbDeliveryShop).attr("checked") == true) {
    if (ddlTime != null && $("#" + ddlTime).val() == "0") {
      errorMsg += "- Vælg leveringsdato \r\n";
    }
  }

  if (ShopID == null || ShopID == "" || ShopID == "0") {
    if (DeliveryMode == "1" && customized < 1) {
      errorMsg += "- Indtast et gyldigt postnummer \r\n";
    }
    else if (DeliveryMode == "2" || DeliveryMode == null || DeliveryMode == "") {
      errorMsg += "- Vælg butik \r\n";
    }
  }

  if (rbDeliveryCentral != null && $("#" + rbDeliveryCentral).attr("checked") == true) {
      if (ddlTimeCentral != null && $("#" + ddlTimeCentral).val() == "0") {
          errorMsg += "- Vælg afhentning dato \r\n";
      }
  }

  if (cbAcceptTerms != null && !$("#" + cbAcceptTerms).is(':checked')) {
    errorMsg += "- Accepter betingelserne.\r\n";
  }
  
  if (errorMsg != "") {
      jAlert(errorMsg);
    return false;
  }
  else {
    return true;
  }
}
    
function ValidateShoppingCart() {
    var countryCode = $.cookie("countryCode");
    var DeliveryMode = $.cookie(DelModeCookieName);
    var ShopID = $.cookie(DelShopIDCookieName);
    var onlineonly = $.cookie("userOnlineOnlyOrder");
    var customized = parseFloat($.cookie("userCustomizedOrderCookie"));
    if (DeliveryMode == null || DeliveryMode == "" ||
    (DeliveryMode == "1" && onlineonly != "True" && customized < 1 && (ShopID == null || ShopID == "" || ShopID == "0"))) {
        jAlert("Indtast et gyldigt postnummer");
        return false;
    }
    else if (countryCode == 'Gl' && document.getElementById(ddlGreenId).value == '0') {
        jAlert("vælge et postnummer");
        return false;
    }
    return true;
}

function confirmationWindow(url) {
  popupWindow = window.open(url, 'popUpWindow', 'height=650,width=620,resizable=0,scrollbars=1,toolbar=0,status=0');
}

function zoomImageWindow(url) {
  window.open(url, 'zoomImageWindow', 'height=430,width=780,resizable=yes,scrollbars=yes,toolbar=0,status=0');
}

function clickButton(e, buttonid) {
  var evt = e ? e : window.event;
  var bt = document.getElementById(buttonid);
  if (bt) {
    if (evt.keyCode == 13) {
      bt.click();
      return false;
    }
  }
}


function getShopInfo(keyword) {
    if (keyword != '') {
        geocoder.getLocations(keyword + ' Denmark', geocodeComplete);       
    }
}

function updateMiniMap() {
    if (request.readyState == 4) {
        if (request.status == 200) {
            var response = request.responseText.split(";;");

            if (response.length > 1) {
                getGoogleMapCountry_hfCountryCenterLat().value = response[0];
                getGoogleMapCountry_hfCountryCenterLng().value = response[1];

                $("#shop-info").html(response[2]);
                initializeCountryMap();
            }
            else {
                $("#shop-info").html(response[0]);
            }
        } else
            jAlert("status is " + request.status);
    }
}

function initUserLocation() {
    $.getJSON("http://jsonip.appspot.com?callback=?",
    function(data) {
        createShopInfoRequest('', 0, '', '', data.ip);
    });   
}

function geocodeComplete(result) {
    if (result.Status.code != 200) {
        //jAlert('Could not geocode "' + result.name + '"');
        return;
    }
    var placemark = result.Placemark[0]; // Only use first result
    //var accuracy = placemark.AddressDetails.Accuracy;
    var lon = placemark.Point.coordinates[0];
    var lat = placemark.Point.coordinates[1];
    createShopInfoRequest(txtSearch.val(), 1, lat, lon, '');    
}

function createShopInfoRequest(keyword, srch, lat, lon, ip) {
    request = createXMLHttpRequest();
    var url = "/Templates/BivaGoogleMap/getShopInfo.aspx?keyword=" + keyword.replace(' ', '_') + "&srch="+srch+"&lat=" + lat + "&lon=" + lon + "&ip=" + ip;
    request.open("GET", url, true);
    request.onreadystatechange = updateMiniMap;
    request.send(null);
}

function googleLocation() {
    if (google.loader.ClientLocation) {
        if (google.loader.ClientLocation.address.country_code == "DK")
            return "Dk";
        else if (google.loader.ClientLocation.address.country_code == "GL")
            return "Gl";
    }
    else {
        return "Dk";
    }
}

function showOverlay() {    
    $("#overlay").show();
}

function greenlandPort(op, quantity, volume) {
    var dropdown = document.getElementById(ddlGreenId);
    var totalVol = $.cookie(TotalVolCookieName);    
    switch (op) {
        case 'minus':
            totalVol = totalVol - (volume * quantity);
            break;
        case 'plus':
            totalVol = parseFloat(totalVol) + (volume * quantity);
            break;
        default:
            break;
    }
    $.cookie(TotalVolCookieName, totalVol, { path: '/' });
    if (dropdown.value != '0') {
        var postcode = dropdown.value.split(',')[0];
        var m3cost = dropdown.value.split(',')[1];

        var totalcost = m3cost * totalVol;
        UpdateShippingPrice(totalcost);
        $.cookie(DelShopIDCookieName, postcode, { path: '/' });
    }
    else {
        UpdateShippingPrice(0);
    }
} 
