var slider = 0;
var timer = 11000;
var timeoutId = 0;

function caption( time ){
	$(".pic:first").children(".caption").css({opacity: 0.8, "top":"0px"}).animate({"top": "-45px"}, 1000, function(){
		$(this).fadeTo((time-3500), 0.8, function(){
			$(this).animate({"top":"0px"},1000);
		});
	});
}

function forwardSlide( time ){
	$("#leftSlide").animate({"top":"-304px"}, 1000, function(){
		$("#leftSlide").css({"top":"0px"}).children(":first").remove().appendTo("#leftSlide");
	});
	
	$("#rightSlide").animate({"left":"-356px"},1000, function(){
		$("#rightSlide").css({"left":"0px"}).children(":first").remove().appendTo("#rightSlide");
		caption( time );
	});
}
function backSlide( time ){
	$("#leftSlide").children(":last").remove().prependTo("#leftSlide").css({"top":"-304px"}).animate({"top":"0px"},1000);
	
	$("#rightSlide").children(":last").remove().prependTo("#rightSlide").css({"left":"0px"}).animate({"left":"0px"},0, function(){
		caption( time );
	});
}

$(function(){
	$('.text p').each(function(){
		var text = $(this).html();
		if(text.length > 350){
			var splitspot = text.indexOf(' ', 300);
			var newStr = text.substring(0, splitspot);
			$(this).html( newStr + " ...");
		}
	});

	caption( timer+1500 );
	
	slider = setInterval( "forwardSlide( timer )", timer);
	
	$(".prev").click(function(){
		clearTimeout(timeoutId);
		$(".pic .caption").css({"top":"0px"});
		backSlide(timer);
		clearInterval(slider);
		slider = 0;
		$(".pause").text('>');
		timeoutId = setTimeout("$('*').stop()", 2000);
	});
	$(".next").click(function(){
		clearTimeout(timeoutId);
		$(".pic .caption").css({"top":"0px"});
		forwardSlide(timer);
		clearInterval(slider);
		slider = 0;
		$(".pause").text('>');
		timeoutId = setTimeout("$('*').stop()", 2000);

	});
	$(".pause").click(function(){
		if( slider == 0 ){
			slider = setInterval( "forwardSlide( timer )", timer);
			$(this).text('II');
		}
		else{
			clearInterval(slider);
			slider = 0;
			$(".pause").text('>');
			$('*').stop();
		}
	});
	$(".pic").children().click(function(){
		$(".pause").text('>');
		timeoutId = setTimeout("$('*').stop()", 10);
	});

});