/* 
Michael's Rolling Archives 
by Michael Heilemann - http://binarybonsai.com
*/

function rollArchive(direction) {

	if (direction == 1 || direction == -1) {
		// Update the variables
		position = position + (direction*offset);
		pagenumber += direction;
	} else if (direction == 'home') {
		// Reset the variables
		pagenumber = 1; 	// Just an indicator for the page counter
		offset = 5; 		// Posts to move per increment + starting position
		position = 5;		// Change this according to your Reading Options Blog Pages
	}

	$('rollingcontent').innerHTML = '<div class="rollloading"></div>'; // Insert Loading Spinner
	$('rollpages').innerHTML = 'Page '+pagenumber+' of '+pagecount; // Update Page Count

	// Make sure we don't allow people to go below page 1
	if (pagenumber < '2') {
		$('rollnext').className = 'inactive';
		$('rollnext').onclick = null;
	} else {
		$('rollnext').className = null;
		$('rollnext').onclick = function() { rollArchive(-1); };
	}

	// Make sure we don't allow people to go above pagecount.
	if (pagenumber >= pagecount) {
		$('rollprevious').className = 'inactive';
		$('rollprevious').onclick = null;
	} else {
		$('rollprevious').className = null;
		$('rollprevious').onclick = function() { rollArchive(1); };
	}

	// This part requires Prototype (http://prototype.conio.net/)
	new Ajax.Updater('rollingcontent', 'http://blog.werci.com/wp-content/plugins/rollingarchives/rollingarchives.php', {method: 'get', parameters: 'paged='+position, onFailure: rollError});
}

function rollError() {
	$('rollingcontent').innerHTML = 'Danger Will robinson! Danger!';
	}

function initRollArchive() {
	// Is only run onload.
	if (pagecount > 0) {
		// There are posts
		$('rollhome').onclick = function() { rollArchive('home'); };
		$('rollprevious').onclick = function() { rollArchive(1); };

		rollArchive('home');
	} else {
		// No archived posts. Turn everything off.
		$('rollingcontent').innerHTML = 'There are no archived posts.';

		$('rollprevious').className = 'inactive';
		$('rollprevious').onclick = null;
		$('rollnext').className = 'inactive';
		$('rollnext').onclick = null;
		$('rollhome').className = 'inactive';
		$('rollhome').onclick = null;
	}
}
// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog, added by Safirul Alredha.
function addLoadEvent(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function'){
        window.onload = func;
        } else {
                window.onload = function(){
                oldonload();
                func();
                }
        }
}

addLoadEvent(initRollArchive);  // run initRollArchive onLoad
