/* Pageable class definition; adds 'Previous' and 'Next' to page */
var Pageable = Class.create({

    initialize: function(element) {

      // record handles to all important elements
      this.element = $(element);

      // options:
      var options = Object.extend({	
  	  itemsPerPage: 5,
  	  pagedElements: document.getElementsByClassName('paged', this.element),
  	  nextButton: (document.getElementsByClassName('next', this.element))[0],
  	  prevButton: (document.getElementsByClassName('prev', this.element))[0],
  	  statusBar: (document.getElementsByClassName('statusbar', this.element))[0],
	  jumpAnchor: 'TopOfSearch'
  	}, arguments[1] || {});


      this.pagedElements = options.pagedElements;

      this.nextButton = $(options.nextButton);
      this.prevButton = $(options.prevButton);
      this.statusBar = $(options.statusBar);

      this.nextButton.onmousedown = this.nextPage.bindAsEventListener(this);
      this.prevButton.onmousedown = this.prevPage.bindAsEventListener(this);
      
      this.options = options;

      this.numPages = Math.ceil(this.pagedElements.size() / this.options.itemsPerPage);      

      this.currentPage = 1;
      this.startUp = true;
      
      // hide all elements to start
      this.pagedElements.each(function(e) {
	  e.hide();
  	});

      this.toggleCurrentPage();
      this.updateStatus();
      this.startUp = false;
      
    },

    numItems: function() {
      return this.pagedElements.size();
    },

    toggleCurrentPage: function() {      

      this.options.itemsPerPage.times(function(n) {	  
  	  i = n + (this.currentPage-1)*this.options.itemsPerPage;
	  if (i < this.pagedElements.size())
	    this.pagedElements[i].toggle();
  	}.bind(this));
    },

    updateStatus: function() {

      
      start = (this.currentPage-1)*this.options.itemsPerPage;
      end = Math.min(start + this.options.itemsPerPage, this.numItems());

      this.statusBar.innerHTML = 'Viewing results ' + (start+1) + ' - ' + (end) + ' of '
            + this.numItems() + '.';

      if (this.numPages <= 1)
	this.statusBar.hide();
      else
	this.statusBar.show();

      if (end == this.numItems())
	this.nextButton.hide();
      else
	this.nextButton.show();

      if (start == 0)
	this.prevButton.hide();
      else
	this.prevButton.show();

      
      if (!this.options.jumpAnchor.empty() && !this.startUp) 
	window.location.hash = this.options.jumpAnchor;
      
    },

    nextPage: function () {
      
      this.toggleCurrentPage();
      this.currentPage = this.currentPage + 1;
      this.toggleCurrentPage();
      this.updateStatus();
    },

    prevPage: function () {

      this.toggleCurrentPage();
      this.currentPage = this.currentPage - 1;
      this.toggleCurrentPage();
      this.updateStatus();
    }
    
  });