/**
 * Крутилка баннеров
 * Copyright Art. Lebedev | http://www.artlebedev.ru/
 * @requires jQuery, jQuery.cookie
 * @author vazzda
*/
var homepage_banners = {
    init: function () {
        var banners, groups, menu, menuItems;

        this.menu_ = menu = jQuery('.home_promotions .home_promotions_menu');
        this.menuItems_ = menuItems = menu.find('.home_promotions_menu_item');
        this.menuPointer_ = menu.find('.home_promotions_menu_pointer');

        this.bannersGroups_ = groups =
            jQuery('.home_promotions .home_promotions_group');
        this.bannerListItems_ = bannerListItems =
            groups.find('.home_promotion_list_item');
        this._banners = banners = groups.find('.home_promotion');

        this._decorateFlowers = jQuery('.home_promotion_decorate_image');
        this._currentBanner = undefined;
        this._currentGroup = undefined;
        this._current = {
            type: undefined,
            index: undefined
        };
        this._autoRotate = true;

        menuItems.bind('click', jQuery.proxy(this._onMenuItemClick, this));
        bannerListItems.bind('click', jQuery.proxy(
            this._onBannerListItemClick
        , this));

        //unselectable
        //FIXME элемент должен обрабатываться глобально,
        //расширяя класс css unselectable
        menuItems.bind('selectstart', jQuery.proxy(function (event) {
            event.preventDefault();
            event.stopPropagation();
        }, this));


        // инициирующий клик по меню
        menuItems.eq(
            Number(this._loadMenuItemIndex())
        ).click();
    },

    /**
     * Обработка клика по меню
     * также переключает состояния группы и авторотации
     * @param event Object Событие
     * @private
    */
    _onMenuItemClick: function (event) {
        var currentType, group, groups, item, type;

        item = jQuery(event.currentTarget).closest('.home_promotions_menu_item');
        currentType = this._current.type;
        type = item.data('type');
        groups = this.bannersGroups_;
        group = groups.eq(item.index());

        if (type !== currentType) {
            if (currentType) {
                if (this._autoRotate) {
                    this._disableAutoRotate();
                }
                groups.eq(this._getMenuItemPosByType(currentType))
                    .removeClass('home_promotions_group_selected');
                this._disableMenuItem(currentType);
            }

            this._enableMenuItem(type);
            this._current.type = type;
            group.addClass('home_promotions_group_selected');
            this._setBanner(type, 0);
            if (group.data('length') > 1) {
                this._enableAutoRotate();
            }
            this._updateMenuPointer(item);
        }
    },

    /**
     * Сдвиг указателя к элементу меню
     * @param menuItem jQuery Object Элемент меню
     * @private
    */
    _updateMenuPointer: function (menuItem) {
        var content, contentLeft, contentOffset;


        content = menuItem;
        contentOffset = content.offset();
        contentLeft = content[0].offsetLeft + (content.width() / 2);
        center = jQuery('#content').width() / 2;

        this.menuPointer_.css({
            'left': (contentLeft - center) + 'px'
        });
    },

    /**
     * Обработка клика по списку баннеров в одном типе
     * @param event Object Событие
     * @private
    */
    _onBannerListItemClick: function (event) {
        var current, currentIndex, i, index, item;

        item = jQuery(event.currentTarget).closest('.home_promotion_list_item');
        index = item.index();
        current = this._current;
        currentIndex = this._currentBanner.index();

        //return
        if (index === currentIndex) { return false };

        this._setBanner(current.type, index);
        if (this._autoRotate) {
            this._disableAutoRotate();
        }
    },

    /**
     * Переключения состояния выбран/невыбран кнопке из списка баннеров одного
     * типа
     * @param type Number индекс
     * @private
    */
    _toggleListItemState: function (index) {
        var items;

        items = this.bannerListItems_;
        items.eq(index).toggleClass('home_promotion_list_item_selected');
    },

    /**
     * Включение элемента меню (общесайтовые фильтры)
     * @param type String Тип меню
     * @private
    */
    _enableMenuItem: function (type) {
        var item;

        item = this.menuItems_.eq(
            this._getMenuItemPosByType(type)
        );
        item.addClass('home_promotions_menu_item_selected');
        item.find('.home_promotions_menu_text').removeClass('pseudo_link');
        this._saveMenuItemIndex(item.index());
    },

    /**
     * Выключение элемента меню (общесайтовые фильтры)
     * @param type String Тип меню
     * @private
    */
    _disableMenuItem: function (type) {
        var item;

        item = this.menuItems_.eq(
            this._getMenuItemPosByType(type)
        );
        item.find('.home_promotions_menu_text').addClass('pseudo_link');
        item.removeClass('home_promotions_menu_item_selected');
    },

    /**
     * Переключение баннера
     * @param type String Тип группы баннеров
     * @param index Number Индекс баннера в группе
     * @private
    */
    _setBanner: function (type, index) {
        var banner, bannerGroup, currentBanner, bannerGroupIndex;

        currentBanner = this._currentBanner;
        if (currentBanner) {
            currentBanner.find('.home_promotion_item').each(
                jQuery.proxy(function (i, item) {
                    this._resetBannerItem(item);
                }, this));
            currentBanner.removeClass('home_promotion_selected');
            this._toggleListItemState(currentBanner.index());
        }

        bannerGroupIndex = index || 0;
        this.bannersGroups_.each(jQuery.proxy(function (index, item) {
            bannerGroup = jQuery(item);
            if (type === bannerGroup.data('type')) {
                banner = bannerGroup.find('.home_promotion')
                    .eq(bannerGroupIndex);
                this._showBanner(banner);
                this._currentBanner = banner;
                this._current.index = banner.index();
                this._current.groupIndex = bannerGroup.index();
                this._toggleListItemState(bannerGroupIndex);
            }
        }, this));
    },

    /**
     * Выбор баннера
     * @param banner jQuery Ссылка на баннер в html
     * @private
    */
    _showBanner: function (banner) {
        var currentBanner, items, percentWidth, previousBanner, speed
            , widthDifference;

        items = banner.find('.home_promotion_item');
        items.each(jQuery.proxy(function (i, item) {
            this._resetBannerItem(item);
        }, this));

        //подготовка баннера
        previousBanner = this._currentBanner;
        currentBanner = {};
        currentBanner.width = banner.width();
        currentBanner.height = banner.height();
        percentWidth = banner.parent().width() / 100;
        widthDifference = (previousBanner
                && Math.abs(currentBanner.width - previousBanner.width()) || 0
            ) / percentWidth;

        if (previousBanner) {
            banner.css({
                width: previousBanner.width() / percentWidth + '%',
                height: previousBanner.height() + 'px'
            });
        }

        banner.addClass('home_promotion_selected');

        //анимация баннера
        speed = 150 + (widthDifference * 8);
        banner.animate({
            width: [currentBanner.width / percentWidth + '%', 'easeOutCubic'],
            height: [currentBanner.height + 'px', 'easeOutCubic']
        }, speed, jQuery.proxy(function () {
            items.each(jQuery.proxy(function (i, item) {
                this._animateBannerItem(item);
            }, this));
        }, this));

        //цветочная анимация
        this._animateDecorateImages(currentBanner, percentWidth);
    },

    /**
     * Сброс элементов баннера (позиции, анимации)
     * Прозрачность текстовых элементов устнавливается hider, ie massage
     * @param item Dom элемент
     * @private
    */
    _resetBannerItem: function (item) {
        var styles, element, hider, rules;

        element = jQuery(item);
        hider = element.find('.home_promotion_hider');
        rules = jQuery(item).data('animation');

        styles = {
            left: rules.positions.left + 'px',
            top: rules.positions.top + 'px'
        };
        if (!hider.length) {
            styles.opacity = '0';
        };

        element.stop();
        element.css(styles);

        if (hider.length) {
            hider.stop();
            hider.css({'opacity': '1', 'display': 'block'});
        }
    },

    /**
     * Анимация элемента баннера
     * Прозрачность текстовых элементов устнавливается hider, ie massage
     * @param item Dom элемент
     * @private
    */
    _animateBannerItem: function (item) {
        var i, element, hider, rules, styles;

        rules = jQuery(item).data('animation');
        element = jQuery(item);
        hider = element.find('.home_promotion_hider');
        styles = {
            left: ['0px', 'easeOutQuint'],
            top: ['0px', 'easeOutQuint']
        };
        if (!hider.length) {
            styles.opacity = ['1', 'easeOutQuint'];
        };

        element.delay(rules.delay).animate(styles, 1000);

        if (hider.length) {
            hider.delay(rules.delay).animate({
                opacity: '0'
            }, function () {
                hider.hide();
            });
        }
    },

    /*
     * Анимация цветочных картинок
     * @param banner Object Баннер, относительно которого анимимруются декорации
     * @param percentWidth Number Пиксельное представление процента ширины родителя
    */
    _animateDecorateImages: function (banner, percentWidth) {
        var margin, element, elements, animation;

        elements = this._decorateFlowers;
        elements.stop();
        margin = ((banner.width / 2) + (percentWidth * 8));
        elements.each(function (index, item) {
            element = jQuery(item);
            animation = {};
            animation[element.data('direction')] = ['-' + (margin / percentWidth) + '%', 'easeOutQuart'];

            element.animate(animation, 1000);
        });
    },

    /**
     * Переключает баннер на следующий, в порядке следования
     * @private
    */
    _cycleBanner: function () {
        var current, lastIndex;
        current = this._current;
        lastIndex =
            (this.bannersGroups_.eq(current.groupIndex).data('length')) - 1;

        this._setBanner(
            current.type, current.index < lastIndex ? current.index + 1 : 0);
    },

    /**
     * Включение авторотации
     * @private
    */
    _enableAutoRotate: function () {
        this._autoRotate = 'true';

        this._autoRotateId = window.setInterval(
            jQuery.proxy(this._cycleBanner, this), 10000);
    },

    /**
     * Выключение авторотации
     * @private
    */
    _disableAutoRotate: function () {
        window.clearInterval(this._autoRotateId);
        this._autoRotateId = undefined;
        this._autoRotate = 'true';
    },

    /**
     * Возвращает позицию итема в меню по типу
     * @param type String тип
     * @return Number
     * @private
    */
    _getMenuItemPosByType: function (type) {
        var itemIndex, element;

        itemIndex = -1;
        this.menuItems_.each(function (i, item) {
            element = jQuery(item);

            if (type === element.data('type')) {
                itemIndex = element.index();
            }
        });

        return itemIndex;
    },

    /**
     * Записывает индекс последнего открытого баннера в куку
     * @param index Number Индекс
     * @private
    */
    _saveMenuItemIndex: function (index) {
        jQuery.cookie('homepage_banner_index', index, {
            expires: 2
        });
    },

    /**
     * Возвращает индекс последнего открытого баннера из куки
     * @return Number Индекс
     * @private
    */
    _loadMenuItemIndex: function () {
        return jQuery.cookie('homepage_banner_index');
    }
};

jQuery(function () {
    homepage_banners.init();
});


