function addToCart(offeringId, parentId, itemType) {
    $("input[name='_event']").val("addToCart");
    $("input[name='offeringId']").val(offeringId);
    $("input[name='parentId']").val(parentId);
    $("input[name='cartItemType']").val(itemType);
    $("#cart").submit();
}
function upgradeToBundle(bundleAssociationId, masterOfferingId) {
    $("input[name='_event']").val("upgradeToBundle");
    $("input[name='offeringId']").val(masterOfferingId);
    $("input[name='bundleAssociationId']").val(bundleAssociationId);
    $("#cart").submit();
}
function upgradeToCrossSellAsBundle(cartItemId, masterOfferingId) {
    $("input[name='_event']").val("upgradeToCrossSellAsBundle");
    $("input[name='offeringId']").val(masterOfferingId);
    $("input[name='cartItemId']").val(cartItemId);
    $("#cart").submit();
}
function selectPromotionChoice(bundleAssociationId, offeringId, promotionId) {
    $("input[name='_event']").val("selectPromotionChoice");
    $("input[name='bundleAssociationId']").val(bundleAssociationId);
    $("input[name='offeringId']").val(offeringId);
    $("input[name='promotionId']").val(promotionId);
    var choice = $("input[name='selectedPromotionChoice']:checked").val();
    if (choice == undefined) {
        $("input[name='promotionChoice']").val("");
    } else if (choice == 'NO-THANK-YOU') {
        $("input[name='promotionChoice']").val("NO-THANK-YOU");
    } else {
        $("input[name='promotionChoice']").val($("select[name='selectedPromotionChoiceOffering_" + choice + "']").val());
    }
    $("#cart").submit();
}

function removeCartItem(selectedItemId, parentId) {
    $("input[name='_event']").val("removeFromCart");
    $("input[name='selectedItemId']").val(selectedItemId);
    $("input[name='parentId']").val(parentId);
    $("#cart").submit();
}
function updateCart(updateTargetElementId, marker, selectedItemId, parentId) {
    $("input[name='_event']").val('updateCart');
    $("input[name='selectedItemId']").val(selectedItemId);
    $("input[name='parentId']").val(parentId);
    var fields = $("#cart").serializeArray();
    $("#" + updateTargetElementId).addClass(marker);
    $("." + marker).html('<img src="/GLOBAL/Images/ajax-loader.gif"/>');
    $("._showLoadingGrey").html('<img style="position:relative; top:5px;" src="/GLOBAL/Images/ajax-loader-grey.gif"/>');
    $("#eu-bose-form-container input,#eu-bose-form-container select").attr({readonly:"readonly", disabled:"disabled"});
    disableCheckoutButton();
    $.getJSON("/app/formFramework", fields, function(data) {
        $("#cart").removeClass("cart-updated").addClass("cart-updating");
        displayResult(data, updateTargetElementId, marker);
    });
}
function enableCheckoutButton() {
    $('#btn_checkout').unbind().bind('click', function() {
        return checkOut();
    });
}
function disableCheckoutButton() {
    $('#btn_checkout').unbind().bind('click', function() {
        return false;
    });
}

function displayResult(data, updateTargetElementId, marker) {
    $("#" + updateTargetElementId).removeClass(marker);
    // Set order total values
    $("#subTotal").html(data.SimpleCart.subTotal);
    $("#shippingCost").html(data.SimpleCart.shipmentGrossPrice);
    $("#grossTotal").html(data.SimpleCart.grossTotal);
    $("#ecoTaxTotal").html(data.SimpleCart.ecoTaxTotal);
    $("#paymentPlanMessage").html(data.SimpleCart.paymentPlanMessage);
    if (data.SimpleCart.paymentPlanMessage != '') {
        $("#paymentPlanMessageDiv").show();
    } else {
        $("#paymentPlanMessageDiv").hide();
    }
    for (var i = 0; i < data.SimpleCart.items.length; i++) {
        var item = data.SimpleCart.items[i];
        var id = item.id;

        // Regular cart items, set values
        $("select[name='cartItemQuantity_" + id + "']").val(item.quantity);
        $("#cartItemQuantity_" + id).html(item.quantity);
        $("#cartItemPrice_" + id).html(item.grossPrice);
        if (item.childItems) {
            for (var j = 0; j < item.childItems.length; j++) {
                var child = item.childItems[j];
                var childId = child.id;
                // Set cart child item values
                $("#cartItemQuantity_" + childId).html(child.quantity);
                $("#cartItemPrice_" + childId).html(child.grossPrice);

                // Show/Hide child quantity select box and appropriate values
                if (item.quantity == 1) {
                    $("#cartItemQuantity_" + childId).show();
                    $("select[name='cartItemQuantity_" + childId + "']").hide();
                    $("#cartItemQuantityTT_" + childId).hide();
                } else {
                    $("#cartItemQuantity_" + childId).hide();
                    $("#cartItemQuantityTT_" + childId).show();
                    var quantitySelect = $("select[name='cartItemQuantity_" + childId + "']");
                    var option1 = $("select[name='cartItemQuantity_" + childId + "'] option[value='1']");
                    quantitySelect.show();
                    for (var k = 1; k <= 9; k++) {
                        var option = $("select[name='cartItemQuantity_" + childId + "'] option[value='" + k + "']");
                        if (k <= item.quantity && option.length == 0) {
                            // create option
                            option1.clone().val(k).text(k).appendTo(quantitySelect);
                        } else if (k > item.quantity && option.length > 0) {
                            // delete option
                            option.remove();
                        }
                    }
                    $("select[name='cartItemQuantity_" + childId + "']").val(child.quantity);
                }

                // Show/Hide child promotional message
                var list = $("#promoMessage_" + childId);
                if (child.promotionalMessages) {
                    list.children("li:first").html(child.promotionalMessages[0]);
                    list.show();
                } else {
                    list.hide();
                }
            }
        }
        if (item.type == "OrderPromotionIncentive" || item.type == "OrderFreeTextPromotionLine") {
            // Show/Hide order promotion incentive depending if it has been applied or not
            if (data.SimpleCart.appliedOrderPromotion) {
                $("#cartItemRow_" + id).parents("div.product").show();
            }
        }
    }
    for (i = 0; i < data.SimpleCart.shipmentMethods.length; i++) {
        var shipmentMethod = data.SimpleCart.shipmentMethods[i];
        id = shipmentMethod.id;
        $("#shipmentMethodPrice_" + id).html(shipmentMethod.shippingCost);
    }
    if (data.SimpleCart.showOrderPromotionalLayer) {
        // show the promotional layer when this flag is set
        showLayer();
    }
    if (data.SimpleCart.orderPromotionCartItem && data.SimpleCart.appliedOrderPromotion) {
        $("#cartItemRow_" + data.SimpleCart.orderPromotionCartItem.id).parents("div.product").show();
    }
    if (data.SimpleCart.orderPromotionSummaryItem && data.SimpleCart.appliedOrderPromotion) {
        // If a price is specified for the order promotion summary item, update it
        if (data.SimpleCart.orderPromotionSummaryItem.grossPrice) {
            $(".orderPromotionSummaryPrice").html(data.SimpleCart.orderPromotionSummaryItem.grossPrice);
        }
        // in case of order price/shipment promo, show this line when applied
        $("div.orderPromotionSummaryItemBlock").show();
    }
    if (!data.SimpleCart.appliedOrderPromotion) {
        // in case of an order promotion which adds an incentive, this line should be hidden when not applied
        $(".orderPromotionLine").parents("div.product").hide();
        // in case of an order price promo or order shipment promo, this line should be hidden when not applied
        $("div.orderPromotionSummaryItemBlock").hide();
    }
    if (__WEBTRENDS_ENABLED) {
        if (data.SimpleCart.webStatisticsParameters) {            
            Bose.statistics.report(data.SimpleCart.webStatisticsParameters);
        }
    }
    $("#eu-bose-form-container input,#eu-bose-form-container select").attr({readonly:"", disabled:""});
    enableCheckoutButton();

    // Reposition tooltips (this fixes tooltips which were hidden before)
    htmltooltip.render();
    // Reiterate over the child items and show the tooltips of those with auto-adjusted quantities
    for (var i = 0; i < data.SimpleCart.items.length; i++) {
        var item = data.SimpleCart.items[i];
        if (item.childItems) {
            for (var j = 0; j < item.childItems.length; j++) {
                var child = item.childItems[j];
                if (child.showTooltip && child.quantity > 1) {
                    $("a[rel='quantityTT_" + child.id + "']").mouseover();
                    setTimeout(function() {
                        $("a[rel='quantityTT_" + child.id + "']").mouseout();
                    }, 5000);
                }
            }
        }
    }
    $("#cart").addClass("cart-updated").removeClass("cart-updating");
}

function addAvbImage(avbUrl, avbTargetUrl, avbTargetWidth, avbTargetheight) {
    if (avbUrl && avbUrl != '') {
        if (avbTargetUrl && avbTargetUrl != '') {
            windowOptions = 'width=' + avbTargetWidth + ',height=' + avbTargetheight;
            $("#avbOrderPromotion").html('<a href="javascript:openNewWin(\'' + avbTargetUrl + '\',' + avbTargetWidth + ',' + avbTargetheight + ');"><img src="' + avbUrl + '" alt="" title=""/></a>');
        } else {
            $("#avbOrderPromotion").html('<img src="' + avbUrl + '" alt="" title=""/>');
        }
    }
}

