// JavaScript Document

(function($) {
	$.fn.homecarousel = function(settings) {
		
		
		var settings = jQuery.extend({
			images:				"#carousel-images",
			controls:			"#carousel-controls"
		}, settings);
		// Caching the jQuery object with all elements matched
		var c = this;
		var slides = $(settings.images+' li', c);
		var numslides = slides.length;
		if (numslides<=1) return false;
		
		var slide = 0;
		var timer;
		
		function _initialize(){
			_resetbuttons();
			_resettime();
		}
		
		function _resetbuttons(){
			var b = 0;
			$(settings.controls+' a',c).each(function(){
				if(!$(this).hasClass('previousslide') && !$(this).hasClass('nextslide')){
					$(this).unbind('click');
					$(this).bind('click', {b: b}, function(e){
						slide = e.data.b;
						_slide();
						return false;
					});
					if(b==slide){
						$(this).addClass('on');
					} else {
						$(this).removeClass('on');	
					}
					b++;
				} else if($(this).hasClass('previousslide')){
					$(this).unbind('click');
					$(this).bind('click', function(){
						_prev();
						return false;
					});
				} else if($(this).hasClass('nextslide')){
					$(this).unbind('click');
					$(this).bind('click', function(){
						_next();
						return false;
					});					
				}
			});
		}
		
		function _prev(){
			if(slide==0){
				slide = numslides-1;
			} else {
				slide--;	
			}
			_slide();
		}
		
		function _next(){
			if(slide==(numslides-1)){
				slide = 0;
			} else {
				slide++;	
			}
			_slide();
		}
		
		function _slide(){
			$(slides).each(function(s){
				if(s==slide){
					$(this).fadeIn();
				} else {
					$(this).fadeOut();
				}
			});
			_resettime();
			_resetbuttons();
		}
		
		function _resettime(){
			clearTimeout(timer);
			timer = setTimeout(function(){
				_next();
			}, 5000);
		}
		
		_initialize();

	};
})(jQuery);