
(function()
    {
      var url = window.location.href;
      var posR = url.lastIndexOf("#st=");
      if (posR == -1) return;
      var state = url.substring(posR + "#st=".length);
      url = url.substring(0,posR); // Removing ref
      var posQ = url.lastIndexOf("?");
      var query = null;
      if (posQ != -1)
      {
        query = url.substring(posQ);
        url = url.substring(0,posQ); // Removing query
        var posState = query.indexOf("st=");
        if (posState != -1)
        {
            // Changing st parameter with ref state (this is the most important)
            var endState = query.indexOf("&",posState);
            if (endState == -1) endState = query.length;
            query = query.substring(0,posState) + "st=" + state + query.substring(endState);
            url = url + query;
        }
        else url = url + query + "&st=" + state;
      }
      else url = url + "?st=" + state;
      url += "#st=" + state;

      if (url != window.location.href)
        window.location.href = url;
    }
)();

function SPISite()
{
    this.detectBackForward = detectBackForward;
    this.detectBackForwardCB = detectBackForwardCB;
    this.setURLReference = setURLReference;

    this.href = null;
    this.disabled = ((navigator.userAgent.indexOf(" IEMobile") != -1) &&
                     (navigator.userAgent.indexOf("MSIEMobile") == -1)); // Pocket IE ever reloads

    function setURLReference(stateName)
    {
        if (this.disabled) return;

        var url = window.location.href;
        var posR = url.lastIndexOf("#");
        if (posR != -1) url = url.substring(0,posR); // Removing current
        url = url + "#st=" + stateName;
        if (url != window.location.href)
            window.location.href = url;

        this.detectBackForward();
    }

    function detectBackForward()
    {
        this.href = window.location.href;

        var func = function()
        {
            arguments.callee.spiSite.detectBackForwardCB();
            window.setTimeout(arguments.callee,200);
        };
        func.spiSite = this;
        window.setTimeout(func,200);
    }

    function detectBackForwardCB()
    {
        // Detecting when only the reference part of the URL changes
        var url = window.location.href;
        if (this.href == url) return;
        var posR = url.lastIndexOf("#st=");
        if (posR == -1) return;
        var posR2 = this.href.lastIndexOf("#st=");
        if (posR != posR2) return;
        var url2 = url.substring(0,posR);
        var spiHref2 = this.href.substring(0,posR);
        if (url2 != spiHref2) return;

        // Only changed the reference part
        this.href = url;

        var stateName = url.substring(posR + "#st=".length);
        if (this.onBackForward) this.onBackForward(stateName);
        else try { window.location.reload(true); }
             catch(ex) { window.location = window.location; }
    }
}

window.spiSite = new SPISite();

