﻿/**
 * Переключалка продуктов
 * Copyright Art. Lebedev | http://www.artlebedev.ru/
 * @requires jQuery
 * @author vazzda
*/
var homepage_products = {
    init: function () {
        var filters, products;

        this.content_ = jQuery('.home_content');
        this.filters_ = filters = jQuery('.sitemap_filters');
        this.products_ = products = jQuery('.home_products');
        this.hider_ = products.find('.home_products_hider');
        this.leads_ = products.find('.home_products_leads');

        //danger: global method
        this.filterType_ = get_filter();
        this.animationQueue_ = jQuery({});

        filters.bind('update', jQuery.proxy(function (event, options) {
            this.animationQueue_.clearQueue('reload');
            this.actualizeProducts_(options.type);
        }, this));
        this.reloadLead_(this.filterType_);

        this.hider_.css({opacity: 0});
    },

    /**
     * Перезагрузка фильтра
     * @param filter String Тип фильтра
     * @private
    */
    actualizeProducts_: function (filter) {
        var products, screen, isFitToScreen;

        products = this.products_;
        screen = jQuery(window);
        isFitToScreen = (screen.scrollTop() + screen.height()) >
            products.offset().top + products.height();

        // собираем последовательность анимаций
        if (isFitToScreen){
            this.reloadProducts_(filter);
        } else {
            this.reloadProducts_(filter);
            this.animationQueue_.queue('reload', jQuery.proxy(
                this.scrollToProducts_, this)
            );
        }

        //выполняем анимации
        this.animationQueue_.dequeue('reload');
    },

    /**
     * Перезагрузка продуктов
     * очередь: скрытие блока, новые лид и высота, апдейт фильтра, показ блока
     * @param filter String Тип фильтра
     * @private
    */
    reloadProducts_: function (filter) {
        var hider, products, queue;

        queue = this.animationQueue_;
        hider = this.hider_;

        hider.stop();
        queue.queue('reload', jQuery.proxy(function (next) {
            this.hideProducts_(next);
        }, this));
        queue.queue('reload', jQuery.proxy(function (next) {
            this.reloadLead_(filter, next);
        }, this));
        queue.queue('reload', jQuery.proxy(function (next) {
            this.filterType_ = filter;
            next();
        }, this));
        queue.queue('reload', jQuery.proxy(function (next) {
            this.showProducts_(next);
        }, this));
    },

    /**
     * Переключение к актуальному лиду
     * @param filter String Тип фильтра
     * @private
    */
    reloadLead_: function (filter, next) {
        var currentLead, index, height, leads, leadsHeight, lead, newLead, selectedClassName, type;

        leads = this.leads_;
        selectedClassName = 'home_products_lead_selected';
        leads.css({'height': leads.height()});
        leads.find('.home_products_lead')
            .each(jQuery.proxy(function(index, item){
                lead = jQuery(item);
                type = lead.data('type');

                if (type === this.filterType_) {
                    lead.removeClass(selectedClassName);
                    currentLead = lead;
                }
                if (type === filter) {
                    lead.addClass(selectedClassName);
                    newLead = lead;
                }
            }, this));


        leadsHeight = leads.height();
        height = newLead ? newLead.height() : 0 ;

        if (leadsHeight !== height) {
            leads.animate({'height': [height, 'easeOutCubic']}, 300, function () {
                if (next) {
                    next();
                }
            });
        } else {
            if (next) {
                next();
            }
        }

    },

    /**
     * Показываем продукты
     * @param next Function Следующая анимация
     * @private
    */
    showProducts_: function (next) {
        this.toggleProductsVisibility_(0, next);
    },

    /**
     * Прячем продукты
     * @param next Function Следующая анимация
     * @private
    */
    hideProducts_: function (next) {
        this.hider_.show();
        this.toggleProductsVisibility_(1, next);
    },

    /**
     * Анимация переключения продуктов
     * работает в очереди, queue
     * @param next Function Следующая анимация
     * @private
    */
    toggleProductsVisibility_: function (opacity, next) {
        var hider;

        hider = this.hider_;
        hider.animate({'opacity': opacity}, 600, function () {
            if (opacity === 0) {
                hider.hide();
            }
            next();
        });
    },

    /**
     * Анимация проматывания к продуктам
     * работает в очереди, queue
     * @param next Function Следующая анимация
     * @private
    */
    scrollToProducts_: function (next) {
        var offset = this.content_.offset().top;
        $('html, body').animate({scrollTop: offset}, 1000, function () {
            next();
        });
    }
};

jQuery(function (){
    homepage_products.init();
	init_filters();
})

