(function () {
    var Overlay = YAHOO.widget.Overlay,
            Prototype = Overlay.prototype,
            Dom = YAHOO.util.Dom;

    Prototype.getConstrainedX = function (x) {
        var oOverlay = this,
                oOverlayEl = oOverlay.element,
                nOverlayOffsetWidth = oOverlayEl.offsetWidth,

                nViewportOffset = Overlay.VIEWPORT_OFFSET,
                viewPortWidth = Dom.getViewportWidth(),
                scrollX = Dom.getDocumentScrollLeft(),

                bCanConstrain = (nOverlayOffsetWidth + nViewportOffset < viewPortWidth),

                aContext = this.cfg.getProperty("context"),
                oContextEl,
                nContextElX,
                nContextElWidth,

                bFlipped = false,

                nLeftRegionWidth,
                nRightRegionWidth,

                leftConstraint = scrollX + nViewportOffset,
                rightConstraint = scrollX + viewPortWidth - nOverlayOffsetWidth - nViewportOffset,

                xNew = x,

                oOverlapPositions = {
                    "tltr": true,
                    "blbr": true,
                    "brbl": true,
                    "trtl": true
                };

        var flipHorizontal = function () {
            var nNewX;
            if ((oOverlay.cfg.getProperty("x") - scrollX) > nContextElX) {
                nNewX = (nContextElX - nOverlayOffsetWidth);
            }
            else {
                nNewX = (nContextElX + nContextElWidth);
            }
            oOverlay.cfg.setProperty("x", (nNewX + scrollX), true);
            return nNewX;
        };

        /*
         Uses the context element's position to calculate the availble width
         to the right and left of it to display its corresponding Overlay.
         */
        var getDisplayRegionWidth = function () {
            // The Overlay is to the right of the context element
            if ((oOverlay.cfg.getProperty("x") - scrollX) > nContextElX) {
                return (nRightRegionWidth - nViewportOffset);
            }
            else {    // The Overlay is to the left of the context element
                return (nLeftRegionWidth - nViewportOffset);
            }
        };

        /*
         Positions the Overlay to the left or right of the context element so that it remains
         inside the viewport.
         */
        var setHorizontalPosition = function () {
            var nDisplayRegionWidth = getDisplayRegionWidth(),
                    fnReturnVal;
            if (nOverlayOffsetWidth > nDisplayRegionWidth) {
                if (bFlipped) {
                    /*
                     All possible positions and values have been
                     tried, but none were successful, so fall back
                     to the original size and position.
                     */
                    flipHorizontal();
                }
                else {
                    flipHorizontal();
                    bFlipped = true;
                    fnReturnVal = setHorizontalPosition();
                }
            }
            return fnReturnVal;
        };


        // Determine if the current value for the Overlay's "x" configuration property will
        // result in the Overlay being positioned outside the boundaries of the viewport
        if (x < leftConstraint || x > rightConstraint) {
            // The current value for the Overlay's "x" configuration property WILL
            // result in the Overlay being positioned outside the boundaries of the viewport
            if (bCanConstrain) {
                //	If the "preventcontextoverlap" configuration property is set to "true",
                //	try to flip the Overlay to both keep it inside the boundaries of the
                //	viewport AND from overlaping its context element.
                if (this.cfg.getProperty("preventcontextoverlap") && aContext &&
                        oOverlapPositions[(aContext[1] + aContext[2])]) {
                    oContextEl = aContext[0];
                    nContextElX = Dom.getX(oContextEl) - scrollX;
                    nContextElWidth = oContextEl.offsetWidth;
                    nLeftRegionWidth = nContextElX;
                    nRightRegionWidth = (viewPortWidth - (nContextElX + nContextElWidth));
                    setHorizontalPosition();
                    xNew = this.cfg.getProperty("x");
                }
                else {
                    if (x < leftConstraint) {
                        xNew = leftConstraint;
                    } else if (x > rightConstraint) {
                        xNew = rightConstraint;
                    }
                }
            } else {
                //	The "x" configuration property cannot be set to a value that will keep
                //	entire Overlay inside the boundary of the viewport.  Therefore, set
                //	the "x" configuration property to scrollY to keep as much of the
                //	Overlay inside the viewport as possible.
                xNew = nViewportOffset + scrollX;
            }
        }
        return xNew;
    };
    Prototype.getConstrainedY = function (y) {
        var oOverlay = this,
                oOverlayEl = oOverlay.element,
                nOverlayOffsetHeight = oOverlayEl.offsetHeight,
                nViewportOffset = Overlay.VIEWPORT_OFFSET,
                viewPortHeight = Dom.getViewportHeight(),
                scrollY = Dom.getDocumentScrollTop(),
                bCanConstrain = (nOverlayOffsetHeight + nViewportOffset < viewPortHeight),
                aContext = this.cfg.getProperty("context"),
                oContextEl,
                nContextElY,
                nContextElHeight,
                bFlipped = false,
                nTopRegionHeight,
                nBottomRegionHeight,
                topConstraint = scrollY + nViewportOffset,
                bottomConstraint = scrollY + viewPortHeight - nOverlayOffsetHeight - nViewportOffset,
                yNew = y,
                oOverlapPositions = {
                    "trbr": true,
                    "tlbl": true,
                    "bltl": true,
                    "brtr": true
                };

        var flipVertical = function () {
            var nNewY;
            // The Overlay is below the context element, flip it above
            if ((oOverlay.cfg.getProperty("y") - scrollY) > nContextElY) {
                nNewY = (nContextElY - nOverlayOffsetHeight);
            }
            else {    // The Overlay is above the context element, flip it below
                nNewY = (nContextElY + nContextElHeight);
            }
            oOverlay.cfg.setProperty("y", (nNewY + scrollY), true);
            return nNewY;
        };


        /*
         Uses the context element's position to calculate the availble height
         above and below it to display its corresponding Overlay.
         */
        var getDisplayRegionHeight = function () {
            // The Overlay is below the context element
            if ((oOverlay.cfg.getProperty("y") - scrollY) > nContextElY) {
                return (nBottomRegionHeight - nViewportOffset);
            }
            else {    // The Overlay is above the context element
                return (nTopRegionHeight - nViewportOffset);
            }
        };

        /*
         Trys to place the Overlay in the best possible position (either above or
         below its corresponding context element).
         */
        var setVerticalPosition = function () {
            var nDisplayRegionHeight = getDisplayRegionHeight(),
                    fnReturnVal;

            if (nOverlayOffsetHeight > nDisplayRegionHeight) {
                if (bFlipped) {
                    /*
                     All possible positions and values for the
                     "maxheight" configuration property have been
                     tried, but none were successful, so fall back
                     to the original size and position.
                     */
                    flipVertical();
                }
                else {
                    flipVertical();
                    bFlipped = true;
                    fnReturnVal = setVerticalPosition();
                }
            }
            return fnReturnVal;
        };


        // Determine if the current value for the Overlay's "y" configuration property will
        // result in the Overlay being positioned outside the boundaries of the viewport

        if (y < topConstraint || y > bottomConstraint) {
            // The current value for the Overlay's "y" configuration property WILL
            // result in the Overlay being positioned outside the boundaries of the viewport
            if (bCanConstrain) {
                //	If the "preventcontextoverlap" configuration property is set to "true",
                //	try to flip the Overlay to both keep it inside the boundaries of the
                //	viewport AND from overlaping its context element.
                if (this.cfg.getProperty("preventcontextoverlap") && aContext &&
                        oOverlapPositions[(aContext[1] + aContext[2])]) {
                    oContextEl = aContext[0];
                    nContextElHeight = oContextEl.offsetHeight;
                    nContextElY = (Dom.getY(oContextEl) - scrollY);
                    nTopRegionHeight = nContextElY;
                    nBottomRegionHeight = (viewPortHeight - (nContextElY + nContextElHeight));
                    setVerticalPosition();
                    yNew = oOverlay.cfg.getProperty("y");
                }
                else {

                    if (y < topConstraint) {
                        yNew = topConstraint;
                    } else if (y > bottomConstraint) {
                        yNew = bottomConstraint;
                    }
                }
            }
            else {
                //	The "y" configuration property cannot be set to a value that will keep
                //	entire Overlay inside the boundary of the viewport.  Therefore, set
                //	the "y" configuration property to scrollY to keep as much of the
                //	Overlay inside the viewport as possible.

                yNew = nViewportOffset + scrollY;
            }
        }
        return yNew;
    };
}());

(function () {
    var Overlay = YAHOO.widget.Overlay,
            Dom = YAHOO.util.Dom,
        // String constants
            _CONTEXT = "context",
            _Y = "y",
            _MAX_HEIGHT = "maxheight",
            _MIN_SCROLL_HEIGHT = "minscrollheight",
            _PREVENT_CONTEXT_OVERLAP = "preventcontextoverlap";
    YAHOO.widget.Menu.prototype.getConstrainedY = function (y) {
        var oMenu = this,
                aContext = oMenu.cfg.getProperty(_CONTEXT),
                nInitialMaxHeight = oMenu.cfg.getProperty(_MAX_HEIGHT),
                nMaxHeight,
                oOverlapPositions = {
                    "trbr": true,
                    "tlbl": true,
                    "bltl": true,
                    "brtr": true
                },
                bPotentialContextOverlap = (aContext && oOverlapPositions[aContext[1] + aContext[2]]),
                oMenuEl = oMenu.element,
                nMenuOffsetHeight = oMenuEl.offsetHeight,
                nViewportOffset = Overlay.VIEWPORT_OFFSET,
                viewPortHeight = Dom.getViewportHeight(),
                scrollY = Dom.getDocumentScrollTop(),
                bCanConstrain = (oMenu.cfg.getProperty(_MIN_SCROLL_HEIGHT) + nViewportOffset < viewPortHeight),
                nAvailableHeight,
                oContextEl,
                nContextElY,
                nContextElHeight,
                bFlipped = false,
                nTopRegionHeight,
                nBottomRegionHeight,
                topConstraint = scrollY + nViewportOffset,
                bottomConstraint = scrollY + viewPortHeight - nMenuOffsetHeight - nViewportOffset,
                yNew = y;

        var flipVertical = function () {
            var nNewY;
            // The Menu is below the context element, flip it above
            if ((oMenu.cfg.getProperty(_Y) - scrollY) > nContextElY) {
                nNewY = (nContextElY - nMenuOffsetHeight);
            }
            else {    // The Menu is above the context element, flip it below
                nNewY = (nContextElY + nContextElHeight);
            }
            oMenu.cfg.setProperty(_Y, (nNewY + scrollY), true);
            return nNewY;

        };

        /*
         Uses the context element's position to calculate the availble height
         above and below it to display its corresponding Menu.
         */
        var getDisplayRegionHeight = function () {
            // The Menu is below the context element
            if ((oMenu.cfg.getProperty(_Y) - scrollY) > nContextElY) {
                return (nBottomRegionHeight - nViewportOffset);
            }
            else {    // The Menu is above the context element
                return (nTopRegionHeight - nViewportOffset);
            }
        };

        /*
         Sets the Menu's "y" configuration property to the correct value based on its
         current orientation.
         */
        var alignY = function () {
            var nNewY;
            if ((oMenu.cfg.getProperty(_Y) - scrollY) > nContextElY) {
                nNewY = (nContextElY + nContextElHeight);
            }
            else {
                nNewY = (nContextElY - oMenuEl.offsetHeight);
            }
            oMenu.cfg.setProperty(_Y, (nNewY + scrollY), true);
        };

        //	Resets the maxheight of the Menu to the value set by the user
        var resetMaxHeight = function () {
            oMenu._setScrollHeight(this.cfg.getProperty(_MAX_HEIGHT));
            oMenu.hideEvent.unsubscribe(resetMaxHeight);
        };

        /*
         Trys to place the Menu in the best possible position (either above or
         below its corresponding context element).
         */

        var setVerticalPosition = function () {
            var nDisplayRegionHeight = getDisplayRegionHeight(),
                    bMenuHasItems = (oMenu.getItems().length > 0),
                    nMenuMinScrollHeight,
                    fnReturnVal,
                    nNewY;
            if (nMenuOffsetHeight > nDisplayRegionHeight) {
                nMenuMinScrollHeight = bMenuHasItems ? oMenu.cfg.getProperty(_MIN_SCROLL_HEIGHT) : nMenuOffsetHeight;
                if ((nDisplayRegionHeight > nMenuMinScrollHeight) && bMenuHasItems) {
                    nMaxHeight = nDisplayRegionHeight;
                }
                else {
                    nMaxHeight = nInitialMaxHeight;
                }
                oMenu._setScrollHeight(nMaxHeight);
                oMenu.hideEvent.subscribe(resetMaxHeight);
                // Re-align the Menu since its height has just changed
                // as a result of the setting of the maxheight property.
                alignY();
                if (nDisplayRegionHeight < nMenuMinScrollHeight) {
                    if (bFlipped) {
                        /*
                         All possible positions and values for the "maxheight"
                         configuration property have been tried, but none were
                         successful, so fall back to the original size and position.
                         */
                        flipVertical();
                    }
                    else {
                        flipVertical();
                        bFlipped = true;
                        fnReturnVal = setVerticalPosition();
                    }
                }
            }
            else if (nMaxHeight && (nMaxHeight !== nInitialMaxHeight)) {
                oMenu._setScrollHeight(nInitialMaxHeight);
                oMenu.hideEvent.subscribe(resetMaxHeight);
                // Re-align the Menu since its height has just changed
                // as a result of the setting of the maxheight property.
                alignY();
            }
            return fnReturnVal;
        };


        // Determine if the current value for the Menu's "y" configuration property will
        // result in the Menu being positioned outside the boundaries of the viewport
        if (y < topConstraint || y > bottomConstraint) {
            // The current value for the Menu's "y" configuration property WILL
            // result in the Menu being positioned outside the boundaries of the viewport
            if (bCanConstrain) {
                if (oMenu.cfg.getProperty(_PREVENT_CONTEXT_OVERLAP) && bPotentialContextOverlap) {
                    //	SOLUTION #1:
                    //	If the "preventcontextoverlap" configuration property is set to "true",
                    //	try to flip and/or scroll the Menu to both keep it inside the boundaries of the
                    //	viewport AND from overlaping its context element (MenuItem or MenuBarItem).
                    oContextEl = aContext[0];
                    nContextElHeight = oContextEl.offsetHeight;
                    nContextElY = (Dom.getY(oContextEl) - scrollY);
                    nTopRegionHeight = nContextElY;
                    nBottomRegionHeight = (viewPortHeight - (nContextElY + nContextElHeight));
                    setVerticalPosition();
                    yNew = oMenu.cfg.getProperty(_Y);
                }
                else if (!(oMenu instanceof YAHOO.widget.MenuBar) &&
                        nMenuOffsetHeight >= viewPortHeight) {
                    //	SOLUTION #2:
                    //	If the Menu exceeds the height of the viewport, introduce scroll bars
                    //	to keep the Menu inside the boundaries of the viewport
                    nAvailableHeight = (viewPortHeight - (nViewportOffset * 2));
                    if (nAvailableHeight > oMenu.cfg.getProperty(_MIN_SCROLL_HEIGHT)) {
                        oMenu._setScrollHeight(nAvailableHeight);
                        oMenu.hideEvent.subscribe(resetMaxHeight);
                        alignY();
                        yNew = oMenu.cfg.getProperty(_Y);
                    }
                }
                else {
                    //	SOLUTION #3:
                    if (y < topConstraint) {
                        yNew = topConstraint;
                    } else if (y > bottomConstraint) {
                        yNew = bottomConstraint;
                    }
                }
            }
            else {
                //	The "y" configuration property cannot be set to a value that will keep
                //	entire Menu inside the boundary of the viewport.  Therefore, set
                //	the "y" configuration property to scrollY to keep as much of the
                //	Menu inside the viewport as possible.
                yNew = nViewportOffset + scrollY;
            }
        }
        return yNew;
    };
}());


/*
 Initialize and render the MenuBar when its elements are ready
 to be scripted.
 */
YAHOO.util.Event.onContentReady("productsandservices", function () {
    var ua = YAHOO.env.ua,
            oAnim;  // Animation instance
    /*
     "beforeshow" event handler for each submenu of the MenuBar
     instance, used to setup certain style properties before
     the menu is animated.
     */
    function onSubmenuBeforeShow(p_sType, p_sArgs) {
        var oBody,
                oElement,
                oShadow,
                oUL;
        if (this.parent) {
            oElement = this.element;
            /*
             Get a reference to the Menu's shadow element and
             set its "height" property to "0px" to syncronize
             it with the height of the Menu instance.
             */
            oShadow = oElement.lastChild;
            oShadow.style.height = "0px";
            /*
             Stop the Animation instance if it is currently
             animating a Menu.
             */
            if (oAnim && oAnim.isAnimated()) {
                oAnim.stop();
                oAnim = null;
            }
            /*
             Set the body element's "overflow" property to
             "hidden" to clip the display of its negatively
             positioned <ul> element.
             */
            oBody = this.body;
            //  Check if the menu is a submenu of a submenu.
            if (this.parent &&
                    !(this.parent instanceof YAHOO.widget.MenuBarItem)) {
                /*
                 There is a bug in gecko-based browsers and Opera where an element whose "position" property is set to
                 "absolute" and "overflow" property is set to "hidden" will not render at the correct width when
                 its offsetParent's "position" property is also set to "absolute."  It is possible to work around
                 this bug by specifying a value for the width property in addition to overflow.
                 */
                if (ua.gecko || ua.opera) {
                    oBody.style.width = oBody.clientWidth + "px";
                }
                /*
                 Set a width on the submenu to prevent its width from growing when the animation is complete.
                 */
                if (ua.ie == 7) {
                    oElement.style.width = oElement.clientWidth + "px";
                }
            }
            oBody.style.overflow = "hidden";
            /*
             Set the <ul> element's "marginTop" property to a negative value so that the Menu's height collapses.
             */
            oUL = oBody.getElementsByTagName("ul")[0];
            oUL.style.marginTop = ("-" + oUL.offsetHeight + "px");
        }
    }

    /*
     "tween" event handler for the Anim instance, used to syncronize the size and position of the Menu instance's
     shadow and iframe shim (if it exists) with its changing height.
     */

    function onTween(p_sType, p_aArgs, p_oShadow) {
        if (this.cfg.getProperty("iframe")) {
            this.syncIframe();
        }

        if (p_oShadow) {
            p_oShadow.style.height = this.element.offsetHeight + "px";
        }
    }

    /*
     "complete" event handler for the Anim instance, used to remove style properties that were animated so that the
     Menu instance can be displayed at its final height.
     */

    function onAnimationComplete(p_sType, p_aArgs, p_oShadow) {
        var oBody = this.body,
                oUL = oBody.getElementsByTagName("ul")[0];
        if (p_oShadow) {
            p_oShadow.style.height = this.element.offsetHeight + "px";
        }

        oUL.style.marginTop = "";
        oBody.style.overflow = "";

        //  Check if the menu is a submenu of a submenu.
        if (this.parent &&
                !(this.parent instanceof YAHOO.widget.MenuBarItem)) {
            // Clear widths set by the "beforeshow" event handler
            if (ua.gecko || ua.opera) {
                oBody.style.width = "";
            }
            if (ua.ie == 7) {
                this.element.style.width = "";
            }
        }
    }


    /*
     "show" event handler for each submenu of the MenuBar
     instance - used to kick off the animation of the
     <ul> element.
     */

    function onSubmenuShow(p_sType, p_sArgs) {
        var oElement,
                oShadow,
                oUL;
        if (this.parent) {
            oElement = this.element;
            oShadow = oElement.lastChild;
            oUL = this.body.getElementsByTagName("ul")[0];
            /*
             Animate the <ul> element's "marginTop" style property to a value of 0.
             */
            oAnim = new YAHOO.util.Anim(oUL,
            { marginTop: { to: 0 } },
                    .5, YAHOO.util.Easing.easeOut);

            oAnim.onStart.subscribe(function () {
                oShadow.style.height = "100%";
            });
            oAnim.animate();
            /*
             Subscribe to the Anim instance's "tween" event for IE to syncronize the size and position of a
             submenu's shadow and iframe shim (if it exists) with its changing height.
             */
            if (YAHOO.env.ua.ie) {
                oShadow.style.height = oElement.offsetHeight + "px";
                /*
                 Subscribe to the Anim instance's "tween" event, passing a reference Menu's shadow
                 element and making the scope of the event listener the Menu instance.
                 */
                oAnim.onTween.subscribe(onTween, oShadow, this);
            }
            /*
             Subscribe to the Anim instance's "complete" event, passing a reference Menu's shadow element and making
             the scope of the event listener the Menu instance.
             */
            oAnim.onComplete.subscribe(onAnimationComplete, oShadow, this);
        }
    }

    /*
     Instantiate a MenuBar:  The first argument passed to the constructor is the id of the element in the page
     representing the MenuBar; the second is an object literal of configuration properties.
     */

    var oMenuBar = new YAHOO.widget.MenuBar("productsandservices", {
        autosubmenudisplay: true,
        hidedelay: 750,
        lazyload: true });

    /*
     Subscribe to the "beforeShow" and "show" events for each submenu of the MenuBar instance.
     */
    oMenuBar.subscribe("beforeShow", onSubmenuBeforeShow);
    oMenuBar.subscribe("show", onSubmenuShow);
    /*
     Call the "render" method with no arguments since the markup for this MenuBar already exists in the page.
     */
    oMenuBar.render();
});
