$(document).ready(function(){
    var sBaseUrl = 'http://www.gm-alex.de/';
    
    var sDivider = '#!/';
    var sSuffixDivider = sDivider.substr(1, sDivider.length);
    var sBaseUrlRegExp = new RegExp('^'+sBaseUrl);
    
    var iAnimationSpeed = 500;
    
    var oLoader = $('<div id="pageloading" class="extratext"><h1>Loading...</h1><p>Please wait for the new awesome content. This text exists only to show you something to read while you are waiting. If you can\'t read this text the loading speed is good.</p></div>');
    var oContent = $('#main');
    var oNavigation = $('#navi');
    var oHeader = $('#header');
    
    var bLock = false;
    var sLastUrl = ''; //(window.location + '').replace(sDivider, '');
    
    var aPageScripts = new Array(
        sBaseUrl + 'wp-content/themes/GMAlex/js/initslider.js'
    );

    /**
     * Returns the width which we have to move.
     * 
     * @returns integer
     */
    function getMoveWidth()
    {
        var iWindowWidth = $(window).width();
        var iMoveWidth = (iWindowWidth/2) + 980;
        
        return iMoveWidth;
    }
    
    /**
     * Scroll to the anchor.
     * 
     * @returns null
     */
    function scrollToAnchor(sAnchor)
    { 
        if (sAnchor != null) {
            var oOffset = $(sAnchor + '').offset();
            
            if (oOffset != null) {
                $('html,body').animate({scrollTop: oOffset.top}, iAnimationSpeed);
            }
        }
    }
    
    /**
     * Loads the url and animate the load.
     * 
     * @param string sUrl The url which we want to call.
     * 
     * @returns null
     */
    function loadContent(sUrl)
    {
        bLock = true;

        $.ajax({
            url: sUrl,
            beforeSend: function() {
                //Scroll to top
                $('html, body').animate({scrollTop: '0px'}, iAnimationSpeed);
                
                //Content
                oContent.animate({left: '-'+getMoveWidth()}, iAnimationSpeed, function(){
                    oContent.slideUp(iAnimationSpeed);
                });
                
                //Loader
                oLoader.css('left', getMoveWidth()+'px');
                oHeader.after(oLoader);
                oLoader.animate({left: '0'}, iAnimationSpeed);
            },
            error: function() {},
            complete: function() {
                //Content
                oContent.stop(true, true);
                oContent.css('left', getMoveWidth()+'px');
                
                oContent.show(iAnimationSpeed, function(){
                    oContent.animate({left: '0'}, iAnimationSpeed, function(){
                        scrollToAnchor(sUrl.match(/#.*$/))
                        bLock = false;
                    });
                });
                
                //Loader
                oLoader.stop(true, true);
                oLoader.animate({left: '-'+getMoveWidth()}, iAnimationSpeed, function(){
                    oLoader.remove();
                });
            },
            success: function(data) {
                //Get the new content
                var oNaviContent = $('#navi > *', data);
                var oMainContent = $('#main > *', data);
                var oScripts = $('.javascript', data);

                //Add event handler to the new content
                $('a', oNaviContent).click(loadLinkContent);
                $('a', oMainContent).click(loadLinkContent);
                $('.edit a').unbind('click');

                //Insert the new content
                oNavigation.html(oNaviContent);
                oContent.html(oMainContent);
                
                //Load scripts               
                /*oScripts.each(function(key, oUl) {
                    $('li', oUl).each(function(key, oLi) {
                        $.getScript($(oLi).html());
                    });
                });*/
                
                for (var i = 0; i < aPageScripts.length; i++) {
                    $.getScript(aPageScripts[i]);
                }
                
                //Set the new pagetitle
                var sTitle = $('#pageTitle', data).text();
                $(document).title = sTitle;
                
                //Track with piwik
                if (piwikTracker !== undefined) {
                    try {
                        piwikTracker.setCustomUrl(sUrl);
                        piwikTracker.setDocumentTitle(sTitle);
                        piwikTracker.trackPageView();
                        piwikTracker.enableLinkTracking();
                    }catch(err) {}
                }
            }
        });
    }
    
    /**
     * The link event handler.
     * 
     * @returns null
     */
    function loadLinkContent()
    {
        //If we are not finished lock click
        if (bLock) {
            return false;
        }
        
        var sRawUrl = (this + '');

        //Filter files and extern links
        var iSearchBase = sRawUrl.search(sBaseUrlRegExp);
        var iSearchFiles = sRawUrl.search(/\.[a-zA-Z]+$/);
        
        if (iSearchBase != -1
            && iSearchFiles == -1
        ) {
            var sUrl = sRawUrl.replace(sDivider, '');
            var sNewUrl = sUrl.replace(sBaseUrlRegExp, '');
    
            var sMatch = sNewUrl.match(/#.*$/);
            
            if (sMatch != '#'
                && window.location != sUrl
            ) {                
                //loadContent(sUrl);
                $(this).attr('href', sDivider + sNewUrl);
            }
        }
    }
    
    //Init history event listener
    $.history.init(
        function(sHash){
            if(sHash == "") {
                // initialize your app
            } else {
                var sFullUrl = (sBaseUrl + sHash).replace(sSuffixDivider, '');
                
                var sAnchor = sHash.match(/#.*$/);
                var sTrimFullUrl = sFullUrl.replace(sAnchor + '', '');
                
                if (sLastUrl != sTrimFullUrl) {
                    loadContent(sFullUrl);
                } else {
                    scrollToAnchor(sAnchor);
                }

                sLastUrl = sTrimFullUrl;
            }
        },
        { unescape: ",/" }
    );
    
    //Init click events
    $('a').click(loadLinkContent);
    $('#wpadminbar a').unbind('click');
    $('.edit a').unbind('click');
});
