var startAtPost = 0;
var iHeight = $(window).height();
var triggerHeight;
var postIds = [];
var path = window.location.pathname;
var isIndexPage = false;
var allowedToLoadMore = true;
var pageNum = 1;

$(document).ready(function(){
	bindEvents();
	if(path == '/' || path.search('page') > 0) { 
		isIndexPage = true;
	}
	if(isIndexPage){
//		learnLeftFromRight();
		$('#offset-l').empty();
		getPhotos('old');
//		var autoUpdate = window.setInterval(getPhotos,30000);
		loadNextPage();
		$('#names').hide();
		}
	else {
			$('.onAnIndexPage').each(function(){
				$(this).remove();
			});
		}
});

$(window).load(function(){
	setPostHeight();
})

function bindEvents()
{
	// on click, erase the placeholder value from a the search <input> element.
	$('input').focus(function(){
		$(this).attr('value','');
	})
	$('input').blur(function(){
		var currentValue = $(this).attr('value');
		if(currentValue == '')
		{
			$(this).attr('value','Search');
		}
	})
	$('.fromtumblr').load(function(){
		$(this).animate({opacity:1}, 'slow');
		setPostHeight();
	});
	$('#contributors h4').click(function(){
		toggleContributors();
	});
	$('#contributors p').click(function(){
		toggleContributors();
	});	

	$(window).resize(function(){
		setPostHeight();
	})
	window.onscroll = scroll;
}

function scroll()
{ 
	var howFarDown = $(window).scrollTop();
//	console.log('how far: ' + howFarDown);
//	console.log('trg hgt: ' + triggerHeight);	
	if(howFarDown >= triggerHeight && allowedToLoadMore)
	{
		getPhotos('old');
//		loadNextPage();
	}

}

	
function getPhotos(oldOrNew)
{
	allowedToLoadMore = false;
	var apiCall = ('/api/read/json?type=photo&num=48&start=' + startAtPost + '&callback=?');
	var stopHere;
	var tumblrData = [];
	var old = false;
	if (oldOrNew == 'old') { old = true; }
	if (!old)
	{
		allowedToLoadMore = true;
		apiCall = ('/api/read/json?type=photo&num=48&callback=?');
		stopHere = $('#left li')[0].id;
//		console.log(stopHere);
	}
	$.getJSON(apiCall, function(data){
		for (var i in data.posts)
		{
			if(data.posts[i]['id'] == stopHere) { break; }
			else {
				tumblrData.push(data.posts[i]);
//				console.log(tumblrData.length);
				i++;
				startAtPost++;
			}
		}
		appendPhotos();
	})
	// getPhotos can't be called again until it finishes inserting posts.
	function appendPhotos()
	{
		// if these are new photos, reverse the tumblrData array so that
		// they'll appear in the right order
		if(!old) { tumblrData.reverse(); }
		
		$(tumblrData).each(function(index)
		{
			var thisId = this['id'];
			var postPhotos = this['photos'];
			var tags = this['tags'];
			var fig = document.createElement('li');
			var aspect = document.createElement('img');
			var tImg = document.createElement('img');
			var permalink = document.createElement('a');


			
			//tags as classes!
			if(index != 0)
			{
				if((index%3 == 0))
				{
					for (var i in tags)
					{
						$(fig).addClass(tags[i]);
					}
				}
			}
			
			aspect.src = 'http://milk.alldayeveryday.com/mmtumblr/images/aspectratio.png';
			aspect.className = 'aspectratio';
			tImg.src = this['photo-url-500'];
			tImg.className = 'fromtumblr';
			permalink.href = this['url'];
			
			if(index == 6 || index == 21 || index == 27 || index == 36 || index == 39 || index == 42)
			{
				$(fig).addClass('featured');
			}
			
			
					
			if(postPhotos.length > 0) { simulatePhotoset.call(this); };				
			$(fig).append(aspect);
			$(permalink).append(tImg);
			$(fig).append(permalink);
			$(fig).attr('id',thisId);
			insertPost();
			function insertPost()
			{
				var mod = index%6;
				var left;
				if(mod < 3)
				{
					left = true;
 				}
				else {
					left = false;
					}
				if(left)
				{
					if(old)
					{
					$('#offset-l').append(fig);
					}
					else 
					{
					$('#offset-l').prepend(fig);
					}
				}
				else{
					if(old)
					{
					$('#offset-r').append(fig);
					}
					else {
					$('#offset-r').prepend(fig);					
					}
					
				}
					
				// figures should fade in when their image loads.
				$(tImg).load(function () { 
					$(this).animate({opacity:1}, 'slow');
					setPostHeight();
					// set allowedToLoadMore to true once the first post has loaded
					if(index == (0)) {
//							console.log(index);
						allowedToLoadMore = true;
						// and set the new trigger height
						triggerHeight = (document.getElementById('left').scrollHeight - iHeight - 600);
					}
				})

				// and do fun opacity hover stuff
				$(fig).mouseover(function(){
					$(this).animate({opacity:.5}, 'fast');
				}).mouseout(function(){
					$(this).animate({opacity:1}, 'fast');
				});
			}
			function simulatePhotoset()
			{	
				// get all the images in the post.
				var slides = [];
				var cache = [];
				var slideNum = 0;
				var numberOfSlidesLoaded = 0;
				$(postPhotos).each(function(){
					var cacheThis = document.createElement('img');
					cacheThis.src = this['photo-url-500'];
					$(cacheThis).load(function(){
						numberOfSlidesLoaded ++;
					})
					slides.push(cacheThis.src);
				});

				var nextSlide = document.createElement('img');
				var rand = Math.random()*3000;
				var slideInterval = rand + 3000;
				var check = window.setInterval(checkWhetherSlidesAreLoaded,3000);
					function checkWhetherSlidesAreLoaded()
					{
//						console.log('checked');
						if(numberOfSlidesLoaded == slides.length)
						{
							window.clearInterval(check);
							var slideshowTimer = window.setInterval(doSlideshow,slideInterval);
						}
					}
				function doSlideshow()
				{
					tImg.src = slides[slideNum];
					$(nextSlide).remove();
					nextSlide = document.createElement('img');
					nextSlide.className = 'next_slide';
					
					//because IE is stupid:
					$(nextSlide).css('height','auto');
					if(slideNum < slides.length-1){
						nextSlide.src = slides[slideNum+1];
						}
					else{
						nextSlide.src = slides[0];
						}
					$(permalink).append(nextSlide);
					$(nextSlide).animate({opacity:1},1000);
					slideNum++;
					if(slideNum == (slides.length)){ slideNum = 0; }
				}
			}
							
		});
	}
}

function setPostHeight()
{
	if(isIndexPage);
	{
		var h = $('.aspectratio').height();
		$('section li').each(function(){
		
			if($(this).hasClass('featured')){ 
				var hTwo = (h*2 + 2);
				var wTwo = $('#offset-l').find('.aspectratio')[0].width;
	//			var hTwo = (h*2);
				$(this).height(hTwo);
				$(this).width(wTwo*2 + 2);			
				$(this).find('.fromtumblr').css('height','auto');
			}
			else {
				$(this).height(h);
				$(this).find('.fromtumblr').css('height','auto');
			}
		})
	}
/*	var centerColumnHeight = ($(document).height() - 137);
	$('nav').height(centerColumnHeight);*/
}


function bigAssPostPagePhotoset(postId)
{	
	// get all the images in the post.
	var slides = [];
	var slideNum = 0;
	var numberOfSlidesLoaded = 0;
	var appendHere = document.getElementById(postId);
	var tImg = document.createElement('div');	
	$.getJSON('/api/read/json?&id=' + postId + '&callback=?', 
		function(data){
			for (var i in data.posts[0]['photos'])
			{
				var img = document.createElement('img');
				img.src = data.posts[0]['photos'][i]['photo-url-1280'];
				//if this is the first image, copy it to a relatively-positioned
				//placeholder, so the containing <li> knows how tall it should be.
				if(i == 0) {
					var a = document.createElement('img');
					a.src = img.src;
					$(a).addClass('sets_size');
					$(appendHere).prepend(a);
				}
				$(img).addClass('photoset');
				$('.cache_here').append(img);
				$(img).load(function(){ numberOfSlidesLoaded++; });
				slides.push(img);
				if(i == 0){
					// append the first slideshow image.
					$(tImg).html(slides[i]);
					$(appendHere).append(tImg);
				}
			}
		})

	var nextSlide;
	var rand = Math.random()*3000;
	var slideInterval = rand + 3000;
	var check = window.setInterval(checkWhetherSlidesAreLoaded,1000);
	function checkWhetherSlidesAreLoaded()
	{
//		console.log('checked');
		if(numberOfSlidesLoaded == slides.length)
		{
			window.clearInterval(check);
			var slideshowTimer = window.setInterval(doSlideshow,slideInterval);
		}
	}
	function doSlideshow()
	{
		$(tImg).html(slides[slideNum]);
		$(tImg).show();
		$(nextSlide).remove();
		nextSlide = document.createElement('div');
		nextSlide.className = 'next_slide';
		if(slideNum < slides.length-1){
			$(nextSlide).html(slides[slideNum+1]);
			}
		else{
			$(nextSlide).html(slides[0]);
			}
		$(appendHere).append(nextSlide);
		$(nextSlide).animate({opacity:1},1000)
		slideNum++;
		if(slideNum == (slides.length)){ slideNum = 0; }
	}
}


function learnLeftFromRight(){
	$('#offset-l li').each(function(index){		
		var mod = index%6;
		if(mod >= 3)
		{
			$('#offset-r').append(this);
		}
		// and do fun opacity hover stuff
		$(this).mouseover(function(){
			$(this).animate({opacity:.5}, 'fast');
		}).mouseout(function(){
			$(this).animate({opacity:1}, 'fast');
		});

	});
}

function loadNextPage(){
	if(allowedToLoadMore)
	{	
		pageNum++;
		allowedToLoadMore = false;
		var loadString = ('/page/' + pageNum + ' #offset-l');
		var data = document.createElement('div');
		$(data).load(loadString, function() {
			var items = $(data).find('li');
//			console.log(items.length);
			$(items).each(function(index){
				var mod = index%6;
				if(mod == 0 || mod == 3) { /*do nothing*/ }
					else { $(this).removeClass('featured'); }
				$(this).mouseover(function(){
					$(this).animate({opacity:.5}, 'fast');
				}).mouseout(function(){
					$(this).animate({opacity:1}, 'fast');
				});	
				
				if(mod < 3)
				{
					$('#offset-r').append(this);
				}
				else {
					$('#offset-l').append(this);
					}
				if(index == (items.length - 1 ))
				{
					var l = $(this).find('.fromtumblr')[0];
//					console.log($(l));
					$(l).load(function(){
						allowedToLoadMore = true;
					});
				}
			});
			setPostHeight();
			triggerHeight = (document.getElementById('left').scrollHeight - iHeight - 100);
		});
	}
	if(pageNum%2 == 0)
	{
		allowedToLoadMore = true;
		loadNextPage();
	}
}

function toggleContributors() {
	if($('#names').hasClass('shown')){
		$('#names').slideUp('fast',function(){ 
			$(this).removeClass('shown');
			$('#credit').css('margin-top','100px');
			});
		$('header, nav').css('position','fixed');
		$('header').height($(document).height());
		$('#fp-share').show();
		absoluteColumn = false;
	}
	else {
		$('#credit').hide();
		$('#names').slideDown('fast',function(){ 
			$(this).addClass('shown');
			var newMargin = $('#names').height();
			$('#credit').show();
			$('#credit').css('margin-top',100+newMargin);
			});
		$('header, nav').css('position','absolute');
		$('header').height($(document).height()+100);		
		$('#fp-share').hide();		
		absoluteColumn = true;
	}
}
