$.fn.disableSelection = function() {
    $(this).attr('unselectable', 'on')
           .css('-moz-user-select', 'none')
           .each(function() { 
               this.onselectstart = function() { return false; };
            });
};

$(function() {	
	$('#introslider').disableSelection();

	var time				= 4000;
	var autoplay			= true;
	var onmousestop			= true;
	/*
	caching
	*/
	var $slider_apps		= $('#slider_apps');
	var $items				= $slider_apps.children('li');
	var $preview_container	= $('#preview_container');
	var $slides				= $preview_container.children('.preview');
	var total_slides		= $slides.length;
	var slide_width			= $preview_container.children('.preview :first').outerWidth();
	var current				= 0;
	var slideshow_time;
	var carousel;
	/*
	carousel init
	*/
	$slider_apps.jcarousel({
		visible: 5,
        initCallback: mycarousel_initCallback
    });

	function mycarousel_initCallback(initializedCarousel) {
		carousel = initializedCarousel;
	};

	/*
	the width of the preview_container is the sum of the widths of all preview divs
	*/
	$preview_container.css('width', (total_slides*slide_width) +'px');
	/*
	when clicking on the items in the carousel,
	the corresponding slide will appear.
	the preview container will animate its left.
	*/
	$items.bind('click',function(){
		var $item	= $(this);
		autoplay 	= false; 
		clearInterval(slideshow_time);
		slideTo($item);
	});
	
	function slideTo($item){
		var idx		= $item.index();
		carousel.scroll(idx);
		$slider_apps.find('.selected').removeClass('selected');
		$item.addClass('selected');
		
		$preview_container.stop()
						  .animate({
							'left'	: -idx * slide_width + 'px'
						  },600);
	}
	
	function slideshow(){
		slideshow_time = setInterval(function(){
			autoslide()
		},time);
	}
	
	function autoslide(){
		++current;
		if(current >= total_slides)
			current = 0;
		slideTo($items.eq(current));
	}
	
	if(autoplay){
		slideshow();
	}
	
	if(onmousestop){
	$preview_container.parent()
					  .bind('mouseenter',function(){
						if(autoplay)
							clearInterval(slideshow_time);
					  })
					  .bind('mouseleave',function(){
						if(autoplay)
							slideshow();
					  });
	}
});
