﻿var currentHash = "";

function ajax_loaded(responseText, textStatus, XMLHttpRequest) {
    if (textStatus == "error") {
        prompt("URL Failed: ", XMLHttpRequest);
    } else {
        // set title
        document.title = titleFromHTML(responseText);
        // update links
        updateLinks("#content-outer A");
    }
}

function history_loaded(hash) {
    // history plugin does not handle well - may call this method more than once for the same URL
    // recursion occurs if the pageLoad() method is called and these conditions are not below
    if (currentHash != hash && escape(hash) != currentHash && escape(currentHash) != hash) {
        // do not remove the line below
        currentHash = hash;
        // load page in hash as necessary
        if (hash != "") {
            var URL = hash;
            if (URL.indexOf(" ") >= 0) {
                URL = escape(URL);
            }
            URL = location.protocol + "//" + location.host + URL;
            loadPage(URL);
        }
    }
}

function loadPage(URL) {
    // added to prevent recursion
    $.history.load(urlToPath(URL));
    $("#content-outer").load(URL + " #content", null, ajax_loaded);
    return false;
}

function check_on_load() {
    // initialise history
    $.history.init(history_loaded);
    // update links
    updateLinks("A");
}

$(document).ready(check_on_load);

// UTILITY METHODS

function urlToPath(URL) {
    return URL.replace(new RegExp("http[s]?://[^/]*"), "");
}

function titleFromHTML(HTML) {
    var regex = new RegExp("<title>([^<]*)</title>");
    var matches = regex.exec(HTML);
    if (matches.length > 1) {
        return matches[1];
    } else {
        return "";
    }
}

function updateLinks(DOMLocation) {
    var links = $(DOMLocation);
    var baseURL = location.protocol + "//" + location.host + "/";
    for (var i = 0; i < links.length; i++) {
        var el = links[i]
        if (
                el.onclick == null &&
                el.href.indexOf(baseURL) == 0 &&
                el.href.indexOf("#") < 0 &&
                el.target == "" &&
                (el.href.indexOf(".aspx") >= 0 || el.href == baseURL) &&
                el.className.toLowerCase().indexOf("no-ajax") < 0
            ) {
            el.onclick = Function("return loadPage(this.href);");
        }
    }
}