/**
 * Pager - Paginate between pages using ajax calls
 *
 * @version		1.0rc1
 *
 * @license		MIT-style license
 * @author		Ahmad Ali
 * @copyright	Author
 */
 
 var Pagination = new Class({
  Implements: Options,
  options: {
        link_class: '',
        link_selected_class: '',
        record_count: 0,
        record_count_per_page: 0,
        visible_links: 0
  },

  initialize: function ( pager, options ){
      this.current_page = 0;
      this.pager = $(pager);
      this.setOptions(options);
      this.paging_offset = Math.ceil( this.options.visible_links / 2 ) - 1;
      this.number_of_pages = Math.ceil( this.options.record_count / 
                                        this.options.record_count_per_page );
      this.set_pager();
  },

  set_record_count: function ( new_record_count )
  {
    this.clear_pager();
    this.current_page = 0;
    this.options.record_count = new_record_count;
    this.number_of_pages = Math.ceil( this.options.record_count / 
                                      this.options.record_count_per_page );
    this.set_pager();    
  },

  set_pager: function () {

     var start_page = ( this.current_page < this.paging_offset ) ? 0 : ( this.current_page - this.paging_offset );
     var visible_links = this.options.visible_links;
     
     // create paging numbers

     for ( i = start_page, j = 0; i < this.number_of_pages && j < visible_links && this.number_of_pages > 1; i++, j++ )
     {
        var href_class = ( i == this.current_page ) ? this.options.link_selected_class : this.options.link_class;
        var page_anchor = new Element('a', {
        	
           'href': 'javascript:void(0);',
           'class': href_class,
           'page_index': i,
           'html': i+1,
           'current_page': ( i == this.current_page ? 'Y' : 'N' ),
           'events': {
              'click': function(ev){
                 el = ev.target;
                 if ( el.getProperty('current_page') == 'Y' ) 
                   return;
                   
                 this.clear_pager();
                 this.current_page = (el.getProperty('page_index')).toInt();
                 this.set_pager();
                 var start = ( this.current_page * this.options.record_count_per_page );
                 var end = this.options.record_count_per_page;
                 this.options.onClick( start, end );
              }.bindWithEvent(this)
           }
       });
       this.pager.adopt(page_anchor);
     }
  },

  clear_pager: function () {
    this.pager.set( 'html', '' );
  }
});