
(function($) {
    $.cookie = function(n, v, opt) {
        if (typeof v != 'undefined') { // name and value given, set cookie
            opt = opt || {};
            if (v === null) {
                v = '';
                opt.expires = -1;
            }
            var expires = '';
            if (opt.expires && (typeof opt.expires == 'number' || opt.expires.toUTCString)) {
                var date;
                if (typeof opt.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (opt.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = opt.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = opt.path ? '; path=' + (opt.path) : '';
            var domain = opt.domain ? '; domain=' + (opt.domain) : '';
            var secure = opt.secure ? '; secure' : '';
            document.cookie = [n, '=', encodeURIComponent(v), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, n.length + 1) == (n + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(n.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };
    Cart = function(t, p) {
        var self = this;
        this.bodyDiv = $('<div class="cart-body"><ul></ul></div>');
        this.sumDiv = null;
        this.items = new Array();
        this.lenLimit = 80;

        $.extend(self, {
            render: function() {
                pos = $(t).position();

                $(t).append(self.bodyDiv);
                var items = null;
                if (p.url == false) {
                    var cookie = $.cookie(p.cookieName);
                    if (cookie != null && cookie != "") {
                        items = $.evalJSON(cookie);
                    }
                    if (items == null || items.length == 0) {
                        self.emptyCart();
                        return;
                    };
                    for (var i = 0; i < items.length; i++) {
                        self.__addItem(items[i]);
                    };
                    self.items = items;
                    p.itemChanged(items);
                }
                else {
                    $.post(p.url,
                        { items: $.cookie(p.cookieName) },
                        function(r) {
                            items = r.items;
                            if (items == null || items.length == 0) {
                                self.emptyCart();
                                return;
                            };
                            for (var i = 0; i < items.length; i++) {
                                self.__addItem(items[i]);
                            };
                            self.items = items;
                            p.itemChanged(items);
                        },
                        "json"
                    );
                }
            },
            __addItem: function(item) {
                var lenLimit = 80;
                $(".cart-item-empty").remove();
                li = document.createElement("li");
                rDiv = document.createElement("div");
                rDiv.itemId = item.id;
                $(rDiv).addClass("cart-item-remove");
                img = $('<img style="margin:0px 5px 0px 0px;width:32px;height:32px;float:left;" src="files/' + item.image + '"/>').click(
                        function(ev) {
                            p.itemClick(ev, item);
                        });
                if (item.qty == null) item.qty = 1;
                uDiv = $('<input type="text" />').addClass("cart-item-number").val(item.qty);
                uDiv.get(0).itemId = item.id;
                if (item.isEbook == 0) {
                    var originalNum = $(uDiv).val();
                    uDiv.keyup(function(ev) {
                        if ($(this).val() == "") return;
                        if (isNaN($(this).val() / 1)) {
                            ev.preventDefault();
                            $(this).val(originalNum);
                            return;
                        }
                        originalNum = $(this).val();
                        items = self.items;
                        itemsForCookie = new Array();
                        for (var i = 0; i < items.length; i++) {
                            if (items[i].id == this.itemId) {
                                items[i].qty = parseInt($(this).val());
                                itemsForCookie.push({id: this.itemId, qty: items[i].qty});
                                if (parseInt($(this).val()) == 0) {
                                    $(".cart-item-remove[itemId=" + this.itemId + "]", self.bodyDiv).click();
                                }
                                break;
                            }
                        };
                        $.cookie(p.cookieName, 
                            $.toJSON(itemsForCookie), 
                            { expires: p.cookieExpires }
                        );
                        p.itemChanged(items);
                    })
                    .blur(function(ev) {
                        if ($(this).val() == "") $(".cart-item-remove[itemId=" + this.itemId + "]", self.bodyDiv).click();
                    });
                }
                else {
                    uDiv.attr("disabled", true);
                }

                $(li).append(rDiv).append(uDiv).append(img);
                $(li).append(
                        '<div >'
                        + item.title + '</div><div style="float:right;font-weight:bold;" >$' + item.price + '</div>'+
                        '<div style="width:450px;">'
                        + item.description.substr(0, 70) + '...</div>');
                $("ul", self.bodyDiv).append(li);
                $(".cart-item-remove", li).click(function() {
                    $(this).parent().remove();
                    items = $.evalJSON($.cookie(p.cookieName));
                    if (items == null) return;
                    for (var i = 0; i < items.length; i++) {
                        if (items[i].id == this.itemId) {
                            items.splice(i, 1);
                            break;
                        }
                    }
                    $.cookie(p.cookieName, $.toJSON(items), { expires: p.cookieExpires });
                    p.itemChanged(items);
                    if (items == null || items.length == 0) {
                        self.emptyCart();
                        return;
                    }
                });
            },
            addItem: function(item) {
                var cookie = $.cookie(p.cookieName);
                var items = new Array();
                if (cookie != null && cookie != "") {
                    items = $.evalJSON(cookie);
                };
                nth = null;
                for (var i = 0; i < items.length; i++) {
                    if (items[i].id == item.id) {
                        nth = i;
                        break;
                    }
                };
                if (item.isEbook == 1 && nth != null) return;
                if (nth == null) {
                    self.__addItem(item);
                    items.push(
                        { id: item.id,
                            qty: (item.qty == null ? 1 : item.qty)
                        });
                }
                else {
                    $(".cart-item-number", self.bodyDiv).each(function() {
                        if (this.itemId == item.id) {
                            $(this).val(parseInt($(this).val()) + 1);
                            return false;
                        }
                    });
                    items[nth].qty++;
                }
                $.cookie(p.cookieName, $.toJSON(items), { expires: p.cookieExpires });
                self.sumaryItems();
                if ($(self.dropdownDiv).is(":hidden")) {
                    $(self.dropdownDiv).slideDown("normal");
                };

            },
            emptyCart: function() {
                $("ul", self.bodyDiv).empty();
                $("ul", self.bodyDiv).append('<li class="cart-item-empty">Empty Cart</li>');
            },
            sumaryItems: function() {
                var cookie = $.cookie(p.cookieName);
                var items = null;
                if (cookie != null && cookie != "") {
                    items = $.evalJSON(cookie);
                }
                var total = 0, amount = 0.0;
                if (items != null) {
                    for (var i = 0; i < items.length; i++) {
                        amount += parseFloat(items[i].price) * items[i].qty;
                        total += items[i].qty;
                    }
                }
                checkoutButton = $('<button style="clear:both;float:right;margin-top: 7px;">Checkout</button>').click(function() {
                    var cookie = $.cookie(p.cookieName);
                    var items = new Array();
                    if (cookie != null && cookie != "") {
                        items = $.evalJSON(cookie);
                    };
                    p.checkout(items);
                });
                if (self.sumDiv == null) {
                    self.sumDiv = $('<div class="cart-item-sumary"></div>');
                    self.sumDiv.append('<div style="float:left;">Total: ' + total + ' Items</div><div style="float:right;">Amount: $' + (Math.round(amount * 100) / 100) + '</div>');
                    self.sumDiv.append(checkoutButton);
                    $("ul", self.bodyDiv).after(self.sumDiv);
                    return;
                }
                $("div:first", self.sumDiv).text("Total: " + total + " Items");
                $("div:last", self.sumDiv).text("Amount: $" + (Math.round(amount * 100) / 100));
            }


        });
    };

    $.fn.cart = function(p, item) {

        if (p === "addItem") {
            this.each(function() {
                cart = $(this).data("cart");
                cart.addItem(item);
            });
            return;
        }
        p = $.extend({
            cookieName: "cookies@drrachael",
            url: false,
            cookieExpires: 90,
            itemClick: function() { },
            checkout: function() { },
            itemChanged: function() { }
        }, p);

        this.each(function() {
            cart = new Cart(this, p);
            cart.render();
            $(this).data("cart", cart);
        });
        return this;
    }
})(jQuery);