jQuery(function($){
	
	duration = (typeof(duration) != "undefined")?duration:2;
	totalduration = (typeof(totalduration) != "undefined")?totalduration:duration * 1000 + 4000;
	var timer;
	
	jQuery(document).ready(function(){
	
		var itemLenth = $('.carousel').children().length;  // get no of items
		var currentIndex;
		var prevIndex = -1;
		/* set up timer to run */	
		var setUpTimer = function(eventduration){ 
			timer = setTimeout(function() {prevIndex = currentIndex++; moveItem(currentIndex);}, eventduration);
		}
		
		/* stop timer to run */	
		var stopTimer = function(){
			if (timer == null) return;
			clearTimeout(timer);
			timer = null;
		}
		
		/*load Carousel*/		
		var loadCarousel = function(){

			for(var i=1; i <= itemLenth ; i++){
				$('.carousel-button').append('<a href="#" class="carouselIndex_'+i+'" >&bull;</a> ');
				$('.carousel-button .carouselIndex_' + i).click(function(){
					prevIndex = currentIndex;
					currentIndex = parseInt($(this).attr('class').split('_')[1]);
					moveItem();
					return false;
				});
			}
			
			// add function if mouse over and leave an image 
			$(".carousel").bind("mouseenter",function(){
				stopTimer();
				$('.carousel .carousel-item:nth-child('+ currentIndex +')').stop();
				$('.carousel .carousel-item:nth-child('+ currentIndex +')').removeAttr("style");
				$('.carousel .carousel-item:nth-child('+ currentIndex +')').show();
				$('.carousel .carousel-item:nth-child('+ currentIndex +')').css('opacity',0.9999);
			}).bind("mouseleave",function(){
				stopTimer();
				$('.carousel .carousel-item:nth-child('+ currentIndex +')').stop();
				setUpTimer(1);
			});

			
			
			currentIndex = parseInt(Math.random()*itemLenth+1);
			moveItem(currentIndex);
		}
		
		var moveItem = function(){
			if(itemLenth < currentIndex) currentIndex = 1;			
			if(prevIndex == -1 || prevIndex != currentIndex){
				$('.carousel-button a').removeClass('tabup');
				$('.carousel-button .carouselIndex_' + currentIndex).addClass('tabup');
				$('.carousel > .carousel-item').hide();
				$('.carousel .carousel-item:nth-child('+ currentIndex +')').css('opacity','0');
				$('.carousel .carousel-item:nth-child('+ currentIndex +')').show();
				$('.carousel .carousel-item:nth-child('+ currentIndex +')').animate({opacity: 0.9999},duration * 1000, function () {
					stopTimer();
					setUpTimer(totalduration);
				});
			}else{
				stopTimer();
				setUpTimer(totalduration);
			}
		}
		loadCarousel();
	});
});
