$(document).ready(function(){
	
	// An Array of our Background Colors in Order
	var bgColor = ['#001A42', '#609F0A', '#000000'];
	
	// For readability I have put the controls in a variable - You can also hard code these in the HTML if you like
	var controls = '<div id="controls"><div class="control" id="next"></div><div class="control" id="prev"></div></div>';
	
	// Set which item will be visible on load
	var position = 0;
        
        // Get Last Feature Item
	var endPostion = $('.feature').size()-1;
	
	//Set Timer Delay in Milliseconds
	var timer = 7000;
	var featureTimer = setInterval(featureSwitch, timer);
	
	// Onload Show Prev & Next Buttons
	$('#featureWrapper').after('<div id="control_wrapper">'+controls+'</div>');
	
        // Onload, run changeFeature function to set feature item and background color
        changeFeature(position, bgColor[position]);
	
	// OnClick li, if already visible do nothing, else show the featured div and change active state
	$('.featureTabs li').click(function(){	
		position = $(this).index('.featureTabs li');
		if ( $('.feature').eq(position).is(':visible') ) {
			return false;
		} else {			
			clearInterval(featureTimer); // Clear current timer
 			featureTimer = setInterval(featureSwitch, timer); // Call Timer function again
			changeFeature(position, bgColor[position]);
			return false;
		}
	});
	
	// Timer Function - Switch Every Time function is called
	function featureSwitch(){
		if (position == endPostion){
			position = 0
		} else {
			position++;
		}
		clearInterval(featureTimer); // Clear current timer
		featureTimer = setInterval(featureSwitch, timer); // Call timer function again
		changeFeature(position, bgColor[position]);	
	}

	
	// OnClick Contorls
	$('.control').click(function(){
		position = $('.feature:visible').index('.feature');
		if ( $(this).attr('id') == 'next' ) {
			if (position == endPostion) {
				position = 0;
			} else {
				position++;
			}
		} else {
			if (position == 0) {
				position >= endPostion;
			} else {
				position--;
			}
		}
		changeFeature(position, bgColor[position]);
	});
	
	
});

function changeFeature (position, bgColor) {
	$('.feature').fadeOut(200);			
	jQuery('#featureWrapper').delay(200).animate({ backgroundColor: bgColor }, 200);
	$('.feature').eq(position).delay(400).fadeIn(200);
	$('.featureTabs li').eq(position).addClass('active').siblings().removeClass('active');
}



