﻿// JavaScript Document
/// <reference path="jquery-1.3.2-vsdoc.js"/>

function Item(id, name, price, quantity)
{
    this.id = id;
    this.name = name;
    this.price = price;
    this.quantity = quantity == null ? 1 : quantity;
    
    this.getTotal = function () { 
        return this.quantity * this.price;
    }
    
    this.increment = function () {
        this.quantity++;
        }
        
      this.decrement = function () { 
        this.quantity--;
    }
        
        
    }


    var Basket = function() {
        var cookieName = "ccb_configurator";
        var items = [];
        var container = null;
        var plus = '<img src="Images/toggle_plus.png" width="16" height="16" class="quantity_plus" productId="{0}" />';
        var minus = '<img src="Images/toggle_minus.png" width="16" height="16" class="quantity_minus" productId="{0}" />';

        function AddItem(id, name, price) {
            items.push(new Item(id, name, price));
            Render();
        }

        function Save() {
            var cookieStr = "";
            $.each(items, function() {
                cookieStr += GetItemString(this) + "|";
            });
            $.cookie(cookieName, cookieStr);
        }

        function Load() {
            var cookieString = $.cookie(cookieName);
            items = [];
            if (cookieString != '' && cookieString != null) {
                var itemStrings = cookieString.split('|');
                if (itemStrings != null && itemStrings.length > 0) {
                    $.each(itemStrings, function() {
                        if (this != '' && this != null)
                            items.push(LoadItemFromString(this));
                    });
                }
            }
        }

        function ClearCookie() {
            $.cookie(cookieName, null);
        }

        function LoadItemFromString(str) {
            var itemParts = str.split('~');
            return new Item(itemParts[0], itemParts[1], parseInt(itemParts[2]), parseInt(itemParts[3]));
        }

        function GetItemString(item) {
            return item.id + "~" + item.name + "~" + item.price + "~" + item.quantity;
        }

        function RemoveItem(id) {
            for (var i = 0; i < items.length; i++) {
                if (items[i].id == id) {
                    items.splice(i, 1);
                    UncheckItem(id);
                    Render();
                    break;
                }
            }
        }

        function UncheckItem(id) {
            var product = $('.productCheck[productid="' + id + '"]');
            if (product.lenght > 0)
                product[0].checked = false;
        }

        function Refresh_Quantity(item) {
            if (item) {
                $("#quantity_" + item.id).text(item.quantity);
            }
        }

        function UpdateTotal() {
            if (items.length > 0) {
                $("#basket_total").text(GetTotal());
                Save();
            }
        }

        function FindItem(id) {
            for (var i = 0; i < items.length; i++) {
                if (items[i].id == id) {
                    return items[i];
                }
            }
            return null;
        }

        function Increment(id) {
            var item = FindItem(id);
            if (item) {
                item.increment();
                Refresh_Quantity(item);
                Refresh_LineTotal(item);
                UpdateTotal();
            }
        }

        function Decrement(id) {
            var item = FindItem(id);
            if (item) {
                if (item.quantity == 1) {
                    RemoveItem(id);
                    UpdateTotal();
                }
                else {
                    item.decrement();
                    Refresh_Quantity(item);
                    Refresh_LineTotal(item);
                    UpdateTotal();
                }
            }
        }

        function Refresh_LineTotal(item) {
            $('#line_total_' + item.id).text(item.getTotal());
        }

        function Clear() {
            $.each(items, function(i, val) {
                UncheckItem(val.id);
            });
            items = [];
            Render();
        }

        function Initialize(cont) {
            container = cont;
            Load();
            Render();
        }

        function Render() {
            container.empty();
            if (items.length == 0) {
                container.hide();
                ClearCookie();
                return;
            }

            container.show();

            container.append('<tr class="header"><td>Name</td><td>Quantity</td><td>Price</td><td>Line total</td></tr>');
            $.each(items, function(i, val) {
                container.append('<tr class="' + (i % 2 ? "alternative" : "") + '"><td class="productName">' + this.name + '</td><td>' + FormatString(minus, this.id) + '<span id="quantity_' + this.id + '">' + this.quantity + '</span>' + FormatString(plus, this.id) + '</td><td class="number">' + this.price + '</td><td class="number"><span id="line_total_' + this.id + '">' + this.getTotal() + '</span></td></tr>');
            });
            container.append('<tr class="basket_footer"><td><a href="#" id="basket_chechout">Check out</a> | <a href="#" id="basket_cancel">Close</a></td><td colspan="3" class="total">' + FormatString('Total: <span id="basket_total">{0}</span>', GetTotal()) + '</td></tr>');

            $('.quantity_plus').click(function() {
                var id = $(this).attr('productId');
                Increment(id);
            });

            $('.quantity_minus').click(function() {
                var id = $(this).attr('productId');
                Decrement(id);
            });

            $('#basket_cancel').click(function() {
                Clear();
            });

            $('#basket_chechout').click(function() {
                
                    var url = "printconfig.aspx?";
                    for (var i = 0; i < items.length; i++) {
                        if (i > 0)
                            url += '&';

                        url += 'item[' + i + ']=' + items[i].id + ',' + items[i].quantity;
                    }
                    window.open(url, "Configuration", "width=600, height=500");
                
            });

            Save();
        }

        function GetTotal() {
            var total = 0;
            $.each(items, function(i, val) {
                total += val.quantity * val.price;
            });
            return total;
        }

        function FormatString(str) {
            if (arguments.length <= 1)
                return str;

            var result = str;
            var placeholder = 0;
            for (var argCount = 1; argCount < arguments.length; argCount++, placeholder++) {
                result = result.replace(new RegExp('\\{' + placeholder + '\\}'), arguments[argCount]);
            }
            return result;
        }

        function Alert() {
            var result = '';
            for (var i = 0; i < items.length; i++) {
                result += 'Id:' + items[i].id + ' Name: ' + items[i].name + ' Price: ' + items[i].price + ' Quantity: ' + items[i].quantity + '\n';
            }
            alert(result);
        }

        return {
            add: AddItem,
            remove: RemoveItem,
            alert: Alert,
            init: Initialize
        };
    } ();

function ProcessCheckbox(input)
{
    //debugger;
    var ctrl = $(input); 
    if(ctrl.get(0).checked)
    {
        Basket.add(ctrl.attr('productId'), ctrl.parents('.compTableItem').find('a').text(), ctrl.attr('productValue'));
    }
    else{
        Basket.remove(ctrl.attr('productId'));
    }
}

$(document).ready(function() {
    Basket.init($('#basket'));
    $('.productCheck').click(function() { ProcessCheckbox(this); });
});
