/* 
A paged list of work
- The paged action should return rendered <li> items, and a total_pages count in the X-JSON header

EXAMPLE:

<div id='works'><!-- id of containing class required -->
  <ul></ul><!-- ul required -->
  <a class='prev'>Prev</a> | <a class='next'>Next</a> <!-- prev and next classes required -->
</div>

<script type='text/javascript'>
  new RB.Carousel('works', '/url/to/paged/action', 4);
</script>

*/

if (!RB)
  var RB = {};

RB.Carousel = Class.create({
  initialize: function(container, options) {
    this.container = $(container);
    this.sourceUrl = options.sourceUrl;
    this.perPage = options.perPage;
    this.scroll = options.scroll;
    this.width = options.width;
    this.buttons = [
      {elem: this.fetch('a.next'), mod: 1,  valid: function(carousel) { return carousel.currentPage < carousel.totalPages }},
      {elem: this.fetch('a.prev'), mod: -1, valid: function(carousel) { return carousel.currentPage > 1 }}
    ]

    loadFunc = function() { 
      if (Element.setVisible != null) {
        this.repaintButtons();
        this.fetch('.no-works').hide();

        this.fetch('.carousel-loading').hide();
        this.getPage(this.currentPage, 0, function() {
          // Initialize next/prev behaviour after first page has been loaded, so we know how many total pages there are
          this.repaintButtons();
          this.container.select('.loading').each(function (e) { e.hide() });
          this.buttons.each(function (direction) {
            direction.elem.writeAttribute('href', '#');       // Make the element clickable
            direction.elem.observe('click', function(e) {
              if (direction.valid(this)) {
                this.fetch('.carousel-loading').appear({duration: 0.5});
                this.getPage(this.currentPage + direction.mod, direction.mod);
                this.repaintButtons();
              }
              e.stop();
            }.bindAsEventListener(this));
          }.bind(this));
        }.bind(this));  
      } else {
        // This is needed for IE - good chance ext/set_visible hasn't executed yet
        loadFunc.bind(this).defer();
      }
    }
    document.observe("dom:loaded", loadFunc.bind(this));
  },
  repaintButtons: function() { // Hide a button if it isn't a valid direction (previous on page 1)
    this.buttons.each(function (direction) { Element.setVisible(direction.elem, direction.valid(this)); }.bind(this));
  },
  fetch: function(handle) {
    return this.container.down(handle);
  },
  getPage: function(page, mod, callback) {
    this.currentPage = page;
    new Ajax.Request(this.sourceUrl, {
      method: 'get',
      parameters: {
        per_page: this.perPage,
        page:     page
      },
      onSuccess: function(transport) {
        if (mod == 0 || !this.scroll) {
          this.fetch('ul').innerHTML = transport.responseText; 
        }

        if (this.scroll) {
          if (mod > 0) {
            toRemove = this.fetch('ul').select('li');
            this.fetch('ul').insert({bottom: transport.responseText}); 
            this.fetch('ul').morph('margin-left: -700px;', {
              duration: 0.7,
              afterFinish: function() {
                toRemove.each(function (e) {
                  e.remove();
                });
                this.fetch('ul').setStyle({'marginLeft': 0})
              }.bind(this)
            });
          }
          if (mod < 0) {
            toRemove = this.fetch('ul').select('li');
            this.fetch('ul').insert({top: transport.responseText}); 
            this.fetch('ul').setStyle({'marginLeft': '-700px'});
            this.fetch('ul').morph('margin-left: 0px;', {
              duration: 0.7,
              afterFinish: function() {
                toRemove.each(function (e) {
                  e.remove();
                });
              }.bind(this)
            });
          }
        }
        this.totalPages = transport.headerJSON.total_pages
        
        if (this.totalPages == 0) {
          this.fetch('ul').hide();
          this.fetch('.no-works').show();
        }
        
        this.fetch('.carousel-loading').fade({duration: 0.5});
        if (callback)
          callback();
      }.bindAsEventListener(this)
    });
  },
  container: null,
  currentPage: 1,
  totalPages: 0,
  perPage: 0,
  sourceUrl: ''
});
