﻿
var leftNavOpen = "/common/images/accodion-open.gif";
var closedImageTag = "<img title=\"Expand/Collapse\" alt=\"Expand/Collapse\" src='"+leftNavOpen+"' />";
var leftNavClose = "/common/images/accodion-close.gif";

$(document).ready(function() {
	// Add img tags if required - level 1
	$(".nav-local > ul > li").each(function() {
		if(hasSubMenu(this)) { return; }
		
		addImgElement($(this).children("h3").children("a"));
		toggleImageAccordingToUlVisibility($(this).children("ul"), $(this).children("h3").children("img"));
		processSubMenu($(this).children("ul"));
	});

    // Level 1
    $(".nav-local > ul > li > h3 > img").each(function() {
        $(this).click(function() {
            var targetImgSrc = leftNavOpen;
            var expand = false;

            if ($(this).attr("src").indexOf(leftNavOpen) > -1) {
                targetImgSrc = leftNavClose;
                expand = true;
            }

            changeMenuVisibility(targetImgSrc, expand, $(this), $(this).parent().parent().children("ul"));
        });
    });

    // Level 2
    $(".nav-local > ul > li > ul > li > img").each(function() {
        $(this).click(function() {
			
            var targetImgSrc = leftNavOpen;
            var expand = false;
            if ($(this).attr("src").indexOf(leftNavOpen) > -1) {
                targetImgSrc = leftNavClose;
                expand = true;
            }
            changeMenuVisibility(targetImgSrc, expand, $(this), $(this).parent().children("ul"));
        });
    });
});

// Add img tags if required - level 2, 3, ...
function processSubMenu(ulElement) {
	$(ulElement).children("li").each(function() {
		if(hasSubMenu(this)) { return; }

		addImgElement($(this).children("a"));
		toggleImageAccordingToUlVisibility($(this).children("ul"), $(this).children("img"));
		processSubMenu($(this).children("ul"));
	});
}

function addImgElement(elementToAddAfter) {
	// Add an img element in the h3
	$(elementToAddAfter).after(closedImageTag);
}

function hasSubMenu(liElement) {
	return (0 == $(liElement).children("ul").length);
}

function toggleImageAccordingToUlVisibility(ulElement, imgElement) {
		// Change image if ul is visible
		var ulStyle = $(ulElement).attr("style");
		if((null != ulStyle) && (ulStyle.toLowerCase().indexOf("block") > 0)) {
			$(imgElement).attr({
				src: leftNavClose
			});
		}
}

function changeMenuVisibility(targetImgSrc, expand, $img, $ul) {

	$img.attr("src", targetImgSrc);
	if (expand) {
		$ul.show(300);
	}
	else {
		$ul.hide(300);
	}
}
