// callback function for ajax panel on MyCart page
MyCart_OnResponseEnd = function(sender, arguments) {
    // catch cancel cart
    try {
        if (arguments.EventArgument[0] == 'cancel') {
            window.location = $("#Header_hlHomeLink").attr('href');
        }
    } catch (e1) {
        try {
            window.location.reload();
        } catch (e2) {
            window.location.href = window.location.href;
        }
    }

    try { initialiseFonts(); } catch (ex) { }

    var hasErrors = checkForException();

    if (!hasErrors) {
        if ($('#SubErrorControl_plError:visible').length == 0) {
            getItems(true);
        }
    }
    if (arguments.EventTarget == 'Shipping$ddlCountries' || arguments.EventTarget == 'Shipping$ddlProviders') {
        toggleFreight(false);
    }
    if (arguments.EventTarget == 'Shipping$ddlCountries') {
        // Only needed if there is multiple shipping providers for a region:
        // location.reload(true);
    }
    initialiseWatermark();
    initialiseGiftWrapPopup();
};

//remove cart item
function deleteItemRad(rowId) {
    try {
        ExecTelerikCallback("del" + rowId, "");
    } catch (ex) { alert("delete item error: " + ex.description); }
}

//validate qty
function validate() {
    if (isNaN(document.getElementById('tbQty').value)) {
        alert("Invalid Quantity");
        return false;
    }
}

function getItems(updateUI) {
    trace('getItems');
    var params = '';
    try {
        // reference total items textbox in my cart control
        var tbMyCartTotalItems = document.getElementById("Header_MyCart_lblItems");
        var tbMyCartTotalPrice = document.getElementById("Header_MyCart_lblTotal");

        var totalPrice = 0;
        var myCartTotalItems = 0;

        // rewrite of below in jQuery :: OMG jQUERY PWNAGE
        $('input[id$=_tbItemId]').each(function(i) {
            try {
                var itemId = this.value;
                var qty = 0;
                var price = 0;

                if ($('input[id$=_tbQty]').length < i) throw 'Quantity for item ' + itemId + ' not found';
                qty = $('input[id$=_tbQty]')[i].value;
                if (qty <= 0) throw 'Quantity must be greater than 0. If you wish to remove an item, please click on remove button';

                if ($('span[id$=_lblPrice]').length < i) throw 'Price for item ' + itemId + ' not found';
                price = $('span[id$=_lblPrice]')[i].innerHTML.replace('$', '');

                trace('itemId: ' + itemId);
                trace('qty: ' + qty);

                params += itemId + '=' + qty + ';';
                myCartTotalItems += eval(qty);
                totalPrice += parseFloat(price) * eval(qty);

                trace(params);
            } catch (e) {
                throw e;
            }
        });

        if (updateUI) {
            tbMyCartTotalItems.innerHTML = myCartTotalItems;
            tbMyCartTotalPrice.innerHTML = "$" + totalPrice.toFixed(2);
        }
    } catch (ex) {
        if (/^Quantity/i.test(ex) || /^Price/i.test(ex)) {
            alert(ex);
        } else {
            alert('Unknown error caught: ' + ex.description);
        }
    } finally {
        return params;
    }
}

applyPromoCode = function(sender) {
    try {
        ExecTelerikCallback("applyPromoCode", $('.promo-code').val());
    } catch (ex) {

    } finally {
        return false;
    }
}

//update cart totals with given qty's
function updateCartRad(sender) {
    try {
        trace('updateCartRad');

        // build params
        var param = getItems(false);

        // execute callback
        ExecTelerikCallback(param, "");
    } catch (ex) {
        trace("delete item error: " + ex.description);
    } finally {
        return false;
    }
}

resetErrorControl = function() {
    // reset error control
    if (document.getElementById('ErrorControlFrontEnd_plError') != null)
        document.getElementById('ErrorControlFrontEnd_plError').innerHTML = '';
};

// cancel cart
cancelCart = function() {
    try {
        ExecTelerikCallback('cancel', "");
    } catch (ex) {
        alert('cancel cart error: ' + ex.description);
    }
};

// load tabs
loadTabs = function() {
    // ie
    var isIE = $.browser.msie;
    //hide second tab
    $("div.tabs-a-two").css("display", "none");
    $(".tabs-a ul li.item").bind('click', function(e) {
        switch (this.id) {
            case "tabs-a-one":
                //change status & style menu
                $("#tabs-a-one").addClass("active");
                $("#tabs-a-two").removeClass("active");
                //display selected division, hide others
                $(".tabs-a-one").fadeIn();
                $(".tabs-a-two").css("display", "none");
                break;
            case "tabs-a-two":
                //change status & style menu
                $("#tabs-a-one").removeClass("active");
                $("#tabs-a-two").addClass("active");
                //display selected division, hide others
                $(".tabs-a-two").fadeIn();
                $(".tabs-a-one").css("display", "none");
                break;
        }
        return false;
    });
};

initialiseWatermark = function() {
    $(".watermark").watermark({ html: "Enter promotion code if applicable", cls: "watermarkLabel" });
}

popupHide = function(refresh) {
    $(".close").click();
    if (refresh) {
        ExecTelerikCallback('', '');
    }
}

initialiseGiftWrapPopup = function() {
    $('.giftWrapPopup').overlay({
        expose: '#000000',
        onBeforeLoad: function() {
            var iframe = (this.getContent().find('iframe').length > 0 ? this.getContent().find('iframe')[0] : undefined); trace(iframe);
            if (typeof iframe != 'undefined') {
                iframe.src = this.getTrigger().attr('href');
            }
        },
        onClose: function() {
            var iframe = (this.getContent().find('iframe').length > 0 ? this.getContent().find('iframe')[0] : undefined); trace(iframe);
            if (typeof iframe != 'undefined') {
                iframe.src = '';
            }
        }
    });
}

toggleFreight = function(dir) {
    var pnl = $(".shipPnl");
    var freightDir = true;
    if (pnl.css('display') == 'none') { freightDir = false; }
    if (dir != null && dir != undefined) { freightDir = dir; }
    pnl.toggle(pnl.css('display') == 'none');
    if (freightDir) {
        $('.toggleFreight').html('more options');
        freightDir = false;
    } else {
        $('.toggleFreight').html('less options');
        freightDir = true;
    }
}

$(function() {
    loadTabs();
    initialiseWatermark();
    $('.editMsg').live('click', function() {
        if ($('#btnGiftMsg').text() == 'Edit') {
            $('#txtGiftMsg').val($('#txtGiftMsg').parent().find('.code').text().replace('Message: ', ''));
            $('#btnGiftMsg').text('Save');
            initCounter();
        } else {
            $('#btnGiftMsg').text('Edit');
            // Persist the changes:
            ExecTelerikCallback('giftWrapMsg', escape($('#txtGiftMsg').val()));
        }
        $('#txtGiftMsg').parent().find('.wordCount').slideToggle('fast');
        $('#txtGiftMsg').parent().find('.code').slideToggle('fast');
        $('#txtGiftMsg').parent().find('.code').text('Message: ' + $('#txtGiftMsg').val());
        $('#txtGiftMsg').slideToggle('fast');
    });
});
