﻿/*!
* article.rotator.js
* ===========================================
* Copyright (c) 2011 Bauer Consumer Media Ltd
* -------------------------------------------
*/

var articleRotator = {
	panel: null,
	timer: null,

	init: function (id) {
		this.panel = $('#' + id);

		if (this.panel.length > 0) {
			this.setTimer();

			this.panel.find('li').mouseenter(function () {
				articleRotator.showItem($(this));
			});

			this.panel.hover(function () {
				articleRotator.clearTimer();
			}, function () {
				articleRotator.setTimer();
			});
		}
	},

	changeMainImage: function (item) {
		var heading = item.find('h3 a');
		var href = heading.attr('href');
		var src = item.find('input[type="hidden"]').val();

		var mainImgs = this.panel.find('.mainImage a');
		var currentImg = mainImgs.first();

		if (currentImg.attr('href') !== href) {
			this.panel.find('.mainHeading a')
				.stop()
				.css('opacity', 0)
				.text(heading.text())
				.attr('href', href)
				.attr('title', heading.attr('title'))
				.animate({ opacity: 1 }, 200);

			mainImgs.stop().not(currentImg).remove();
			var newImg = $('<img />').attr({ alt: '', src: src });

			$('<a></a>')
				.attr('href', href)
				.css({ 'zIndex': 10, opacity: 0 })
				.append(newImg)
				.insertAfter(currentImg)
				.animate({ opacity: 1 }, 500, function () {
					$(this).css('zIndex', 20)
				});

			currentImg.animate({ opacity: 0 }, 500, function () {
				$(this).remove();
			});
		}
	},

	clearTimer: function () {
		window.clearInterval(this.timer);
	},

	setTimer: function () {
		this.timer = window.setInterval(this.timerTick, 5000);
	},

	showItem: function (item) {
		articleRotator.panel.find('.selected').stop().removeClass('selected');
		item.stop().addClass('selected');
		articleRotator.changeMainImage(item);
	},

	timerTick: function () {
		var item = articleRotator.panel.find('.selected');
		var next = item.next().length > 0 ? item.next() : item.parent().children().first();
		articleRotator.showItem(next);
	}
};
