var title = "Offend Me";

var baseUrl = window.location.protocol + "//" + window.location.host;
baseUrl += "/";

var dynamic = true;
var noTabs = false;

function load_page(url, save) {
    jQuery.getJSON(url, {
        mode: "content"
    }, function(data) {
        for(var prop in data) {
            jQuery("#" + prop).html(data[prop]);
        }

        // Set page title
        if(data.title) {
            jQuery("title").text("Offend Me: " + data.title);
        }

        // Scroll to the top
        window.scroll(0, 0);

        if(save) {
            // Update browser history
            history.pushState({url: url}, jQuery("title").text(), url);
        }

        // Disqus page tracking
        DISQUS.reset({
            reload: true,
            config: function () {  
                this.page.identifier = data.path;
                this.page.url = data.path;
            }
        });
    });
}

// Are we a kindle?
if(/kindle/i.test(window.navigator.userAgent)) {
    dynamic = true;
    noTabs = true;
}

// Save current state
history.replaceState({url: window.location.href}, jQuery("title").text(), window.location.href);

// Load our previous state
window.onpopstate = function(event) {
    if(event.state && event.state.url) {
        load_page(event.state.url);
    }
};

jQuery("a").live("click", function(e) {
    var url = this.href;

    if(dynamic && new RegExp("^" + baseUrl, "i").test(url) && !/#\w+$/.test(url)) {
        e.preventDefault();

        load_page(url, true);

        return false;
    } else if(!noTabs) {
        this.target = "_blank";
    }
    return true;
});

