/* Author: Adrian Quek
 * Last Modified: 21 June 2007
 * Purpose: Pagination hack for Blogger.
 * License:
 * This is a small piece of code and I do not speak legalese; that's up to the suits.
 * So feel free to copy, distribute or modify the code to suit your needs.
 *
 * Description:
 * This hack is based on the Blogger data API. In particular,
 * it uses the "updated-max" and "max-results" query parameters.
 *
 * Addendum: If you have found this code to be useful and wish to reward the author,
 * feel free to donate to his Beer Fund at http://donaq.blogspot.com
 *
 */

//this function writes the older posts link
function writeOlder(max, datestr, page){
	var t = Date.parse(datestr);
	//replace the following with the date of your oldest post if you want to hide older post link when oldest
	//post appears on the page
	var oldestConst = Date.parse("1970-01-01 00:00:00");

	//page does not have meaning for blogger's search function, hence we use it to signal writeNewer to hide
	//the newer posts link when we are at the homepage.
	page++;

	//we subtract 1 second from the earliest post on the current page to get our updated-max value
	t = t - 1000; 

	if(t<oldestConst){
		document.getElementById("old").style.display="none";
		return;
	}

	//actual writing of the link
	writeLinks(t, page, max, "older", "max");
}

//this function writes the newer posts link
function writeNewer(page){
	//0th page, we don't show newer posts link
	if(page==0){
		document.getElementById("new").style.display="none";
		return;
	}
	document.getElementById("newer").href="javascript:window.history.back()";
}

//function to write the links
function writeLinks(t, page, max, elemstr, updatemode){
	var d = new Date();
	var refstr = "";

	d.setTime(t);
	//for some reason, javascript's getMonth() function returns a number from 0-11, which seems at odds with the getYear() function
	var mth = d.getMonth() + 1;
	//write the links
	refstr = "search?page=" + page + "&updated-" + updatemode + "=";
	refstr += encodeURIComponent(d.getFullYear() + "-" + mth + "-" + d.getDate() + "T");
	refstr += encodeURIComponent(d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "+00:00")
	refstr += "&max-results=" + max;
	//prefix is for labels
	prefix = location.href.charAt(location.href.length-1)=="/"?"":location.href + "/";
	document.getElementById(elemstr).href=prefix+refstr;
}

//this function parses the "page" parameter from the URI and calls writeOlder and writeNewer with the resultant arguments
function getParams(datestr){
	var max = 10; //max number of posts, edit to desired number
	var params = decodeURIComponent(location.search);

	params = params.substring(1);
	var parr = params.split("&");
	var i=0;
	var pagestr = "";
	for(i=0;i<parr.length;i++){
		pagestr = parr[i].split("=");
		if(pagestr[0]=="page"){
			writeOlder(max, datestr, pagestr[1]);
			writeNewer(pagestr[1]);
			return;
		}
	}
	writeOlder(max, datestr, 0);
	writeNewer(0);
}

