var Basket = Class.create({
    initialize: function (location, products) {
        this.products = products;
        this.location = $(location);
        this.basket_div = $('basketDiv');
        this.tab_top = $$('.tab_top');
        this.tab_bottom = $$('.tab_bottom');
        this.cart_icon = $('cartIcon');

        //this.resolutionFix();
        
        for (i = 0; i < this.products.length; i++) {
            //this.products[i] = new Product(this.products[i]);
            if ($('remove_'+this.products[i].id))
                new RemoveButton('remove_'+this.products[i].id, this.products[i]);
            if ($('update_'+this.products[i].id))
                new UpdateButton('update_'+this.products[i].id, this.products[i]);
        }
        
        this.tab_top.invoke('observe', 'click', this.cartSlider.bind(this));
        this.tab_bottom.invoke('observe', 'click', this.cartSlider.bind(this));
    },
    // p should be a ProductRow Object
    cartSlider: function (){
        var animation_speed = 1;
        if (this.basket_div.style.left == '0px' || this.basket_div.style.left == '0pt'){
            new Effect.Morph(this.basket_div, {
                  style: 'left:-550px;', // CSS Properties
                  duration: animation_speed, // Core Effect properties
                  queue: 'end'
            });
            this.cart_icon.src = '/images/layout/cart_yellow.png';
        }
        else {
            new Effect.Morph(this.basket_div, {
                style: 'left:0px;', // CSS Properties
                duration: animation_speed, // Core Effect properties
                queue: 'end'
            });
            this.cart_icon.src = '/images/layout/cart_yellowX.png';
        }
    },
    resolutionFix: function () {
        if (screen.height <= 768) {
            $('rezNormal').hide();
            $('rez1024').show();
            $('basket_holder').style.height = '85px';
            $('cornerImage').src = '/images/other/ipad_corner-1024.png'; // this does not belong here
        }
    }
});

var number_format = function (value, decimal_digits) {
    var separator_length = 3;
    var original_value = value;
    var temp_value = "" + original_value;
    var new_value = '';
    var p_str;
    var d_str;

    if (temp_value.indexOf('.') == -1)
        temp_value += '.';

    d_str = temp_value.substr(0, temp_value.indexOf('.')); // before decimal
    p_str = temp_value.substr(temp_value.indexOf('.')); // after decimal

    while (p_str.length-1 < decimal_digits)
        p_str += '0';

    if (p_str == '.')
        p_str = '';

    if (d_str.length > separator_length) {
        while (d_str.length > separator_length) {
            new_value = "," + d_str.substr(d_str.length - separator_length) + new_value;
            d_str = d_str.substr(0, d_str.length - separator_length);
        }

        new_value = d_str + new_value;
    }
    else {
        new_value = d_str;
    }

    new_value = new_value + p_str;

    return new_value;
}

var Button = Class.create({
    initialize: function (id, properties) {
        this.button = $(id);
        this.properties = properties;

        this.button.observe('click', this.on_click.bind(this));

        return this.button;
    },
    on_click: function () {},
    getNewSubtotal: function () {
        var subtotal = 0;
        $$('span.price').each(function (price) {
            subtotal += parseFloat(price.innerHTML);
        }.bind(this));

        return subtotal;
    },
    applyS: function (qty) {
        if (qty == 1)
            $$('span.qty_s').invoke('update', '');
        else
            $$('span.qty_s').invoke('update', 's');
    },
    freeShippingQualify: function () {
        subtotal = this.getNewSubtotal();
        if (subtotal >= 29.98) {
            if ($('free_ship_qual'))
                $('free_ship_qual').update('<span class="zaggGreenNew oblique">You qualify!</span>');
        }
        else {
            if ($('free_ship_qual')) {
                var remaining = 29.98 - subtotal;
                $('free_ship_qual').update('<span>$'+ remaining.toFixed(2) +' remaining!</span>');
            }
        }
    }
});

var UpdateButton = Class.create(Button, {
    initialize: function ($super, id, properties) {
        $super(id, properties);
        this.sku = this.properties.cart_sku;                        
        this.id = this.button.identify().replace(/update_/, '');
        this.qty = $('qty_'+this.id);
        this.orig_qty = this.qty.value;
        this.form = $('form_'+this.id);

        this.basket_qty = this.getBasketQty();
        this.form.observe('submit', this.on_click.bind(this));
    },
    on_click: function () {
        this.updateItems();
    },
    getBasketQty: function () {
        var new_qty = 0;
        $$('.itemQtyInput').each(function (qty) {
            new_qty += parseInt(qty.value);
        });
        return new_qty;
    },
    updateItems: function () {
        new Ajax.Request('/basket.php', {
            method: 'post',
            parameters: {
                sku: this.properties.cart_sku,
                id: this.id,
                ajax: true,
                action: 'edit',
                qty: this.qty.value
            },
            onSuccess: function (e) {
                /* change the prices */
                // change the item counts
                // find out the new qty
                //var new_qty = 0;
                //$$('.itemQtyInput').each(function (qty) {
                //    new_qty += parseInt(qty.value);
                //});
                // find out if we need the 's' on items
                this.basket_qty = this.getBasketQty() - (this.qty.value - this.orig_qty);
                
                this.applyS(this.basket_qty + (this.qty.value - this.orig_qty));
                            
                //$$('span.cart_qty').invoke('update', this.basket_qty + (this.qty.value - this.orig_qty));
                this.getProductCount();
                
                // set the item price
                $('price_'+this.id).update((this.qty.value*this.properties.cart_price).toFixed(2));

                if (this.qty.value < 1) {
                    // remove the view cart link
                    $$('div.view_cart, span.view_cart').invoke('hide');
                    // remove the product row
                    $('form_'+this.id).remove();
                }
                
                // now the cart subtotal and estimated total
                var subtotal = this.getNewSubtotal();
                $('cart_subtotal').update(subtotal.toFixed(2));
                $('order_total').update(subtotal.toFixed(2));
                
                // and recalc shipping
                document.fire('subtotal:changed', subtotal);
                document.fire('totals:changed', 'hide_error');

                // free shipping
                this.freeShippingQualify();
                this.basket_qty = this.getBasketQty();
            }.bind(this)
        });
    },
    getProductCount: function () {
        new Ajax.Request('/store/checkout/ajax/safe_cart_ajax.php', {
            method: 'post',
            parameters: {
                'func': 'getCartCount'
            },
            onSuccess: function (e) {
                $$('span.cart_qty').invoke('update', e.responseText);
                if (e.responseText.empty())
                    $$('span.cart_qty').invoke('update', 0);
            }
        });
    }
});

var RemoveButton = Class.create(Button, {
    initialize: function ($super, id, properties) {
        $super(id, properties);
        this.id = this.button.identify().replace(/remove_/, '');
        this.form = $('form_'+this.id);
    },
    on_click: function () {
        this.removeItem();
    },
    removeItem: function () {
        // ajax request to remove the item
        new Ajax.Request('/basket.php', {
            method: 'post',
            parameters: {
                ajax: 'true',
                id: this.id,
                action: 'remove'
            },
            onSuccess: function () {
                // get it's qty
                var removed_qty = $('qty_'+this.id).value;
                var original_qty = $$('span.cart_qty')[0].innerHTML;
                // subtract the qty from appropriate places
                var new_qty = original_qty - removed_qty;
                $$('span.cart_qty').invoke('update', new_qty);
                this.applyS(new_qty);

                if (new_qty < 1)
                    $$('div.view_cart, span.view_cart').invoke('hide');

                // subtract the price from cart subtotal and estimated total
                var subtotal = this.getNewSubtotal() - parseFloat($('price_'+this.id).innerHTML);
                $('cart_subtotal').update(subtotal.toFixed(2));
                $('order_total').update(subtotal.toFixed(2));

                // and recalc shipping
                document.fire('subtotal:changed', subtotal);
                document.fire('totals:changed', 'hide_error');
                // remove it from the DOM
                this.form.remove();

                // free shipping
                this.freeShippingQualify();
            }.bind(this),
            onFailure: function (e) {
                // let the user know somehow
            }
        });
    }
});
