jQuery.fn.ffhistory = function () {
  // check for existence of html5 history
  var lib = fff;
  var html5 = !!(window.history && history.pushState);
  if (html5) {
//    console.log('using html5 history');
  } else {
//    console.log('using address plugin');
  }

  // default for a function which must be supplied by the user
  // it takes a string (screen description string), and brings the screen to the appropriate
  // state in whatever way necessary
  var load = function (sds) {
    console.log('ffhistory plugin: no load function defined');
  }

  

  // to be called in document.ready()
  jQuery.fn.ffhistory.init = function (userload, track) {
    // TODO check for address plugin
    load = userload;


    // Set the event handlers
    if (html5) {
      // init html5 history
      var hash=window.location.hash;
      if (hash) {
        // strip off the hash symbol
        var sds = hash.slice(1);
        // load the appropriate content
        load(sds); // sets document.title
        // we replace the old hashed url with the correct one
        window.history.replaceState(
        {
          'sds': sds
        }, document.title, sds);
      }
      // set html5 handler
      window.onpopstate = function(ev) {
        var state = ev.state;
        console.log(state);
        if (state) {
          load(state.sds);
        } else {
          // no state elem
          load(jQuery.fn.ffhistory.defaults.defaultPath);
        }
      }

      jQuery.fn.ffhistory.historyLoad = function (sds) {
        load(sds); // sets document.title
        // put on history stack
        window.history.pushState({
          sds:sds
        },document.title,sds);
        if (track) {
          track(sds);
        }
      }
    } else {
      // no html5 history
      // using the address plugin
      // do some initialization
      var url = window.location.href;
      var i = url.indexOf('#');
      if (i == -1) {
        // there is no # in the url, so we use the given path as starting point for the
        // address plugin.
        // otherwise it would use '/' as current value
        var path = window.location.pathname;
        $.address.value(path);
      }
      // set address plugin handler
      $.address.change(function (ev){
        load(ev.value);
      })
      // set address plugin tracker
      $.address.tracker(track);
      // set up historyLoad function
      jQuery.fn.ffhistory.historyLoad = function (sds) {
        $.address.value(sds);
      }
    }
  }
};

jQuery.fn.ffhistory.defaults = {
  defaultPath : '/',
  log : false
}
$.fn.ffhistory();


