var scroller = null;
var currentPage = "";

function setupPage() {
    // This function gets called on page load and also after an AJAX load
    // Anything you would have put in the page header should prob go here
    setupAjaxLinks();

    jQuery("a.videolink").fancybox({
      transitionIn  :	'elastic',
      transitionOut :	'fade',
      frameWidth    : 640,
      frameHeight   : 385,
      overlayShow   : true,
	  hideOnOverlayClick	:	true,
	  overlayOpacity	:	0.5,
	  overlayColor    :    '#000'
    });
    $("a.group").fancybox({
      transitionIn  :	'elastic',
      transitionOut :	'fade',
      speedIn	    :	400,
      speedOut	    :	400,
      overlayShow   : true,
	  hideOnOverlayClick	:	true,
	  overlayOpacity	:	0.5,
	  overlayColor    :    '#000'
    });

}

function doLoad(toLoad,effect) {
    currentPage = toLoad;
    // Put the hash on the url in the address bar
    

    // Slightly hacky, we just assume the section class is the same as
    // the first part of the url path
    var section = toLoad.split("/");
    if (toLoad == "/") {
        section = "home";
    } else if (toLoad[0] == "/") {
       section = section[1];
    } else {
        section = section[0];
    }
    $('body').attr('id',section);

    $.get(toLoad + " #content",ajaxLoaded);
    function ajaxLoaded(responseText) {
        var rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
        // Create a dummy div to hold the results
	responseText = jQuery("<div>")
	// inject the contents of the document in, removing the scripts
	// to avoid any 'Permission Denied' errors in IE
	    .append(responseText.replace(rscript, ""))
            .find("#content");

        if (effect == "fade") {
            // We wait until fade out is finished before starting the ajax load,
            // this adds 200ms to the response time so might be an idea to change
            $('#content').fadeOut(200,fadeOutFinished);
        } else if (effect == "slideleft") {            
            $('#content').hide('slide', {direction: 'left'}, 200, fadeOutFinished);
        } else if (effect == "slideright") {
            $('#content').hide('slide', {direction: 'right'}, 200, fadeOutFinished);            
        } else {
            fadeOutFinished();
        }

        function fadeOutFinished() {
            window.location.hash = "!" + toLoad.substr(0,toLoad.length);
            $("#content").html(responseText);
            if (effect == "fade") {
                $('#content ').fadeIn('slow',fadeInFinished);
            } else if (effect == "slideleft") {            
                $('#content').show('slide', {direction: 'right'}, 1000, fadeInFinished);
            } else if (effect == "slideright") {
                $('#content').show('slide', {direction: 'left'}, 1000, fadeInFinished);
	    } else {
                $('#content').show();
            }
            setupPage();        
        }
    }

    function fadeInFinished() {
	// any code to be run after the new content fadein should go here
        $('#load').fadeOut('normal');
    }
}

function loadWithFade(toLoad, effect) {
    if (toLoad != currentPage) {
        doLoad(toLoad, effect || "fade");
    }
}


function setupAjaxLinks() {
        // Add a click handler to all a tags with the "ajax" class
	$('a.ajax').not(".ajax-setup").addClass("ajax-setup").click(function(){
            $('a.ajax').addClass('active').not(this).removeClass('active');
            // Show a "LOADING..." display
	    $('#load').remove();
	    $('#wrapper').prepend('<span id="load">LOADING...</span>');
	    $('#load').fadeIn(200);
            // Actually do the ajax loading
            var toLoad = $(this).attr('href');
            var effect = $(this).attr("class").match(/effect-([^ ]+)/);

            if (effect) {
                effect = effect[1];
            } else {
                effect = "fade";
            }
            loadWithFade(toLoad, effect);
	    return false;
	});

};

function maybeLoad() {
        // Check if there's a hash in the url and if there isload the appropriate content right away
        // This should probably check we're don't already have the right content.
	var hash = window.location.hash.substr(2);
	var href = $('a.ajax').each(function(){
		var href = $(this).attr('href');
		if(hash==href.substr(0,href.length)){
		    var toLoad = hash 
                    doLoad(toLoad, "none");
		}
	});


}

// This handles it getting called on page load, see ajaxLoaded above for the ajax case
jQuery(document).ready(maybeLoad);
jQuery(document).ready(setupPage);

//Setup history management
$(window).history(function( e, ui ){
    var page = window.location.hash.substr(2);
    // Ok, so the hash has changed, is it the same as the current page we know about?
    // If not then load it up
    if (page != currentPage) {
        doLoad(page, "none");
    }
});



