var loadpage;
$(function() {

    var $el = $(),
        $mainContent = $("#main-content");

    // Used for fading out the content while leaving whiteness/main content area along
    $mainContent.wrapInner("<div id='fade-wrapper' />");

    // add in AJAX spinning graphic (hidden by CSS)
    $mainContent.append('<img src="images/ajax-loader.gif" id="ajax-loader" />');

    var $fadeWrapper = $("#fade-wrapper"),
    	$allNav = $("#main-nav a"),
        $allListItems = $("#main-nav li"),
        url = '',
        liClass = '',
        hash = window.location.hash,
        $ajaxLoader = $("#ajax-loader");



    // remove ID, which is used only for nav highlighting in non-JS version
    $("body").attr("id", "");

    // If, when the page loads, it has a #hash value in the URL
    if (hash) {
        hash = hash.substring(1);
        liClass = hash;
        url = hash + ".html #inside-content";
        $fadeWrapper.load(url);
        $("." + liClass).addClass("active");
    } else {
        // No hash tag present, so make the first item in the nav the active nav
        $("#main-nav li:first").addClass("active");
    }

   loadpage = function(e) {

        $el = $(e.target);

        // Only proceed with the AJAX nav if the click is the non-current page
        if (!$el.parent().hasClass("active")) {

            // Scroll the page up (mostly so they can see the spinner graphic begin)
            $(window).scrollTop(0);

	    var hrel = $el.attr("href");
	    if (hrel == "/") {
		hrel = "/index/"
	    }
            url = hrel.substr(0,hrel.length-1) + ".html" + " #inside-content";

            $fadeWrapper.animate({ opacity: 0.1 });
            $ajaxLoader.fadeIn(400, function() {

                $fadeWrapper.load(url, function() {

		    if (hrel == "/index/") {
                    	window.location.hash = "";
		    } else {
                    	window.location.hash = hrel.substr(1,hrel.length-2);
		    }

                    $fadeWrapper.animate({ opacity: 1 });
                    $ajaxLoader.fadeOut();

                });

                $allListItems.removeClass("active");
		//if ($el.attr("liclass")) {
               		$("#main-nav li."+hrel.substr(1,hrel.length-2)).addClass("active");
		//} else {
               	//	$el.parent().addClass("active");
		//}
            });

        }

        // Make sure the links don't reload the page
        e.preventDefault();
    }

    $allNav.click(loadpage);

});

