var Pager = Class.create({
	
	initialize: function(div){
		this.div = div;
		this.window = div.down('.window');
		this.pagination = this.div.down('.pagination');
		this.children = this.window.childElements();
		this.original_width = this.window.getWidth();
		this.children_width = this.children.size() * this.children.first().getWidth();
		this.pages = 1;
		this.window.setStyle({width: (this.children_width + (10 * this.children.size())) + 'px'});
		if (this.children_width > this.original_width) {
			this.pages = Math.ceil(this.children_width / this.original_width);
			this.build_pagination();
		}
	},
	
	build_pagination: function(){
		// Add the page links
		for (var i=1; i <= this.pages; i++) {
			var css = (i == 1) ? 'active' : '';
			this.pagination.insert('<a href="javascript:void(0);" class="' + css + '">' + i + '</a>');
		}
		// Hook up the page links
		this.pagination.childElements().each((function(p){
			p.observe('click', this.handle_click.bind(this));
		}).bind(this));
	},
	
	handle_click: function(e){	
		Event.stop(e);
		var btn = $(e.target);
		if (btn.hasClassName('active')) { return false; }
		
		btn.siblings().invoke('removeClassName', 'active');
		btn.addClassName('active');
		// Hack for Firefox
		var page = parseInt(btn.innerHTML);
		var new_x = ((page - 1) * (this.original_width + 10)) * -1;
		new Effect.Move(this.window, { x: new_x, mode: 'absolute' });
	}
	
});

Event.observe(window, 'load', function() {
	$$('.pager').each(function(div){
		new Pager(div);
	});
});