// GLOBALS
var highestZ = 0;
var fadeSpeed = 200;
var animationSpeed = 550;

var currentSetId;
var currentFrameId;

// true if the last click event
// was fired by jQuery
var ghostClick = false;

var frameCoefficient = 0.8;
var menuSquished = false;

var blogURL = 'http://sbenine.wordpress.com/';
var currentHash;


var openDelay = 0;


// ONCE DOM'S LOADED
$(document).ready(function() {

	// SETUP

	// make sure to preserve percentage representation of test strips
	storeOriginalLeftPositions();
	
	// hide contents of strips
	$('.test-strip .inner').hide();
	
	// hide folder menu children
	$('#work-link').parent().find('ul').hide();
	$('#about-link').parent().find('ul').hide();
	$('#cv-link').parent().find('ul').hide();
	
	// make home link active
	$('#home-link').addClass('active');
	
	// start listening for resize events, then run the resize routine once so everything starts correctly
	$(window).bind('resize', function () {
		resizeProcedures();
	});
	resizeProcedures();	
		  
  // FIRST LEVEL MENU LINKS
  
	$('#home-link').click(function(event) {
		event.preventDefault();
		
		// clear the hash
		window.location.hash = '';
		
		closeStrips();
		closeFolders();
		
		
		activateLink($(this));
	});
	
		
	$('#about-link').click(function(event) {
		event.preventDefault();

		activateLink($(this));
		
		// close other if open
		$('#cv-link').parent().find('ul').slideUp(animationSpeed);		
		$('#work-link').parent().find('ul').slideUp(animationSpeed);

		// open children
		$(this).parent().find('ul').slideDown(animationSpeed);

		// open the strip, then click first child kludge
		
		var tempThis = this;
		
		openStrip($('#about'), function() { $($(tempThis).parent().find('ul li a')[0]).click(); });
		
	});
	
	
	$('#work-link').click(function(event) {
		event.preventDefault();
		
		activateLink($(this));
		
		// close other if open
		$('#about-link').parent().find('ul').slideUp(animationSpeed);
		$('#cv-link').parent().find('ul').slideUp(animationSpeed);

		// open children
		$(this).parent().find('ul').slideDown(animationSpeed);

		if(!currentFrameId) {
			// make the first photo the current if needed
			var tempFirstPhoto = $('div#work div.inner div.photoset:first div.frame:first')[0];
			currentFrameId = '#' + tempFirstPhoto.id;					
		}
			
		
		var tempThis = this;
		// open strip click first child (what a mess)		
		openStrip($('#work'), function() { 		$($(tempThis).parent().find('ul li a')[0]).click(); });		
		


		
	});	
	
	$('#cv-link').click(function(event) {
		event.preventDefault();

		activateLink($(this));
		
		// close other if open		
		$('#work-link').parent().find('ul').slideUp(animationSpeed);
		$('#about-link').parent().find('ul').slideUp(animationSpeed);

		// open children
		$(this).parent().find('ul').slideDown(animationSpeed);
				
		var tempThis = this;		
		openStrip($('#cv'), function() { $($(tempThis).parent().find('ul li a')[0]).click(); });		
		
	});
	
	$('#blog-link').click(function(event) {
		event.preventDefault();
		openStrip($('#blog'));
		closeFolders();
		activateLink($(this));		
	});
	
	$('div#menu-arrow').click(function(event) {
		if (menuSquished) {
			growMenu();
		}
		else {
			squishMenu();
		}	
	});
	
	
	// SECOND LEVEL MENU LINK

	// Here's the scroll-to documentation
	// http://flesler.blogspot.com/2007/10/jqueryscrollto.html	

	// About Links
	$('#about-link').parent().find('ul li a').each(function(i) {
		
		// have it scroll to the frame of the same name
		$(this).click(function(event) {
			event.preventDefault();
			currentHash = String(this.id).replace('-link', '');
			var cleanId = '#' + currentHash + '-frame';
						
			// mark as active
			activateLink($(this));
			
			// set hash
			//console.log.log(cleanId);
			window.location.hash = currentHash;
			
			// scroll
			//console.log.log('scrolling to ' + cleanId);
			
			// pause if auto-click
			
			// need to wait the number of auto link


			//if(event.button != 0) {
		
			
			$('#about .inner').scrollTo(cleanId, animationSpeed, {easing: 'easeInOutCubic'});
			//setTimeout(function() { $('#about .inner').scrollTo(cleanId, animationSpeed, {easing: 'easeInOutCubic'});}, animationSpeed * openDelay);


			
		});
		
	});
	
	// Work Links
	$('#work-link').parent().find('ul li a').each(function(i) {
		
		// have it scroll to the set of the same name
		$(this).click(function(event) {
			event.preventDefault();		
			var cleanId = '#' + String(this.id).replace('-link', '');
			
			// mark as active
			activateLink($(this));	
			

			
			// store the current set
			currentSetId = cleanId;
			
			// make sure the click was human before doing this
			// assume that the current image is the first one
			currentFrameId = '#' + $(currentSetId).children()[0].id;
			
			// set hash
			window.location.hash = currentFrameId.replace('-frame', '');
			
			$('#work .inner').scrollTo(currentFrameId, animationSpeed, {easing: 'easeInOutCubic'});

			fadeArrows();
		});
		
	});	
	
	// CV Links
	$('#cv-link').parent().find('ul li a').each(function(i) {
		
		// have it scroll to the frame of the same name
		$(this).click(function(event) {			
			event.preventDefault();
			currentHash = String(this.id).replace('-link', '');
			var cleanId = '#' + currentHash + '-frame';
						
			// mark as active
			activateLink($(this));
			
			// set hash
			//console.log.log(cleanId);
			window.location.hash = currentHash;

			

			
			// scroll
			// pause if auto-click
			// reset the open delay if we have a real click



			//setTimeout(function() { $('#cv .inner').scrollTo(cleanId, animationSpeed, {easing: 'easeInOutCubic'});}, animationSpeed * openDelay);			
				$('#cv .inner').scrollTo(cleanId, animationSpeed, {easing: 'easeInOutCubic'});



				
					
		});
		
	});	


	
	// IMAGE OVERLAY NAVIGATION

	// Start with the left arrow hidden
	$('#left-arrow').hide();

	$('#left-arrow').click(function(event) {
		previousPhoto();
	});
	
	$('#right-arrow').click(function(event) {
		nextPhoto();
	});
	
	
	// Go to hash
	requestedHash = window.location.hash;
	////console.log.log.log(requestedHash);
	

	if((requestedHash != '') && (requestedHash != '#')) {
		// do we have one?
		////console.log.log.log("no hash");

		// try to locate the menu item		
		if($(requestedHash + '-link')[0]) {
		
			////console.log.log.log('menu hash found');
					
			$(requestedHash + '-link').parent().parent().parent().find('a:first').click();
		
			//$(requestedHash + '-link').pause(5000).click();
			
			setTimeout(function() { $(requestedHash + '-link').click(); }, animationSpeed * 2);
		}
		else if( $(requestedHash + '-frame')) {
			////console.log.log.log('frame hash found');
			
			////console.log.log.log($(requestedHash + '-frame'));
	
			// open work
			$('#work-link').click();
			
			// open photoset
			var photosetName = $(requestedHash + '-frame').parent()[0].id;
			var photosetLink = '#' + photosetName + '-link';

			setTimeout(function() { $(photosetLink).click();}, animationSpeed * 2);

			// scroll to photo
			setTimeout(function() { $('#work .inner').scrollTo($(requestedHash + '-frame'), animationSpeed, {easing: 'easeInOutCubic'}); }, animationSpeed * 3);		
			currentFrameId = requestedHash + '-frame';
			////console.log.log.log('current frame');
			////console.log.log.log(currentFrameId);
			fadeArrows();			

		}
	
	}
		

});



// After the DOM stuff is finished, load the images in the background
$(window).load(function() {

	function loadImages() {
		// Find all the image placeholders
		var imageHolders = $('div.load-background');
			
		// Iterate through each one
		imageHolders.each(function(i) {
			// Grab the source from the placeholder's ID
			var source = $(this).attr('id');
						
			var img = new Image();
				 
			$(img).hide();
			$(img).attr('src', source);
			$(this).html(img); // put the image inside the loader
			
			// Fade it in once it's loaded, and remove the border from the parent.
			$(img).load(function() {
				$(img).parent().removeClass('load-background');
				$(img).fadeIn(fadeSpeed);
			});
			
		});

	}
	
	loadImages();

});


// KEYBOARD NAVIGATION
$(document).keydown(function(k) {
	//console.log(k.keyCode);

	// Left arrow	
	if(k.keyCode == 37) {
		previousPhoto();
	}

	// Right arrow	
	if(k.keyCode == 39) {
		nextPhoto();
	}
});


// FUNCTION LIBRARY

// PHOTO NAVIGATION
var nextPhoto = function() {
	// get next frame
	var nextFrame = $(currentFrameId).next()[0];
	

	// scroll to it, if it exists
	if (nextFrame) {
		$('#work .inner').scrollTo(nextFrame, animationSpeed, {easing: 'easeInOutCubic'});
		currentFrameId = '#' + nextFrame.id;
	}
	else {
		// scroll to next set, if it exists
		var nextSet = $(currentSetId + '-link').parent().next().find('a')[0];
		
		if (nextSet) {
			$(nextSet).click();
		}

	}
	
	// set the hash	
	////console.log.log.log(currentFrameId);
	
	if(nextFrame || nextSet) {
		window.location.hash = IdUnFrame(currentFrameId);	
	
		fadeArrows();		
	}
}


var activateLink = function(link) {
	// deactivate siblings
	link.parent().parent().find('a').each(function(i) {
		if($(this).hasClass('active')) {
			$(this).removeClass('active');
		}
	});
	
	// activate self
	link.addClass('active');
}

var previousPhoto = function() {
	// get previous frame
	var previousFrame = $(currentFrameId).prev()[0];


	// scroll to it, if it exists	
	if (previousFrame) {
	
		$('#work .inner').scrollTo(previousFrame, animationSpeed, {easing: 'easeInOutCubic'});
		currentFrameId = '#' + previousFrame.id;


	}
	else {
		// scroll to the previous set, if it exists
		var previousSet = $(currentSetId + '-link').parent().prev().find('a')[0];
		
		if (previousSet) {
		

			$(previousSet).click();
			
			var lastFrame = $(currentSetId + ' div.frame:last-child')[0];			
			
			// and scroll to last photo
			$('#work .inner').scrollTo(lastFrame, animationSpeed, {easing: 'easeInOutCubic'});
			currentFrameId = '#' + lastFrame.id;
			
		}
		
	}

	if(previousFrame || previousSet) {
		// set the hash	
		////console.log.log.log(currentFrameId);
		window.location.hash = IdUnFrame(currentFrameId);
		
		fadeArrows();
	}
}


// removes '-frame' from the end of an ID string
var IdUnFrame = function(id) {
	return id.substr(0, id.length - 6)
}

// Arrow Fading
var fadeArrows = function() {
	var veryFirstPhoto = $('div#work div.inner div.photoset:first div.frame:first')[0];
	var veryLastPhoto = $('div#work div.inner div.photoset:last div.frame:last')[0];
	
	var veryFirstPhotoId = '#' + veryFirstPhoto.id;
	var veryLastPhotoId = '#' + veryLastPhoto.id;
	
	if (currentFrameId == veryFirstPhotoId) {
		// fade the left arrow
		$('#left-arrow').fadeOut(fadeSpeed);
	}
	else {
		// fade in if necessary
		$('#left-arrow').fadeIn(fadeSpeed);		
	}
	
	if (currentFrameId == veryLastPhotoId) {
		$('#right-arrow').fadeOut(fadeSpeed);	
	}
	else {
		$('#right-arrow').fadeIn(fadeSpeed);	
	}
}


// RESIZING
var resizeProcedures = function() {
	setPhotoFrameWidth();
	centerImages();
	
	// keep the current frame in the center
	if (currentFrameId) {
		$('#work .inner').scrollTo(currentFrameId, 0);
	}
	
	// position the arrows vertically
	var navArrowPosition = ($(window).height() / 2) - 25;
	$('div#left-arrow').css('top', navArrowPosition + 'px');
	$('div#right-arrow').css('top', navArrowPosition + 'px');
	
	// make sure the teaser is a static width
	$('#teaser').css('width', ($(window).width() * 0.18) + 'px');
}

// control the menu
var squishMenu = function() {
	menuSquished = true;
	
	$('div#menu-arrow').fadeOut(fadeSpeed, function() {
		$('div#menu-arrow').addClass('squished');
			$('div#menu-arrow').css('width', '100%');
			$('div#menu-arrow').fadeIn(fadeSpeed);
	});	
		
	
	$('#menu ul').fadeOut(fadeSpeed);
	
	$('#menu').animate({left: 0, width: '1.5%'}, animationSpeed, 'easeInOutCubic');
	
	
	// move the arrow over
	$('div#left-arrow').animate({left: '1.5%'}, animationSpeed, 'easeInOutCubic');
	
	
	// expand the work... add boolean check?
	$('div#work').animate({left: '1.5%', width: '98.5%'}, animationSpeed, 'easeInOutCubic');
		
	
	frameCoefficient = 0.985;
	animatePhotoFrameWidth();
}

var growMenu = function() {
	menuSquished = false;

	
	$('div#menu-arrow').fadeOut(fadeSpeed, function() {
		$('div#menu-arrow').removeClass('squished');
			$('div#menu-arrow').css('width', '7.5%'); // 7.5% of parent is 1.5% of the whole screen
			$('div#menu-arrow').fadeIn(fadeSpeed);
	});	
	
	$('#menu').animate({left: 0, width: '20%'}, animationSpeed, 'easeInOutCubic', function() {
		$('#menu ul').fadeIn(fadeSpeed);
		$('#about-link').parent().find('ul').hide(); // fix weird expanding menu bug
		$('#cv-link').parent().find('ul').hide(); // fix weird expanding menu bug			
	});
	
	$('#work').animate({left: '20%', width: '80%'}, animationSpeed, 'easeInOutCubic');
	
	// move the arrow back over
	$('div#left-arrow').animate({left: '20%'}, animationSpeed, 'easeInOutCubic');
	

	
	// contract the work... add boolean check?
	$('div#work').animate({left: '20%', width: '80%'}, animationSpeed, 'easeInOutCubic', function() {

	
	
	});

	frameCoefficient = 0.8;	
	animatePhotoFrameWidth();
}


var setPhotoFrameWidth = function() {
	$('div.photoset div.frame').css('width', $(window).width() * frameCoefficient);
	$('div.photoset div.frame').css('height', $(window).height());
}



// smooth version of above for the menu squish and grow
var animatePhotoFrameWidth = function() {
	$('div.photoset div.frame').animate({width: $(window).width() * frameCoefficient}, animationSpeed, 'easeInOutCubic');
	$('div.photoset div.frame').css('height', $(window).height());

	// get our index
	var thisFrameIndex = $(currentFrameId).attr('class').split(' ').pop().split('-').pop();
	var eachFrameWidth = $(window).width() * frameCoefficient;
	var totalOffset = thisFrameIndex * eachFrameWidth;
	
	

	$('#work .inner').scrollTo(totalOffset + 'px', { duration: animationSpeed, axis:'x', easing:'easeInOutCubic'});

}

var centerImages = function() {
	// also centers video...
	$('div.photoset div.frame .center').each(function(i) {
		// container height minus image height dividided by 2
		var topMargin =  Math.round((parseInt($(this).parent().css('height')) - parseInt($(this).css('height'))) / 2);

		// set margin
		$(this).css('margin-top', topMargin);
	});
}


// TEST STRIPS

var storeOriginalLeftPositions = function() {
	// first time, undefined, store the starting left position
	$('.test-strip').each(function(i) {
		$(this).attr('originalLeft', (i * 20) + '%');
	});
}

// get the test strip element that's currently open
var findOpenStrip = function(strip) {
	var result = false
	
	$('.test-strip').each(function(i) {
		if($(this).hasClass('open') && (this.id != strip.attr('id'))) {
			result = this;		
		}
	});
	
	return result;
}

// Open a test strip and close any that are already open
var openStrip = function(strip, callback) {
		
	if(!callback) {
		var callback = function() { };
	}	

		
	// erase the teaser no matter what
	$('#teaser').fadeOut(fadeSpeed);	
	
	// only open if it's not already open
	if(!strip.hasClass('open')) {
	
		// open it
		strip.addClass('open');
	
		// find the old strip, to close if need be		
		var oldOpenStrip = findOpenStrip(strip);
	
		// default open strip position and width
		var leftPosition = '20%';
		var newWidth = '80%';
		
		// special case for work
		if(strip[0].id == 'work') {
			leftPosition = '1.5%';
			newWidth = '98.5%';
		}
	
		if(oldOpenStrip) {
			$(oldOpenStrip).removeClass('open');
			$(oldOpenStrip).children('.inner').fadeOut(fadeSpeed);
			$(oldOpenStrip).animate({left: $(oldOpenStrip).attr('originalLeft'), width: '20%'}, animationSpeed, 'easeInOutCubic', function() {
				strip.css('z-index', ++highestZ);
				
				if(oldOpenStrip.id == 'work') {
					$('div#menu-arrow').fadeOut(fadeSpeed);				
				}

				if(strip[0].id == 'work') {
					squishMenu();
				}

				strip.animate({left: leftPosition, width: newWidth}, animationSpeed, 'easeInOutCubic', function() {
					strip.children('.inner').fadeIn(fadeSpeed);
					callback();
					



					// redirect if we just opened the blog
					if(this.id == 'blog') {
						//window.location = '/blog';
						window.location = blogURL;
					}
					
					
				});

			});
		}
		else {
			// opening for the first time
			strip.css('z-index', ++highestZ);

			// close the menu if it's the work strip
			if(strip[0].id == 'work') {
				squishMenu();					
			}
				
			// open the strip
			strip.animate({left: leftPosition, width: newWidth}, animationSpeed, 'easeInOutCubic', function() {
				// then fade it in
				strip.children('.inner').fadeIn(fadeSpeed);
				callback();
				
				// redirect if we just opened the blog
				if(this.id == 'blog') {
					window.location = blogURL;
				}

			});
		
		}
	}	
	
}

var closeStrips = function() {

		$('div#menu-arrow').fadeOut(fadeSpeed);
		
		$('.open .inner').fadeOut(fadeSpeed, function() {
			$('.open').animate({left: $('.open').attr('originalLeft'), width: '20%'}, animationSpeed, 'easeInOutCubic', function() {
			
					$('#teaser').fadeIn(fadeSpeed);
			
			});
			$('.open').removeClass('open');
		});
}

var closeFolders = function() {
	// close others if open
	
	$('#about-link').parent().find('ul').slideUp(animationSpeed);
	$('#about-link').removeClass('active');
	$('#work-link').parent().find('ul').slideUp(animationSpeed);
	$('#work-link').removeClass('active');
	$('#cv-link').parent().find('ul').slideUp(animationSpeed);
	$('#c-link').removeClass('active');	
}



// via http://stackoverflow.com/questions/251204/delay-jquery-effects
$.fn.pause = function(duration) {
    $(this).animate({ dummy: 1 }, duration);
    return this;
};


//	static public const FLICKR_API_KEY:String = "6c56ce9998f83a2cbdaa118a7de5da40";
//	static public const FLICKR_SHARED_SECRET:String = "68d7bd74397fbed2";
// http://api.flickr.com/services/rest/?method=flickr.test.echo&name=value