$(document).ready(function() {
	
	/**
	 * Scrollable 
	 */
	
		var clickedCarouselController = false;
		
		//Controller links get a name attribut (valid w3c), the Links now have the clickIndex, because srollableControllerApi.getClickIndex() is not working.
		scrollableControllerItems = $('#carousel_control_wrapper ul li a').size();
		for(i=0; i<=scrollableControllerItems; i++){
			$('#carousel_control_wrapper ul li a').eq(i).attr('name',i);
		}
		
		//Initialising of the receiver (the big images on the left)	 
	 	srollableReceiverApi = $("#carousel_floater").scrollable({
			size: 1, 
			speed: 400, 
			vertical: true, 
			loop: true,
			clickable: false
		}).circular({
			api: true
		});
		
		//Initialising of the controller (the small images on the right)
		srollableControllerApi = $("#carousel_control_wrapper").scrollable({
			size: 3, 
			speed: 400, 
			vertical: true,
			clickable: true,
			loop: true
		}).circular().autoscroll({
			autoplay: true, 
			api: true,
			interval: 4000
		});
		
		
		//This happens before the contoller moves automatically
		srollableControllerApi.onBeforeSeek(function(){
			if(clickedCarouselController == true){
				srollableReceiverApi.move(srollableControllerApi.getIndex()-srollableReceiverApi.getIndex()+1);//getMoveTo(srollableControllerApi.getIndex())+1) is somehow not working properly
				//Stop the scrolling for a while otherwise it's quite annoying
				srollableControllerApi.stop();
			}
		});

		//This happens when the contoller moves automatically
		srollableControllerApi.onSeek(function(){
			if (clickedCarouselController == false) {
				srollableReceiverApi.next();
			}else{
				setTimeout(function(){
					srollableControllerApi.play();
				}, 1000);
				clickedCarouselController = false;
			}
		});
		

		//This happens when you click a teaser in the controller
		$('#carousel_control_wrapper ul li a').click(function(){
			//Unfortunatly srollableControllerApi.getClickIndex() doesn't work properly. This makes it nessasary that we have a work around with $(this).attr('name'); 
			/*
			 * When you use the circular plugin the seekTo method is buggy. For this reason you need to use the move method.
			 * Otherwise you could use srollableReceiverApi.seekTo(parseInt($(this).attr('name')));...
			 */
			srollableReceiverApi.move(getMoveTo($(this).attr('name')));
			clickedCarouselController = true;
			return false;
			
		});
		

		


});

function getMoveTo(contollerPosition){
	if(contollerPosition < srollableReceiverApi.getIndex()){
		return contollerPosition - srollableReceiverApi.getIndex() + scrollableControllerItems;
	}else{
		return contollerPosition - srollableReceiverApi.getIndex();
	}
}