/**
 * Класс для всяких интерфейсных плюшек
 * @requires js/utils.js
 * @requires js/location.js
 */
Interface = new Object();

/**
 * Настраивает отображения пирамидки
 * @param {Enum} type [big, small]
 */
Interface.setupPyramid = function(type) {
    var selector = (type == 'big')
        ? '#center div.pyramid'
        : '#right-bar div.pyr-s';
    var srcPrefix = (type == 'big')
        ? '/i/p/i'
        : '/i/p/is';
    var $pyramid = $(selector).eq(0);
    if ($pyramid.length) {

        /**
         * Увеличивает кнопку
         * @param {Object} buttonEl DOM-объект ссылки
         * @param {Boolean} st Зафиксировать?
         */
        function raiseGuideButton(buttonEl, st) {
            var img = buttonEl.__img;
            if (!buttonEl.__imgWrap)
                buttonEl.__imgWrap = buttonEl.getElementsByTagName('b')[0];
            if (!img.complete) {
                buttonEl.__imageLoadTimer = window.setTimeout(function () { raiseGuideButton(buttonEl, st); }, 100);
                return;
            }
            var $b = $(buttonEl.__imgWrap);
            var bW = $b.width();
            var bH = $b.height();
            if (!st)
                $(buttonEl.offsetParent).css('z-index', 50);
            if (!buttonEl.__$image) {
                if (!Browser.isMSIE) {
                    buttonEl.__$image = $(document.createElement('img'))
                        .attr({
                            src: img.src
                        })
                } else {
                    buttonEl.__$image = $(document.createElement('em'))
                        .append(
                            $(document.createElement('b'))
                            .css({
                                filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + img.src + '", sizingMethod="scale")'
                            })
                        )
                }
                buttonEl.__$image
                    .css({
                        display: 'block',
                        position: 'absolute',
                        left: 0,
                        top: 0,
                        width: bW,
                        height: bH,
                        opacity: 1
                    })
                    .appendTo($b);
            }
            buttonEl.__$image
                .stop()
                .animate({
                    opacity: 1,
                    left: ((bW - img.width) / 2),
                    top: ((bH - img.height) / 2),
                    width: img.width,
                    height: img.height
                }, 200, 'swing')
                .fadeIn();
            if (type == 'small')
                buttonEl.__$span.fadeIn(200);
        }

        /**
         * Уменьшает кнопку
         * @param {Object} buttonEl DOM-объект ссылки
         */
        function lowerGuideButton(buttonEl) {
            var $b = $(buttonEl.__imgWrap);
            var bW = $b.width();
            var bH = $b.height();
            if (buttonEl.__imageLoadTimer) {
                window.clearInterval(buttonEl.__imageLoadTimer);
                buttonEl.__imageLoadTimer = null;
            }
            if (!buttonEl.__$image)
                return;
            buttonEl.__$image
            .stop()
            .animate({
                left: 0,
                top: 0,
                opacity: 0,
                width: bW,
                height: bH
            }, 200, 'swing', function() { $(buttonEl.offsetParent).css('z-index', 20); $(this).hide() })
            ;
            if (type == 'small')
                buttonEl.__$span.fadeOut(200);
        }


        var elements = [];
        var $items = $pyramid.find('li');
        $items.each(function(i) {
            var $b = $(document.createElement('b'))
                .css({
                    width: '100%',
                    height: '100%',
                    left: 0,
                    top: 0
                });
            var $item = $(this);
            var $a = $item.find('a').append($b);
            elements.push(this.getElementsByTagName('a'));
            var img = new Image();
            img.src = srcPrefix + (i + 1) + '.png';
            var _a = $a.get(0);
            _a.__img = img;
            if (type == 'small') {
                var $span = $a.find('span');
                $span.css('left', ($item.width() - $span.width()) / 2).hide();
                _a.__$span = $span;
            }
            if (!$item.hasClass('active')) {
                $a.hover(
                    function() {
                        raiseGuideButton(this);
                    },
                    function() {
                        lowerGuideButton(this);
                    }
                );
            } else {
                raiseGuideButton(_a, true);
            }
        });

        if (type =='big'){
            function _runer(i){
                if (elements[i+1]){ lowerGuideButton(elements[i+1][0]) };
                if (i>=0) {
                    raiseGuideButton(elements[i][0]);
                    window.setTimeout(function(){ _runer(i-1) },1000);
                };
            }
            window.setTimeout(function(){ _runer(3) },1000);
        }

        /*$pyramid.find('.profit img').click(function(){
            var r = $pyramid.find('.i4 a').attr('href');
            window.location = r;
        })*/

        /*$(function(){
            var blocks = document.getElementsByTagName('b');
            for (var i=0; i<blocks.length; i++) {
                raiseGuideButton(blocks[i]);
            }
        })*/
    }
}

/**
 * Класс для показа слайд-страниц
 */
Interface.Slides = function() {

    var wrapper, $slides, $slidesContainer, $nextLinks;

    var animationDuration = 500;
    var cookieName = '_bad_advise';

    var currentSlide;


    /**
     * Найти слайд по хэшу
     * @param {String} hash хэш
     */
    function getSlideIndexByHash(hash) {
        for (var i = 0; i < $slides.length; i++) {
            var slide = $slides.get(i)
            if (slide._hash == hash)
                return i;
        }
        return -1;
    }

    /**
     * Показать слайд
     * @param {Number} index индекс слайда
     *
     */
    function showSlide(index) {
        if (currentSlide) {
            currentSlide._$
                .css({
                    zIndex: 10
                })
                .fadeOut(animationDuration);
        }

        var slide = $slides.get(index);
        if ((slide) && (slide != currentSlide)) {
            currentSlide = slide;
            slide._$
                .css({
                    position: 'absolute',
                    width: '100%',
                    left: '-100%',
                    top: 0,
                    opacity: 0,
                    zIndex: 20
                }).
                show();
            $slidesContainer.stop().animate({
                height: slide._$.outerHeight()
            }, animationDuration);
            slide._$.stop().animate({
                left: 0,
                opacity: 1
            }, animationDuration, 'swing');

            FLocation.setHash(slide._hash, true);
            Cookies.set(cookieName, index);

            var nextIndex = index + 1;
            if (nextIndex > $slides.length - 1)
                nextIndex = 0;
            var nextHash = $slides.get(nextIndex)._hash;
            $nextLinks.attr({
                href: '#' + nextHash
            });
        }
    }

    /**
     * Показать слайд, соответсвующий текущему хэшу страницы
     */
    function showCurrentSlide() {
        var index = getSlideIndexByHash(FLocation.getHash());
        if (index > -1)
            showSlide(index);
    }

    return {
        /**
         * Закрывает все слайды сразу
         */
        closeAll: function() {
            wrapper = document.getElementById('page-slides-wrap');
            $slidesContainer = $(wrapper).children('ul');
            if ($slidesContainer.length)
                $slides = $slidesContainer.children('li').hide();
        },

        /**
         * Настройка показа слайдов
         */
        setup: function() {
            if (!$slides.length)
                return;
            var currentHash = FLocation.getHash();

            $nextLinks = $('a[rel=next-slide]', wrapper).show();

            var currentIndex = -1;
            $slides.each(function(index) {
                var slide = this;
                var $slide = slide._$ = $(slide);
                var anchor = $slide.find('h2>a').get(0);
                if (anchor) {
                    slide._hash = anchor.getAttribute('name');
                    anchor.removeAttribute('name');
                }
                if (currentHash == slide._hash)
                    currentIndex = index;
            });
            if (Browser.isMSIE)
                $slides.css('background-color', '#ffffff');
            if (currentIndex == -1)
                currentIndex = parseInt(Cookies.get(cookieName)) || 0;
            showSlide(currentIndex);
            FLocation.attachListener(function() {
                showCurrentSlide();
            });
        }
    }
}();

/**
 * Класс для показа разворачивающихся страниц
 */
Interface.AccordeonPage = function() {

    var wrapper, $items, activeItem;
    var items = new Array();

    var animationDuration = 500;

    /**
     * Ищет элемент по хэшу
     * @param {String} hash хэш
     */
    function getItemByHash(hash) {
        for (var i = 0; i < items.length; i ++)
            if (items[i]._hash == hash)
                return items[i];
        return null;
    }

    /**
     * Показывает элемент
     * @param {Object} item DOM-объект элемента
     * @param {Boolena} scrollBodyFlag крутить контент?
     */
    function showItem(item, scrollBodyFlag) {
        if (item != activeItem) {
            if (activeItem) {
                activeItem._$.addClass('closed');
                activeItem._$inner.slideUp(animationDuration);
            }
            activeItem = item;
            item._$.removeClass('closed');
            FLocation.setHash(item._hash, true);
            if (scrollBodyFlag)
                item._$inner.slideDown(animationDuration, function() { scrollBodyToItem(item); });
            else
                item._$inner.slideDown(animationDuration);
        }
    }

    /**
     * Крутит контент до элемента
     * @param {Object} item DOM-объект элемента
     */
    function scrollBodyToItem(item) {
        var top = item._$.offset().top;
        $(Browser.getScrollBody()).animate({
            scrollTop: top
        }, 500, 'swing');
    }

    return {
        /**
         * Закрывает все пунткы при загрузке
         */
        closeAll: function() {
            wrapper = document.getElementById('page-accordeon-wrap');
            if (!wrapper)
                return;
            $items = $('ul.page-accordeon>li', wrapper);
            $items.find('div.inner').hide();
        },

        /**
         * Настройка показа
         */
        setup: function() {
            var currentHash = FLocation.getHash();
            $items.each(function() {
                var item = this;
                var $item = item._$ = $(item);
                $item.addClass('closed');
                var $link = $item.find('h2>a').eq(0);
                var hash = $link.attr('name');
                if (hash) {
                    item._hash = hash;
                    $link.get(0)._item = item;
                    item._$inner = $item.find('div.inner');
                    $link.click(function() {
                        showItem(this._item);
                        return false;
                    })
                    .removeAttr('name');
                    items.push(item);
                    if (hash == currentHash)
                        showItem(item, true);
                }
            });
            if (items.length) {
                if (!activeItem)
                    showItem(items[0]);
                FLocation.attachListener(function() {
                    var hItem = getItemByHash(FLocation.getHash());
                    if (hItem)
                        showItem(hItem, true);
                });
            }
        }

    }
}();

/**
 * Класс для страницы-попапов
 * TODO: написать для нашей галереи
 */
Interface.PopupsPage = function() {
    return {
        setup: function(width, height) {
            var currentHash = FLocation.getHash();
            var $links = $(document.getElementById('i-popups')).find('a[target=popup]').fancybox({
                frameWidth: width,
                frameHeight: height,
                showNavArrows: false
            });
            $(document.getElementById('i-popups')).find('div.inner-content').hide();

            for (var i = 0; i < $links.length; i++) {
                var $link = $links.eq(i);
                var hash = $link.attr('name');
                if ((hash) && (hash == currentHash)) {
                    $(Browser.getScrollBody()).animate(
                        {
                            scrollTop: $link.offset().top - 20
                        },
                        500,
                        'swing',
                        function() {
                            $link.trigger('click.fb');
                        }
                    );
                    break;
                }
            }
        }
    }
}();


Interface.toggleDifference = function(containerId, button, txt) {
    var container = document.getElementById(containerId);
    if (container) {
        var $diff = $(container).children('div');
        if (container.__diffState) {
            if (Browser.isMSIE) {
                $diff.hide();
            } else {
                $diff.fadeOut(500);
            }
            button.innerHTML = button._html;
            container.__diffState = false;
        } else {
            if (Browser.isMSIE) {
                $diff.show();
            } else {
                $diff.fadeIn(500);
            }
            button._html = button.innerHTML;
            button.innerHTML = txt + '<ins></ins>';
            container.__diffState = true;
        }
    }
};

