(function($){

/**
 * <a title="__TITLE__" href="__IMAGE_LOCATION__" rel="photoflow[__IMAGE_ID__]"></a>
 */
var ns = "Photoflow";

window[ns] = function ( options ) {
  this.options = options;

  this.anchor = $(options.anchor);
  this.more = $(options.more);
  
  this.ajax_base = AJAX_BASE + 'morephoto/?';

  this.observe();
  this.init();
}

window[ns].prototype = {
  
  init: function () {
    this.storage = {};
    this.buffer = [];
    this.index = 0;
    this.restore( this.anchor );
  },
  
  restore: function ( elements ) {
    var storage = this.storage;
    elements.each( function ( i, element ) {
      var index = /^photoflow\[(\d+)\]$/.exec($(element).attr('rel'))[1];

      if ( ! storage[index] ) storage[index] = [];
      storage[index].push(element);

    });
  },
  
  observe: function () {
    this.anchor.click( $.proxy( this.click, this ) );
    this.more.click( $.proxy( this.loadMore, this ) );
  },
  
  register: function ( anchor ) {
    this.restore( anchor );
    anchor.click( $.proxy( this.click, this ) );
  },
  
  loadMore: function ( event ) {
    var button = $(event.currentTarget);
    var match = /\/post\/(\d+)\/$/.exec(button.attr('href'));
    if ( ! match ) return;
    
    // Start
    event.preventDefault();
    if ( button.hasClass('loading') ) return;
    button.blur();
    
    var wall_id = match[1];
    var para = { wall_id: wall_id };
    var url = this.ajax_base + $.param( para );
    var root = button.parent().find('ul');
    
    button.addClass('loading');
    
    $.ajax(url).done(function ( data ) {
      
      $(data).each(function(i,element){
        if ( 1 != element.nodeType ) return;
        var block = $(element);
        block.hide().appendTo(root).fadeIn();
        Activate(block);
      });
      
      button.remove();
      
    });

  },
  
  registerMore: function ( button ) {
    button.click( $.proxy( this.loadMore, this ) );
  },
  
  click: function ( event ) {
    event.preventDefault();
    var element = event.currentTarget;
    
    var key = /^photoflow\[(\d+)\]$/.exec($(element).attr('rel'))[1];
    this.buffer = this.storage[key];
    var index = $.inArray(element, this.buffer);
    
    new PhotoSlide( this.buffer, index, function() {
      // do something if close
    } );
  }
  
};

})(jQuery);
