/**
 * Created by JetBrains PhpStorm.
 * User: BoShurik
 * Date: 14.09.11
 * Time: 17:20
 * To change this template use File | Settings | File Templates.
 */

//$('#teaser img').slidingGallery({
//    container: $('#teaser'),
//    Lwidth: 422,
//    Lheight: 253,
//    galleryTop: 22,
//    gutterWidth: 40,
//    Lshrink: function(dimension) {
//        return dimension * 0.5;
//    },
//    useZoom: false
//});

(function($) {
    $.teaserUtility = {};
    $.teaserUtility.Options = {
        'selector' : null,    // Селектор для тизеров
        'zIndex'   : 0,      // Начальный z-index
        'evenRight': 0,  // Отступ справа для четных
        'oddRight' : 50, // Отступ справа для нечетных
        'margin': 0,         // Оступ от сверху/снизу
        'imgMarginTop': -20, // Оступ от предыдущего тизера
        'imgHeight': 124,    // Высота тизера //TODO: Высоту картинки можно и самому вычислять
        'newImgHeight': 200, // Высота увеличенного тизера //TODO: Высоту картинки можно и самому вычислять
        'newImgZIndex': 99   // z-index увеличенного тизера
    };

    function Teasers(element, options) {
        //global settings
        var self = this;
        if (options.selector) {
            var imgs = element.find(options.selector);
        } else {
            var imgs = element.find('img');
        }

        var lastIndex;
        var top = 0;

        var teasersSize = imgs.each(function(i){
            $(this).attr({
                'data-index': i,
                'data-prev': (i - 1),
                'data-next': (i + 1),
                'data-src': $(this).attr('src')
            }).css({
                'position': 'absolute',
                'z-index': options.zIndex + i,
                'top': top
            });

            if (i % 2 == 0) {
                $(this).attr('data-right', options.evenRight).css({
                    'right': options.evenRight
                });
            } else {
                $(this).attr('data-right', options.oddRight).css({
                    'right': options.oddRight
                });
            }

            top += $(this).height() + options.marginTop;
            lastIndex = i;
        }).hide().size();

        // Если количество тизеров меньше шести, то увеличить, чтобы было чему крутиться
        // Если количество тизеров нечетное, то увеличить в два раза, чтобы отступы лево/право чередовались

        if ((teasersSize < 6) || (teasersSize % 2 == 1)) {
            var currIndex = 0;
            var newTeasersSize = teasersSize;
            while ((newTeasersSize < 6) || (newTeasersSize % 2 == 1)) {
                newTeasersSize = newTeasersSize * 2;
            }
            while (teasersSize < newTeasersSize) {
                var clone = imgs.filter('[data-index="' + currIndex + '"]').clone().attr({
                    'data-index': lastIndex + 1,
                    'data-prev': lastIndex,
                    'data-next': lastIndex + 2
                });
                
                if ((lastIndex + 1) % 2 == 0) {
                    clone.attr('data-right', options.evenRight).css({
                        'right': options.evenRight
                    });
                } else {
                    clone.attr('data-right', options.oddRight).css({
                        'right': options.oddRight
                    });
                }

                imgs.filter('[data-index="' + (lastIndex) + '"]').after(clone);
                imgs = imgs.add('img[data-index="' + (lastIndex + 1) + '"]');

                lastIndex++;
                currIndex++;
                teasersSize++;
            }
        }

        imgs.filter('[data-index="' + lastIndex + '"]').attr('data-next', 0);
        imgs.filter('[data-index="0"]').attr('data-prev', lastIndex);

        // Рассчитаем положения для трех тизеров и невидимых контейнеров
        var positions = $.teaserUtility.definePositions(options)

        // Инициализируем начальный контейнер невидимых тизеров
        positions.firstImageStorage.image = imgs.filter(':last').css({
            top: positions.firstImageStorage.top
        });

        // Инициализируем первое место
        positions.firstImage.image = $(imgs[0]).css({
            top: positions.firstImage.top,
            zIndex: positions.firstImage.zIndex
        }).hover(function(){
            $.teaserUtility.hoverIn($(this), options, positions.firstImage);
        },
        function(){
            $.teaserUtility.hoverOut($(this), options, positions.firstImage);
        }).show();

        // Инициализируем второе место
        positions.secondImage.image = $(imgs[1]).css({
            top: positions.secondImage.top,
            zIndex: positions.secondImage.zIndex
        }).hover(function(){
            $.teaserUtility.hoverIn($(this), options, positions.secondImage);
        },
        function(){
            $.teaserUtility.hoverOut($(this), options, positions.secondImage);
        }).show();

        // Инициализируем третье место
        positions.thirdImage.image = $(imgs[2]).css({
            top: positions.thirdImage.top,
            zIndex: positions.thirdImage.zIndex
        }).hover(function(){
            $.teaserUtility.hoverIn($(this), options, positions.thirdImage);
        },
        function(){
            $.teaserUtility.hoverOut($(this), options, positions.thirdImage);
        }).show();

        // Инициализируем конечный контейнер невидимых тизеров
        positions.lastImageStorage.image = $(imgs[3]).css({
            top: positions.lastImageStorage.top
        });

        $.extend(self, {
            prev: function(e) {
                var animationCount = 4;
                // third > storage
                positions.thirdImage.image.unbind('mouseenter mouseleave').animate({
                    'opacity': 'hide',
                    'top': positions.lastImageStorage.top
                }, 'normal', 'linear', function() {}); // speed, easing, callback

                // second > third
                positions.secondImage.image.unbind('mouseenter mouseleave').animate({
                    'top': positions.thirdImage.top
                }, 'normal', 'linear', function() {}); // speed, easing, callback

                // first > second
                positions.firstImage.image.unbind('mouseenter mouseleave').animate({
                    'top': positions.secondImage.top
                }, 'normal', 'linear', function() {}); // speed, easing, callback

                // storage > first
                positions.firstImageStorage.image.unbind('mouseenter mouseleave').animate({
                    'opacity': 'show',
                    'top': positions.firstImage.top
                }, 'normal', 'linear', function() {
                    // TODO: А вдруг эта анимация закончится раньше всех? -_-
                    // Добавим событие на hover
                    positions.firstImage.image.hover(function(){
                        $.teaserUtility.hoverIn($(this), options, positions.firstImage);
                    },
                    function(){
                        $.teaserUtility.hoverOut($(this), options, positions.firstImage);
                    });

                    positions.secondImage.image.hover(function(){
                        $.teaserUtility.hoverIn($(this), options, positions.secondImage);
                    },
                    function(){
                        $.teaserUtility.hoverOut($(this), options, positions.secondImage);
                    });

                    positions.thirdImage.image.hover(function(){
                        $.teaserUtility.hoverIn($(this), options, positions.thirdImage);
                    },
                    function(){
                        $.teaserUtility.hoverOut($(this), options, positions.thirdImage);
                    });
                }); // speed, easing, callback

                // Назначим новые картинки
                positions.lastImageStorage.image = positions.thirdImage.image.css('z-index', positions.lastImageStorage.zIndex);
                positions.thirdImage.image = positions.secondImage.image.css('z-index', positions.thirdImage.zIndex);
                positions.secondImage.image = positions.firstImage.image.css('z-index', positions.secondImage.zIndex);
                positions.firstImage.image = positions.firstImageStorage.image.css('z-index', positions.firstImage.zIndex);

                positions.firstImageStorage.image = imgs.filter('[data-index="'+ positions.firstImageStorage.image.attr('data-prev') +'"]').css({
                    top: positions.firstImageStorage.top,
                    'z-index': positions.firstImageStorage.zIndex
                });

                return self;
            },
            next: function(e) {
                // first > storage
                positions.firstImage.image.unbind('mouseenter mouseleave').animate({
                    'opacity': 'hide',
                    'top': positions.firstImageStorage.top
                }, 'normal', 'linear', function() {}); // speed, easing, callback

                // second > first
                positions.secondImage.image.unbind('mouseenter mouseleave').animate({
                    'top': positions.firstImage.top
                }, 'normal', 'linear', function() {}); // speed, easing, callback

                // third > second
                positions.thirdImage.image.unbind('mouseenter mouseleave').animate({
                    'top': positions.secondImage.top
                }, 'normal', 'linear', function() {}); // speed, easing, callback

                // storage > third
                positions.lastImageStorage.image.unbind('mouseenter mouseleave').animate({
                    'opacity': 'show',
                    'top': positions.thirdImage.top
                }, 'normal', 'linear', function() {
                    // TODO: А вдруг эта анимация закончится раньше всех? -_-
                    // Добавим событие на hover
                    positions.firstImage.image.hover(function(){
                        $.teaserUtility.hoverIn($(this), options, positions.firstImage);
                    },
                    function(){
                        $.teaserUtility.hoverOut($(this), options, positions.firstImage);
                    });

                    positions.secondImage.image.hover(function(){
                        $.teaserUtility.hoverIn($(this), options, positions.secondImage);
                    },
                    function(){
                        $.teaserUtility.hoverOut($(this), options, positions.secondImage);
                    });

                    positions.thirdImage.image.hover(function(){
                        $.teaserUtility.hoverIn($(this), options, positions.thirdImage);
                    },
                    function(){
                        $.teaserUtility.hoverOut($(this), options, positions.thirdImage);
                    });
                }); // speed, easing, callback

                // Назначим новые картинки
                positions.firstImageStorage.image = positions.firstImage.image.css('z-index', positions.firstImageStorage.zIndex);
                positions.firstImage.image = positions.secondImage.image.css('z-index', positions.firstImage.zIndex);
                positions.secondImage.image = positions.thirdImage.image.css('z-index', positions.secondImage.zIndex);
                positions.thirdImage.image = positions.lastImageStorage.image.css('z-index', positions.thirdImage.zIndex);

                positions.lastImageStorage.image = imgs.filter('[data-index="'+ positions.lastImageStorage.image.attr('data-next') +'"]').css({
                    'top': positions.lastImageStorage.top,
                    'z-index': positions.lastImageStorage.zIndex
                });

                return self;
            }
        });
    }

    $.fn.teasers = function(options) {
        var el = this.data("teasers");
		if (el) { return el; }

		options = $.extend(true, $.teaserUtility.Options, options);

		this.each(function() {
			el = new Teasers($(this), options);
			$(this).data("teasers", el);
		});

		return el;
    };

    $.teaserUtility.definePositions = function(options){
        return {
            firstImageStorage: {
                top: - options.imgHeight,
                zIndex: options.zIndex
            },

            firstImage: {
                top: options.margin,
                zIndex: options.zIndex + 1
            },
            secondImage: {
                top: options.margin + options.imgHeight + options.imgMarginTop,
                zIndex: options.zIndex + 2
            },
            thirdImage: {
                top: options.margin + (options.imgHeight + options.imgMarginTop) * 2,
                zIndex: options.zIndex + 3
            },

            lastImageStorage: {
                top: options.margin + options.imgHeight * 3,
                zIndex: options.zIndex + 4
            }
        };
    };

    $.teaserUtility.hoverIn = function(element, options, oldParams){       
        var right = element.attr('data-right');

        var newTop = Math.ceil(oldParams.top - (options.newImgHeight - options.imgHeight) / 2);
        var newRight = Math.ceil(right - (element.width() * (options.newImgHeight / options.imgHeight) - element.width()) / 2);

        element.attr('src', element.attr('data-large-src')).css({
            'z-index': options.newImgZIndex,
            'height': options.imgHeight,
            'top': oldParams.top,
            'right': right
        }).animate({
            'height': options.newImgHeight,
            'top': newTop,
            'right': newRight
        }, 'fast', 'linear', function() {});
    }

    $.teaserUtility.hoverOut = function(element, options, oldParams){
        var right = element.attr('data-right');

        element.stop(true, false).css({
            'z-index': oldParams.zIndex,
            'height': options.imgHeight +'px',
            'top': oldParams.top +'px',
            'right': right +'px'
        }).attr('src', element.attr('data-src'));
    }

})(jQuery);
