//
// $Id: advanced_banner.js 8787 2010-02-04 08:04:02Z klerik $
//

(function($){

	function advancedBanner(elem, conf)
	{
		var self = this;
		var elem = $(elem);
		var interval_id;

		elem.current_index = 0;

		if (conf.speed > conf.delay) {
			conf.delay = conf.speed + 100;
		}

		var items = $('.banner-items-holder', elem).children();
		var items_count = items.length;
		var first_item = $('.nav-item', elem).eq(0);

		for (var i = 2; i <= items_count; i++) {
			first_item.clone().text(i).insertAfter($('.nav-item:last', elem));
		}

		items.each(function(ind) {
			$(this).css('z-index', items_count - ind);
		});
		items.eq(0).show();

		$('.nav-item', elem).eq(0).addClass(conf.current_class);
		$('.nav-item', elem).click(function() {
			var index = $('.nav-item', elem).index(this);
			if (index != elem.current_index) {
				self.switchElements(elem.current_index, index);
			}
			self.restartSlideShow();
		});
		$('.prev-item', elem).click(function() {
			self.prevElements();
			self.restartSlideShow();
		});
		$('.next-item', elem).click(function() {
			self.nextElements();
			self.restartSlideShow();
		});

		$('.banner-nav-panel', elem).css('z-index', items_count).show();

		jQuery.extend(self,
		{
			switchElements: function(prev, next)
			{
				items.eq(prev).fadeOut(conf.speed);
				items.eq(next).fadeIn(conf.speed);
				elem.current_index = next;
				$('.nav-item', elem).removeClass(conf.current_class).eq(elem.current_index).addClass(conf.current_class);
			},
			nextElements: function()
			{
				var next_ind = elem.current_index + 1 >= items_count ? 0 : elem.current_index + 1;
				self.switchElements(elem.current_index, next_ind);
			},
			prevElements: function()
			{
				var prev_ind = elem.current_index - 1 < 0 ? items_count - 1 : elem.current_index - 1;
				self.switchElements(elem.current_index, prev_ind);
			},
			startSlideShow: function()
			{
				interval_id = setInterval(self.nextElements, conf.delay);
			},
			restartSlideShow: function()
			{
				clearInterval(interval_id);
				self.startSlideShow();
			}
		});
		self.startSlideShow();
	};

	jQuery.fn.advancedBanner = function(conf)
	{
		var defaultConf = {
			speed: 1000,
			delay: 5000,
			current_class: 'strong'
		};
		jQuery.extend(defaultConf, conf);

		return this.each(function()
		{
			new advancedBanner(this, defaultConf);
		});
	};

})(jQuery);