﻿
$(document).ready(function () {
    $(".removeProduct").click(function (e) {
        e.preventDefault();
        var data = $(this).metadata();
        //     alert(data.toSource());
        $.getJSON('/Handlers/CartWebHandler.ashx?cartProductId=' + data.productId,
                function (data) {
                    removeCallback(data);
                });
    });

    $(".addProduct").click(function (e) {
        e.preventDefault();
        $.cursorMessage('Adding...');
        var buttonClicked = $(this);
        buttonClicked.hide();
        var data = $(this).metadata();
        $(this).before("<img src='/App_Themes/Moff/images/ajax-loader.gif' class='loading' />");

        var productX = $(".productAddToBasket" + data.productId + data.Control).offset().left;
        var productY = $(".productAddToBasket" + data.productId + data.Control).offset().top;
        var basketEl = $("#basketPosition");
        if (basketEl.length == 0) {
            basketEl = $(".ico-cart");
        }

        var basketX = basketEl.offset().left;
        var basketY = basketEl.offset().top;

        var gotoX = basketX - productX;
        var gotoY = basketY - productY;
        var newImageWidth = $(".productAddToBasket" + data.productId + data.Control).width() / 3;
        var newImageHeight = $(".productAddToBasket" + data.productId + data.Control).height() / 3;

        $(".productAddToBasket" + data.productId + data.Control)
            .clone()
            .prependTo(".productAddToBasket" + data.productId + data.Control)
            .css({ 'position': 'absolute' })
            .animate({ opacity: 0.001, marginLeft: gotoX, marginTop: gotoY, width: 1, height: 1 }, 600, function () { //leave duartion as 600 - Chrome didn't like less

                $(this).remove();

                //  get qty and weight fields if we're on product page
                var qtyBox = $(".item-qty");
                var wgtBox = $(".item-weight");

                if ((qtyBox.length > 0) && (wgtBox.length == 0)) {
                    $.getJSON('/Handlers/CartWebHandler.ashx?productId=' + data.productId + '&productQty=' + qtyBox[0].value, function (data) { postCartUpdate(data); });
                }
                else if ((qtyBox.length > 0) && (wgtBox.length > 0)) {
                    $.getJSON('/Handlers/CartWebHandler.ashx?productId=' + data.productId + '&productQty=' + qtyBox[0].value + "&productWgt=" + wgtBox[0].value, function (data) { postCartUpdate(data); });
                }
                else {
                    $.getJSON('/Handlers/CartWebHandler.ashx?productId=' + data.productId, function (data) { postCartUpdate(data, buttonClicked); });
                }

            });

    });
});

//  remove html from cart before page refresh - can't use document.ready for this
function removeProductNewest(CartItemId) {
    $.getJSON('/Handlers/CartWebHandler.ashx?cartProductId=' + CartItemId, function (data) {
        removeCallback(data);
    });
}

function postCartUpdate(result, buttonClicked) {
    if (result.RedirectTo != undefined && result.RedirectTo != '') {
        $.cursorMessage(result.Message);
        window.location.replace(result.RedirectTo);
        return;
    }

    $.cursorMessage('Product added to cart. ');
    if (buttonClicked == null || buttonClicked.length == 0) {
        buttonClicked = $(".addProduct");
    }
    buttonClicked.show();
    var p = buttonClicked.parent();

    $(p).find('img.loading').remove();

    var items = 'items';
    if (result.Quantity == '1')
        items = 'item';

    // set the new header count
    $(".your_basket_text02 a").html("(" + result.Quantity + ")");
    //  and for LH cart view count..
    $(".totals-items").html('Items :' + result.Quantity);
    //  and total cost
    $(".totals-total").html('Total :' + result.Price);

    $(".no-items-basket span").html("");

    //  check that the tblMiniCart exists. if not, create a table.
    var tblMiniBasket = document.getElementById("tblMiniCart");

    if (tblMiniBasket == null) {

        var CartStr = '<div class="items"><table id="tblMiniCart"><tbody><tr class="' + result.LastAddedCartItemId + '"><td valign="top" style="vertical-align:top;">' +
                                '<span class="quantity">' + result.LastAddedItemQty + ' x </span>' +
                                '</td><td>' +
                                '<a href="' + result.LastAddedItemUrl + '" class="product-name" >' + result.LastAddedItemTitle + '</a><br>' +
                                '<span class="productPrice">' + result.LastAddedItemPrice + '</span><br>' +
                                '<div class="remove-button">' +
                                '<a href=\'#\' onclick=\'removeProductNewest(' + result.LastAddedCartItemId + ')\'>[remove]</a>' +
                                '</div></td></tr></tbody></table></div>';

        //  check the dummy cart div is avaiable
        var dummyCart = document.getElementById("temp-items");
        if (dummyCart != null) {
            document.getElementById("temp-items").innerHTML = CartStr;
            // hide'empty basket' msg
        }
    }
    else {//  table already exists, so append row

        var quantitySpan = $('tr.' + result.LastAddedCartItemId + ' span.quantity');

        if (quantitySpan[0] == null) { //Check row already exists or not if not add new row
            $('#tblMiniCart > tbody:last').append(  '<tr class="' + result.LastAddedCartItemId + '"><td valign="top" style="vertical-align: top;">' +
                                                    '<span class="quantity">' + result.LastAddedItemQty + ' x </span>' +
                                                    '</td><td>' +
                                                    '<a href="' + result.LastAddedItemUrl + '" class="product-name" >' + result.LastAddedItemTitle + '</a><br>' +
                                                    '<span class="productPrice">' + result.LastAddedItemPrice + '</span><br>' +
                                                    '<div class="remove-button">' +
                                                   '<a href=\'#\' onclick=\'removeProductNewest(' + result.LastAddedCartItemId + ')\'>[remove]</a>' +
                                                    '</div></td></tr>');
        }
        else {// Row already exists add quantity

            var quantity = 0;
            quantity = quantitySpan[0].innerHTML.replace('x', '').trim(' ');

            var qty = parseInt(quantity) + 1;

            quantitySpan[0].innerHTML = qty + ' x ';
        }
    }

    var currentURL = document.location.href;

    if (currentURL.indexOf("shoppingcart.aspx") != -1)
        window.location = currentURL;
}
//  remove html from cart after page has been refreshed
function removeCallback(data) {
    $.cursorMessage('Product has been removed from your cart.');
    //  remove table row
    $("." + data.RemovedCartItemId).replaceWith("");
    //  set header total
    $(".your_basket_text02 a").html("(" + data.Quantity + ")");
    //  and for rh cart view count..
    $(".totals-items").html('Items : ' + data.Quantity);
    //  and total cost
    $(".totals-total").html('Total : ' + data.Price);

    if (data.Quantity == 0) {
        $(".no-items-basket span").html("You have no items in your shopping cart.");
    }
}

