//animate the opening of the branch (span.grower jQueryElement)
function openBranch(jQueryElement, noAnimation) {
	jQueryElement.addClass('OPEN').removeClass('CLOSE');
	if(noAnimation)
		jQueryElement.parent().find('ul:first').show();
	else
		jQueryElement.parent().find('ul:first').slideDown();
			
	if(jQueryElement.parent().children('p:first').hasClass('article')) {
		if(noAnimation)
			jQueryElement.parent().children('p.article').show();
		else
			jQueryElement.parent().children('p.article').slideDown();
	}

}
//animate the closing of the branch (span.grower jQueryElement)
function closeBranch(jQueryElement, noAnimation) {
	jQueryElement.addClass('CLOSE').removeClass('OPEN');
	if(noAnimation)
		jQueryElement.parent().find('ul:first').hide();
	else
		jQueryElement.parent().find('ul:first').slideUp();
		
	if(jQueryElement.parent().children('p:first').hasClass('article')) {
		if(noAnimation)
			jQueryElement.parent().children('p.article').hide();
		else
			jQueryElement.parent().children('p.article').slideUp();
	}
}

//animate the closing or opening of the branch (ul jQueryElement)
function toggleBranch(jQueryElement, noAnimation) {
	if(jQueryElement.hasClass('OPEN'))
		closeBranch(jQueryElement, noAnimation);
	else
		openBranch(jQueryElement, noAnimation);
}

//when the page is loaded...
$(document).ready(function () {
	//to do not execute this script as much as it's called...
	if(!$('#topics_block ul.dhtml').hasClass('dynamized'))
	{
		// desactive pour dogLiving
//		if($('.topicName').length === 0) {
			//add growers to each ul elements
			$('ul.dhtml ul').prev().before("<span class='grower OPEN'> </span>");
//		}
		$('ul.dhtml li').each( function() {
			$(this).find('p.article:first').prev().before("<span class='grower OPEN'> </span>");
		});
				
		//dynamically add the '.last' class on each last item of a branch
		$('ul.dhtml ul li:last-child, ul.dhtml li:last-child').addClass('last');
		
		// For DogLiving
		$('ul.dhtml span.grower.OPEN').addClass('CLOSE').removeClass('OPEN').parent().find('p.article, ul:first').hide();
		$('ul.dhtml').show();

		//open the tree for the selected branch
		$('ul.dhtml .selected').parents().each( function() {
			if ($(this).is('ul'))
				toggleBranch($(this).prev().prev(), true);
		});
		toggleBranch( $('ul.dhtml .selected').prev(), true);
		
		//add a fonction on clicks on growers
		$('ul.dhtml span.grower').click(function(){
			toggleBranch($(this));
		});

		// For DogLiving (affichage des articles dans le menu)
		$('ul.dhtml span.topicName').click(function(){
			toggleBranch($(this).parent().find('span:first'));
		});
				
		//mark this 'ul' elements as already 'dynamized'
		$('ul.dhtml').addClass('dynamized');

		$('ul.dhtml').removeClass('dhtml');

	}
});
