/**
 * Fade Gallery
 * 
 * Copyright (c) 2010 Andrei Valuyev, Minsk Belarus for http://prointerior.by
 * mailto: a.valuyev@gmail.com
 *
**/

(function($){
	$.extend($.fn, {
		fadeGallery: function(options){
			return this.each(function() {

				if($(this).data('fadeGallery')) {
					var thisData = $(this).data('fadeGallery');

					if (typeof options == 'object') {
						thisData.opt = $.extend(thisData.opt, options);
					}
				} else {			
					$(this).data('fadeGallery', new FadeGallery (this, options));
				}
			});
		}
	});
	
	var FadeGallery = function(el, options) {
		var th = this;
		
		th.opt = $.extend({
			itemClass: 'galleryItem',
			pagerClass: 'galleryPager',
			fadeDelay: 800,
			delay: 5000,
			start: 0
		}, options);
		
		// save wraper
		th.wraper = $(el);
		
		// save wraper
		th.items = th.wraper.find('.'+th.opt.itemClass);
		
		//save items count
		th.itemsLength = th.items.length;
		
		//save pager
		th.pager = th.wraper.find('.'+th.opt.pagerClass+':first');
		
		th.timer = null;
		
		th.init();

		return th;
	};
	
	$.extend(FadeGallery.prototype, {
		init: function () {
			var th = this;
			
			var pagerHTML = '<ul>';
			
			for (var i=0; i<th.itemsLength; i++) {
				pagerHTML += '<li'+ (i + 1 == th.itemsLength ? ' class="last"' : '') +'><a href="javascript:void(0)"><i><!-- --></i><span>' + (i+1) + '</span></a></li>';
			}
			
			pagerHTML += '</ul>';
			
			th.pager.html(pagerHTML);
			
			if (th.opt.start >=0 && th.opt.start < th.itemsLength) {
				th.count = th.opt.start;
			} else {
				th.count = 0;
			}
			
			th.pagerItems = th.pager.find('a');
			
			th.pagerItems.eq(th.count).addClass('active');
			
			th.items.eq(th.count).show();
			
			th.pagerItems.bind('click.FadeGallery', function () {
				clearTimeout(th.timer);
				th.timer = null;
				
				th.hide();
				
				th.count = th.pagerItems.index($(this));
				
				th.show();
			});
			
			th.timerLoop();
		},
		
		timerLoop: function () {
			var th = this;
			
			th.timer = setTimeout(function () {
				th.hide();
				
				th.count++;
				
				if (th.count >= th.itemsLength) {
					th.count = 0;
				}
				
				th.show();
				
				th.timerLoop();
			}, th.opt.delay);
		},
		
		hide: function () {
			var th = this;
			
			th.items.eq(th.count).fadeOut(th.opt.fadeDelay);
			th.pagerItems.eq(th.count).removeClass('active');
		},
		
		show: function () {
			var th = this;
			
			th.items.eq(th.count).fadeIn(th.opt.fadeDelay);
			th.pagerItems.eq(th.count).addClass('active');
		}
	});
})(jQuery);



