jQuery(document).ready(function($){
	var currentIndex=1;
	var arr_images = $("#tdslideshow");
	var tid;
	var playing = true;
	
	//globally accessible functions
	window.nextOrPreviousClick = function (i){
		pause();
		changeImg(i);
	}
	
	window.playPause = function(){
		if (playing) {
			pause();
		}
		else {
			play();
		}
	}
	
	//private functions
	function changeImg(i){
		var rc = $("#tdslideshow img").size();
		var oldIndex = currentIndex;
		if(rc > 1){
			currentIndex = currentIndex+i;
			if(currentIndex > rc){
				currentIndex = 1;
			}
			if(currentIndex < 1){
				currentIndex = rc;
			}
			var $next = $("#img" + currentIndex);
			var $active = $("#img" + oldIndex);
			
			$("#tdindex").html(currentIndex);
			$active.addClass('last-active');
		    $next.css({opacity: 0.0})
		    .addClass('active')
		    .animate({opacity: 1.0}, 1000, function() {
		            $active.removeClass('active last-active');	
		    });
		}
	}
	
	function play() {	
		changeImg(1);
		tid = setInterval(function(){changeImg(1);},5000);
		playing = true;
		$(".tdplaybuttons #tdpause").show();
		$(".tdplaybuttons #tdplay").hide();
	}
	
	function pause() {	
		clearInterval(tid);
		playing = false;
		$(".tdplaybuttons #tdplay").show();
		$(".tdplaybuttons #tdpause").hide();
	}
	
	tid = setInterval(function(){changeImg(1);},5000);
});
