/**
 * Ajax Navigation plugin
 * - apply jQuery History events
 * - load remote content upon specifed links [href]
 * - reload functions if needed through callbacks
 * 
 * Dependencies on :
 * - jquery.history.js
 */
$.fn.ajaxNavigation = function(params){
  /*
   * Extending parameters
   */
  var params = typeof params == 'object' ? params : {};
  params = $.extend({
    basepath:    '',
    event:       'click',
    not:         '[href^=#], a.noajax, a.ajaxified',
    onStart:     function($to, href, hash){},
    onExecution: function($to, href, hash, data){},
    onComplete:  function($to, href, hash){},
    to:          '#general-container'
  }, params);

  /*
   * Main function called as callback (can be entirely hooked in the future)
   * Its power: everything is pluggable
   */
  var _main_callback = function($to, href, hash)
  {
    hash = typeof hash == 'undefined' ? '' : hash;
    $to.data('hash', hash);
    params.onStart.call(this, $to, href, hash);

    $.ajax({
      type:      'GET',
      url:       href,
      success:   function(data){ params.onExecution.call(this, $to, href, hash, data); },
      complete:  function(data){ params.onComplete.call(this, $to, href, hash); } 
    });

    console.log('onComplete: %s (#%s)', $to.data('initialized'), $to.data('hash'));
  }

  //get data from the recipient
  //can check if we need to init jQuery History
  var $to = $(params.to);
  if (typeof $to.data('initialized') == 'undefined' || !$to.data('initialized'))
  {
    /*
     * This function is called :
     * - on init
     * - on .historyLoads calls (each time URI change, even by hand)
     */
    $.historyInit(function(hash){
      /*
       * hash & first time ? load
       * hash & second time ? yes if current hash and hash are different (else we are on the same page
       */
      console.log('historyInit: %s (#%s)', $to.data('initialized'), $to.data('hash'));
      if ((hash && !$to.data('initialized')) || (hash && hash != $to.data('hash')))
      {
        /*
         * If the hash exists as an ID on the page it is an anchor
         * We don't load the content
         * .length seems not to be available at the time of the operation
         */
        var $internal_link = $('#'+hash);
        if ($internal_link.length)
        {
          console.log('history(null): %s is an internal link', hash);
          return false;
        }
        
        console.log('historyInit(call): %s (#%s)', $to.data('initialized'), $to.data('hash'));
        _main_callback.call(this, $to, params.basepath + '/' + hash, hash);
      }
    });
    $to.data('initialized', true)
    console.log('initialized: %s (#%s)', $to.data('initialized'), $to.data('hash'));
  }

  //loop on elements and remove all static links (typically ajax links)
  //@todo : can play without params.not to fasten the loop
  return this
    .filter('a[href^=#]').click(function(){ return false; }).addClass('anchor').end()
    .not(params.not).each(function(){
    $(this)
      .one(params.event, function(){
        //guess the basepath
        //this.href is absolutize by the browser, it's easier for us to work with it
        //it basepath is relative, the loading will be fine but the permalink may be not (@todo fix this)
        var hash = this.href.replace(new RegExp('^'+params.basepath+'/', 'g'), '');

        var $to = $(params.to);
        _main_callback.call(this, $to, this.href, hash);

        //save the hash in the history
        $.historyLoad(hash);
      })
    .addClass('ajaxified')
    .bind(params.event, function(){
      return false;
    });
  });
};