var featureLength = 0;
var current = 0;
var tid = 0;

function rotateFeature(offset) {
	clearTimeout(tid);
	var index = current + offset;
	var old_current = current;
	if (index != current) {
		if (index < featureLength) {
			if (index < 0) {
				current = featureLength - 1;
			} else {
				current = index;
			}
		} else {
			current = 0;
		}
		// rotate features
		switchDivs(old_current, current);
		
	}
	autoRotate();
}

function rotateFeatureUpdate(offset) {
	clearTimeout(tid);
	var index = current + offset;
	var old_current = current;
	if (index != current) {
		if (index < featureLength) {
			if (index < 0) {
				current = featureLength - 1;
			} else {
				current = index;
			}
		} else {
			current = 0;
		}
		// rotate Feature
		switchDivs(old_current, current);
	}
	tid = setTimeout('rotateFeature(1)',12000);
} 

function rotateFeaturePause() {
	clearTimeout(tid);
}

function rotateFeatureResume() {
	tid = setTimeout('rotateFeature(1)', 12000);
}

function switchDivs(oldnum, newnum) {
	old_id = "feature_" + oldnum;
	new_id = "feature_" + newnum;
	
	if( old_id && new_id ) {
		var old_obj = $( "#" + old_id );
		if( old_obj.hasClass("hidden") ) {
			old_obj.removeClass("hidden");
			old_obj.addClass("show");
		} else {
			old_obj.addClass("hidden");
			old_obj.removeClass("show");
		}
		
		var new_obj = $( "#" + new_id );
		new_obj.removeClass("hidden");
		new_obj.addClass("show");
		
		$( '#xofy' ).html( (newnum+1) + ' of ' + featureLength );
	}
}


function autoRotate() {
	tid = setTimeout('rotateFeature(1)',12000);
}

function pauseOnHover() {
	
	$( 'div.features' ).hover(
		function() {
			rotateFeaturePause();
		}, function() {
			rotateFeatureResume();
		}
	);
	
}


function startRotator() {

	if( featureLength > 1 ) {
		pauseOnHover();
		autoRotate();
	}

}

$( document ).ready( function() {
	
	startRotator();
	
} );
