Pager = Class.create({

	initialize: function(element) {
		this.element = $(element);
		if (this.element)
		{
			this.readVariables();
			this.hookEvents();
		}
	},
	
	readVariables: function() {
		this.pageIndex 	= parseInt(this.element.readAttribute("pageIndex"));
		this.pageCount 	= parseInt(this.element.readAttribute("pageCount"));
		this.url		= this.element.readAttribute("url");
	},
	
	hookEvents: function() {
		this.element.observe("blur", 		this.pagerLostFocus.bindAsEventListener(this));
		this.element.observe("focus", 		this.pagerGotFocus.bindAsEventListener(this));
		this.element.observe("keypress",	this.pagerKeyPress.bindAsEventListener(this));
	},
	
	pagerLostFocus: function(e) {
		this.element.value = this.pageIndex + " / " + this.pageCount;
	},
	
	pagerGotFocus: function(e) {
		this.element.value = this.pageIndex;
		this.element.select();
	},
	
	pagerKeyPress: function(e) {
		var keyCode = e.keyCode;
		switch (keyCode)
		{
			case 0:
				if (!(e.charCode >= 48 && e.charCode <= 57))
				{
					Event.stop(e);
					return false;
				}
				break;
			case Event.KEY_RIGHT:
			case Event.KEY_LEFT:
			case Event.KEY_HOME:
			case Event.KEY_END:
			case Event.KEY_TAB:
			case Event.KEY_DELETE:
			case Event.KEY_BACKSPACE:
				break;
			case Event.KEY_RETURN:
				var value = parseInt(this.element.value);
				if (!isNaN(value))
				{
					if (value < 1)
					{
						value = 1;
					} else if (value > this.pageCount)
					{
						value = this.pageCount;
					}
					top.location = this.url.replace("999999", value);
				} else
				{
					alert("Please enter a valid numeric value to go to specific result page.");
				}
				break;
			default:
				Event.stop(e);
				return false;	
		}
	}
});

function windowLoadedPager()
{
	new Pager("pagerInput");
}

(function() {
	Event.observe(window, "load", windowLoadedPager);
})();

