var timer = null;
$(function(){
	
	if($('.scrollable').get(0)){
		$('.items li:first').addClass('first');
		$('.items li:last').addClass('last');
		var SIZE = 5;
		var api;
		var img;
		var slidesow = false;
		$('.scrollable').scrollable({keyboard:true,onBeforeSeek : function(e,tab){ if(tab == (this.getSize()-(SIZE-1)) || (this.getSize()-(SIZE-1) )<1){  return false; } } });
		api = $('.scrollable').data('scrollable');
		$('.scrollable').mousewheel(function(event, delta){ if(delta<0){ api.prev(); }else{ api.next(); } });
		
		$('.items li a').click(function() {
			if ($(this).parent('li').hasClass('active')) { return false; }
			var url = $(this).attr('href');
			var wrap = $('#image_wrap');
			if(img) $(img).unbind('load');
			img = new Image();
			$(img).bind('load', function(){
				wrap.css({backgroundImage:'url('+url+')'});
				wrap.find('.caption').html($('.items li.active a img').attr('alt'));
				wrap.fadeTo('fast', 1);
			});
			$(img).attr('alt', $(this).attr('alt'));
			$('.items li').removeClass('active');
			$(this).parent('li').addClass('active');
			wrap.fadeTo('medium', 0,function(){img.src = url;});
			return false;
		}).filter(':first').click();
		
		$('.navigator a.previousImg').click(function(){
			if(!slidesow){
				if($('.items li.active').prev().get(0)){
					$('.items li.active').prev().find('a').click();
				}
			}
		});
		$('.navigator a.nextImg').click(function(){
			if(!slidesow){
				if($('.items li.active').next().get(0)){
					$('.items li.active').next().find('a').click();
				}
			}
		});
		$('.navigator a.toggleSlideShow').toggle(function(){
			$(this).addClass('stop').removeClass('play');
			slideshow(true);
		},function(){
			$(this).addClass('play').removeClass('stop');
			slideshow(false);
		});
	}	
});
function slideshow(state){
	if(state){
		if(timer == null){ 
			timer = setInterval('slideshow(true)',3000); 
		}else{
			if(!$('.items li.active').hasClass('last')){
				$('.navigator a.nextImg').click();
			}else{
				$('.items li:first a').click();
			}
		}
	}else{
		clearInterval(timer);
		timer = null;
	}
}
