$(document).ready(function(){
	site.init();

});

$(window).resize(function(){
	site.resize();
});

var site = {

	window				:	{},
	curPage				:	false,
	pageType			:	'',
	curProject			:	0,
	curCategory			:	0,
	curImage			:	0,
	curProcessImage		:	0,
	description			:	0,
	curText				:	0,
	player				:	'',
	scrollState			:	'',
	cookie				:	0,
	sound				:	{},
	
	init				:	function(){
		this.height = $(window).height();
		this.width = $(window).width();

		//INITIAL POSITIONING
		//Move scroll container to center first image
		this.resize();
		var left = (this.width - $('#scrollContainer:first-child').width()) / 2;
		$('#scrollContainer').css({'padding-left':left, 'visibility':'visible', 'display':'none'});
		
		
		//Center images in containers
		$('#scrollContainer img').each(function(){
			if ($(this).height() < 600){
				$(this).parent().find('.prev, .next').css({
					'bottom': ((600 - $(this).height())/2)
				})
			}
		});
		
		
		
		//NAV MENU HANDLERS	
		//Category link
		$('.categoryLink').click(function(e){
			var category = this.className.match(/category-id-([0-9]+)/);
			
			if (!categories[category[1]].projects[0]){
				cancel(e);
			}
			site.checkCookie();
			site.curCategory = category[1];
			site.curProject = categories[category[1]].projects[0].order;
			site.curImage = 0;
			site.pageType = 'project';
			site.curPage = false;
			site.setAddress()
			cancel(e)
		});
		//Project link
		$('.projectLink').click(function(e){
			site.checkCookie();
			var project = this.className.match(/project-([0-9]+)/);
			site.curCategory = $(this).attr('data-category');
			site.curProject = project[1];
			site.curImage = 0;
			site.pageType = 'project';
			site.setAddress();
			cancel(e);
		});
		
		//Title index link handler
		$('#title').click(function(e){
			site.curCategory = 0;
			site.curProject = 0;
			site.curImage = 0;
			site.pageType = 'index';
			site.setAddress();
			cancel(e);
		})
		
		//Overview link handler
		$('#overviewLink').click(function(e){
			if ($('#overview').is(':visible')){
				site.pageType = 'project';
				$('#overviewLink').html('Overview');
			} else {
				site.pageType = 'overview';
				$('#overviewLink').html('Close');
			}
			site.setAddress();
			cancel(e);
		});
		
		//Overview image link handler
		$('.overviewImageCont .overviewImageLink').click(function(e){
			
			var catNum = this.className.match(/category-([0-9]+)/)
			var projNum = this.className.match(/project-([0-9]+)/);
			var imageNum = this.className.match(/image-([0-9]+)/);
			site.curCategory = catNum[1]
			site.curProject = projNum[1]
			site.curImage = imageNum[1]
			site.pageType = 'project';
			site.setAddress();

			$('#overviewLink').html('Overview');
			cancel(e);
		});
		
		
		//PROJECT AREA HANDLERS
		//Previous & next links
		$('#scrollContainer .prev, #scrollContainer .next').click(function(e){
			
			site.pageType = 'project';
			site.curImage = $(this).attr('data-next')
			site.setAddress();

			cancel(e);
		});	
		
		//Project image links
		$('.projectImageCont a').click(function(e){
			site.checkCookie();
			var $img = $(this).find('img')
			if ($img.data('category') != site.curCategory ||
				$img.data('project') != site.curProject ||
				$img.data('image') != site.curImage
			){
				site.curCategory = $img.data('category');
				site.curProject = $img.data('project');
				site.curImage = $img.data('image');
				site.pageType = 'project';
				site.setAddress();
			} else {
				site.nextImage();
			}
			cancel(e);
		})
		
		//Arrow key handlers
		$(document).keyup(function(e){
			if (site.pageType == 'project' || site.pageType == 'index'){
				switch (e.keyCode){
					case 37:
						site.previousImage();
						break;
					case 38:
						site.previousCategory();
						break;
					case 39:
						site.nextImage();
						break;
					case 40:
						site.nextCategory();
						break;
				}
			}
			cancel(e);
		});
		
		//Description link handlers
		$('#descriptionLink, #processOverlay').click(function(e){
			if (site.pageType != 'description'){
				site.pageType = 'description';
			} else {
				site.pageType = 'project';
			}
			site.setAddress();
			cancel(e);
		});
		
		$()
		
		//Process link handler
		$('#processLink').click(function(e){
			site.pageType = 'process';
			site.setAddress();
			cancel(e);
		})
		
		//Process link previous and next
		$('#process a.prev').click(function(e){
			if (site.curProcessImage > 0) {
				--site.curProcessImage;
			} else {
				site.curProcessImage = categories[site.curCategory].projects[site.curProject].attachments.length - 1;
			}
			site.setAddress();
			cancel(e);
		});
		
		$('#process a.next, #process a#processImgLink').click(function(e){
			if (site.curProcessImage < categories[site.curCategory].projects[site.curProject].attachments.length - 1) {
				++site.curProcessImage;
			} else {
				site.curProcessImage = 0;
			}
			site.setAddress();
			cancel(e);
		});
		
		//Page link handler
		$('#pageNav a').click(function(e){
			site.curPage = [$(this).attr('href').split('/')[1]];
			site.pageType = 'page';
			site.setAddress();
			cancel(e);
		})
		
		//Get & handle the current address when the window loads
		$(window).load(function(){
			window.setTimeout(function(){site.handleAddress(0);}, 1000);
		});
		
		// JavaScript object for later use
		$('#player').jPlayer({
			swfPath: '/wp-content/themes/blank/library/', 
			solution:"flash, html", 
			supplied: 'mp3',
			preload:'none'
		})
		
		//Audio link handler
		$('a#audioLink').click(function(e){
			if (site.sound.isPlaying){
				$('#player').jPlayer('clearMedia');
				site.sound.isPlaying = false;
				$(this).html('Play sound');
			} else {
				$('#player').jPlayer( "setMedia", {
			      mp3: $(this).attr('href')
			    });
				$('#player').jPlayer('play');
				site.sound.isPlaying = true;
				site.sound.project = site.curProject;
				$(this).html('Stop sound');
			}
			cancel(e);
		})
		
		$.address.change(site.handleAddress);
	},
	checkCookie	:	function(){

		if (site.cookie == 0){
			site.cookie = 1;
			$('#instructions').show();
			window.setTimeout(function(){
				$('#instructions').fadeOut();
			}, 5000)
		}

	},
	changeState	:	function(){
		//Run set functions depending on page type
		if (this.pageType == 'page'){
			this.setActiveLayers();
			this.setDescription();
		}
		else if (this.pageType == 'overview'){
			this.setActiveLayers();
		} 
		else if (this.pageType == 'index'){
			this.setActiveLayers();
			this.setScrollState();
		}
		else {
			this.setPage();
			this.setActiveLayers();
			this.setPageNavState();
			this.setScrollState();
		}
		this.setPage();
		this.setProcess();
		this.setOverview();
		this.setDescription();
		this.setSound();
	},
	
	setScrollState	:	function(){
		
		var margin = 90;

		//Find the current image
		var $fImage = $($('#scrollContainer .category-id-' + this.curCategory + ' .project-' + this.curProject + ' .projectImageCont a')[this.curImage]);

		//Calculate position
		var pos = $fImage.offset();
		var iW = $fImage.innerWidth();
		var iH = $fImage.innerHeight();
		var left = pos.left + $('#scrollContainer').scrollLeft() - (this.width - iW) / 2;
		var top = pos.top + $('#scrollContainer').scrollTop() - margin;
		this.scrollState = {
			location	:	{left:left, top:top},
			scrolling	:	true
		}
		//Scroll to position
		$('#scrollContainer').scrollTo({'left':left, 'top':top}, 300, function(){
			site.scrollState.scrolling = false;
		});
	},
	
	checkScroll	:	function(){
		if (!this.scrollState.scrolling){
			$.scrollTo(this.scrollState.location);
		}
	},
	
	setPageNavState	:	function(){
		
		//Set the nav menu state based on current object status
		
		var category = site.curCategory;
		var project = site.curProject;
		
		//Collapse all lists except the current ones
		$('.projectNavProject').not('ul.project-' + project).slideUp(300);
		$('.projectNavCategory').not('ul.category-id-' + category).slideUp(300).css({'height':'auto'});
		
		//Slide project down if we're already in its category, otherwise just show
		if (!$('ul.category-id-' + category).is(':visible') && this.pageType != 'description'){
			$('ul.category-id-' + category +' ul.project-' + project).show();
		} else {
			if (this.pageType != 'description'){
				$('ul.category-id-' + category +' ul.project-' + project).slideDown(300);
			} else {
				$('ul.category-id-' + category +' ul.project-' + project).slideUp(300);
			}
		}
		
		//Set selected project
		$('#projectNav a.selected').removeClass('selected');
		$('#projectNav a.project-' + project).addClass('selected');
		
		
		//Open the category menu
		$('ul.category-id-' + category).slideDown(300);

	},
	
	setDescription	:	function(){
	
		//Controller for description link and text
		if (this.pageType == 'description' || this.pageType == 'process'){ 
			$('#descriptionLink').html('Close');
			$('body').addClass('description');
		} else {
			$('#descriptionLink').html('Description');
			$('body').removeClass('description');
		}
		
		$description = $('.category-id-'+this.curCategory+' .project-' + this.curProject + ' .description');
		if (this.pageType != 'page' && this.pageType != 'overview' && this.pageType != 'index' && $description.html()){
			$('#descriptionText').html($description.html());
			$('#descriptionLink').show();
		}
		else{
			$('#descriptionLink').hide()
		}
	},
	setSound	:	function(){
		if (this.sound.isPlaying){
			if (this.curProject == this.sound.project && this.pageType == 'project'){
			} else {
				$('#player').jPlayer('clearMedia');
				this.sound.isPlaying == false;
				$('#audioLink').html('Play sound');
			}
		}
		$sound = $('.category-id-'+this.curCategory+' .project-' + this.curProject + ' .audioLink');
		if ($sound.length > 0 && this.pageType == 'project'){
			$('#audioLink').attr('href', $sound.attr('href')).show();
		} else {
			$('#audioLink').hide();
		}
	},
	setProcess	:	function(){
		if (this.pageType == 'description'){
			if (categories[this.curCategory].projects[this.curProject].attachments){
				$('#processLink').show();
				this.resize();
			} else {
				$('#processLink').hide();
			}
		}
		if (this.pageType != 'process'){
			this.curProcessImage = 0;
		}
		else {
			var img = categories[this.curCategory].projects[this.curProject].attachments[this.curProcessImage];
			
			$('#processLink').hide();
			$('#process img').attr({
				'src'	:	img.location,
				'width'	:	 img.width,
				'height' :	img.height
			})
			$('#process').show();
		}
	},
	setOverview	:	function(){
		
		//Controller for the overview link
		
		if (this.pageType == 'overview'){
			$('#overviewLink').html('Close');
			$('body').addClass('overview');
		} else {
			$('#overviewLink').html('Overview');
			$('body').removeClass('overview');
		}
	},
	setAddress	:	function(){
		//Set the address based on current object state
		
		var address = '';
		if (this.pageType == 'project'){
			address += 'projects/';
			address += categories[this.curCategory].projects[this.curProject].slug + '/';
			if (this.curImage) address += this.curImage;
		}
		else if (this.pageType == 'description'){
			address += 'projects/';
			address += categories[this.curCategory].projects[this.curProject].slug + '/';
			address += 'description';
		}
		else if (this.pageType == 'overview'){
			address = 'overview';
		}
		else if (this.pageType == 'page') {
			test = this.curPage;
			address = this.curPage.join("/")
		}
		else if (this.pageType == 'process'){
			address += 'projects/';
			address += categories[this.curCategory].projects[this.curProject].slug + '/';
			address += 'process/';
			address += site.curProcessImage == 0 ? '' : site.curProcessImage;
		}
		else {
			address += 'projects/';
			address += categories[this.curCategory].projects[this.curProject].slug + '/';
		}
		$.address.path(address);
	},
	
	handleAddress	:	function(e){
		
		//Parse address to figure out where we are, set object status based on address
		
		//If this is the onload call we won't get an event object
		if (typeof e === 'undefined' || typeof e === 'number'){
			return false;
		}
		if (!e || !e.pathNames){
			e = $.address.pathNames;
		} else {
			e = e.pathNames;
		}
		
		//PROJECT
		if (e[0] == 'projects'){
			var projNum;
			for (var i = 0; i < categories.length; ++i){
				if (projNum) break;
				if (categories[i].projects.length){
					for (var j = 0; j < categories[i].projects.length; ++j){
						if (categories[i].projects[j].slug == e[1]) {
							projNum = [i, j];
							break;
						};
					}
				}
			}
			if (projNum){
				site.curCategory = projNum[0];
				site.curProject = projNum[1];
				if (e[2] == 'description') site.pageType = 'description';
				else if (e[2] == 'process'){
					site.curProcessImage = e[3] ? e[3] : 0;
					site.pageType = 'process';
				}
				else {
					site.curImage = e[2] ? e[2] : 0;
					site.pageType = 'project';
				}
			}
		} 
		
		//OVERVIEW
		else if (e[0] == 'overview') site.pageType = 'overview';
		else if(e[0] === undefined) {
			site.pageType = 'index';
			site.curCategory = Math.floor(Math.random() * categories.length);
			site.curProject = Math.floor(Math.random() * categories[site.curCategory].projects.length);
			site.curImage = 0;
		}
		
		//ABOUT
		else {
			site.curPage = e[1] ? e : [e[0]];
			site.pageType = 'page';
		}
		site.changeState();
		return false;
	},
	setPage	:	function(){
		//Set up about page, make Ajax call if it isn't cached
		if (this.curPage && this.pageType == 'page'){
			
			$('#descriptionLink').hide();
			$('.projectNavCategory, .projectNavProject').hide();
			var base = this.curPage[0];

			if (!this.loadedPage){
			
				var url = '';
				
				if (base == 'about' || base == 'cv'){
					url = base;
				}
				
				else if (base=='texts'){
					if (site.curPage[1]){
						url = site.curPage[1];
					} else {
						url = site.curPage[0];
					}
				}
				
				else if (base=='weblog' || base=='posts' || base=='log'){
					if (site.curPage[1]){
						if (site.curPage[1] == 'tag'){
							if (site.curPage[3] = 'page' && site.curPage[4]){
								url = site.curPage[1] + '/' + site.curPage[2] + '/page/' + site.curPage[4];
							} else {
								url = site.curPage[1] + '/' + site.curPage[2];
							}
						} else if (site.curPage[1] == 'page'){
							url = site.curPage.join('/');
						}
						else {
							url = site.curPage[0] + '/' + site.curPage[1];
						}
					} else {
						url = site.curPage[0];
					}
				} 
				$.ajax(url, {success:this.pageLoaded});
			}
			else {
				var $page = $(this.loadedPage);
				this.loadedPage = false;

		
				$('#pageNav .selected').removeClass('selected');
				$('a[href="#/'+ this.curPage[0] +'"]').parent().addClass('selected');
				
				var main = $page.find('#page').html();
				var side = $page.find('#info').html();
				if (this.curPage[0]=='log') this.curPage[0] = 'weblog';
				$('#page').html(main).attr('class', this.curPage[0]);
				$('#info').html(side);

				if (base == 'texts' || base == 'weblog' || base=='log'){
					$('#blogNav a, .blogPost a.h1, a.tagLink, a.textLink').bind('click', function(e){
						site.curPage = $(this).attr('href').replace(baseURL, '').split('/');
						site.pageType = 'page';
						site.setAddress();
						cancel(e);
					});
				}
				$('body').addClass('page');
				this.setActiveLayers();
				$('body').css('height', $('#pageText').outerHeight() + 100);
				$('body').scrollTo(0);

			}
		} else {
			$('body').removeClass('page');
			$('body').css('height', '100%')
			$('#page, #info').html('');
			$('#pageNav .selected').removeClass('selected');
		}
	},
	pageLoaded	:	function(d){
		site.loadedPage = d; 
		site.setPage();
	},
	setActiveLayers	:	function(){
	
		//Hide & show the layers for this page type
		
		var map = {
			'overview'	:	'#overview',
			'description'	:	'#description',
			'page'	:	'#page, #info',
			'index'	:	'#scrollContainer',
			'project'	:	'#scrollContainer',
			'process'	:	'#description, #process'
		}
		
		

		//Record window scroll position in case we have to hide the scroll container
		if ($('#scrollContainer').is(':visible')){
			$('#scrollContainer').data('scroll', {
				'top': $('#scrollContainer').scrollTop(),
				'left': $('#scrollContainer').scrollLeft()
			});
		}
		var pageType = this.pageType;
		//If we don't know where this is, assume it's the index
		if (map[pageType] === undefined){
			pageType = 'index';
		}
		
		//Show & hide
		for (var type in map){
			if (type == this.pageType){
				$(map[type]).show();
			} else {
				$(map[type]).hide()
			}
		}
		$(map[pageType]).show();
		
		//Set remembered scroll position
		if($('#scrollContainer').data('scroll')){
			$('#scrollContainer').scrollLeft($('#scrollContainer').data('scroll').left)
			$('#scrollContainer').scrollTop($('#scrollContainer').data('scroll').top)
		}
	},
	nextCategory	:	function(){
		var initCat = parseInt(site.curCategory) + 1
		var newLoc = false;
		while (!newLoc){
			for (var i = initCat; i < categories.length; ++i ){
				if (categories[i].projects.length > 0){
					newLoc = [i, 0, 0];
					break;
				}
			}
			if (i >= categories.length - 1) {
				initCat = 0;
			}
		}
		site.curCategory = newLoc[0];
		site.curProject = newLoc[1];
		site.curImage = newLoc[2];
		site.setAddress();
	},
	previousCategory	:	function(){
		var initCat = parseInt(site.curCategory) - 1
		var newLoc = false;
		
		while (!newLoc){
			for (var i = initCat; i >= 0; --i ){
				if (categories[i].projects.length > 0){
					newLoc = [i, 0, 0];
					break;
				}
			}
			if (i <= 0) {
				initCat = categories.length - 1;
			}
		}
		
		site.curCategory = newLoc[0];
		site.curProject = newLoc[1];
		site.curImage = newLoc[2];
		
		site.setAddress();
	},
	nextImage	:	function(){
		var initCat = parseInt(site.curCategory);
		var initProj = parseInt(site.curProject);
		var initImg = parseInt(site.curImage) + 1;
		var newLoc = false;
		while (!newLoc){
			for (var i = initCat; i < categories.length; ++i ){
				if (newLoc) break;
				for (var j = initProj; j < categories[i].projects.length; ++j ){
					if (newLoc) break;
					var imgsLength = $('#scrollContainer .category-id-' + i + ' .project-' + j + ' .projectImageCont').length;
					for (var k = initImg; k < imgsLength; ++k ){
						var test = [i, j, k];
						if (newLoc) break;
						if($('#scrollContainer .category-id-' + i + ' .project-' + j + ' .projectImageCont')[k]){
							newLoc = [i, j, k];
							break;
						}
					}
					initImg = 0;	
				}
				initProj = 0;
			}
			if (i >= categories.length - 1) {
				initCat = 0;
			}
		}
		site.curCategory = newLoc[0];
		site.curProject = newLoc[1];
		site.curImage = newLoc[2];
		site.setAddress();
	},
	previousImage	:	function(){
		
		var initCat = site.curCategory;
		var initProj = site.curProject;
		var initImg = site.curImage - 1;
		var newLoc = false;
		
		while (!newLoc){
			for (var i = initCat; i >= 0; --i ){
				if (newLoc) break;
				for (var j = initProj; j >= 0; --j ){
					if (newLoc) break;
					for (var k = initImg; k >= 0; --k ){
						if (newLoc) break;
						if($('#scrollContainer .category-id-' + i + ' .project-' + j + ' .projectImageCont')[k]){
							newLoc = [i, j, k];
							break;
						}
					}
					initImg = $('#scrollContainer .category-id-' + i + ' .project-' + (j-1) + ' .projectImageCont').length - 1;
				}
				if (i > 0){
					initProj = categories[i-1].projects.length;
				} else {
					initProj = categories[categories.length - 1].projects.length;
				}
			}
			if (i == -1) {
				initCat = categories.length - 1;
			}
		}
		
		site.curCategory = newLoc[0];
		site.curProject = newLoc[1];
		site.curImage = newLoc[2];
		
		site.setAddress();

	},
	resize 	:	function(){
		this.height = $(window).height();
		this.width = $(window).width();
		
		$('#processLink').css({
			'top'	: (this.height - $('#processLink').outerHeight()) / 2 + 'px'
		})
	}
}

function cancel(e)
{
  e.preventDefault();
  return false;
}
