﻿if ( window.addEventListener )
{
    initMenu();
}
else if ( window.attachEvent )
{
    window.attachEvent('onload', initMenu);
}

function initMenu()
{
    var currentUrl = filenameFromUrl(document.URL);

    if (document.getElementById) 
    {
	    var container = document.getElementById("menu");
	    var root = container.getElementsByTagName("UL")[0];
    	
	    for (var i=0; i < root.childNodes.length; i++) 
	    {
		    var node = root.childNodes[i];
    		    		
		    if (node.nodeName == "LI")
		    {										    
                // Highlight the active parent menu
                if (menuIsActive(node, currentUrl))
                {
	                node.className += " active";
	            }
    	        
		        // Attach mosueover/mouseout bahaviours to each parent menu
		        if (node.childNodes.length > 2)
		        {		        
			        node.onmouseover=
			            function() { 
			                this.className += " mouseover"; 
			                //this.childNodes[0].className += " mouseover";
			                //this.cancelBubble = true;
			            };
    				    
			        node.onmouseout=
			            function() { 
			                this.className = this.className.replace("mouseover", ""); 
			                //this.childNodes[0].className = this.childNodes[0].className.replace(" mouseover", ""); 
			                //this.cancelBubble = true;
			            };
			    }
            }
	    }
    }
}

function menuIsActive(node, currentUrl)
{
    var anchor = node.getElementsByTagName("A")[0];
    
    // Special case(s)
    if (filenameFromUrl(anchor.href) == "pricing.html")
    {
        return false;
    }
    if (anchor.href == "http://blog.smartcarping.com/") {
        return false;
    }    
        
    if (filenameFromUrl(anchor.href) == currentUrl)
    {
        return true;
    }
    else
    {    
        var subMenuSearch = node.getElementsByTagName("UL");
        if (subMenuSearch.length > 0)
        {
            var subMenu = subMenuSearch[0];
        
            for (var i=0; i < subMenu.childNodes.length; i++) 
		    {
		        var isMenuActive = false;
		    
		        var childNode = subMenu.childNodes[i];
		        if (childNode.nodeName == "LI")
		        {
		            if (!isMenuActive)
		            {
	                    isMenuActive = menuIsActive(childNode, currentUrl);
	                    if (isMenuActive) return true;
	                }
	            }
		    }
        }
    }

    return false;
}

function filenameFromUrl(url)
{
    var urlParts = url.split('/');
    if (urlParts.length > 0) return urlParts[urlParts.length-1];
}