var inProgress = false;
var noMoreAvailable = false;

function checkPage(){
	var scrolled;
	var pageHeight = getPageHeight();
	
	if (self.pageYOffset) {
		scrolled = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop) {
		scrolled = document.documentElement.scrollTop;
	}
	else if (document.body) {
		scrolled = document.body.scrollTop;
	}
	
	// Find a good ratio to fetch more content at
	// If the page is short, we will need to fetch more when it
	// hasn't been scrolled as far.  When it gets longer, we can 
	// allow the user to scroll more freely, getting close to the bottom
	var quotient = 65;
	
	if(pageHeight > 30000){
		quotient = .90;
	} else if(pageHeight > 20000) {
		quotient = .85;
	} else if(pageHeight > 10000) {
		quotient = .75;
	} else {
		quotient = .65;
	}
	
	if( (scrolled/pageHeight) > quotient){
		getMoreData();	
	}
}

function getPageHeight() {
	return document.body.offsetHeight;
}

function getMoreData(){
	if(!inProgress && !noMoreAvailable){
		
		var nodes = $('main_content_full').childNodes;
		var curNum= 0;
		
		for(var i=0; i<nodes.length; i++)
		{
			if(nodes[i].hasChildNodes())
			{
				curNum++
				//alert(nodes[i].offsetHeight());
			}
		}	
		
		var url = "/more_post_data2.php?base="+curNum+"&toget=3";
		
		inProgress = true;
		
		request = createRequest();
		request.open("GET", url, true);
		request.onreadystatechange = function(){displayContent()};
		request.send(null);
		
	}
}

function displayContent() {
	if (request.readyState == 4){
		var main_content = $('main_content_full');
		
		if (request.status == 200){
			var newContent = request.responseText;
			
			if(newContent == "nomore"){
				var endMessage = "<div class='post'><h2>That's All, Folks</h2><p>Boy, you're persistant aren't you.</p><p>You've come to the end of the internet.<br /><a href='/'>Click here to go back.</a></p></div>";

				noMoreAvailable = true;
				main_content.innerHTML += endMessage;
			}
			else {
				main_content.innerHTML += newContent;
			}
		}
		else{ 
			var errorMessage = "<div class='post'><h2>Woops, there was an error</h2><p>I'm very sorry, but it looks like there was an error fetching more content. Check out the <a href='/archives/'>archives</a> for more content.</p></div>";
			main_content.innerHTML += errorMessage;
		}
		
		inProgress = false;
	}
	else{
	}
}

//this doesn't change very often, thus it is condensed
function createRequest() {	try{request=new XMLHttpRequest();return request;}catch(trymicrosoft){try{request = new ActiveXObject("Msxml2.XMLHTTP");return request;}catch(othermicrosoft){try{request=new ActiveXObject("Microsoft.XMLHTTP");return request;}catch(failed){return false;}}}if(!request){alert("Error initializing XMLHttpRequest!");} }

function $(id){ return document.getElementById(id);	}

window.onscroll = checkPage;