var globalTimer;
var storyTimer;
var currentStory;

function randomStory(){
	mystory = (Math.floor(Math.random()*4))+1;
	currentStory = mystory;
	activateStory($('#story'+mystory+'-link'));
}	

function nextStory(){
	numStories = $('#stories .story').size();
	if (currentStory < numStories) {
		currentStory++;
	} else {
		currentStory = 1;
	}
	return $('#story'+currentStory+'-link').get(0);
}

function swapStory(storyid){
	if (globalTimer){
		globalTimer.stop();
	}
	if (storyTimer){
		storyTimer.stop();
	}
	$("#screen img").fadeOut(1000);
	$("#stories b.niftyfill").remove();
	$("#"+storyid).fadeIn(1000).addClass('active');
	$("#"+storyid+"-screen").fadeIn(1000);
	$("#screen img.active").removeClass('active');
	$("#"+storyid+"-screen").addClass('active');
	rotateScreens();
	Nifty('div#stories,div#phone', 'same-height, none');
}

function activateStory(navlink){
	$('#storynav a').removeClass('active');
	$(navlink).addClass('active');
	storyid = $(navlink).attr('id').split("-")[0];
	if ($('.story.active').get(0)){
		$('.story.active').fadeOut(1000, function(e){
			swapStory(storyid);
		}).removeClass('active');
	} else {
		swapStory(storyid);		
	}
	$.timer(10000, function (timer) {
		storyTimer = timer;
		activateStory(nextStory());
		
	});
}

function rotateScreens(){
	activeWidth = $("#screen img.active").width();
	if (activeWidth > 100){
		$.timer(5000, function (timer) {
			globalTimer = timer;
			activeImage = $("#screen img.active").get(0);
			activePosition = $("#screen img.active").position();
			if (activeWidth > 100){
				if ((-1*(activePosition.left)+100)< activeWidth){
					$("#screen img.active").fadeOut(500, function(e){
						activeImage.style.left=(activePosition.left-100)+"px";
						$("#screen img.active").fadeIn(500);
					});
				} else {
					$("#screen img.active").fadeOut(500, function(e){
						activeImage.style.left="0";
						$("#screen img.active").fadeIn(500);
					});
				}
			}
		});
	}
}
function storyListeners() {
	$('#storynav a').each(
		function(e){
      $(this).click(function(g){
        g.preventDefault();
        activateStory(this); 
        return false;
      });
		}
	);
}


function headshotPreload(){
	tmp = new Array();
	$(".story img").each(function(e){
		tmp[e] = new Image();
		tmp[e].src = this.src;
	});
}

$(document).ready(function(){
	if(typeof(supersleight)!="undefined"){
		supersleight.init();
	}
	storyListeners();
	headshotPreload();
	rotateScreens();
	randomStory();
})
