/**
 * Контейнеры
 * Список контейнеров + изображение текущего + текст под ним
 *
 * @property jQuery[] nodesList
 *           элементы контейнеров из списка
 * @property jQuery nodesBig
 *           элементы с большими фотографиями
 * @property jQuery nodesText
 *           элементы с текстами
 * @property ItemClass{} items
 *           отдельные экземпляры контейнеров (объём => экземпляр)
 * @property string current
 *           текущий контейнер
 * @property function[] listeners
 *           слушатели выбора контейнера
 */
CalcClass.ContainersClass = go.Class({

    /**
     * Фильтры по типу мусора
     */
    'TYPE_FILTERS': {
        'household' : ["0.8", "1.1", "8", "20", "27", "33"],
        'debris'    : ["8", "20", "27", "33"],
        'bulky'     : ["8", "20", "27", "33"],
        'snow'      : ["8", "20"]
    },


    /**
     * Конструктор
     *
     * @param jQuery[] nodesList
     *        указатель на элементы контейнеров из списка
     * @param jQuery[] nodesBig
     *        элементы с большими фотографиями
     * @param jQuery[] nodesText
     *        элементы с текстами
     */
    '__construct': (function(nodesList, nodesBig, nodesText) {
        this.nodesList = $(nodesList);
        this.nodesBig  = $(nodesBig);
        this.nodesText = $(nodesText);
        this.listeners = [];
        this.loadItems();
    }),
    
    /**
     * Деструктор
     */
    '__destruct': (function() {
        var items = this.items;
        var len   = items.length;
        for (var i = 0; i < len; i++) {
            items[i].destroy();
        }
    }),
    
    /**
     * Получить объём текущего контейнера
     */
    'getCurrentContainer': (function() {
        return this.current && this.current.volume;
    }),
    
    /**
     * Установить слушатель события: выбран новый контейнер
     *
     * @param function listener
     */
    'addEventListener': (function(listener) {
        this.listeners.push(listener);
    }),
    
    /**
     * Формирование списка вложенных контейнеров
     */
    'loadItems': (function() {
        this.items = {};
        var len    = this.nodesList.length;
        for (var i = 0; i < len; i++) {
            var item = new this.ItemClass(this, this.nodesList.eq(i), this.nodesBig.eq(i), this.nodesText.eq(i));
            var volume = item.getVolume();
            this.items[volume] = item;
            if (item.isSelected()) {
                this.current = item;
            }
        }
    }),
    
    /**
     * Событие: выбран один из элементов
     *
     * @param ItemClass item
     *        выбранный элемент
     */
    'onSelect': (function(item) {
        if (item == this.current) {
            return;
        }
        if (this.current) {
            this.current.unselect();
        }
        this.current = item;
        this.runListeners();
    }),
    
    /**
     * Фильтр контейнеров
     *
     * @param list containers
     *        список объёмов показываемых контейнеров
     */
    'filter': (function(containers) {
        var c = {};
        var len = containers.length;
        for (var i = 0; i < len; i++) {
            c[containers[i]] = true;
        }
        var items = this.items;
        for (var volume in items) {
            if (c[volume]) {
                items[volume].show();
            } else {
                items[volume].hide();
            }
        }
        if ((this.current) && (!this.current.isVisible())) {
            this.current.unselect();
            this.current = items[containers[0]];
            this.current.select();
            this.runListeners();            
        }
    }),
    
    /**
     * Фильтр по типу мусора
     *
     * @param string type
     *        тип мусора
     */
    'filterGarbage': (function(type) {
        this.filter(this.TYPE_FILTERS[type]);
    }),
    
    /**
     * Запустить слушатели событий
     */
    'runListeners': (function() {
        var listeners = this.listeners;
        var len       = listeners.length;
        var current   = this.current.getVolume();
        for (var i = 0; i < len; i++) {
            listeners[i](current);
        }
    }),

    /**
     * Класс отдельного контейнера
     *
     * @property ContainerClass list
     *           список контейнеров в который вложен данный
     * @property jQuery nodeList
     *           элемент контейнера из списка
     * @property jQuery nodeBig
     *           элемент большой фотографии контейнера
     * @property jQuery nodeText
     *           элемент с текстом
     * @property string volume
     *           объём контейнера (строкой)
     * @property bool selected
     *           является ли элемент выбранным
     * @property bool visible
     *           показывается ли данный элемент
     */
    'ItemClass': go.Class({
    
        /**
         * Конструктор
         *
         * @param ContainerClass list
         * @param jQuery nodeList
         * @param jQuery nodeBig
         * @param jQuery nodeText
         */ 
        '__construct': (function(list, nodeList, nodeBig, nodeText) {
            this.list     = list;
            this.nodeList = $(nodeList);
            this.nodeBig  = $(nodeBig);
            this.nodeText = $(nodeText);
            this.volume   = this.nodeBig.attr("rel");
            this.selected = this.nodeList.hasClass("active");
            this.visible  = true;
            this.nodeList.find("a").click(this.onClick);
        }),
        
        /**
         * Получить объём
         *
         * @return string
         */
        'getVolume': (function() {
            return this.volume;
        }),
        
        /**
         * Является ли контейнер выбранным
         *
         * @return bool
         */
        'isSelected': (function() {
            return this.selected;
        }),
        
        /**
         * Показывается ли контейнер
         */
        'isVisible': (function() {
            return this.visible;
        }),
        
        /**
         * Выбрать данный контейнер
         */
        'select': (function() {
            if (this.selected) {
                return;
            }
            this.selected = true;
            this.nodeList.addClass("active");
            this.nodeBig.addClass("calc-current");
            this.nodeText.addClass("calc-current");
        }),
        
        /**
         * Снять выбор с данного контейнера
         */
        'unselect': (function() {
            if (!this.selected) {
                return;
            }
            this.selected = false;
            this.nodeList.removeClass("active");
            this.nodeBig.removeClass("calc-current");
            this.nodeText.removeClass("calc-current");
        }),
        
        /**
         * Показать контейнер
         */
        'show': (function() {
            if (this.visible) {
                return;
            }
            this.visible = true;
            this.nodeList.show();
        }),
        
        /**
         * Спрятать контейнер
         */
        'hide': (function() {
            if (!this.visible) {
                return;
            }
            this.visible = false;
            this.nodeList.hide();
        }),
        
        /**
         * Обработка щелчка по контейнеру
         */
        'onClick_bind': (function(e) {
            if (!this.selected) {
                this.select();
                this.list.onSelect(this);                    
            }
            e.preventDefault();
            return false;
        }),
    
        'eoc': null
    }),

    'eoc': null
});

