// currently o0nly allows one paginator/page
var paginator = new (Class.create({
  initialize: function(options) {
    Object.extend(this, {
      callback: null,
      cache: [],
      index: null,
      root: null
    });
    return this;
  },

  togglePrevious: function(enable) {
    this.cache[0][enable ? 'removeClassName' : 'addClassName']('inactive');
  },
  toggleNext: function(enable) {
    var last = (this.cache.length - 1);
    this.cache[last][enable ? 'removeClassName' : 'addClassName']('inactive');
  },

  getRoot: function() {
    if (!this.root) {
      this.setRoot();

      this.cache = this.root.childElements();
    }
    return this.root;
  },
  setRoot: function() {
    this.root = $('paginator');
  },

  getIndex: function () {
    return this.index || 1;
  },
  setIndex: function(index) {
    this.getRoot();

    index = parseInt(index, 10);
    if (index < 1) {
      index = 1;
    }

    // lengrh-2 to ignore next and previous
    if (index > (this.cache.length - 2)) {
      index = (this.cache.length - 2);
    };

    if (this.index !== index) {
      $('paginator_index').value = this.index = index;

      return true;
    }
    return false;
  },

  page: function(index, callback) {
    this.callback = callback;

    if (index === 'next') {
      index = (this.getIndex() + 1);
    } else if (index === 'previous') {
      index = (this.getIndex() - 1);
    }
    
    if (this.setIndex(index)) {
      this.togglePrevious(this.index > 1);
      this.toggleNext(this.index < (this.cache.length - 2));


      this.root.select('.active')[0].removeClassName('active');
      this.cache[this.index].addClassName('active');


      if (this.callback) {
        this.callback();
      }
    }
  }
}))();

Object.extend(paginator, {
  test: function() {
    
  }
});
