/*!
 * Helper functions for allowing browser-history aware page
 * changes for AJAX parts of the site.
 */
function onPageLoad()
{
    window.curHashVal = window.location.hash;

    // Check if there is a hash depicting an inline-search
    var newURL = window.location.hash.split("#")[1];
    if (newURL && newURL.substring(0, 21) == "/search/inlinesearch/")
    {
        $("#searchResults").html('<img src="{{ MEDIA_URL }}images/loading.gif" />')
        new $.ajax({url: newURL,
                    cache: false,
                    success: function( transport ) { $( '#searchResults' ).html( transport ); }
                    });
    }

    // Start the hash monitoring function
    setInterval(reloadPage, 200);
}

function updateCurrentPageHash(value)
{
    window.location.hash = value;
    window.curHashVal = window.location.hash;
}

function reloadPage()
{
    // Check if the has has changed
    if (window.curHashVal != window.location.hash)
    {
        // Differ between "real" pages and AJAX pages
        var newURL = window.location.hash.split("#")[1];
        if (!newURL)
        {
            scroll(0, 0);
            $("#searchResults").html('<img src="{{ MEDIA_URL }}images/loading.gif" />')
            window.location = window.location.hash.split("#")[0];
        }
        else
        {
            if (newURL.substring(0, 21) == "/search/inlinesearch/")
            {
                scroll(0, 0);
                $("#searchResults").html('<img src="{{ MEDIA_URL }}images/loading.gif" />')
                new $.ajax({url: newURL,
                            cache: false,
                            success: function( transport ) { $( '#searchResults' ).html( transport ); }
                            });
            }
        }

        updateCurrentPageHash(newURL);
    }
}

