﻿var Carousel = {

	timer: null,

	showItem: function ($item) {
		$('#carouselContent .selected')
            .stop()
            .toggleClass('selected');

		$item
            .stop()
            .toggleClass('selected');

		Carousel.changeMainPic($item);
	},

	changeMainPic: function ($item) {
		var alt = $item.find('h3 a').text(),
            src = $item.find('.image').val(),
            excerpt = $item.find('.excerptText').val(),
            href = $item.find('h3 a').attr('href'),
            $links = $('#carouselContent .mainPic a'),
            $current = $links.eq(0);

		if ($current.attr('href') !== href) {

			$links
                .stop()
                .not($current)
                .remove();

			var $img = $('<img />').attr({ alt: alt, src: src });

			$('.excerpt').html('<p>' + excerpt + '</p>');

			$('<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 = $('#carouselContent .selected'),
            $next = $item.next();

		if ($next.length === 0) {
			$next = $item.parent().children(':first-child');
		}

		Carousel.showItem($next);
	},

	initialize: function () {

		this.setTimer();

		$('#carouselContent li').bind('mouseenter', function () {
			Carousel.showItem($(this));
		});

		$('#carouselContent').hover(
            function () {
            	Carousel.clearTimer();
            },

            function () {
            	Carousel.setTimer();
            }
        );
	}
};

$(document).ready(function () {
	Carousel.initialize();
});
