﻿var postponedLocation;

userData = new Array();

function BasketInfo(color, pricePlan, subscription) {
    this.color = color;
    this.pricePlan = pricePlan;
    this.subscription = subscription;
}


function PricePlan(id, articleNo, planName, monthlyPrice, numberOfMonths, upFrontPrice,freightCost) {
    this.id = id;
    this.articleNo = articleNo;
    this.planName = planName;
    this.monthlyPrice = monthlyPrice;
    this.numberOfMonths = numberOfMonths;
    this.upFrontPrice = upFrontPrice;
    this.freightCost = freightCost;
    
}

function Subscription(id, bindingPeriod, monthlyPrice,subscriptionDiscount ) 
{
    this.id = id;
    this.bindingPeriod = bindingPeriod;
    this.monthlyPrice = monthlyPrice;
    this.subscriptionDiscount = subscriptionDiscount;
}

function stripUrlVars(url) {
   if(url != null)
    return url.substring(0, url.lastIndexOf("/") + 1);
   
}

function getProductUrlVars(productIds) {
    var query = "";
    var queryVar = "product";
    for (var i = 0; i < productIds.length; i++) {
        if (i == 0)
            query += "?" + queryVar + "=";
        else
            query += "&" + queryVar + "=";
        query += productIds[i];
    }
    return query;
}


function updateDevicePriceTag(controlIndex) {

      var ud = userData[controlIndex];
      var totalPrice = 0;
      var upfrontPrice = 0;

      if (ud != undefined && ud.pricePlan != "" && ud.subscription != "") {
          var prices = ud.pricePlan.upFrontPrice.split(",");
          for (var i = 0; i < prices.length; i++) {
              if (prices[i].split(":")[1] == ud.subscription.id) {
                  upfrontPrice = prices[i].split(":")[0];
                  break;
              }
          }
          totalPrice = parseInt(upfrontPrice) + (ud.pricePlan.monthlyPrice * ud.pricePlan.numberOfMonths)
            + (ud.subscription.monthlyPrice * ud.subscription.bindingPeriod) + ud.pricePlan.freightCost 
            - ud.subscription.subscriptionDiscount;
      }

      $(".pris", $("#upfrontprice" + controlIndex)).eq(0).text(upfrontPrice);
    $(".totalprice" + controlIndex ).eq(0).text(totalPrice);
    
    $("#basket-deviceprice").text(upfrontPrice);
}

function setBasketHrefTo(controlIndex) {
    var selector = ".basketlink" + controlIndex;
    var ud = userData[controlIndex];
    var href = $(selector).eq(0).attr("href");
    $(selector).attr("href",
        stripUrlVars(href) + getProductUrlVars([ud.color, ud.pricePlan.id, ud.subscription.id])
      );
}


function replaceDevicePageNumberTag() {
    var defaultNumberTag = '<span class="pris">0</span>';
   if($(".upfrontprice").html() != null)
   {
    $(".upfrontprice").html($(".upfrontprice").html().replace("{0}", defaultNumberTag));
    $(".monthamount").eq(0).html(
		$(".monthamount").eq(0).html().replace("{0}", defaultNumberTag)
	);
	}
}

function updateAllPriceTags() {
    for(var i = 0; i < userData.length; i++)
        updateDevicePriceTag(i);
}

function updateAllBasketLinks() {
    for (var i = 0; i < userData.length; i++)
        
		if (typeof (userData[i]) != "undefined") 
        {
            setBasketHrefTo(i);
        }
}

function AddItem(itemId, selectedValue) {
    AddItem(itemId, selectedValue, true)
}
function AddItem(itemId, selectedValue, countItem) {


    $.ajax({
        type: "POST",
        url: "/templates/UtilityPages/BasketHandler.aspx",
        data: "command=add&pagelink=" + itemId + "&selectedValue=" + selectedValue,
        success: function(data) {

            var htmlContainer = data.split("¤¤¤¤");


            $("#basket-container").html(htmlContainer[0]);
            $("#bigbasket-container").html(htmlContainer[1]);
            $("#script-dummy").html(htmlContainer[2]);
            if (countItem) {
                var count = parseInt($("#item-count").html());
                count++;
                $("#item-count").html(count);
                if (count > 1)
                    $("#item-r").html('varer');
                else
                    $("#item-r").html('vare');
            }

        }
    });

}

function RemoveItem(itemId, selectedValue) {
    $.ajax({
        type: "POST",
        url: "/templates/UtilityPages/BasketHandler.aspx",
        data: "command=remove&pagelink=" + itemId + "&selectedValue=" + selectedValue,
        success: function(data) {

            var htmlContainer = data.split("¤¤¤¤");
            
            $("#basket-container").html(htmlContainer[0]);
            $("#bigbasket-container").html(htmlContainer[1]);
            $("#script-dummy").html(htmlContainer[2]);
            var count = parseInt($("#item-count").html());
            count--;
            $("#item-count").html(count);
            if(count > 1)
                $("#item-r").html('varer');
            else
                $("#item-r").html('vare');


        }
    });
}

function ClearBasket(onCompleteUrl) {
    $.ajax({
        type: "POST",
        url: "/templates/UtilityPages/BasketHandler.aspx",
        data: "command=removeall",
        success: function(data) {
            //alert(onCompleteUrl);
            window.location = onCompleteUrl;
        }
    });
}

function ChangeBasketPricePlan(itemId, selectedValue) {
    $.ajax({
        type: "POST",
        url: "/templates/UtilityPages/BasketHandler.aspx",
        data: "command=changepriceplan&pagelink=" + itemId + "&selectedValue=" + selectedValue,
        success: function(data) {

            var htmlContainer = data.split("¤¤¤¤");


            $("#basket-container").html(htmlContainer[0]);
            $("#bigbasket-container").html(htmlContainer[1]);
            $("#script-dummy").html(htmlContainer[2]);
        }
    });
}

function setSelectedValue(value) {

    $("#afdrag0 option").each(function() {
        if ($(this).attr("value") == value) {
            $(this).attr("selected", true);
        }

    });

}
/* // disables links in the shop flow, preventing the user to leave when the basket isn't empty
function disableLinks() {
    $(document).ready(function() {
        $(".hidden a").addClass("noPop");
        
        $(window).unload(function()
        {
			//alert(String(window.location).indexOf("oister"))
            //postponedLocation = window.location;
            
            Popcorn.Pop('#cancelPurchase', null, null);
            evt.preventDefault();
        });
    })
}
*/
/*
function disableLinks() {
    $(document).ready(function() {
        $(".hidden a").addClass("noPop");
        $("a:not(#TB_overlay,#backToPurchase,.removeDeviceLink,.noPop,#cancelPurchase a)").click(function(evt) {
            postponedLocation = $(this).attr("href");
            Popcorn.Pop('#cancelPurchase', null, null);
            evt.preventDefault();
        });
    })
}

*/
// deprecated function
function disableLinks(){}


$(document).ready(function() {
    replaceDevicePageNumberTag();
    updateAllPriceTags();
    updateAllBasketLinks();
    Popcorn.Init();
});
