var $j = jQuery.noConflict();
$j(function () {
    var cartItemCount = $j('#searchResults span.cartItemCount');
    showCart(cartItemCount.html().substring(0, 1) != '0');

    $j('#cart table tbody tr:odd').addClass('alt');
    $j("input.quantity").numeric();

    $j('.packagingConfirm').live("click", function (event) {
        return confirm('For printing purposes, in most cases, there is a minimum order of 1 unit (20 copies). Additional copies are also usually in multiples of 20. For example: 1 unit = 20 copies and 2 units = 40 copies. Please note packaging unit information under each title for more details.\r\n\r\nAre you sure you have selected the correct quantites and wish to proceed?');
    });

    $j('.update').live("click", function (event) {
        event.preventDefault();
        var link = $j(this);
        var siblings = link.parent().prevAll();

        var bwQuantity = siblings.eq(3).children();
        var bwCost = siblings.eq(2).children();
        var colourQuantity = siblings.eq(1).children();
        var colourCost = siblings.eq(0).children();

        var bwQty = '0';
        var colourQty = '0';

        if (bwQuantity.length) {
            bwQty = bwQuantity.val();
        }

        if (colourQuantity.length) {
            colourQty = colourQuantity.val();
        }

        if (!isNumeric(bwQty) && !isNumeric(colourQty)) {
            showMessage(link, 'Oops! One of the values provided is not a positive whole number. Please correct and try updating again.');
            bwQuantity.addClass('invalid');
            colourQuantity.addClass('invalid');
            return;
        }
        else {
            bwQuantity.removeClass('invalid');
            colourQuantity.removeClass('invalid');
        }

        updateQuantity(link, colourQty, bwQty, colourCost, bwCost);
    }); // end click

    $j('.remove').live("click", function (event) {
        event.preventDefault();
        var link = $j(this);
        updateQuantity(link, 0, 0, null, null);
    }); // end click

    function updateQuantity(link, colourQuantity, bwQuantity, colourCost, bwCost) {
        showMessage(link, 'Your cart is being updated. Please wait...');

        var remove = colourQuantity == 0 && bwQuantity == 0;
        var recordId = link.nextAll('span').html();

        var data = JSON.stringify({ "resourceId": recordId, "colourQuantity": colourQuantity, "bwQuantity": bwQuantity });

        $j.ajax({
            type: "POST",
            url: "/Services/CartWebService.asmx/UpdateQuantity",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var d = msg.d;

                var count = d.TotalCount;
                var message = count + " items";
                if (count == 1) {
                    message = "1 item";
                }

                if (remove) {
                    $j('#cart table tbody tr').removeClass('alt');
                    link.parents('tr:first').replaceWith('');
                    $j('#cart table tbody tr:odd').addClass('alt');
                    cartItemCount.html(message);
                }
                else {
                    var newTotal = (colourCost.html().replace('$', '') * colourQuantity) + (bwCost.html().replace('$', '') * bwQuantity);
                    link.parent().next('.costs').children().html(formatCurrency(newTotal));
                }

                var hasItems = count > 0;

                if (hasItems) {
                    var runningTotal = 0;
                    $j('.cost').each(function (i) {
                        runningTotal += parseFloat(($j(this).html().replace('$', '')));
                    });
                    updateTotals(runningTotal.toFixed(2));
                }

                showCart(hasItems);

                showMessage(link, 'Your cart has been updated. You have ' + message + ' in your cart.');
                if (remove) {
                    $j('#cart').append('<div id="cartNotification"></div>');
                }
            },
            error: function (xhr, msg) {
                var response = JSON.parse(xhr.responseText);
                var cart = $j('#cart');
                if (response.Message) {
                    cart.before(' <div class="error">' + response.Message + '</div> ');
                }
                else {
                    cart.before(' <div class="error">An unexpected error occurred.</div> ');
                }
            }
        }); // end ajax

        return false;
    }

    function updateTotals(subtotal) {
        var data = JSON.stringify({ "subtotal": subtotal });

        $j.ajax({
            type: "POST",
            url: "/Services/CartWebService.asmx/GetCartTotals",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var d = msg.d;

                $j('#subTotalCost').html(d.SubTotalInCurrency);
                $j('#shippingCost').html(d.ShippingInCurrency);
                $j('#gstCost').html(d.GstInCurrency);
                $j('#totalCost').html(d.TotalInCurrency);
                $j('#subTotalCostStaff').html(d.SubTotalInCurrency);
                $j('#totalCostStaff').html(d.SubTotalInCurrency);
            },
            error: function (xhr, msg) {
                var response = JSON.parse(xhr.responseText);
                var cart = $j('#cart');
                if (response.Message) {
                    cart.before(' <div class="error">' + response.Message + '</div> ');
                }
                else {
                    cart.before(' <div class="error">An unexpected error occurred.</div> ');
                }
            }
        }); // end ajax
    }

    function isNumeric(form_value) {
        if (form_value.match(/^\d+$/) == null) {
            return false;
        }
        else {
            return true;
        }
    }

    function showCart(hasItems) {
        var operations = $j('#operations');
        var totals = $j('#totals');
        if (hasItems) {
            operations.show();
            totals.show();
        }
        else {
            operations.hide();
            totals.hide();
        }
    }

    function formatCurrency(amount) {
        var i = parseFloat(amount);
        if (isNaN(i)) {
            i = 0.00;
            $j('#cart').before(' <div class="error">An unexpected error occurred formatting currency. Please refresh your browser and try again.</div> ');
        }
        return '$' + i.toFixed(2);
    }

    function showMessage(ctrl, msg) {
        var notification = $j('#cartNotification');
        // see http://www.pengoworks.com/workshop/jquery/stop_bug.htm for bug with stop and fix for 1.2 
        notification.hide().html(msg).appendTo(ctrl).stop(true, true).animate({ opacity: "show" }, "slow");
        setTimeout(function () {
            notification.stop(true, true).animate({ opacity: "hide" }, "slow");
        }, 5000);
    }


    var popup = $j("#shippingRates");
    var popupLink = $j("#shippingLink");

    popupLink.hover(function () {
        popup.stop(true, true).animate({ opacity: "show", right: "170" }, "slow");
    }, function () {
        popup.animate({ opacity: "hide", right: "150" }, "fast");
    });

    popupLink.click(function () { return false; });
});                                 // end document ready
