(function($){
//loosely based on the previous version of this file. 
//Not sure for some of the reasoning in original, but where 
//required i'll have to copy (eg, ie6) - Dan
$(function() {
	//bail in ie6 or less
	if ($.browser.msie && $.browser.version.substr(0,1)<7) {
		return;
	}
        if (document.referrer.indexOf('q=') != -1) { return;}
	fluid._setup();
	fluid.init();
});

var fluid = {
    init: function() {
        currentSection = fluid.getActiveSection();
        if (currentSection !== false) {
            fluid.toggleSection(currentSection);
        }
    },
	getActiveSection: function() {
		anchor = String(window.location).match(/#(.*)$/);
		if (anchor == null) {
			return fluid.getActiveSectionFromQueryString();
		}
		anchor = anchor[1];
		if ($('#'+anchor).length==0) {
			anchor = $('div.collapsible:first').attr('id');
		}
		return anchor;
	},
	getActiveSectionFromQueryString: function() {
		tabString = String(window.location).match(/\?.*tab=([a-z0-9_]+)/i);
		if (!tabString) {
			return false;
		}
		return tabString[1];
	},
	toggleSection: function(section, hidingOnly) {
		if (!hidingOnly && $('div.collapsible.visible').length == 0) {
			fluid._show(section, true);
			return;
		}		
		$('div.collapsible.visible').slideUp().removeClass('visible');
		if (!hidingOnly) {
			fluid._show(section, true);
		}
	},
	_setup: function() {
		$('#accordion p.elem').removeClass('hidden');
		$('h5.toggler').each(function(i) {
			newName = $(this).text().toLowerCase();
			newName = 's_' + newName.replace(/[^a-z]/ig, '');
			collapsibleName = newName + '_collapsible';
			$(this)
				.attr('id', newName)
				.find('a')
					.data('section', collapsibleName)
					.attr('href', '#'+collapsibleName)
					.end()
				;
			$('+ div', this)
				.attr('id', collapsibleName)
				.data('headerId', newName)
				.addClass('collapsible')
				.slideUp(0)
				;
		});
	},
	_show: function(id, scrollToPage) {
		if (typeof scrollToPage == 'undefined' || scrollToPage != true) {
			scrollToPage = false;
		}
		$('#'+id).addClass('visible').slideDown('fast', scrollToPage==true?function() {
			//there's a moment where the animation hasn't finished....
			$(window).data('toScrollToId', $(this).data('headerId'));
			window.setTimeout(function() {
				scrollToLocation = $('#'+$(window).data('toScrollToId')).offset().top;
				$('html, body').animate({scrollTop:scrollToLocation}, 'medium');
			}, 400);
		} : function(){ });
		$('#'+$(id).data('headerId')).removeClass('hidden');
	}
}

$(window).hashchange( function(){
    fluid.init();
});

//////////
})(jQuery);
