﻿$(function() {
    myBasket = new ShoppingBasket();
    myBasket.Init();
});

ShoppingBasket = function() { }

ShoppingBasket.prototype.url = '/ShoppingBasket.ashx';

ShoppingBasket.prototype.pnlItems = null;   // Items list container
ShoppingBasket.prototype.pnlTotal = null;

ShoppingBasket.prototype.products = [];
ShoppingBasket.prototype.itemsQty = 0;      // Number of items in list

ShoppingBasket.prototype.Init = function() {
    this.pnlItems = $('#items-list');
    this.pnlTotal = $('#basket-total');
    
    this.getItems(false);
};

ShoppingBasket.prototype.getItems = function (update) {
    var s = this;

    $.ajax({
        url: s.url,
        cache: false,
        data: { method: 'getItems' },
        success: function (data) {

            var basketItems = eval('(' + data + ')');

            $(basketItems).each(function (index, item) {

                var i = s.products.length;

                s.products[i] = [];
                s.products[i]['productId'] = item.productId;
                s.products[i]['qty'] = item.quantity;

                var itemDiv = s.createItem(item);

                s.pnlItems
                    .css('display', 'none')
                    .append(itemDiv);

                s.itemsQty += parseInt(item.quantity);
            });

            if (s.itemsQty > 0) {
                if (update) {
                    s.pnlItems.slideDown(600);
                    s.pnlTotal.slideDown(600);
                } else {
                    s.pnlItems.fadeIn(100);
                    s.pnlTotal.fadeIn(200);
                }

                s.calcTotal();
            }

            s.updateQty();
        }
    });
};

ShoppingBasket.prototype.addItem = function(btnBuy, productId, chassisId, catId) {
    var s = this;

    var existing = false;
    var index = null;

    var qty = 0;

    // check if product is already in basket
    for (var i = 0; i < s.products.length; i++) {

        if (s.products[i]['productId'] == productId) {
            existing = true;
            index = i;
            break;
        }
    }

    if (existing) {
        // if product is already in basket, just increase quantity
        qty = parseInt(s.products[index]['qty']) + 1;

        s.products[index]['qty'] = qty;

        //alert('?method=increaseQty&productId=' + productId + '&chassisId=' + chassisId + '&catId=' + catId + '&quantity=' + s.products[index]['qty']);

        $.ajax({
            url: s.url,
            cache: false,
            data: {
                method: 'increaseQty',
                productId: productId,
                quantity: qty
            },
            success: function(data) {
                var item = eval('(' + data + ')');

                $('#item_' + item.itemId + ' .quantity')
                    .fadeOut(250, function() {
                        $(this).html(item.quantity)
                            .fadeIn(250);
                    });

                $('#item_' + item.itemId + ' .subtotal')
                    .fadeOut(250, function() {
                        $(this).html(item.subtotal)
                            .fadeIn(250);
                    });

                s.itemsQty++;
                s.updateQty();
                s.calcTotal();

                if (btnBuy != null)
                    s.flagItem(btnBuy, qty);
            }
        });
    } else {
        // if product is not in basket, add it to it

        index = s.products.length;

        s.products[index] = [];
        s.products[index]['productId'] = productId;
        s.products[index]['qty'] = 1;

        qty = 1;

        $.ajax({
            url: s.url,
            cache: false,
            data: {
                method: 'addItem',
                productId: productId,
                quantity: 1
            },
            success: function(data) {
                /*var basketItem = eval('(' + data + ')');

                var itemDiv = s.createItem(basketItem[0]);

                s.pnlItems.append(itemDiv.fadeIn(600));

                s.itemsQty++;
                s.updateQty();
                s.calcTotal();*/

                window.location = '/user/basket/';
            }
        });
    }

    //    if (btnBuy != null)
    //        this.flagItem(btnBuy, qty);

    return false;
};

ShoppingBasket.prototype.removeItem = function (itemId) {
    var s = this;

    $.ajax({
        url: s.url,
        cache: false,
        data: {
            method: 'removeItem',
            itemId: itemId
        },
        success: function (data) {
            var removedItem = eval('(' + data + ')');

            for (var i = 0; i < s.products.length; i++) {

                if (s.products[i]['productId'] == removedItem.productId) {
                    s.products.splice(i, 1);
                }
            }

            s.itemsQty = s.itemsQty - removedItem.quantity;

            s.updateQty();

            $('div#item_' + itemId)
                .slideUp(500, function () {
                    s.calcTotal();
                });
        }
    });

    s.removeFlag(itemId);

    return false;
};

ShoppingBasket.prototype.createItem = function(item) {

    var html = [];

    html.push('<a href="#" title="Remove Item" onclick="return myBasket.removeItem(');
    html.push(item.itemId);
    html.push(');">');
    html.push('<img class="imgRemove" src="/_common/img/btn_remove_icon.gif" alt="Remove item" /></a>');

    html.push('<strong class="red">');
    html.push(item.productName);
    html.push('</strong><br />');

    html.push('Product Code <strong>');
    html.push(item.productCode);
    html.push('</strong>');

    html.push('<div class="hr"></div>');

    html.push('<div class="left">Quantity:</div>');
    html.push('<div class="right quantity">');
    html.push(item.quantity);
    html.push('</div>');
    html.push('<div class="clear"></div>');

    html.push('<div class="left">Subtotal:</div>');
    html.push('<div class="right subtotal">');
    html.push(item.subtotal);
    html.push('</div>');
    html.push('<div class="clear"></div>');

    return itemDiv = $('<div />')
        .attr('id', 'item_' + item.itemId)
        .attr('class', 'basket-item')
        .append(html.join(' '));
};

ShoppingBasket.prototype.calcTotal = function () {
    var s = this;

    $.ajax({
        url: s.url,
        cache: false,
        data: { method: 'calcTotal' },
        success: function (data) {

            var total = eval('(' + data + ')');

            //alert(data);

            if (total.totDiscount > 0 && total.totBasket > 0) {

                if ($('#discount').length < 1) {
                    var html = [];

                    html.push('<strong class="red">Discount</strong><br />');
                    html.push('Discount Code: <strong>', total.discountCode, '</strong>');
                    html.push('<div class="hr"></div>');

                    html.push('<div class="left" style="position: relative;">Subtotal:</div>');
                    html.push('<div id="discountValue" class="right quantity" style="position: relative;">&pound;', total.totDiscount, '</div>');
                    html.push('<div class="clear"></div>');

                    var discountDiv = $('<div />')
                            .attr('id', 'discount')
                            .attr('class', 'basket-item')
                            .css('background', '#f7d8d8')
                            .append(html.join(''));

                    s.pnlItems.append(discountDiv);
                } else {
                    $('#discountValue')
                        .fadeOut(300, function () {
                            $(this)
                                .html('&pound;' + total.totDiscount)
                                .fadeIn(300);
                        });
                }
            } else {
                if ($('#discount').length > 0)
                    $('#discount').slideUp(500);
            }

            if (total.totBasket > 0) {

                $('#b-tot')
                    .fadeOut(300, function () {
                        $(this)
                            .html('&pound;' + total.totBasket)
                            .fadeIn(300);
                    });

                s.pnlTotal.fadeIn(300);
            } else {
                s.pnlTotal.fadeOut(300);
            }
        }
    });

};

ShoppingBasket.prototype.updateQty = function() {
    var s = this;

    $('#itemsQty')
        .fadeOut(200, function() {
            $(this)
                .text(s.itemsQty)
                .fadeIn(200);
        });
};

ShoppingBasket.prototype.flagItem = function(btnBuy, qty) {

    // find product panel where button is contained
    var pnlProduct = $(btnBuy).parents('.product-item');

    try {
        // try and find all product panels on the page
        // that belong to same product 
        // (for example in different tabs)
        var pnlProductId = pnlProduct.attr('class').split(' ')[1];

        var panels, pnlFlag;

        // if class with id is found try and update 
        // all panels with that class
        if (pnlProductId != null && pnlProductId.length > 0) {
            panels = $('.' + pnlProductId);

            // find flag div and add product id to its class
            // so it can be retrieved when removind products            
            pnlFlag = $(panels)
                .find('.product-added')
                .addClass(pnlProductId);
        } else {
            panels = pnlProduct;
            pnlFlag = $(panels).find('.product-added')
        }

        $(panels).find('span[id$=lblItemBasketQty]')
        .fadeOut(200, function() {
            $(this).text(qty).fadeIn(200);
        });

        pnlFlag.fadeIn(500);

    } catch (Error) {
        sendErrorAlert(Error);
    }
};

ShoppingBasket.prototype.removeFlag = function(itemId) {
    var s = this;

    $.ajax({
        url: s.url,
        cache: false,
        data: {
            method: 'getProductId',
            itemId: itemId
        },
        success: function(pId) {
            $('.pnlItem-' + pId + ' .product-added')
                .fadeOut(500, function() {
                    $(this).remove();
                });
        },
        error: function(request, status, error) {
        //sendErrorAlert(response.status + ' - ' + status + ' - ' + error);
        }
    });
};
