﻿Ext.ns("OXX.Basket");

// content - element

OXX.BasketItem = Ext.extend(Object, {
    constructor: function(id, basketId, count, title, price) {
        this.id = id;
        this.basket_id = basketId;         
        this.count = count;
        this.title = title;
        this.unitPrice = parseInt(price/100);
        
        this.updatePrice();

     },

    updatePrice: function() {
        this.price = parseInt((this.unitPrice) * this.count);
    },

    incCount: function(count) {
        this.count = parseInt(this.count) + 1;
        this.updatePrice();
    },

    updateCount: function(count) {
        this.count = count;
        this.updatePrice();
    }
    
    
    
    
});



OXX.Basket = Ext.extend(Object, {

    constructor: function(id) {

        if (Ext.isObject(Ext.fly('mybasket'))) {

            this.basketId = id;
            this.basketName = "cookie_" + id;
            this.items = {};
            this.id = id;
            this.contentEl = Ext.isObject(Ext.get('basket-content-checkout')) ? Ext.get('basket-content-checkout') : Ext.get(id).down('div.mycontent');

            //  this.shortContentEl = 

            this.totalPrice = 0;
            this.totalCount = 0;
            this.init();

            OXX.Application.addEvents("basket_update");
        }
    },

    create: function(cookieValues) {
        var productArray = new Array();
        var splits = cookieValues.split('/');

        for (var i = 0; i < splits.length; i++) {
            var innerSplits = splits[i].split('.');
            if (innerSplits.length > 1) {
                var _id = innerSplits[0];
                var _count = innerSplits[1];
                this.items[_id] = this.createItem(_id, _count);

            }
        }
    },

    createItem: function(id, count) {
        var item = new OXX.BasketItem(id, this.basketId, count, OXX.ProductCollection.getProduct(id).title, OXX.ProductCollection.getProduct(id).price);


        return item;
    },

    update: function(itemId) {

        if (itemId == null) {

        } else {



            var productId = itemId.replace('basket_product_count_', '');

            if (Ext.isObject(this.items[productId])) {
                this.items[productId].updateCount(Ext.fly(itemId).dom.value);

            }
        }

        var cookieStr = '';
        for (var i in this.items) {
            cookieStr += this.items[i].id + '.' + this.items[i].count;
            cookieStr += '/';
        }

        OXX.Cookie.create(this.basketName, cookieStr, 1);
        OXX.Application.fireEvent('basket_update');
    },

    totalize: function() {
        this.totalCount = 0;
        this.totalPrice = 0;


        for (var key in this.items) {
            var item = this.items[key];
            this.totalCount += parseInt(item.count);
            this.totalPrice += item.price;
        }

        this.tax = ((this.totalCount < 100) ? 19 : 29);

    },


    isEmpty: function() {
        this.totalize();
        return (this.totalCount == 0);
    },


    init: function() {

        var cookieValues = OXX.Cookie.read(this.basketName);

        if (Ext.isPrimitive(cookieValues)) {
            this.create(cookieValues);
        } else {

        }

        this.render();
        this.initEvents();
    },


    initEvents: function() {

        Ext.fly(this.contentEl).on('click', function(e, t) {

            if (t.name == 'delete') {
                this.remove(t.className);
            }
            else if (t.name == 'checkout') {
                this.checkout();

            }
            else if (t.name == 'show') {
                this.show();
            }
            else if (t.name == 'counter') {

            }
            else {
                this.update();
                this.render();
            }

        }, this);


        Ext.fly(this.contentEl).on('keyup', function(e, t) {
            this.update(t.id);
            this.render();

            //setTimeout(function() {
            //t.focus(false, 9000);
            //}, 5);

        }, this);
    },

    add: function(productId) {

        if (this.items[productId] == null) {
            this.items[productId] = this.createItem(productId, 1);
        } else {
            //this.items[productId].count = parseInt(this.items[productId].count) + 1;
            this.items[productId].incCount();
        }

        var productCountEl = 'basket_product_count_' + productId;
        if (Ext.isObject(Ext.fly(productCountEl))) {
            Ext.fly(productCountEl).frame("ff0000", 1, { duration: 1 });
        }


        this.update();
        this.render();
    },

    removeAll: function() {

        for (var i in this.items)
            delete this.items[i];

        this.update();
        this.render();
    },


    remove: function(productId) {

        delete this.items[productId];

        this.update();
        this.render();
    },

    checkout: function() {

        this.totalize();

        if (this.totalCount < 10) {
            alert('Du må minimum kjøpe 10 varer!');
        } else {
            if (OXX.Application.security.isAnonymous()) {
                OXX.Util.redirect(5);
            } else {
                OXX.Util.redirect(3);
            }

        }
    },


    show: function() {
        OXX.Util.redirect_aid(9078657, 2);
    },

    createFieldTemplate: function(colname) {
        switch (colname) {
            case "title": return new Ext.Template('<div class="row-field row-field-{name}">{title}</div>');
            case "count":

                if (OXX.Util.paramvalue('state') == 'buy') {
                    return new Ext.Template('<div class="row-field row-field-{name}"><div id="basket_product_count_{id}" value="{count}">{count}</div></div>');

                } else {
                    return new Ext.Template('<div class="row-field row-field-{name}"><input style="width:34px;" name="counter" id="basket_product_count_{id}" value="{count}"></div>');
                }

            case "price": return new Ext.Template('<div class="row-field row-field-{name}">{unitPrice},-</div>');

            case "tax": return new Ext.Template('<div class="tax_row"><span>Kr.{tax},- (Ekspedisjonsgebyr)</span></div>');

            case "pricesum": return new Ext.Template('<div class="row-field row-field-{name}">{price},-</div>');
        }
    },

    renderColumn: function(tableEl, col) {
        var columnEl = document.createElement('div');
        columnEl.className = 'checkout-col checkout-col-' + col.name;
        //columnEl.className = 'checkout-col checkout-col-' + colname;
        var headerRow = new Ext.Template('<div class="row-header row-header-{name}">{txt}</div>');
        headerRow.append(columnEl, col);
        var totalSum = 0;
        var totalCount = 0;
        for (var i in this.items) {
            var fieldRow = this.createFieldTemplate(col.name);

            fieldRow.append(columnEl, Ext.apply(this.items[i], col));
            totalSum += this.items[i].price;
            totalCount += this.items[i].count;
        }

        var footerRow = new Ext.Template('<div class="footer-divide-1">&nbsp;</div><div class="row-footer row-footer-{name}">{totalsum}</div>');

        this.tax = ((totalCount < 100) ? 19 : 29);

        var footerSumRow = new Ext.Template('<div class="footer-divide-1">&nbsp;</div><div class="row-footer tax-label">eks.gebyr {tax},-</div></div><div class="footer-divide-2">&nbsp;</div><div class="row-footer row-footer-{name}">Totalt:{totalsum},-</div><div class="clear"></div><div class="footer-divide-3">&nbsp;</div>');
        if (col.name == 'pricesum') {

            footerSumRow.append(columnEl, Ext.apply(col, { totalsum: totalSum + this.tax, tax: this.tax }));
        } else {
            footerRow.append(columnEl, col);
        }

        tableEl.appendChild(columnEl);
    },


    getRowTemplate: function() {
        return [
            '<div id="basket_product_{id}">',
                '<div class="price_row_1">',
                    '<div class="pro"><input style="width:40px;" name="counter" id="basket_product_count_{id}" value="{count}">',
                        '<span class="product-link hover" id="product_link{id}">{title}</span>',
                    '</div>',
                    '<div class="img"><img class="{id}" width="14px;" name="delete" src="im/buttons/basket_delete.gif"></div>',
                '</div>',
                '<div class="price_row_2">',
                     '<span>Kr.{price},-</span>',
                '</div>',
            '</div>'
        ];
    },


    getBottomTemplate: function(empty, detail) {



        return (empty) ?
        [
          '<div class="bottom-row">',
            '<div class="total_price">Handlekurven er tom</div>',
          '</div>', '<div class="clear"></div>'
        ] : (detail) ? [
                '<div class="bottom-row">',
                    '<div class="total_price">{totcount} varer i handlevognen</div>',
                '</div>', '<div class="clear"></div>'

            ] : [
                '<div class="bottom-row">',
                    '<div class="total_price">Sum kr.{totprice},-</div>',
                    '<div class="left-bottom">',
                        '<img class="basket_image" name="checkout" src="im/buttons/basket_checkout.png">',
                    '</div>',
                    '<div class="right-bottom">',
                        '<img class="basket_image" name="show" src="im/buttons/basket_show.png">',
                    '</div>',
                '</div>', '<div class="clear buttonbottom"></div>'
            ];
    },


    resize: function(shortmode) {
        var basketHeight = this.contentEl.getHeight();
        Ext.select(shortmode ? '' : '.basket_longer').setHeight(basketHeight + 20);


    },

    renderTitle: function(shortmode) {
        var titleEl = Ext.get('mybasket').select('div.header').item(0);
        var renderTo = Ext.DomHelper.overwrite(titleEl, true);
        var textTemplate = (shortmode) ? new Ext.Template('<div class="small-title">Viser {count} produkter</div>') : new Ext.Template('<div class="large-title">{title}</div>');
        textTemplate.append(renderTo, { count: this.totalCount, title: 'Handlevogn' });
        shortmode ? Ext.select('div.basket > div.mycontent').hide() : Ext.select('div.basket').show();


        Ext.select('.mybox_BASKET').addClass(shortmode ? 'basket_short' : 'basket_longer');
    },

    // Can we render to content area ??
    isContentCheckout: function() {
        return Ext.isObject(Ext.get('basket-content-checkout'));
    },


    renderFull: function(shortmode) {
        var renderTo = Ext.DomHelper.overwrite(this.contentEl, true);

        if (this.isContentCheckout()) {
            var tableEl = document.createElement('div');
            tableEl.className = 'checkout-table'

            Ext.each([{ name: 'title', txt: 'Varenavn' },
                      { name: 'count', txt: 'Antall' },
                      { name: 'price', txt: 'Pris' },
                      { name: 'pricesum', txt: 'Sum'}],
                         function(item, idx, allItems) {
                             this.renderColumn(tableEl, item);
                         }, this);

            renderTo.appendChild(tableEl);

        } else {

            var t2 = new Ext.Template(this.getRowTemplate());
            var t3 = new Ext.Template(this.getBottomTemplate((this.totalPrice == 0), shortmode));

            if (!shortmode) {
                for (var i in this.items) {
                    t2.append(renderTo, this.items[i]);
                }

                if (this.totalPrice > 0) {
                    var taxRow = this.createFieldTemplate('tax');
                    taxRow.append(renderTo, { tax: this.tax });
                }

            }

            t3.append(renderTo, { id: 100, totprice: this.totalPrice + this.tax, totcount: this.totalCount });
        }
    },



    render: function() {
        this.totalize();
        var shortmode = (!Ext.isObject(Ext.fly('myproducts'))) && (!this.isContentCheckout());

        this.renderFull(false);

        this.renderTitle(false);

        this.resize(false);

        OXX.Application.resizeLayout();
    }
});


