﻿function replaceParts(newContent) {

    var pageStyle = findObj("pagestyle");
    var href = newContent
    href = href.substr(href.indexOf('<link id="pagestyle"'));
    href = href.substr(href.indexOf('href="') + 6);
    href = href.substr(href.indexOf('/')+1);
    href = href.substr(0, href.indexOf('"'));
    pageStyle.href = pageStyle.href.substr(0, pageStyle.href.lastIndexOf("/")+1) + href;

    // Inhalt ersetzen

    $('div').remove();

    var text = newContent;
    var start = "</object>";
    var end = "</body>";

    text = text.substring(text.indexOf(start) + start.length, text.indexOf(end));

    $('body').append(text);

    recreateSharingButtons();
}


function recreateSharingButtons() {
    if (FB != undefined && FB.XFBML != undefined)
        FB.XFBML.parse();

    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "http://platform.twitter.com/widgets.js");
    document.getElementsByTagName("head")[0].appendChild(script);
}


// Leitet auf index.html um
function redirectToIndex() {
    if (!supportsAjax) return;
    var path = location.pathname;
    if (path.indexOf("index.html") > -1) return;
    if (path.indexOf("shop.aspx") > -1) return;
    if (path.indexOf("/") > -1) {
        path = path.substr(path.lastIndexOf("/") + 1);
    }
    location.href = "index.html#" + path;
}
redirectToIndex();


function navi(lnk) {
    if (!supportsAjax) return true;

    // Shop geht nicht per AJAX
    if (location.href.indexOf("shop.aspx") > -1) return true;
    if (lnk.href.indexOf("shop.aspx") > -1) return true;


    location.hash = lnk.href.substr(lnk.href.lastIndexOf("/") + 1);

    return false;
}


$(window).load(function () {

    // Keep a mapping of url-to-container for caching purposes.
    var cache = {};

    // Bind an event to window.onhashchange that, when the history state changes,
    // gets the url from the hash and displays either our cached content or fetches
    // new content to be displayed.
    $(window).bind('hashchange', function (e) {

        // Get the hash (fragment) as a string, with any leading # removed. Note that
        // in jQuery 1.4, you should use e.fragment instead of $.param.fragment().
        var url = $.param.fragment();
        if (url == "") return;

        if (cache[url]) {
            // Since the element is already in the cache, it doesn't need to be
            // created, so instead of creating it again, let's just show it!
            replaceParts(cache[url]);

        } else {

            ajax(url, function (html) {
                cache[url] = html;
                replaceParts(html);
            });

        }
    });

    // Since the event is only triggered when the hash changes, we need to trigger
    // the event now, to handle the hash the page may have loaded with.
    $(window).trigger('hashchange');

});

