// jQuery anchor-based navigation plugin
// Created by Spencer Tipping, licensed under the MIT source code license

(function ($) {
  var state_changed_listeners = []
  var the_current_state       = document.location.hash

  $.anchor = {
    encodeURL: function (state) {
      var result = ''
      $.each (state, function (k) {result += k + '=' + this + '&'})
      return '#' + result.replace (/&$/, '')
    },

    decodeURL: function (anchor_part_of_url) {
      var result = {}
      $.each (anchor_part_of_url.replace (/^#/, '').split (/&/), function () {
        var pair = this.split (/=/)
        result[pair[0]] = pair[1]
      })
      return result
    },

    state: function (the_new_state) {
      if (the_new_state) return document.location.hash = $.anchor.encodeURL (the_new_state)
      else               return $.anchor.decodeURL (document.location.hash)
    },

    listen: function () {
      $.each (arguments, function () {state_changed_listeners.push (this)})
    },

    notify: function () {
      if (document.location.hash != the_current_state) {
        var the_new_state = $.anchor.decodeURL (the_current_state = document.location.hash)
        $.each (state_changed_listeners, function () {
          this.apply (the_new_state, [])
        })
      }
    }
  }

  $(document).ready (function () {
    window.setInterval ($.anchor.notify, 100)
  })
}) (jQuery)