////////////////////////////////////////////////////////////////////////////////
// Configurable parameters. Tweak if you like. /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

var checkInterval = 200 /*milliseconds*/;
var preloadDistance = 500 /*pixels*/;

////////////////////////////////////////////////////////////////////////////////
// Global status variables. Don't mess. ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

var checker;
var isUpdating = false;

if (typeof addEvent != 'function') {
	function addEvent (obj, evType, fn, useCapture) {
		if (obj.addEventListener){
			obj.addEventListener(evType, fn, useCapture);
			return true;
		} else if (obj.attachEvent){
			var r = obj.attachEvent("on"+evType, fn);
			return r;
		} else {
			return false;
		}
	}
}

// Ecumenical XMLHttpRequest. Derived from technique and code presented
// by Jim Ley at <http://www.jibbering.com/2002/4/httprequest.html>
if (typeof get_xmlhttp != 'function') {
	function get_xmlhttp () {
		var xmlhttp=false;
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
		// JScript gives us Conditional compilation, we can cope with old IE versions.
		// and security blocked creation of the objects.
			try {
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (E) {
					xmlhttp = false;
				}
			}
		@end @*/
		if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
			xmlhttp = new XMLHttpRequest();
		}
		return xmlhttp;
	}
}

// Ecumenical methods for getting page and scrollbar height.
// Derived from <http://www.humanized.com/reader/static/javascript/utils.js>,
// which derived them from code at <http://www.quirksmode.org/viewport/compatibility.html>
if (typeof getPageHeight != 'function') {
	function getPageHeight(){
		var y;
		var test1 = document.body.scrollHeight;
		var test2 = document.body.offsetHeight
		
		 // all but Explorer Mac
		if (test1 > test2) {
			y = document.body.scrollHeight;
		}
		// Explorer Mac; would also work in Explorer 6 Strict, Mozilla and Safari
		else {
			y = document.body.offsetHeight;
		}
		return parseInt(y);
	}
}

if (typeof _getWindowHeight != 'function') {
	function _getWindowHeight(){
		if (self.innerWidth) {
			frameWidth = self.innerWidth;
			frameHeight = self.innerHeight;
		}
		else if (document.documentElement && document.documentElement.clientWidth) {
			frameWidth = document.documentElement.clientWidth;
			frameHeight = document.documentElement.clientHeight;
		}
		else if (document.body) {
			frameWidth = document.body.clientWidth;
			frameHeight = document.body.clientHeight;
		}
		return parseInt(frameHeight);
	}
}

if (typeof getScrollHeight != 'function') {
	function getScrollHeight(){
		var y;
		// all except Explorer
		if (self.pageYOffset) {
			y = self.pageYOffset;
		}
		else if (document.documentElement && document.documentElement.scrollTop) {
			y = document.documentElement.scrollTop;
		}
		 // all other Explorers
		else if (document.body) {
			y = document.body.scrollTop;
		}
		return parseInt(y)+_getWindowHeight();
	}
}

////////////////////////////////////////////////////////////////////////////////
// Do the actual fetching and insert the resulting snippet. ////////////////////
////////////////////////////////////////////////////////////////////////////////

function getMorePosts () {
	var el = document.getElementById('pager-links'); // Insertion point
	var startEl = document.getElementById('pager-prev-link'); // Link to prev page

	if (el && startEl) { // Sanity check: do we have an insertion point and a link to fetch?
		xmlhttp = get_xmlhttp();
		if (xmlhttp) { // Sanity check: did we get an XmlHttpRequest object?
			var uri = null;
			var link = startEl.getElementsByTagName('a');
			for (var i=0; i<link.length; i++) {
				uri = link[i].href;
			}
			if (uri) { // Sanity check: did we get a usable link?
				// This is a rock stupid way to do it.
				if ((uri.indexOf('?format=') == -1) && (uri.indexOf('&format=') == -1)) {
					if (uri.indexOf('?') == -1) {
						uri += '?format=posts'; // no query string
					} else {
						uri += '&format=posts'; // query string not including format
					} // if
				} // if

				// If users style the insertion point to be invisible, make it visisble.
				el.style.display = 'block';
				el.className = 'humanized-history-getting-more';
				el.innerHTML = "<p>Patientez pendant que nous allons chercher au grenier plus de posts juste pour vous…</p>";
	
				xmlhttp.open("GET", uri, true);
				xmlhttp.onreadystatechange=function() {
					var historyNextWindow = document.getElementById('pager-links');
					if (xmlhttp && xmlhttp.readyState==4) { // HTTP GET completed; resutls ready
						if (xmlhttp.status == 200) {
							// HTTP GET OK. Replace the insertion point with the HTML snippet.
							var newHistory = document.createElement('div');
							historyNextWindow.parentNode.replaceChild(newHistory, historyNextWindow);
							newHistory.innerHTML = xmlhttp.responseText;
							historyNextWindow = null;
						} else if (xmlhttp.status == 404) {
							// Error: Not Found. Get off; it's the end of the line.
							historyNextWindow.setAttribute('id', 'history-next-finished'); // Disable further queries...
							historyNextWindow.innerHTML = '<p>There are no more posts in this view.</p>';
						} else {
							// Some kind of status code that we don't know how to deal with.
							historyNextWindow.setAttribute('id', 'history-next-finished'); // Disable further queries...
							historyNextWindow.innerHTML = '<p>Humanized History error: '+xmlhttp.status+" from "+uri+'</p>';
						}
						isUpdating = false;
						sIFR_replace();
						$('#pager-prev-link').click(function(){
							getMorePosts();
							return false;
						});
					}
				}
				xmlhttp.send('');
			}
		}
	}
}

////////////////////////////////////////////////////////////////////////////////
// Poll the status of the scrollbar to see if we're getting near the bottom. ///
////////////////////////////////////////////////////////////////////////////////

function updatePage () {
	if (!isUpdating && (getPageHeight() - getScrollHeight() < preloadDistance)) {
		isUpdating = true;
		getMorePosts();
	} // if
}

function postWindowInit() {
	var el = document.getElementById('pager-links');
	$('#pager-prev-link').click(function(){
		getMorePosts();
		return false;
	});
}

addEvent(window, 'load', postWindowInit, false);


