//
// core.js
//
var visX = 0;
var visY = 0;
var secAnimate = false;
var projAnimate = false;
var imgAnimate = false;

var scrollVert = false;

function switchProject(projRef)
{
	$(projRef).parent().children().children().removeClass('selected-link');
	$(projRef).children().addClass('selected-link');
	
	var clicked = parseInt($(projRef).attr('id').split('-')[2]);		
	var moveLeft = $('.single-project').width() + parseInt($('.single-project').eq(1).css('margin-left').replace('px',''));
	
	projAnimate = true;
	$(".section-container").eq(getCurSection()).animate({
		'left': -1*moveLeft*clicked
	},'normal',function(){ projAnimate = false; });
	
	setScrollPosition(clicked,getCurSection(),400);

	lazyLoad(getCurSection(),clicked);
}

function switchSection(secRef,callback)
{
	if($(secRef).siblings().eq(0).css('display') == 'none')
	{	
		// slide menu items up or down
		$('.section-title').siblings('.section-collection:visible').slideUp('fast');
		$(secRef).siblings('.section-collection').slideDown('fast');
		
		// move sections
		var clicked = parseInt($(secRef).attr('id').replace("sec-", ""));
		var sectionSpacing = parseInt($(".section-container").eq(1).css('margin-top').replace('px',''));
		
		secAnimate = true; // used so we can't click up/down so fast (see bottom of script)
		$(".section-container").animate({
			'top': -(clicked*($(".section-container").height()+sectionSpacing))
		},'fast',function(){ secAnimate = false; if(callback){callback();}});
		
		var curProject = parseInt($('.selected-link').eq(clicked).parent().attr('id').split('-')[2]);
		lazyLoad(clicked,curProject);
		setScrollPosition(curProject,clicked,1);
	}
	else
	{
		$(secRef).siblings('.section-collection').slideUp('fast');
	}
	var curProject = parseInt($('.selected-link').eq(clicked).parent().attr('id').split('-')[2]);
	lazyLoad(clicked,curProject);
}

function initVis()
{
	var secLeft = parseInt($('#scroll-container').css('left').replace('px',''));
	// projects visible
	visX = Math.ceil(($(window).width()-secLeft)/($(".single-project").width()+parseInt($(".single-project").eq(1).css('margin-left').replace('px','')))); 

	// sections visible
	visY = Math.ceil($(window).height() / ($(".section-container").height() + parseInt($(".section-container").eq(1).css('margin-top').replace('px',''))));	
}

// returns ID of current focused section
// note: section change menu animation must be complete or this won't return correct value
function getCurSection()
{
	return parseInt($('.section-collection:visible').siblings('.section-title').attr('id').split('-')[1]);
}

// returns the ID of the current selected proj
function getCurProject()
{
	return parseInt($("#sec-"+getCurSection()).siblings('.section-collection').children().children('a.selected-link').parent().attr('id').split('-')[2]);
}

// this buffers a group of images in a sliding area
function lazyLoadProj(proj)
{
	$('#image-mover-'+proj+' > .single-image > img').each(function(){
		$(this).attr('src',$(this).attr('data-original'));
	});
}

// called while scrolling through a section
// lazy loads visible images
function lazyScroll(section)
{
	var sLeft = -1*parseInt($('.section-container').eq(section).css('left').replace('px',''));
	
	var missingProjects = sLeft / ($('.single-project').width() + parseInt($('.single-project').eq(1).css('margin-left').replace('px','')));
	var projID = Math.floor(missingProjects+visX);
	$('.section-container').eq(section).children('.single-project:eq('+projID+')').find('div.single-image > img').eq(0).each(function (){
		$(this).attr('src',$(this).attr('data-original'));
	});
	
	// we also need to change the currently highlighted project
	$('.section-collection').eq(section).children('.section-project').children().removeClass('selected-link');
	$('.section-collection').eq(section).children('.section-project:eq('+(Math.floor(missingProjects+visX)-2)+')').children().addClass('selected-link');
}

// lazy-loading of images
function lazyLoad(section, proj)
{
	//console.log("section: "+section+", proj:"+proj);
	// loads all images for a particular project
	function bufferProject(projID,secID)
	{
		//console.log('sec: '+secID+', proj: '+projID);
		$('.section-container').eq(secID).children().eq(projID).children().eq(0).find('.image-container > .image-mover > .single-image:first-child > img').each(function(){
			$(this).attr('src',$(this).attr('data-original'));
		});
	}
	
	posX = proj;
	posY = section;
	
	for(x = 0; x < visX; x++)
	{
		for(y = 0; y < visY; y++)
		{
			bufferProject(posX+x,posY+y);
		}
	}
}

// for scrolling
function trackPiwikLink(link)
{
	var the_link = 'http://laurenkim.com/' + link.attr('href');
	piwikTracker.setCustomUrl(the_link);
	piwikTracker.trackPageView(link.attr('href'));
}

// for direct clicks
function trackPiwikClick(link)
{
	piwikTracker.setCustomUrl(link);
	piwikTracker.trackPageView();
}

$(document).ready(function(){
	// this is useful for animating project->project movement
	var orig_margin_left = parseInt($(".section-container").eq(0).css('margin-left').replace("px",""));
	
	// hide all on menu
	$('.section-collection').hide();
	
	// select first section and open all under it
	$('.section-title').eq(0).siblings('.section-collection').show();
	
	// initially select the first project form each section
	$('.section-collection').children(':first-child').children().addClass('selected-link');
	
	// expand all image-movers
	$('.image-mover').each(function(){
		$(this).css('width',$(this).children().length*$('.single-image').width());
	});
	
	initVis(); // load how many projects are visible at once based on browser size
	lazyLoad(0,0); // lazy-load visible projects
	setScrollbarWidth(1); // initially set the scrollbar width to a section
	
	switchSection($('.section-block:eq(1) > .section-title')); // switch to second section
	
	// what happens when we click on a section
	$('.section-block > .section-title').click(function(){
		
		switchSection($(this));
	});
	
	// what happens when we click on a project
	$('.section-project').click(function(event){
		switchProject($(this));
	});
	
	// set the content container to be the width and height of the window
	$('#content').css('width',$(window).width()+'px');
	$('#content').css('height',$(window).height()+'px');
	
	// if the document resizes, change content dimensions
	// also reset total visible projects
	$(window).resize(function(){
		$('#content').css('width',$(window).width()+'px');
		$('#content').css('height',$(window).height()+'px');
		initVis();
	});
	
	// set all section widths by # of projects
	$(".section-container").each(function(i){
		var totalChildren = $(this).children().length;
		var projectMargin = parseInt($(".single-project").eq(1).css('margin-left').replace("px", ""));
		var projectWidth = $(".single-project").width() + projectMargin;
		
		$(this).width(totalChildren * projectWidth - projectMargin);
	});
	
	// what happens when we click an image arrow
	$('.arrow').click(function(){

		var projID = parseInt($(this).attr('id').split('-')[2]);
		
		// lazyload all images for project
		lazyLoadProj(projID);
		
		var curItem = parseInt($('#cur-image-'+projID).html());
		var totalItems = parseInt($('#total-images-'+projID).html());
		var imageSize = $('.image-container').width();
		
		var imageMover = $('#image-mover-'+projID);
		
		if($(this).hasClass('left-arrow'))
		{
			// if we try to go left of the first item
			if(curItem == 1) 
			{ 
				curItem = totalItems; 
				imageMover.animate({'margin-left': -1*(totalItems - 1)* imageSize},'fast');
			}
			// else
			else 
			{ 
				curItem = curItem - 1; 
				imageMover.animate({'margin-left':'+='+imageSize},'fast');
			}			
		}
		else // click right
		{
			// if we try to go right of the last item
			if(curItem == totalItems) 
			{ 
				curItem = 1; 
				imageMover.animate({'margin-left': 0},'fast');
			}
			else 
			{ 
				curItem = curItem + 1; 
				imageMover.animate({'margin-left':'-='+imageSize},'fast');
			}
		}
		$('#cur-image-'+projID).html(curItem);
	});

	// enable mouse wheel left/right
	$('#content').mousewheel(function(event, delta){
		if (delta > 0) { // left
			if(getCurProject() != 0 && !projAnimate)
			{
				var newProj = getCurProject() - 1;
				var projRef = $('.section-collection:eq('+getCurSection()+') > .section-project').eq(newProj);
				switchProject(projRef);
				trackPiwikLink(projRef.children());
			}
			return false;
		}
		if (delta < 0) { // right
			if(getCurProject() != ($('.section-collection:eq('+getCurSection()+') > .section-project').length-1) && !projAnimate)
			{
				var newProj = getCurProject() + 1;
				var projRef = $('.section-collection:eq('+getCurSection()+') > .section-project').eq(newProj);
				switchProject(projRef);
				trackPiwikLink(projRef.children());
			}
			return false;
		}
	});
	
	// enable mouse wheel up/down
	$("#menu").mousewheel(function(event,delta){
		if (delta > 0) { // up
			if(getCurSection() != 0 && !secAnimate)
			{
				var newSec = getCurSection() - 1;
				var secRef = $('.section-block > .section-title').eq(newSec);
				switchSection(secRef);
			}
			return false;
		}
		
		if (delta < 0) { // down
			if(getCurSection() != ($('.section-block > .section-title').length - 1) && !secAnimate)
			{
				var newSec = getCurSection() + 1;
				var secRef = $('.section-block > .section-title').eq(newSec);
				switchSection(secRef);
			}
			return false;
		}
	});
	
	// enable arrow keys
	$(document).keydown(function(e){
		if (e.keyCode == 37) { // left
			if(getCurProject() != 0 && !projAnimate)
			{
				var newProj = getCurProject() - 1;
				var projRef = $('.section-collection:eq('+getCurSection()+') > .section-project').eq(newProj);
				switchProject(projRef);
				trackPiwikLink(projRef.children());
			}
			return false;
		}
		if (e.keyCode == 39) { // right
			if(getCurProject() != ($('.section-collection:eq('+getCurSection()+') > .section-project').length-1) && !projAnimate)
			{
				var newProj = getCurProject() + 1;
				var projRef = $('.section-collection:eq('+getCurSection()+') > .section-project').eq(newProj);
				switchProject(projRef);
				trackPiwikLink(projRef.children());
			}
			return false;
		}
		if (e.keyCode == 38) { // up
			if(getCurSection() != 0 && !secAnimate)
			{
				var newSec = getCurSection() - 1;
				var secRef = $('.section-block > .section-title').eq(newSec);
				switchSection(secRef);
			}
			return false;
		}
		
		if (e.keyCode == 40) { // down
			if(getCurSection() != ($('.section-block > .section-title').length - 1) && !secAnimate)
			{
				var newSec = getCurSection() + 1;
				var secRef = $('.section-block > .section-title').eq(newSec);
				switchSection(secRef);
			}
			return false;
		}
	});

	initScroll(); // initialize the scrollbar callback
	
	// clicking on a gallery image
	$('.single-image > img').click(function(){
		var imgMover = $(this).parent().parent();
		var clickedProj = parseInt(imgMover.parent().parent().parent().attr('id').split('-')[3]);
		var clickedSec = parseInt(imgMover.parent().parent().parent().attr('id').split('-')[2]);
		
		if(!imgAnimate && imgMover.children().length > 1 && (getCurSection() == clickedSec) && (clickedProj == getCurProject()))
		{
			var curProj = parseInt(imgMover.parent().attr('id').split('-')[2]);
			var cur = parseInt($('#cur-image-'+curProj).html());
			var totItems = parseInt($('#total-images-'+curProj).html());
			var imgSize = $('.single-image').width();
			
			// if cur image is last one, go back to beginning
			if(cur == totItems)
			{
				imgAnimate = true;
				$('#cur-image-'+curProj).html('1')
				imgMover.animate({'margin-left': 0},'fast',function(){ imgAnimate = false;});
			}
			else // advance slide
			{
				imgAnimate = true;
				imgMover.animate({'margin-left':'-='+imgSize},'fast',function(){ imgAnimate = false;});
				$('#cur-image-'+curProj).html(cur+1);
				lazyLoadProj(curProj); // lazyload rest of images
			}
		}
	});
	
	// clicking on a single project container when we aren't currently looking at it
	$(".single-project").click(function(){
		var destSec = parseInt($(this).attr('id').split('-')[2]);
		var destProj = parseInt($(this).attr('id').split('-')[3]);
		
		var callback = function(){
			
			if(getCurProject() != destProj)
			{	
				var projRef = $('.section-collection:eq('+destSec+') > .section-project').eq(destProj);
				switchProject(projRef);
			}
		};
		
		if(getCurSection() !=  destSec)
			switchSection($('.section-block:eq('+destSec+') > .section-title'),callback);
		else if(getCurProject() != destProj)
		{	
			var projRef = $('.section-collection:eq('+destSec+') > .section-project').eq(destProj);
			switchProject(projRef);
		}
	
		
	});
});
