// create left/top navigation manager for clubs and leagues

// **************** NavMgr class ****************** //
function _NavMgr(siteSectionIds, cmsSiteSectionIds, nonCmsSiteSectionIds) {
    if (typeof HashMap == "undefined") {
        // alert("NavMgr class requires HashMap.js to be imported.");
    }
    this.sections = new HashMap();
    this.siteSectionIds       = siteSectionIds;
    this.cmsSiteSectionIds    = cmsSiteSectionIds;
    this.nonCmsSiteSectionIds = nonCmsSiteSectionIds;

    this.animateCurrentPosition = null;
    this.animateEndPosition     = null;
    this.animateStatus          = "";
    
    for (var i=0; i<siteSectionIds.length; i++) {
        this.sections.put(siteSectionIds[i], null);
    }

    // NOTE: idx is currently unused, and the value is unreliable, as its
    // often set both by the template here and the data generated by
    // newsroom to possibly conflicting values

    this.addLink = function(sectionId, label, contentId, url, idx) {
        idx = parseInt(idx, 10);
        if (this.sections.get(sectionId) == null) {
            // alert("In addLink(), the section '"+sectionId+"' does not exist.");
        } else {
            this.sections.get(sectionId).addNavItem(new NavItem(sectionId, label, contentId, url, idx));
        }
    }

    this.removeLink = function(sectionId, contentId) {
        if (this.sections.get(sectionId) == null) {
            // alert("Int removeLink(), the section '"+sectionId+"' does not exist.");
        } else {
            this.sections.get(sectionId).removeNavItem(contentId);
        }
    }

    // this adds a section, rather than really just setting the URL
    this.setSectionURL = function(id, contentId, url) {
        this.sections.put(id, new Section(id, contentId, url));
    }

    // given a section, set its label
    this.setSectionLabel = function(id, label) {
        // this fails if we try and set the label for ballpark/about links
        // but those pages have not yet been hooked up in Newsroom
        try {
            this.sections.get(id).label = label;
        } catch(e) { }
    }

    this.getSectionURL = function(id) {
        if (this.sections.get(id) != null) {
            return this.sections.get(id).homepageLinkURL;
        }
        return "";
    }

    this.getSectionLabel = function(id) {
        if (this.sections.get(id) != null) {
            return this.sections.get(id).label;
        }
        return "";
    }

    // fill the menu with the appropriate contents and show it
    this.showMenu = function(event, secId, elItem) {

        var el = document.getElementById('navMgrMenu');
        if (!el) { return; }

        var navItems = NavMgr.sections.get(secId).navItemsArray;
        if (navItems.length == 0) { return; } // if we dont have any sub items, dont bother showing the menu

        var html = "";
        for (var j=0; j<navItems.length; j++) {
            if (j>=15) { break; }  // limit menus to a max of 15 items, so clubs dont get carried away
            html += "<a href=\"" + navItems[j].url + "\" style=\"margin: 0px;\">" + navItems[j].label + "</a>";
        }
        el.innerHTML  = html;        
        
        function getOffset(el) {
            var valueTop  = 0;
            var valueLeft = 0;
            do {
                valueTop  += el.offsetTop  || 0;
                valueLeft += el.offsetLeft || 0;
                el = el.offsetParent;
            } while (el);
            return {x: valueLeft, y: valueTop};
        }

        var position  = getOffset(elItem);
        el.style.left = position.x + "px";
        el.style.top  = (position.y + elItem.offsetHeight - 1) + "px";
        el.style.display = "block";
        el.style.clip = "rect(auto auto auto auto)";
        
        var toEl;
        var fromEl;
        if (window.event) {
            toEl   = window.event.toElement;
            fromEl = window.event.fromElement;
        } else {
            toEl   = event.relatedTarget;
            fromEl = event.currentTarget;
        }
        
        if (!((toEl.id == "navMgrMenu" || null) && (fromEl.className == "navMgrSection" || null))) { 
            this.animateCurrentPosition = 0;
            this.animateEndPosition = el.offsetHeight;
            this.animateStatus = "down";
            window.setTimeout("NavMgr.animateMenu()");
        }

        // doesnt detect full overlap, just good enough for most of
        // the selects on the minor league site
        function overlap(menu, select) {
            menu.offset   = getOffset(menu);
            select.offset = getOffset(select);

            // if the whole menu is above the select ..
            if ((menu.offset.y + menu.offsetHeight) < select.offset.y) {
                return false;
            }
            // if the whole menu is to the left of the select ..
            if ((menu.offset.x + menu.offsetWidth) < select.offset.x) {
                return false;
            }
            // if the right side menu starts before the left side of the select ..
            if (menu.offset.x < (select.offset.x + select.offsetWidth)) {
                return true;
            }
            return false; 
        }

        try { 
            // should only hide selects for IE6 and below
            if ((isIE) && !((navigator.appVersion.indexOf("MSIE 7") > -1) || 
                            (navigator.appVersion.indexOf("MSIE 8") > -1))) { // good enough for now.  by the time IE8 is widespread enough,
                // you should be able to just remove this check ...
                var selects = document.getElementsByTagName("select");
                if (selects) { 
                    for (var i=0; i<selects.length; i++) {
                        var select = selects[i];
                        if (select.style.visibility != "hidden") {
                            if (overlap(el, select)) { 
                                select.style.visibility = "hidden";
                                select.navMgrHidden = true;
                            }
                        }
                    }
                }
            }
        } catch(e) {}

    }

    this.hideMenu = function(event, secId, elItem) {

        var el = document.getElementById('navMgrMenu');
        if (!el) { return; }

        function contains(el1, el2) {
            while (el2.parentNode) {
                if (el2 == el1) { return true; }
                el2 = el2.parentNode;
            }
            return false;
        }

        var toEl;
        if (window.event) {
            toEl = window.event.toElement;
        } else {
            toEl = event.relatedTarget;
        }
        
        if ((el != toEl) && (!contains(el, toEl)) && (toEl.className != "navMgrSection")) {
            el.style.clip = "rect(auto auto auto auto)";
            this.animateCurrentPosition = el.offsetHeight;
            this.animateEndPosition = 0;
            this.animateStatus = "up";
            this.animateMenu();
        }
    }
    
    this.animateMenu = function() {

        var el = document.getElementById('navMgrMenu');
        if (!el) { return; }

        if (this.animateStatus == "up") { 
            this.animateCurrentPosition = this.animateCurrentPosition - 10;
        } else if (this.animateStatus == "down") {
            this.animateCurrentPosition = this.animateCurrentPosition + 10;
        } else {
            return;
        }

        if ((this.animateCurrentPosition < 0) || (this.animateCurrentPosition == this.animateEndPosition)) {
            if (this.animateStatus == "up") {
                el.style.display = "none"; 
                var selects = document.getElementsByTagName("select");
                if (selects) { 
                    for (var i=0; i<selects.length; i++) {
                        var select = selects[i];
                        if (select.navMgrHidden) {
                            select.style.visibility = "";
                            select.navMgrHidden = false;
                        }
                        
                    }
                }

            }

            this.animateCurrentPosition = 0;
            this.animateStatus = "";
            el.style.clip = "rect(auto auto auto auto)";
            return;
        } else if ((this.animateCurrentPosition > this.animateEndPosition) && (this.animateStatus == "down")) {
            this.animateCurrentPosition = 0;
            this.animateStatus = "";
            el.style.clip = "rect(auto auto auto auto)";
            return;
        }

        el.style.clip = "rect(0 auto " + this.animateCurrentPosition + "px 0)";
        window.setTimeout("NavMgr.animateMenu()", 10);
    }

    // write top nav for "layout 2/4" templates:
    this.writeTopNav = function(suppressedSectionNamesArray, siteType) {
        if (arguments.length == 0) {
            suppressedSectionNamesArray = [];
        }
        var s = "";
        
        var len;
        if (siteType == "league") { 
            len = LEAGUESITE_SECTIONS.length;
        } else { 
            len = CLUBSITE_SECTIONS.length;
        }
        
        for (var i=0; i<len; i++) {
            
            var secId;
            if (siteType == "league") { 
                secId = LEAGUESITE_SECTIONS[i];
            } else { 
                secId = CLUBSITE_SECTIONS[i];
            }

            var supressed = false;
            for (var l=0; l<suppressedSectionNamesArray.length; l++) {
                if (suppressedSectionNamesArray[l] == secId) {
                    supressed = true;
                }
            }
            
            if (supressed) { continue; }
            
            s += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a style=\"padding:0px; margin:0px;\" class=\"navMgrSection\"" ; 
            s += "onmouseover=\"NavMgr.showMenu(event, '" + secId + "', this)\" onmouseout=\"NavMgr.hideMenu(event, null, this)\" ";
            s += "href=\"" + this.getSectionURL(secId) + "\">";
            
            // allow for labels on section objects to be used inplace of section name
            // if we dont have a label, take the ID and uppercase the first letter
            
            var label = this.getSectionLabel(secId);
            
            if (label) {
                s += label;
            } else {
                s += secId.charAt(0).toUpperCase() + secId.substring(1);
            }
            
            s += "</a>";
            s += "<div id=\"navMgrMenu\" style=\"text-align: left; display: none; position: absolute;\" onmouseout=\"NavMgr.hideMenu(event, null, this)\"></div>";
        }
        document.write(s);
    }

    // write left nav for "layout 1/3" templates (these have no top nav,
    // so functionally this is the same as the above method):
    this.writeLeftNavTRs = function(currSection, isHomepage) {
        var s = "";
        var auxSections = ["tickets", "shop"];
        var isAuxSection = false;
        
        for (var i=0; i<window.CLUBSITE_SECTIONS.length; i++) {
          var secId = CLUBSITE_SECTIONS[i];
          if (!(secId == "account")) {

            // flag aux sections so we can give them a different style 
            isAuxSection = false;
            for (var l=0; l<auxSections.length; l++) {
                if (auxSections[l] == secId) {
                    isAuxSection = true;
                }
            }

            s += "<tr align=\"left\">";

            // write the top level links

            s += "<td class=\"leftnavsectionlabel";
            if (isAuxSection) { s += "aux"; }
            s += "\" style=\"padding-left: 7px;\"><a href=\"" + this.getSectionURL(secId) + "\">";

            // allow for label attribute on section objects to be used inplace of section name
            // if we dont have a label, take the ID and uppercase the first letter
            var section = NavMgr.sections.get(secId);
            if (section && section.label) {
                s += section.label;
            } else {
                s += secId.charAt(0).toUpperCase() + secId.substring(1);
            }
            s+="</a><br/></td></tr>";
        
            // if the section has sub pages, then write a new table with a list of them
            if (currSection == secId && !isHomepage) {
                var navItems = NavMgr.sections.get(currSection).navItemsArray;
                if (navItems!=null && navItems.length>0) {
                    s += "<tr align=\"left\"><td>";
                    s += "<table class=\"leftNavSubSection\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\">";
                    s += "<tr align=\"left\"><td height=\"8\" width=\"17\" nowrap=\"nowrap\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\" /><br/></td><td nowrap=\"nowrap\"><img src=\"/images/spacer.gif\" height=\"1\" width=\"1\" /><br/></td></tr>";

                    for (var j=0; j<navItems.length; j++) {
                        var item = navItems[j];
                        s += "<tr align=\"left\">";
                        s += "<td><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\" /><br/></td>";
                        s += "<td style=\"height:14px;\"><a href=\"" + item.url + "\">" + item.label + "</a><br/></td>";
                        s += "</tr>";
                    }

                    s += "<tr align=\"left\"><td height=\"8\" nowrap=\"nowrap\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\" /><br/></td><td><img src=\"/images/spacer.gif\" height=\"1\" width=\"1\" /><br/></td></tr>";
                    s += "</table>";
                    s += "</td></tr>";
                }
            }
	    } //end if "account"
        }
        document.write(s);
    }
    
}

// **************** Section class ****************** //

// label is the last param, not the second param like the NavItem
// below.  

function Section(id, homepageLinkContentId, homepageLinkURL, label) {
    this.id = id;
    this.homepageLinkContentId = homepageLinkContentId;
    this.homepageLinkURL       = homepageLinkURL;
    this.label = label;
        
    if (this.homepageLinkURL.indexOf("sid=") == -1) {
        if (this.homepageLinkURL.indexOf("?") == -1) {
            this.homepageLinkURL += "?";
        } else {
            this.homepageLinkURL += "&";
        }
        this.homepageLinkURL += "sid=" + window.sid;
    }
    if (this.homepageLinkURL.charAt(0) == "/") {
	  this.homepageLinkURL = navCacheServerURL + this.homepageLinkURL ;
    }

    
    this.navItemsArray = [];

    this.addNavItem = function(navItem) {
        this.navItemsArray[this.navItemsArray.length] = navItem;
    }

    this.removeNavItem = function(contentId) {
        if (contentId == null) {
//            alert("In removeNavItem, contentId cannot be null.");
        } else {
            var newItemsArray = [];
            var itemsArray = this.navItemsArray;
            for (var i=0; i<itemsArray.length; i++) {
                var item = itemsArray[i];
                if ((item.contentId == null) || (item.contentId != contentId)) {
                    newItemsArray[newItemsArray.length] = item;
                }
            }
            this.navItemsArray=newItemsArray;
        }
    }

}


// **************** NavItem class ****************** //

// NOTE: idx is currently unused, and the value is unreliable, as its
// often set both by the template here and the data generated by
// newsroom to possibly conflicting values

function NavItem(sectionId, label, contentId, url, idx) {
    this.sectionId = sectionId;
    this.label     = label;
    this.contentId = contentId;
    this.url       = url;
    this.idx       = parseInt(idx, 10);
    
    if ((this.url.indexOf("sid=") == -1) && ((this.url.indexOf(domainGlobal) > -1) || (this.url.charAt(0) == "/"))) {
        if (this.url.indexOf("?") == -1) {
            this.url += "?";
        } else {
            this.url += "&";
        }
        this.url += "sid=" + window.sid;
    }
    if (this.url.charAt(0) == "/") {
	  this.url = navCacheServerURL + this.url;
    }

}

