﻿var Carousel = {

    timer: null,

    showItem: function($item) {
        $('#latest .selected')
            .stop()
            .css('backgroundColor', '#E5CDDB')
            .toggleClass('selected');

        $item
            .stop()
            .css('backgroundColor', '#745189')
            .toggleClass('selected');

        Carousel.changeMainPic($item);
    },

    changeMainPic: function($item) {
        var alt = $item.find('a').text(),
            src = $item.find('input').val(),
            href = $item.find('a').attr('href'),
            $links = $('#latest .mainPic a'),
            $current = $links.eq(0);

        if ($current.attr('href') !== href) {

            $links
                .stop()
                .not($current)
                .remove();

            var $img = $('<img />').attr({ alt: alt, src: src });

            $('<a></a>')
                .attr('href', href)
                .css({ 'zIndex': 10, opacity: 0 })
                .append($img)
                .insertAfter($current)
                .animate({ opacity: 1 }, 500, 'easeOutSine', function() {
                    $(this).css('zIndex', 20)
                });

            $current.animate({ opacity: 0 }, 500, 'easeInSine', function() {
                $(this).remove();
            });
        }
    },

    setTimer: function() {
        this.timer = window.setInterval(this.timerTick, 4000);
    },

    clearTimer: function() {
        window.clearInterval(this.timer);
    },

    timerTick: function() {
        var $item = $('#latest .selected'),
            $next = $item.next();

        if ($next.length === 0) {
            $next = $item.parent().children(':first-child');
        }

        Carousel.showItem($next);
    },

    initialize: function() {

        this.setTimer();

        $('#latest li').mouseenter(function() {
            Carousel.showItem($(this));
        });

        $('#latest').hover(
            function() {
                Carousel.clearTimer();
            },

            function() {
                Carousel.setTimer();
            }
        );
    }
};

$(document).ready(function() {

    Carousel.initialize();

});
