/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 * API rewrite by Lauris Buk�is-Haberkorns
 *
 * EdM: Modified the way Safari plugin works. Like FF just sense the location.hash every tenth second, and load accordingly.
 */

(function($) {

function History()
{
  this._curHash = '';
  this._callback = function(hash){};
};

$.extend(History.prototype, {

  init: function(callback) {
    this._callback = callback;
    this._curHash = location.hash;

    if($.browser.msie) {
      if(location.search)
        this._curHash += location.search;
      // To stop the callback firing twice during initilization if no hash present
      if (this._curHash == '') {
        this._curHash = '#';
      }

      // add hidden iframe for IE
      $("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
      var iframe = $("#jQuery_history")[0].contentWindow.document;
      iframe.open();
      iframe.close();
      iframe.location.hash = this._curHash;
    }
    setInterval(this._check, 100);
  },

  _check: function() {
    if($.browser.msie) {
      // On IE, check for location.hash of iframe
      var ihistory = $("#jQuery_history")[0];
      var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
      // EdM: msie seems to strip of the search parameter, even if it is defined behind the hash. So add it again
      var current_hash = iframe.location.hash;
      if(iframe.location.search)
        current_hash += iframe.location.search;
      if(current_hash != $.history._curHash) {
        location.hash = current_hash;
        $.history._curHash = current_hash;
        $.history._callback(current_hash.replace(/^#/, ''));
      }
    } else {
      // otherwise, check for location.hash
      var current_hash = location.hash;
      if($.browser.safari)
        current_hash = current_hash.replace(/^#/, '');
      if(current_hash != $.history._curHash) {
        $.history._curHash = current_hash;
        $.history._callback(current_hash.replace(/^#/, ''));
      }
    }
  },

  add: function(hash) {
    var newhash;
    
    if ($.browser.safari)
      newhash = hash;
    else
      newhash = '#' + hash;
    location.hash = newhash;
    this._curHash = newhash;
    if ($.browser.msie) {
      var ihistory = $("#jQuery_history")[0]; // TODO: need contentDocument?
      var iframe = ihistory.contentWindow.document;
      iframe.open();
      iframe.close();
      iframe.location.hash = newhash;
    }
  },

  load: function(hash) {
    this.add(hash);
    this._callback(hash);
  }

});

$(document).ready(function() {
  $.history = new History(); // singleton instance
});

})(jQuery);
