/*global jQuery, hsp, window*/
/*jslint browser:true , devel:true, white:false, maxerr:3 */
(function () {
  try {
    // a plugin for unified history management through the address plugin or, if present, html5 history
    // depends on:
    //   jQuery
    //   address plugin
    //
    // The plugin api has only two functions:
    // 1. The lib.ffhistory.init method has to be called during document.ready
    // 2. Whenever the app wants to go to a URL with history support, it has to call
    //   ffhistory.historyLoad(sds)
    //
    //
    var $,lib,html5,load,ffhistory;

    $ = jQuery;
    lib = hsp;
    html5 = (typeof(lib.history) === 'undefined')? !!(history && history.pushState):lib.history;
    lib.ffhistory = function () {};
    ffhistory = lib.ffhistory;

    if (html5) {
      lib.info('using html5 history');
    } else {
      lib.info('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
    load = function (sds) {
      lib.error('ffhistory plugin: no load function defined');
    };

    ffhistory.defaults = {
      defaultPath : '/',
      log : false
    };

    // to be called in document.ready()
    ffhistory.init = function init(userload, track) {
      if (!$.isFunction(userload)) {
        lib.error('no valid userload function');
      }
      if (!$.isFunction(track)){
        lib.error('no valid tracking function');
      }
      // check if the address plugin is present
      if (typeof($.address)!='object') {
        lib.error('address plugin missing');
      }
      load = userload;

      // Set the event handlers
      if (html5) {
        initHtml5(track);
      } else {
        initAdressPlugin();
      }
    };
  
    function initHtml5(track){
      // init html5 history
      var hash,sds;
      hash = location.hash;
      if (hash) {
        // strip off the hash symbol
        sds = hash.slice(1);
        // load the appropriate content
        load(sds); // sets document.title
        // we replace the old hashed url with the correct one
        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(ffhistory.defaults.defaultPath);
        }
      };

      ffhistory.historyLoad = function (sds) {
        load(sds); // sets document.title
        // put on history stack
        history.pushState({
          sds:sds
        },document.title,sds);
        if (track) {
          track(sds);
        }
      };
    }

    function initAdressPlugin(track) {
      // no html5 history
      // using the address plugin
      // do some initialization
      var url,i,path;
      url = location.href;
      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
        path = 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
      ffhistory.historyLoad = function (sds) {
        var currentSds = $.address.value();
        if (currentSds === sds) {
          // if we just set the value, address will not call the callback, as we have the same val
          // again
          // we fix this to be like the html5 behaviour
          $.address.update(sds);
        } else {
          // the sds is different
          $.address.value(sds);
        }
      };
    }


  } catch(e) {
    lib.handle(e)
  }
}());
