/**
 * Original Script by James Padosley for Nettuts.com
 * Updated to be based on his script as of Nov 18, 2009
 *
 * Modified by Patrick Eisenmann to support history and lightbox/PrototypeJS libraries
 *	(peisenmann@gatech.edu)
 *
 * Modified by Andre Bluehs to support PHP (and any other user added extensions)
 *	(contagious@gatech.edu)
 */

// Do this when the document loads
$j(document).ready(function() {    
    // Id of the tag that will wrap the content
    var contentWrapID = '___content-wrapper';
        
    // Wrapping the content. This will keep us from duplicating the content div
    // This is an important change from James' script because his would not work
    // for Safari
    var wrapDiv = document.createElement("div");
    wrapDiv.id = contentWrapID;
    $j('#content').wrap(wrapDiv);
    
    // Once we've loaded the new content, show it
    function showNewContent() {
        // Show the wrapper that contains the content
        $j("#" + contentWrapID).slideDown();
        
        // Hide the ajax loader icon
        $j('#load').fadeOut();   
    }
    
    // Load a page based on a hash (Given from the address bar)
    function pageload(hash) {
        // If the hash is not empty or undefined
        if(hash) {            
            // Hide the content
            $j("#" + contentWrapID).slideUp('fast',
                function()
                {
                    // Load the #content div from page of the mentioned in the hash
                    $j("#" + contentWrapID).load(hash + " #content",'',function (responseText, textStatus, XMLHttpRequest) {
                        
                        // Don't bother if the hash was busted
                        if (textStatus == "error") return;
                        
                        // This helps show the content only when it's all loaded
                        if($j('img:last',this).get(0)) {
                            $j('img:last',this).load(function(){
                                showNewContent();
                            });
                        } else {
                            showNewContent();
                        }

                    });
                }
            );


        } else {
            // Load this page
            pageload(window.location.href);
        }
    }
    // Initialize history
    $j.historyInit(pageload);
    
    // Adds the onclick function to the links
    $j('#nav li a').click(function(){
        
        // Get the hash from the link that was clicked
        var hash = $j(this).attr('href');
        hash = hash.replace(/^.*#/, '');

        // Load this hash with the history plugin
        $j.historyLoad(hash);
        
        if(!$j('#load').get(0)) {
            $j('#wrapper').append('<span id="load">LOADING...</span>');
        }
        $j('#load').fadeIn('normal');
        return false;
    });
});
