/* ajaxification */
var Ajaxify = {
    // intialize
    init: function() {
        this.bindGeneralAjaxLinks();
        this.bindContentAjaxLinks();
        this.bindHashchange();
    },
    // ajaxify links (all that are not in ajaxtTargets)
    bindGeneralAjaxLinks: function() {
        $("a.ajax").filter(":parents(.inner_content)").unbind("click").click(function(){
            window.location.hash = $(this).attr("rel");
            return false;
        });
    },
    // ajaxify links (content)
    bindContentAjaxLinks: function() {
        // ajaxify links
        $(".inner_content a.ajax").unbind("click").click(function(){
            // do hashchange
            window.location.hash = $(this).attr("rel");
            // do nothing else
            return false;
        });
    },
    // manage hashes
    bindHashchange: function() {
        // what to do when hashtag has changed
        $(window).bind('hashchange', function(){
            // get hash without the '#'
            newHash = window.location.hash.substring(1);
            // track site change
            try { pageTracker._trackPageview("/" + newHash); } catch (e) {}
            $.get(
                HTTP + newHash + '/',
                {
                    type: 'ajax' // tell controller to use the ajax-template
                }, function(data) {
                    Ajaxify.loadHashContent(data);
                    // activate chosen menu-item
                    var regEx       = /[A-Za-z0-9-]*/;
                    var cleanedHash = regEx.exec(window.location.hash.substring(1)).toString();
                    $('#nav li.active').removeClass('active');
                    $('#nav a.ajax[rel=#' + cleanedHash + ']').closest('li').addClass('active');
                }, 'json'
            );
        });

        // initial triggering of the hashchange-events (in case of deeplinks)
        if (window.location.hash != '' && window.location.hash != '#start') {
            $(window).trigger('hashchange');
        }
    },
    // handle new content
    loadHashContent: function(data) {
        // change site-title
        document.title = data.title;
        // change body id
        $("body").attr("id", data.contentName);
        // show content
        $("#column-two-inner").append("<div class='inner_content_new'></div>").find(".inner_content_new").html(data.newContent).find(".hidden").hide();
        $(".inner_content").animate({
            marginLeft: 750
        }, function(){
            $(this).remove();
            $(".inner_content_new").animate({
                marginLeft: 0
            }, function(){
                $(this).removeClass("inner_content_new").addClass("inner_content");
                Ajaxify.bindContentAjaxLinks();            
            });
        });
    }
};

// jQuery Ready-Handler
$(function() {

    Ajaxify.init();

});

