$(function() {

    GetShippingEstimate();
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(GetShippingEstimate);

});

function GetShippingEstimate() {

    if (typeof spC != 'undefined' && spC == true) {
        UpdateTotalsFreeShipping();
        return;
    }

    var dataToServer = {
        cartID: ctID,
        storeID: stID,
        customerID: cuID,
        applicablePromos: prCD,
        vendorDeliveryOptionID: -1,
        shippingType: ''
    }

    Calculating(true, 0);

    $.ajax({
        type: "POST",
        url: "/WebServices/PricingService.asmx/GetShippingEstimate",
        data: Sys.Serialization.JavaScriptSerializer.serialize(dataToServer),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            UpdateTotals(msg.d);
        }
    });


}

function UpdateTotals(result) {

    var totalAmount = 0;
    var subTotal = parseFloat($("#subTotal").text().toString().replace('£', '').replace('$', '').replace(',', ''));
    var taxTotal = parseFloat($("#taxTotal").text().toString().replace('£', '').replace('$', '').replace(',', ''));

    if (subTotal != null && !isNaN(subTotal)) {
        totalAmount += subTotal;
    }
    if (taxTotal != null && !isNaN(taxTotal)) {
        totalAmount += taxTotal;
    }

    totalAmount += result.Estimate;

    $("#shippingTotal").removeClass("calculating");
    $("#cartTotal").removeClass("calculating");

    $("#shippingTotal").text(ToMoney(result.Estimate));
    $("#cartTotal").text(ToMoney(totalAmount));

    UpdatePromoDiscountedFullyView(result.IsPromoDiscountedFully);
}

function UpdateTotalsFreeShipping() {

    var totalAmount = 0;
    var subTotal = parseFloat($("#subTotal").text().toString().replace('£', '').replace('$', '').replace(',', ''));
    var taxTotal = parseFloat($("#taxTotal").text().toString().replace('£', '').replace('$', '').replace(',', ''));

    if (subTotal != null && !isNaN(subTotal)) {
        totalAmount += subTotal;
    }
    if (taxTotal != null && !isNaN(taxTotal)) {
        totalAmount += taxTotal;
    }

    $("#shippingTotal").removeClass("calculating");
    $("#cartTotal").removeClass("calculating");

    $("#shippingTotal").text(ToMoney(0));
    $("#cartTotal").text(ToMoney(totalAmount));

    UpdatePromoDiscountedFullyView(true);
}

function UpdatePromoDiscountedFullyView(isFreeShipping) {
    if (isFreeShipping) {
        var promoText = 'Free Standard Shipping';
        promoText += $("#promoTotal").text().replace('$0.00', '').replace('You Save', ' <br />Plus Saved');

        $("#promoTotal").html(promoText).css('color', '#17A605');
        //$("#shippingTotalTitle").css('color','#F00');
        $("#shippingTotal").css('color', '#17A605').text('Free!');
    }
}

function ToMoney(amount) {
    return curChr + amount.toFixed(2);
}

function Calculating(begin, itr) {

    if (begin == true || $("#shippingTotal").hasClass("calculating")) {
        if ($("#shippingTotal").hasClass("calculating") == false) {
            $("#shippingTotal").addClass("calculating");
            $("#cartTotal").addClass("calculating");
        }

        var newText = 'Calculating';
        if (itr % 4 == 0) {
            newText += '&nbsp;&nbsp;&nbsp;'
        }
        if (itr % 4 == 1) {
            newText += '.&nbsp;&nbsp;'
        }
        if (itr % 4 == 2) {
            newText += '..&nbsp;'
        }
        if (itr % 4 == 3) {
            newText += '...'
        }

        $("#shippingTotal").html(newText);
        $("#cartTotal").html(newText);

        setTimeout(function() { Calculating(false, ++itr) }, 300);
    }
}

function AddPromo() {
    var newPromo = $("[id$='_tbPromoCode']").val();
    var found = false;

    if (!prCD) // if not defined for some reason
        return;

    for (var i = 0; i < prCD.length; i++) {
        var item = prCD[i];
        if (item == newPromo)
            found = true;
    }

    if (!found)
        prCD.push(newPromo);
}

window.keyCount = 0;

function runKeyUp() {
    var curKeyCount = ++window.keyCount;
    window.setTimeout(function() {
        if (curKeyCount == window.keyCount) {
            UpdatePricing();
        }
    }, 500);
}

function UpdatePricing() {
    $("[id$='_btnUpdate']").click();
}

function RemovePromo(sender) {
    var promoToRemove = $(sender).attr("promocode");

    var index = prCD.indexOf(promoToRemove);
    if (index >= 0) {
        prCD.remove(index);
    }

}

function ResizeTemplate(gotoDesigner, enID, powerDesignLink) {
    if (gotoDesigner) {
        window.location = powerDesignLink;
    } else {
        window.location = window.location;
    }
}

$('iframe:last').hide();

