function Route() {
    $('[data-route]').each(function () {
        var url = $(this).data('route');
        var $this = $(this);
        $.get(url, function (data) {
            $this.replaceWith(data);
            $('window').trigger('load');
        });
    });
}

function Nav() {
    $('body').on('click', 'a', function (e) {
        if (this.host == window.location.host && !this.hasAttribute('data-reload')) {
            $('body').append('<div class="overlay"></div>');
            e.preventDefault();
            history.pushState(null, '', $(this).attr('href'));

            $('#content').load($(this).attr('href') + ' #content > *', function (response, status, xhr) {
                if (status == 'error') {
                    $('head > title').text(xhr.statusText);
                    $("#content").html('<h1>' + xhr.status + " " + xhr.statusText + '</h1>');
                } else {
                    var $head = $('<head></head>');
                    $.each($(response), function () {
                        var allowed = ['LINK', 'META', 'TITLE'];
                        if (allowed.indexOf($(this).context.nodeName) > -1) {
                            $head.append($(this).context);
                        }
                    });
                    $('head').replaceWith($head);
                    Route();
                }
                window.scrollTo(0, 0);
            });
            $('.overlay').remove();
        }
    });
}

function LoadCSS(filename) {

    var file = document.createElement("link");
    file.setAttribute("rel", "stylesheet");
    file.setAttribute("type", "text/css");
    file.setAttribute("href", filename);

    if (typeof file !== "undefined" && document.querySelector('[href="' + filename + '"]') == null)
        document.getElementsByTagName("head")[0].appendChild(file);
}

function LoadJS(filename, ready) {

    var file = document.createElement("script");
    file.setAttribute("type", "text/javascript");
    file.setAttribute("src", filename);

    file.onload = function () {
        ready();
    };

    if (typeof file !== "undefined" && document.querySelector('[src="' + filename + '"]') == null) {
        document.getElementsByTagName("head")[0].appendChild(file);

    }
    return file;
}

Route();
Nav();

function Extend(route) {
    $('body').append('<div class="overlay"></div>');
    $('<iframe id="extender" style="display: none;" name="extender" src="' + route + '">').appendTo("body").load(function () {
        var $this = $(this);
        var $new = $('body #content');
        var $body = $this.contents().find('body');
        $body.find('#content').replaceWith($new);
        $('body').replaceWith($body);
        Route();
        Nav();
    });
}