/**
 * Калсс для работы с блоком корзины сбоку
 * @param {Object} wrapEl DOM-элемент
 */
DesignCafe.Basket.Block = function(wrapEl) {

    var ITEM_SLIDE_DURATION = 300;

    var $wrap = $();

    /** @type {Array} массив элементов в корзине */
    var items = new Array();

    function init() {
        $wrap = $(wrapEl);
        $wrap.find('input:text')
            .inputArrowCounter({ clearButton : true })
            .bind('clear', _removeItemHandler)
            .bind('change', _updateItemHandler);

        var itemElements = wrapEl.getElementsByTagName('li');
        for (var i = 0; i < itemElements.length; i++) {
            var item = new DesignCafe.Basket.Block.Item();
            item.constructFromDOM(itemElements[i]);
            items.push(item);
        }

    }

    function _removeItemHandler() {
        var id = this.id.substr(3);
        DesignCafe.Basket.update(id, 0);
    }

    function _updateItemHandler() {
        var id = this.id.substr(3);
        DesignCafe.Basket.update(id, this.value);
    }

    /**
     * Найти элемент по id
     * @param {String} id
     */
    this.getItemById = function(id) {
        for (var i = 0; i < items.length; i++)
            if (items[i].id == id)
                return items[i];
        return null;
    }

    /**
     * Обновить сумму заказа
     */
    this.updateTotal = function() {
        var total = 0;
        for (var i = 0; i < items.length; i++)
            total += items[i].count * items[i].price;
        $wrap.find('.total-price').html(total.toPrice());
    }

    /**
     * Добавить элемент
     * @param {Object} _item
     */
    this.appendItem = function(_item) {
        var item = new DesignCafe.Basket.Block.Item(_item.id, _item.name, _item.count, _item.price);
        items.push(item);
        var $el = item.draw();
        $el.find('input')
            .inputArrowCounter({ clearButton : true })
            .bind('clear', _removeItemHandler)
            .bind('change', _updateItemHandler);

        $el.hide().appendTo($wrap.find('ul')).slideDown(ITEM_SLIDE_DURATION);
    }

    /**
     * Обновить элемент
     * @param {Object} item
     * @param {Boolean} [insert] вставить, если нет в списке
     */
    this.updateItem = function(item, insert) {
        var listItem = this.getItemById(item.id);

        if (listItem) {
            listItem.update(item.count);
        } else {
            if (insert)
                this.appendItem(item);
        }
        this.updateTotal();
    }

    /**
     * Убрать элемент по id
     * @param {String} id
     */
    this.removeItemById = function(id) {
        var item = this.getItemById(id);
        if (item) {
            item.$el.slideUp(ITEM_SLIDE_DURATION, function() { $(this).remove(); });
            items.splice(items.indexOf(item), 1);
        }
        this.updateTotal();
    }

    /**
     * Получить хэш { id : count }
     * @return {Object}
     */
    this.getItemsHash = function() {
        var r = {};
        for (var i = 0; i < items.length; i++)
            r[items[i].id] = items[i].count;
        return r;
    }

    if (wrapEl) {
        init();
    } else {
        return null;
    }
};


/**
 * Класс элемента корзины
 * @class DesignCafe.Basket.Block.Item
 * @param {String} [id] идентификатор товара
 * @param {String} [name] название
 * @param {Number} [count] количество
 * @param {Number} [price] цена
 */
DesignCafe.Basket.Block.Item = function(id, name, count, price) {
    this.id = id;
    this.name = name;
    this.count = parseInt(count);
    this.price = parseFloat(price);
    this.$el = $();
}
DesignCafe.Basket.Block.Item.prototype = {
    /**
     * Собрать из DOM-элемента
     * @param {Object} el
     */
    constructFromDOM : function(el) {
        var $el = $(el);
        var input = $(el).find('input:text').get(0);
        if (input) {
            this._input = input;
            this.$el = $el;
            this.count = input.value;
            this.id = input.id.substr(3);
            this.name = $(el).find('label').html();
            var price = '';
            var $s = $(el).find('.price span');
            for (var i = 0; i < $s.length; i++)
                price += $s.eq(i).html().toString();
            this.price = parseFloat(price);
        }
    },
    /**
     * Нарисовать элемент
     */
    draw : function() {
        this.$el = $(document.createElement('li'))
            .html(
                '<label>' + this.name + '</label>' +
                '<div class="count"><input type="text" value="' + this.count + '" id="bpc' + this.id + '" /></div>' +
                '<div class="price">' + this.price.toPrice() + '</div>'
            );
        this._input = this.$el.find('input').get(0);
        return this.$el;
    },
    /**
     * Изменить количетсво
     * @param {Number} count
     */
    update : function(count) {
        this.count = count;
        if (this._input)
            this._input.value = count;
    }
};

