$(document).ready(function(){

	/* universal variables */
	var headline_interval;
	var old_headline = 0;
	var current_headline = 0;
	var story_number = 0;
	var headline_count = $("#features li").size();
	var story_tabs = $("#chooser a");
	var play_stop_controls = $("#controls");
	
	/* play at start */
	var auto_start = "true"; // true or false
	if (auto_start == "true") {
		headline_interval = setInterval(headlineRotate,7000);
		startPlaying();
	}
	
	/* story rotation function */
	function headlineRotate(){
		current_headline = (old_headline + 1) % headline_count;
		$("#features li:eq(" + old_headline + ")").fadeOut(750);
		$("#features li:eq(" + current_headline + ")").fadeIn(750);
		story_tabs.removeClass("selected");
	 	$("#chooser a:eq(" + current_headline + ")").addClass("selected");
	 	old_headline = current_headline;
	}
	
	/* manual story selection */
	story_tabs.click(function(){
		if ($(this).attr("class") != "selected") {
			story_tabs.removeClass("selected");
			$(this).addClass("selected");
			story_number = $(this).attr("rel");
			$("#features li:visible").not("#f" + story_number).fadeOut(500);
			$("#f" + story_number + ":hidden").fadeIn(500);
			old_headline = (story_number - 1);
			stopPlaying();
		}
		return false;
	});
	
	/* show story headline title preview */
	story_tabs.hover(function(){
		story_number = $(this).attr("rel");
		$("#f" + story_number + " h2").clone().appendTo("#teaser");
	},function(){
		$("#teaser").empty();
	});
	
	/* convert to lowercase */
/*	$("#features li h2 a").each(function(){
		var title_text = $(this).text();
		title_text_lowered = title_text.toLowerCase();
		$(this).text(title_text_lowered);
	});*/
	
	/* add link indicator */
	$("#features h2 a").append("&nbsp;&raquo;");
	
	/* set features div height to accomodate tallest story */
	var max_story_height = 0;
	$("#features li").each(function(){
		if ($(this).height() > max_story_height) {
			max_story_height = $(this).height();
		}
	});
	$("#features").css("height",(max_story_height+20));
	play_stop_controls.css("top",max_story_height + 25); // reason: superfluous rule for safari because it positions this according to #features initial demensions

	/* play/stop button functions */
	$("#play a").click(function(){
		headline_interval = setInterval(headlineRotate,7000); //time in milliseconds
		startPlaying();
		return false;
	});
	$("#pause a").click(function(){
	 	clearInterval(headline_interval);
		stopPlaying();
		return false;
	});
	function startPlaying(){
	 	play_stop_controls.removeClass("paused");
	 	play_stop_controls.addClass("playing");
	}
	function stopPlaying(){
	 	clearInterval(headline_interval);
	 	play_stop_controls.removeClass();
	 	play_stop_controls.addClass("paused");
	}

});