/**
 * @author Adam McIntyre
 * Builds the Media Bar / Carousel / Lightbox combo on the article detail page.
 * Also contains the "client" awesomebox uses to process images.
 */
/*
 The following information must not be removed:
 Awesome Box v2
 Written by: Paul Armstrong, Paul Armstrong Designs
 Site: http://paularmstrongdesigns.com
 Idea and some functions from "LightBox" http://www.huddletogether.com
 Example & Documentation: http://paularmstrongdesigns.com/awesome/box/
 Last Updated: Friday, February 2, 2007 at 12:31:10

 This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License
 http://creativecommons.org/licenses/by-sa/2.5/

 Required Yahoo! UI Files:
 * yahoo.js
 * dom.js
 * event.js
 * [ or: yahoo-dom-event.js ]
 * animation.js
 * [ or: animation-min.js ]

 Modified for NikonUSA.com by Adam McIntyre -- adam.mcintyre@molecular.com
 */
aLoadImgSrc = "/static/js/awesome-box-v2/images/aBox-loading.gif";
var aClient = {};
aClient.photos = [];
aClient.allAssets = {};
aClient.groups = {};
aClient.aTypes = {'jpg':true, 'gif':true, 'png':true, 'bmp':true, 'flv':true, 'swf':true, 'mp3':true, 'wav':true}; // types of images to place in Awesome Box
aClient.imgTypes = {'jpg':true,'gif':true,'bmp':true};
aClient.mediaTypes = {'flv':true, 'swf':true, 'mp3':true, 'wav':true};
/*
 *  aClient.addItem()
 *    Given an item, determines if it should be displayed in the lightbox and
 *    adds it to appropriate array.
 *  @param lbItem Item to test.
 */
aClient.addItem = function(lbItem) {
    var fileType = lbItem.href.substr(lbItem.href.lastIndexOf('.') + 1).toLowerCase();
    if(fileType in aClient.aTypes) {
        var mixed = fileType in aClient.mediaTypes;
        this.photos.push(lbItem);
        this.addToGroup(lbItem, mixed);
        YAHOO.awesomebox.setClickAction(lbItem, YAHOO.awesomebox);
    }
};

/*
 *  aClient.addMCItem()
 *    Given a MediaCenter item, determines if it should be displayed in the lightbox and
 *    adds it to appropriate array. Note that this defers adding the item's click action to the Media Center
 *    object itself.
 *  @param lbItem Item to test.
 */
aClient.addMCItem = function(lbItem) {
    var fileType = lbItem.href.substr(lbItem.href.lastIndexOf('.') + 1).toLowerCase();
    if(fileType in aClient.aTypes) {
        var mixed = fileType in aClient.mediaTypes;
        this.photos.push(lbItem);
        this.addToGroup(lbItem, mixed);
    }
};

/*
 *  aClient.noDownloadLink
 *    A constant object holding items that should not have a "download" link displayed for them.
 */
aClient.noDownloadLink = {'jpg':true, 'gif':true, 'png':true, 'bmp':true, 'flv':true, 'swf':true };

/***
 * Adds an item to a given photo "group," as specified in its "rel" attribute.
 * If that group exists, the item is added. Otherwise, the group is created than added.
 * @param {Object} lbItem
 * @param {Boolean} mixed Whether or not this is "mixed" media that requires SWFObject and therefore stops pagination.
 */
aClient.addToGroup = function(lbItem, mixed) {
    if(! (lbItem.rel in this.groups)) {
        this.groups[lbItem.rel] = [];
        this.groups[lbItem.rel].items = [];
    }
    var grp = this.groups[lbItem.rel];
    grp.items.push(lbItem);
    if(mixed) {
        grp.mediaType = "mixed";
    }
    grp[lbItem.href] = grp.items.length - 1;     // hold array index of this item in a map for quick lookup
}

/***
 * Returns a group with the given name, or an empty array if it doesn't exist.
 * @param {String} groupName Name of group we're looking for.
 */
aClient.getGroup = function(groupName) {
    if(this.groups[groupName]) {
        return this.groups[groupName];
    }
    return [];
}

/***
 * Determines whether a given value is present in a group.
 * @param {String} groupName Name of group we would like to check.
 * @param {String} value Value we'd like to test for presence in group.
 */
aClient.isInGroup = function(groupName, value) {
    if(value in this.getGroup(groupName)) {
        return this.groups[groupName][value];
    }
    return null;
}

/*
 *  aClient.pageWidth() and aClient.pageHeight()
 *    Returns the width and height of the content in the document.
 */
aClient.pageWidth = function() {
    var xScroll;
    if(window.innerHeight && window.scrollMaxY) {
        xScroll = document.body.scrollWidth;
    } else if(document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        xScroll = document.body.scrollWidth;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
    }
    if(xScroll < $D.getViewportWidth()) {
        pageWidth = $D.getViewportWidth();
    } else {
        pageWidth = xScroll;
    }
    return pageWidth;
};

aClient.pageHeight = function() {
    var yScroll;
    if(window.innerHeight && window.scrollMaxY) {
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if(document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        yScroll = document.body.offsetHeight;
    }
    if(yScroll <= $D.getViewportHeight()) {
        pageHeight = $D.getViewportHeight();
    } else {
        pageHeight = yScroll;
    }
    return pageHeight;
};

/*
 *  aClient.xScroll(), aClient.yScroll()
 *    Returns the position of the X and Y scrollbars.
 */
aClient.xScroll = function() {
    var xScroll = window.scrollX || document.documentElement.scrollLeft;
    return xScroll;
};
aClient.yScroll = function() {
    var yScroll = window.scrollY || document.documentElement.scrollTop;
    return yScroll;
};

MediaCenterUtils = function() {
    var intvl;

    return{
        /***
         *  Removes "centered" and "sized" classes from an element to prepare it for another treatment.
         *  Removes pre-set width and height, too.
         */
        _setupTreatment : function(imgEl) {
            YAHOO.util.Dom.removeClass(imgEl, 'auto_centered');
            YAHOO.util.Dom.removeClass(imgEl, 'auto_sized');

            YAHOO.util.Dom.setStyle(imgEl, 'width', '');
            YAHOO.util.Dom.setStyle(imgEl, 'height', '');
            YAHOO.util.Dom.setStyle(imgEl, 'top', '');
            YAHOO.util.Dom.setStyle(imgEl, 'left', '');
        },
        /***
         * Kicks off the show
         * @param {HTMLElement|String} img Image we're centering
         */
        handleImageTreatment : function(img) {
            this.centerImage(img);
            this.positionEnlargeImage(img);
        },
        /***
         * "Centers" a given image inside the viewport created by its parent.
         * @param {HTMLElement|String} img Image we're centering
         */
        centerImage : function(img) {
            var imgEl = YAHOO.util.Dom.get(img);
            var imgP = imgEl.parentNode;

            if(! YAHOO.util.Dom.hasClass(imgEl, 'auto_centered')
                       && imgEl.offsetWidth > 0 && imgEl.offsetHeight > 0) {
                imgEl.style.position = 'absolute';

                // Horizontally center
                var lOffset = (imgEl.offsetWidth - imgP.offsetWidth) / 2;
                if(lOffset < 0) {
                    imgEl.style.left = (-1 * lOffset) + 'px';
                }
                else {
                    imgEl.style.left = '-' + lOffset + 'px';
                }

                // Vertically center
                var tOffset = (imgEl.offsetHeight - imgP.offsetHeight) / 2;
                if(tOffset < 0) {
                    imgEl.style.top = (-1 * tOffset) + 'px';
                }
                else {
                    imgEl.style.top = '-' + tOffset + 'px';
                }
                YAHOO.util.Dom.addClass(imgEl, 'auto_centered');
            }

            // IE6 will not run this event at the right time, so we'll delay it just in case
            if(YAHOO.env.ua.ie > 0 && YAHOO.env.ua.ie < 7 && (imgEl.offsetWidth == 0 || imgEl.offsetHeight == 0)) {
                setTimeout(function() {
                    MediaCenterUtils.handleImageTreatment(img);
                }, 250);
            }
        },
        /***
         * Resizes a given image to the maximum size allowed by the viewport created by its parent.
         * @param {HTMLElement|String} img Image we're scaling
         */
        resizeImage : function(img) {
            var imgEl = YAHOO.util.Dom.get(img);
            var imgP = imgEl.parentNode;

            var pWidth = imgP.offsetWidth;
            var pHeight = imgP.offsetHeight;
            var iWidth = imgEl.offsetWidth;
            var iHeight = imgEl.offsetHeight;

            if(iWidth > pWidth && iHeight > pHeight && ! YAHOO.util.Dom.hasClass(imgEl, 'auto_sized')) {
                var newAspectRatio = Math.floor(Math.min(iWidth / pWidth, iHeight / pHeight));
                if(newAspectRatio > 1) {
                    imgEl.style.width = parseFloat(iWidth / newAspectRatio) + 'px'
                    imgEl.style.height = parseFloat(iHeight / newAspectRatio) + 'px';
                    YAHOO.util.Dom.addClass(imgEl, 'auto_sized');
                }
            }
        },
        /***
         * Positions the "enlarge image" button to the right edge of a given image
         * @param {HTMLElement|String} img Image we're scaling; we'll use it's ID to obtain enlarge imgae's ID
         */
        positionEnlargeImage : function(img) {
            img = YAHOO.util.Dom.get(img);
            var parentWidth = img.offsetWidth;

            var enlargeBtn = document.getElementById('enlarge_' + img.id);

            var newRight = img.parentNode.offsetWidth - parentWidth;

            // The mimimum "right" value is 10px; we need to enforce this on images larger than the parent
            // viewport, which would produce a negative value here. We also need to account for "centered" images
            // with a positive left value in the else statement.
            if((newRight - 10) < 0) {
                YAHOO.util.Dom.setStyle(enlargeBtn, 'right', '10px');
            }
            else {
                var leftOffset = parseInt(YAHOO.util.Dom.getStyle(img, 'left'), 10);
                if(leftOffset > 0) {
                    newRight -= leftOffset;
                }
                YAHOO.util.Dom.setStyle(enlargeBtn, 'right', newRight + 'px');
            }
        },
        /***
         * Sets the click and mouse actions on a single item, which won't have a media center and
         * otherwise won't receive them.
         * @param {HTMLElement|String} el Element we're configuring
         */
        setSingleItemActions : function(el) {
            var el = YAHOO.util.Dom.get(el);
            var baseId = el.id.substr('link_'.length);
            var iSrc = '';
            if(document.getElementById(baseId + '_intermediateImage')) {
                iSrc = document.getElementById(baseId + '_intermediateImage').getAttribute('data-intimage');
            }
            else {
                iSrc = document.getElementById(baseId).src;
            }

            YAHOO.awesomebox.setClickAction(el, YAHOO.awesomebox);
            YAHOO.util.Event.addListener(el, 'click', function() {
                OmnitureHelper.setMCEnlargeClickEvents(this.getAttribute('data-mediatype'), this.href, this.title);
            });

            // Wire up appropriate "enlarge image" actions
            if(MCCarouselWidget.prototype.enlargeable(iSrc, el.href)) {
                var fileType = el.href.substr(el.href.lastIndexOf('.') + 1);
                if(fileType.toLowerCase() in aClient.imgTypes) {    // Enlarge-image friendly types
                    var enlargeLink = document.getElementById('enlargeLink_' + baseId);

                    // Clear old attributes
                    enlargeLink.removeAttribute('data-fulldescription');
                    enlargeLink.removeAttribute('title');

                    if(el.getAttribute('title')) {
                        enlargeLink.setAttribute('title', el.getAttribute('title'));
                    }

                    if(el.getAttribute('data-fulldescription')) {
                        enlargeLink.setAttribute('data-fulldescription', el.getAttribute('data-fulldescription'));
                    }

                    enlargeLink.setAttribute('href', el.href);
                    YAHOO.awesomebox.setClickAction(enlargeLink, YAHOO.awesomebox);
                    YAHOO.util.Dom.removeClass('enlarge_' + baseId, 'noD');
                }
                // Do we need to wire up the actions for a "read more" link in the item's description?
                var rm = YAHOO.util.Selector.query('a.read_more', 'summary_' + baseId, true);
                if(rm) {
                    YAHOO.awesomebox.setClickAction(rm, YAHOO.awesomebox);
                }
            }
            this.maybeShowPlayButton(el, 'play_' + el.id);
        },
        /***
         * Determines whether or not the "play" icon should appear over a given Media Center Element, and displays it if it should.
         * This works like the enlarge image button functionality, copying/setting attributes, etc.
         * @param {HTMLElement|String} el Element we're checking. It's ID should be in the form of "link_selectedImage_[index]"
         * @param {String} id ID of the play icon we're working with
         */
        maybeShowPlayButton : function(el, id) {
            var piLink = document.getElementById(id);

            if(el.href.indexOf('.flv') > -1) {
                setTimeout(function() {
                    // Clear old attributes
                    piLink.removeAttribute('data-fulldescription');
                    piLink.removeAttribute('title');
                    piLink.removeAttribute('size');

                    if(el.getAttribute('title')) {
                        piLink.setAttribute('title', el.getAttribute('title'));
                    }

                    if(el.getAttribute('data-fulldescription')) {
                        piLink.setAttribute('data-fulldescription', el.getAttribute('data-fulldescription'));
                    }

                    if(el.getAttribute('size')) {
                        piLink.setAttribute('size', el.getAttribute('size'));
                    }

                    piLink.setAttribute('href', el.href);
                    YAHOO.awesomebox.setClickAction(piLink, YAHOO.awesomebox);
                    if(YAHOO.env.ua.ie == 0 || YAHOO.env.ua.ie > 6) {
                        YAHOO.util.Dom.setStyle(piLink, 'opacity', 0);
                        YAHOO.util.Dom.removeClass(piLink, 'noD');
                        new YAHOO.util.Anim(piLink, {opacity : {to : 0.99 }}, 0.25).animate();
                    }
                    else {
                        YAHOO.util.Dom.removeClass(piLink, 'noD');
                    }
                }, 500);
            }
            else {
                YAHOO.util.Dom.addClass(piLink, 'noD');
            }
        }
    }
}();

function MCCarouselWidget(cId, replaceImgId, size, numVisible, scrollInc) {
    this.tabId = cId;

    var curSize = size || YAHOO.util.Selector.query('ul.carousel-list li', cId).length;
    numVisible = numVisible || 6;
    scrollInc = scrollInc || numVisible;

    var configOpts =
    {
        "numVisible":                numVisible,
        "animationSpeed":            0.35,
        "scrollInc":                 scrollInc,
        "navMargin":                 0,
        "revealAmount":              0,
        "firstVisible":              1,
        "size":                      curSize,
        "prevElement":               cId + "-prev",
        "nextElement":               cId + "-next"
    };

    var carousel = new YAHOO.extension.Carousel(cId, configOpts);
    var navId = cId + "-navigation";

    this.replaceImgId = replaceImgId;
    this.getCarouselEl = function() { return carousel._carouselElemID; };
    this.getNav = function() { return document.getElementById(navId); };

    this.getCarousel = function() { return carousel; };

    this.scrollable = (curSize > numVisible && this.getNav()) ? true : false;

    var obj = this;

    var _wireChildActions = function() {
        var anchors = YAHOO.util.Selector.query('ul.carousel-list li a', cId);
        var linkEl = YAHOO.util.Dom.get('link_' + obj.replaceImgId);

        YAHOO.util.Dom.batch(anchors, function(o) {
            YAHOO.util.Event.addListener(o, 'click', function(e) {
                YAHOO.util.Event.preventDefault(e);

                var curEl = this;

                // Configure Omniture actions for this thumbnail click
                OmnitureHelper.setMCThumbClickEvents(mcTabs.get('activeTab').get('labelEl').innerHTML,
                        curEl.getAttribute('data-mediatype'), curEl.href, curEl.title);

                // Fade in loader, fade out current image
                obj.fadeSwap('preload_' + obj.replaceImgId, obj.replaceImgId);
                obj.setHighlighted(curEl);
                YAHOO.util.Dom.addClass('enlarge_' + obj.replaceImgId, 'noD');
                YAHOO.util.Dom.addClass('play_link_' + obj.replaceImgId, 'noD');

                setTimeout(function() {
                    var im = new Image();
                    var iSrc = document.getElementById(curEl.id + '_intermediateImage').getAttribute('data-intimage');

                    im.onload = function() {
                        // Set new click action/href on replaced image to wire it into the lightbox
                        //
                        // BUT, we only do it if there is indeed an enlarged version of this image to show.
                        if(obj.enlargeable(iSrc, curEl.href)) {
                            YAHOO.util.Event.removeListener(linkEl, 'click');
                            linkEl.setAttribute('href', curEl.href);
                            YAHOO.awesomebox.setClickAction(linkEl, YAHOO.awesomebox);
                        }
                        else {
                            YAHOO.util.Event.removeListener(linkEl, 'click');
                            linkEl.setAttribute('href', 'javascript:void(0)');
                            YAHOO.util.Event.addListener(linkEl, 'click', function() { return false; });
                        }

                        // Also, set up link's Omniture tagging properties
                        linkEl.setAttribute('data-mediatype', curEl.getAttribute('data-mediatype'));

                        // Remove any old attributes just in case they're not used on this item
                        linkEl.removeAttribute('title');
                        linkEl.removeAttribute('data-fulldescription');

                        linkEl.title = curEl.getAttribute('title') ? curEl.getAttribute('title') : '&nbsp;';

                        // Hook up truncated/non-truncated description attrubutes to the viewport link
                        linkEl.setAttribute('data-fulldescription', curEl.getAttribute('data-fulldescription'));

                        // Do we need a size attribute here?
                        if(curEl.getAttribute('size')) {
                            linkEl.setAttribute('size', curEl.getAttribute('size'));
                        }
                        else if(linkEl.getAttribute('size')) {
                            linkEl.removeAttribute('size');
                        }

                        // Swap in the new "intermediate" image
                        obj.swapImages(obj, iSrc, function() {
                            // Center this image
                            MediaCenterUtils._setupTreatment(obj.replaceImgId);
                            MediaCenterUtils.handleImageTreatment(obj.replaceImgId);
                            obj.fadeSwap(obj.replaceImgId, 'preload_' + obj.replaceImgId);

                            // Add the element's title and description to the appropriate elements
                            document.getElementById('title_' + obj.replaceImgId).innerHTML = curEl.getAttribute('title') ? curEl.getAttribute('title') : '&nbsp;';
                            document.getElementById('summary_' + obj.replaceImgId).innerHTML = curEl.getAttribute('alt') ? curEl.getAttribute('alt') : '&nbsp;';

                            // Do we need to wire up the actions for a "read more" link in the item's description?
                            // Also, Safari seems to want to return "null" (the string) for missing attributes in getAttribute calls.
                            if(obj.enlargeable(iSrc, curEl.href)
                                       && (curEl.getAttribute('alt') && curEl.getAttribute('alt').indexOf('...') == curEl.getAttribute('alt').length - 3)
                                       && !(curEl.getAttribute('alt') == null || curEl.getAttribute('data-fulldescription') == null)
                                    && !(linkEl.alt == linkEl.getAttribute('data-fulldescription'))) {
                                var baseId = linkEl.id.substr('link_'.length);
                                var moreEl = document.getElementById('more_' + baseId);
                                var tmpLink = moreEl.cloneNode(true);
                                tmpLink.id = '';

                                if(curEl.getAttribute('size')) {
                                    tmpLink.setAttribute('size', curEl.getAttribute('size'));
                                }
                                tmpLink.setAttribute('href', curEl.href);
                                tmpLink.title = curEl.getAttribute('title') ? curEl.getAttribute('title') : '&nbsp;';

                                // Hook up truncated/non-truncated description attrubutes to the viewport link
                                tmpLink.setAttribute('data-fulldescription',
                                        curEl.getAttribute('data-fulldescription'));
                                YAHOO.util.Dom.removeClass(tmpLink, 'noD');
                                document.getElementById('summary_' + obj.replaceImgId).appendChild(tmpLink);

                                var rm = YAHOO.util.Selector.query('a.read_more', 'summary_' + baseId, true);
                                rm.innerHTML = rm.innerHTML.replace(/^(\s)+(.*)(\s)+$/, '$2');
                                YAHOO.awesomebox.setClickAction(rm, YAHOO.awesomebox);

                            }

                            // Display download link and file size for this item?
                            obj._addExtraInfo(curEl, true);

                            // Wire up appropriate "enlarge image" actions
                            var fileType = curEl.href.substr(curEl.href.lastIndexOf('.') + 1);
                            var enlargeEl = document.getElementById('enlarge_' + obj.replaceImgId);

                            if(fileType.toLowerCase() in aClient.imgTypes && obj.enlargeable(iSrc,
                                    curEl.href)) {    // Enlarge-image friendly types
                                var enlargeLink = YAHOO.util.Selector.query('a', enlargeEl, true);

                                // Clear old attributes
                                enlargeLink.removeAttribute('data-fulldescription');
                                enlargeLink.removeAttribute('title');

                                if(curEl.getAttribute('title')) {
                                    enlargeLink.setAttribute('title', curEl.getAttribute('title'));
                                }

                                if(curEl.getAttribute('data-fulldescription')) {
                                    enlargeLink.setAttribute('data-fulldescription',
                                            curEl.getAttribute('data-fulldescription'));
                                }

                                enlargeLink.setAttribute('href', curEl.href);
                                YAHOO.awesomebox.setClickAction(enlargeLink, YAHOO.awesomebox);
                                setTimeout(function() {
                                    YAHOO.util.Dom.removeClass(enlargeEl, 'noD');
                                }, 100);
                            }
                            else {
                                YAHOO.util.Dom.addClass(enlargeEl, 'noD');
                            }

                            // Display/wire up "play" button?
                            MediaCenterUtils.maybeShowPlayButton(curEl, 'play_link_' + obj.replaceImgId);
                        });
                    };

                    im.src = iSrc;
                }, 300);
            });

            YAHOO.util.Event.addListener(o, 'mouseover', function(e) {
                var curEl = this;

                // This item has a "default icon" to swap, such as a video or audio file.
                if(document.getElementById(curEl.id + '_fileIcon')) {
                    // Swap the file icon and store the previous for later retrieval onmouseout.
                    var imgEl = YAHOO.util.Dom.getFirstChild(curEl);
                    var fileEl = document.getElementById(curEl.id + '_fileIcon');
                    var oldSrc = imgEl.src;

                    imgEl.src = fileEl.getAttribute('data-icon');
                    fileEl.setAttribute('data-icon', oldSrc);
                }
            });

            YAHOO.util.Event.addListener(o, 'mouseout', function(e) {
                var curEl = this;

                // This item has a "default icon" to swap, such as a video or audio file.
                // Now we reset it.
                if(document.getElementById(curEl.id + '_fileIcon')) {
                    // Swap the file icon and store the previous for later retrieval onmouseout.
                    var imgEl = YAHOO.util.Dom.getFirstChild(curEl);
                    var fileEl = document.getElementById(curEl.id + '_fileIcon');
                    var oldSrc = imgEl.src;

                    imgEl.src = fileEl.getAttribute('data-icon');
                    fileEl.setAttribute('data-icon', oldSrc);
                }
            });

            aClient.addMCItem(o);
        });

        // Add click action for initially loaded MC image
        //aClient.addMCItem(document.getElementById('link_' + obj.replaceImgId));
        var lHref = linkEl.href;
        var baseId = linkEl.id.substr('link_'.length);
        var mcSrc = document.getElementById(baseId).src;

        if(obj.enlargeable(lHref, mcSrc)) {
            YAHOO.awesomebox.setClickAction(linkEl, YAHOO.awesomebox);
            // Do we need to wire up the actions for a "read more" link in the item's description?
            var rm = YAHOO.util.Selector.query('a.read_more', 'summary_' + baseId, true);
            if(rm) {
                YAHOO.awesomebox.setClickAction(rm, YAHOO.awesomebox);
            }
        }

        // And, let's see if we need to add an enlarge image action...
        var fileType = anchors[0].href.substr(anchors[0].href.lastIndexOf('.') + 1);
        var enlargeEl = document.getElementById('enlarge_' + obj.replaceImgId);

        if(fileType.toLowerCase() in aClient.imgTypes && obj.enlargeable(mcSrc,
                anchors[0].href)) {    // Enlarge-image friendly types
            var enlargeLink = YAHOO.util.Selector.query('a', enlargeEl, true);

            // Clear old attributes
            enlargeLink.removeAttribute('data-fulldescription');
            enlargeLink.removeAttribute('title');

            if(anchors[0].getAttribute('title')) {
                enlargeLink.setAttribute('title', anchors[0].getAttribute('title'));
            }

            if(anchors[0].getAttribute('data-fulldescription')) {
                enlargeLink.setAttribute('data-fulldescription', anchors[0].getAttribute('data-fulldescription'));
            }

            enlargeLink.setAttribute('href', anchors[0].href);
            YAHOO.awesomebox.setClickAction(enlargeLink, YAHOO.awesomebox);
            YAHOO.util.Dom.removeClass(enlargeEl, 'noD');
        }
        else {
            YAHOO.util.Dom.addClass(enlargeEl, 'noD');
        }

        // Display/wire up "play" button?
        MediaCenterUtils.maybeShowPlayButton(anchors[0], "play_link_" + obj.replaceImgId);

        YAHOO.util.Event.addListener(obj.replaceImgId, 'load', function() {
            MediaCenterUtils._setupTreatment(obj.replaceImgId);
            MediaCenterUtils.handleImageTreatment(obj.replaceImgId);
        });

        // Set up Omniture tracking on this image
        YAHOO.util.Event.addListener('link_' + obj.replaceImgId, 'click', function() {
            OmnitureHelper.setMCEnlargeClickEvents(this.getAttribute('data-mediatype'), this.href, this.title);
        });

        // Display download link and file size for the initially loaded file?
        obj._addExtraInfo(anchors[0], true);
    };

    var init = function() {
        _wireChildActions();
        if(obj.getNav()) {
            obj._configureNav();
        }
    };

    init();
}

// For showing the enlarge image button: Are the src attributes of the media center image and enlarge image the same?
MCCarouselWidget.prototype.enlargeable = function(smSrc, bigSrc) {
    return ! (smSrc == bigSrc || bigSrc.indexOf(smSrc) > -1 || smSrc.indexOf(bigSrc) > -1)
}

MCCarouselWidget.prototype.fadeSwap = function(inId, outId) {
    if(YAHOO.util.Dom.hasClass(inId, 'preload')) {
        YAHOO.util.Dom.addClass(inId, 'preload_on');
    }

    var anim = new YAHOO.util.Anim(outId, {
        opacity : { to : 0}
    },
            0.25, YAHOO.util.Easing.easeIn);

    anim.onStart.subscribe(function() {
        new YAHOO.util.Anim(inId, {
            opacity : { to : .99 }
        },
                0.10, YAHOO.util.Easing.easeIn).animate();
    });

    anim.onComplete.subscribe(function() {
        YAHOO.util.Dom.removeClass(outId, 'preload_on');
    });

    anim.animate();
}

// Add "extra" info, like a download link, and file info
MCCarouselWidget.prototype._addExtraInfo = function(link, showLink) {
    var fileType = link.getAttribute('data-filetype');

    if(fileType && ! (fileType.toLowerCase() in aClient.noDownloadLink)) {
        if(showLink) {
            this._displayDownloadLink(fileType, link.href);
        }
        this._displayFileInformation(fileType, link.getAttribute('data-filesize'));
    }
    else {
        YAHOO.util.Dom.addClass('download_' + this.replaceImgId, 'noD');
    }
}

MCCarouselWidget.prototype._mouseOverExtraInfo = function(link) {
    var fileType = link.getAttribute('data-filetype');

    if(fileType && ! (fileType.toLowerCase() in aClient.noDownloadLink)) {
        this._displayFileInformation(fileType, link.getAttribute('data-filesize'));
    }
}

MCCarouselWidget.prototype._displayDownloadLink = function(fType, sUrl) {
    var el = document.getElementById('download_' + this.replaceImgId);

    // If link points at a file type that is not flagged as not displaying a download link, display the link
    // and the associated file information in the item's title.
    el.href = sUrl;
    YAHOO.util.Dom.removeClass(el, 'noD');
};

MCCarouselWidget.prototype._displayFileInformation = function(fType, fSize) {
    // If link points at a file type that is not flagged as not displaying a download link, display the link
    // and the associated file information in the item's title.
    var fileSize = fSize || '';

    // Append file type and size to the item's title if it isn't already present, as is the case with the
    // first asset in a list
    var fileInfo = ' (' + fType + ', ' + fileSize + ')';

    if(document.getElementById('title_' + this.replaceImgId).innerHTML.indexOf(fileInfo) < 0) {
        document.getElementById('title_' + this.replaceImgId).innerHTML += fileInfo;
    }

};

MCCarouselWidget.prototype.swapImages = function(obj, newSrc, callback) {
    var i = YAHOO.util.Dom.get(obj.replaceImgId);

    // Are we trying to load the same image? Safari will never fire the onload event and the callback, so we fire it ourselves
    if(i.src.indexOf(newSrc) > -1) {
        callback();
    }
    else {
        i.onload = function() {callback();}
        i.src = newSrc;
    }
};

MCCarouselWidget.prototype.setHighlighted = function(obj) {
    if(typeof MediaCenter[this.tabId].highlighted == "undefined") {
        MediaCenter[this.tabId].highlighted = YAHOO.util.Selector.query('ul.carousel-list', this.tabId, true);
    }
    if(typeof MediaCenter[this.tabId].current == "undefined") {
        MediaCenter[this.tabId].current = YAHOO.util.Selector.query('ul.carousel-list li', this.tabId, true);
    }

    // Remove selected from current selections
    YAHOO.util.Dom.removeClass(MediaCenter[this.tabId].highlighted, 'selected');
    YAHOO.util.Dom.removeClass(MediaCenter[this.tabId].current, 'selected');

    // Add to new selections
    YAHOO.util.Dom.addClass(obj.parentNode, 'selected');
    YAHOO.util.Dom.addClass(this.getCarousel().carouselList, 'selected');

    MediaCenter[this.tabId].highlighted = obj.parentNode;
    MediaCenter[this.tabId].current = this.getCarousel().carouselList;

    // Calculate currently clicked image number and update the nav counters
    if(this.getNav()) {
        var id = obj.parentNode.id;
        var num = id.substr(id.indexOf('item-') + 5);
        this._setCurrentNumber(num);
    }
}

MCCarouselWidget.prototype._configureNav = function() {
    if(this.scrollable) {
        this._setCurrentNumber(1);
    }
    else {
        var cn = this.getNav().childNodes;
        for(var i = 0; i < cn.length; i++) {
            if(cn[i].className && cn[i].className.indexOf('rnd') < 0) {
                cn[i].style.display = 'none';
            }
        }
    }
}

MCCarouselWidget.prototype._setCurrentNumber = function(curNumber) {
    YAHOO.util.Dom.get(this.getCarouselEl() + "-curNum").innerHTML = curNumber;
    YAHOO.util.Dom.get(this.getCarouselEl() + "-maxNum").innerHTML = this.getCarousel().cfg.getProperty('size');
};

MCCarouselWidget.prototype._getNavInfo = function() {
    var rt = {};
    rt.xy = YAHOO.util.Dom.getXY(this.getNav());
    rt.h = this.getNav().offsetHeight;
    return rt;
};

MCCarouselWidget.prototype._setShowNavEvent = function() {
    //YAHOO.util.Event.addListener(this.getCarouselEl()+"-container",'mouseover',this.handleShowNavigation,this);
    YAHOO.util.Event.addListener(this.getNav(), 'mousemove', this.handleShowNavigation, this);
};

MCCarouselWidget.prototype.handleShowNavigation = function(e, o) {
    //YAHOO.util.Event.removeListener(o.getCarouselEl()+"-container",'mouseover');
    YAHOO.util.Event.removeListener(o.getNav(), 'mousemove');
    o._fadeInNav();
    //o._showNavigation();
    o._setHideNavEvent();
};

MCCarouselWidget.prototype._fadeInNav = function(e, o) {
    var anim = new YAHOO.util.Anim(this.getNav(),
    { opacity : { to : 1 } },
            0.25,
            YAHOO.util.Easing.easeOut
            );

    anim.animate();
};

MCCarouselWidget.prototype._showNavigation = function() {
    var coordInfo = this._getNavInfo();
    var top = coordInfo.xy[1] + coordInfo.h;

    var anim = new YAHOO.util.Motion(this.getNav(),
    { points : { to: [coordInfo.xy[0], top] } },
            0.25,
            YAHOO.util.Easing.easeOut
            );

    anim.animate();
};

MCCarouselWidget.prototype._setHideNavEvent = function() {
    //YAHOO.util.Event.addListener(this.getCarouselEl()+"-container",'mouseout',this.handleHideNavigation,this);
    YAHOO.util.Event.addListener(this.getNav(), 'mouseout', this.handleHideNavigation, this);
};

MCCarouselWidget.prototype.handleHideNavigation = function(e, o) {
    if(e.explicitOriginalTarget.tagName && e.explicitOriginalTarget.tagName.toLowerCase() == "html") {
        YAHOO.util.Event.removeListener(o.getCarouselEl() + "-container", 'mouseout');
        o._fadeOutNav();
        //o._hideNavigation();
        o._setShowNavEvent();
    }
};

MCCarouselWidget.prototype._fadeOutNav = function(e, o) {
    var anim = new YAHOO.util.Anim(this.getNav(),
    { opacity : { to : 0.35 } },
            0.25,
            YAHOO.util.Easing.easeOut
            );

    anim.animate();
};

MCCarouselWidget.prototype._hideNavigation = function() {
    var coordInfo = this._getNavInfo();
    var top = coordInfo.xy[1] - coordInfo.h;

    var anim = new YAHOO.util.Motion(this.getNav(),
    { points : { to: [coordInfo.xy[0], top] } },
            0.25,
            YAHOO.util.Easing.easeOut
            );

    anim.animate();
};

/*
 The following information must not be removed:
 Awesome Box v2
 Written by: Paul Armstrong, Paul Armstrong Designs
 Site: http://paularmstrongdesigns.com
 Idea and some functions from "LightBox" http://www.huddletogether.com
 Example & Documentation: http://paularmstrongdesigns.com/awesome/box/
 Last Updated: Friday, February 2, 2007 at 12:31:10

 This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License
 http://creativecommons.org/licenses/by-sa/2.5/

 Required Yahoo! UI Files:
 * yahoo.js
 * dom.js
 * event.js
 * [ or: yahoo-dom-event.js ]
 * animation.js
 * [ or: animation-min.js ]

 Modified for NikonUSA.com by Adam McIntyre -- adam.mcintyre@molecular.com
 */

//var aLoadImgSrc = '../images/aBox-loading.gif'; // where is the loading image? (recommend absolute)
//var siteURL = 'http://localhost/'; // requires trailing / (after .com)
var isSafari = false;
if(YAHOO.env.ua.webkit > 0) {
    isSafari = YAHOO.env.ua.webkit < 525.19;
}

/*
 *  ***************************************
 *  EDIT BEYOND THIS POINT AT YOUR OWN RISK
 *  ***************************************
 */


/*
 *  Helper Variables
 */
var $D = YAHOO.util.Dom;
var $E = YAHOO.util.Event;
var $A = YAHOO.util.Anim;
var $M = YAHOO.util.Motion;
var $S = YAHOO.util.Scroll;
var $Ease = YAHOO.util.Easing;
var $ = $D.get;

/*
 *  AnimMgr
 *    Sets the default frames per second higher so Safari will display animations
 *    at the correct speed. Degrades for slower browsers.
 */
YAHOO.util.AnimMgr.fps = 500;

YAHOO.widget.aEffect = function(el) { this.oEl = YAHOO.util.Dom.get(el); };

/*
 *  YAHOO.widget.aEffect.aShowLoad()
 *    Animation widget for transition period on Awesome Box initialize or between images.
 */
YAHOO.widget.aEffect.prototype.aShowLoad = function() {
    var showLoad = new $A('aLoadImg', {opacity: {to: 1}}, 0.2);
    showLoad.onStart.subscribe(function() {
        var loadImg = document.getElementById('aLoadImg');
        $D.setStyle(loadImg, 'display', 'block');

        $D.setXY(loadImg, [
            ($D.getViewportWidth() / 2) - 16 + aClient.xScroll(),
            ($D.getViewportHeight() / 2) - 16 + aClient.yScroll()
        ]);
        if($D.hasClass('aBoxMeta', 'aOpen')) {
            var hideMeta = new $A('aBoxMeta', {opacity: {to: 0}, height: {to: 0}}, 0.2);
            $D.setStyle('aCloseButton', 'visibility', 'hidden');
            hideMeta.onStart.subscribe(function() {
                $D.setStyle('aImg', 'opacity', '0');
                $D.setStyle('aImg', 'visibility', 'hidden');
                $D.setStyle('aInfoTitle', 'visibility', 'hidden');
                $D.setStyle('lightbox_share', 'visibility', 'hidden');
            });
            hideMeta.animate();
        }
        else {

            var aBox = document.getElementById('aBox');
            $D.setStyle('aCloseButton', 'visibility', 'hidden');
            $D.setStyle(aBox, 'width', loadImg.offsetWidth + 'px');
            $D.setStyle(aBox, 'height', loadImg.offsetHeight + 'px');
            $D.setXY(aBox, [
                ($D.getViewportWidth() / 2) - 16 + aClient.xScroll(),
                ($D.getViewportHeight() / 2) - 16 + aClient.yScroll()
            ]);
        }
    });
    showLoad.animate();
};

/*
 *  YAHOO.widget.aEffect.aShowOverlay
 *    Fades in #aOverlay and #aBox.
 *    Initializes YAHOO.widget.aEffect.aShowLoad()
 */
YAHOO.widget.aEffect.prototype.aShowOverlay = function() {
    selects = document.getElementsByTagName("select");
    for(i = 0; i != selects.length; i++) {
        $D.setStyle(selects[i], 'visibility', 'hidden');
    }

    var fadeOverlay = new $A('aOverlay', {opacity: {to: 0.55}}, 0.3);
    fadeOverlay.onStart.subscribe(function() {
        $D.setStyle('aOverlay', 'display', 'block');
        $D.setStyle('aOverlay', 'height', aClient.pageHeight() + 'px');
    });
    var showBox = new $A('aBox', {opacity: {to: 1}}, 0.3);
    showBox.onStart.subscribe(function() {
        $D.setStyle('aBox', 'display', 'block');
        var showLoad = new YAHOO.widget.aEffect();
        showLoad.aShowLoad();
    });
    showBox.animate();
    fadeOverlay.animate();
};

/*
 *  YAHOO.widget.aEffect.aResizeBox()
 *    Initialized after new image is completed loading. Resizes and moves #aBox, times out
 *    and displays #aBoxMeta information
 */
YAHOO.widget.aEffect.prototype.aResizeBox = function(aPreload) {
    if(window.imageLoad) {
        clearInterval(window.imageLoad);
    }

    $D.addClass('aBox', 'image');
    // Since we need to open Safari in a new window, we must make sure these
    // display properties are set.
    if(isSafari) {
        $D.setStyle('aDiv', 'visibility', 'hidden');
        $D.setStyle('aDiv', 'display', 'none');
        $D.setStyle('aDiv', 'opacity', '0');
    }

    if(document.getElementById('container_colors')) {
        ColorVariantManager.setSelectedEl(this.oEl);
        if($D.hasClass(this.oEl, 'enlargeImg')) {
            $D.addClass('aBoxMeta', 'variant');
            if(!document.getElementById('container_lbVariants')) {
                var colors = $D.getElementsByClassName('color', 'div', 'container_colors');
                var lb_variantBlock = document.createElement('div');
                lb_variantBlock.id = 'container_lbVariants';
                lb_variantBlock.className = 'container_colors';
                var selectedColor = '';
                for(var i = 0; i < colors.length; i++) {
                    var el = colors[i];
                    var swatchImg = $D.getNextSibling($D.getFirstChild(el)).cloneNode(false);
                    swatchImg.id = 'lightbox_' + swatchImg.id;
                    var tmp = el.cloneNode(false);
                    tmp.id = el.id.replace('swatch_container', 'swatch_lb');
                    tmp.removeAttribute('onmouseover');
                    tmp.removeAttribute('onmouseout');
                    tmp.onclick = function() {
                        ColorVariantManager.lightboxClick(this.id.substr(this.id.lastIndexOf('_') + 1));
                    };
                    if($D.hasClass(el, 'selected')) {
                        tmp.className = 'color selected';
                        selectedColor = swatchImg.alt;
                        ColorVariantManager.setOriginalColor(el.id.substr(el.id.lastIndexOf('_') + 1));
                    } else {
                        tmp.className = 'color';
                    }
                    var sp = document.createElement('span');
                    sp.className = 'sm_border';
                    tmp.appendChild(sp);
                    tmp.appendChild(swatchImg);
                    lb_variantBlock.appendChild(tmp);
                }
                var colorInfo = document.createElement('span');
                colorInfo.className = 'color_info';
                colorInfo.innerHTML = 'Select color: <strong id="label_colorName">' + selectedColor + '</strong>';
                lb_variantBlock.appendChild(colorInfo);
                document.getElementById('variant_label').innerHTML = selectedColor + '&nbsp;';
                document.getElementById('variant_label').style.display = 'inline';
                document.getElementById('aBoxMeta').insertBefore(lb_variantBlock,
                        document.getElementById('aBoxMeta').firstChild);
            }
        }
    }

    var imgScale = YAHOO.awesomebox.scaleImage(aPreload);

    var metaHeight = 80;    // Standard height for "meta" information at bottom of lightbox.

    // Calculate the height of our description node to make sure we center things properly
    var tmpSpan = document.createElement('span');
    tmpSpan.style.visibility = 'hidden';
    document.body.appendChild(tmpSpan);
    tmpSpan.innerHTML = $('aInfo').innerHTML;

    if(imgScale[0] == 0 || isNaN(imgScale[0])) {
        // Something is wrong here. Bail out and try a width of 100px, otherwise we'll get a ridiculous result
        tmpSpan.style.width = '100px';
    }
    else {
        tmpSpan.style.width = imgScale[0] + 'px';
    }

    tmpSpan.style.display = 'block';
    tmpSpan.style.position = 'absolute';
    tmpSpan.style.left = '-5000px';

    var tmpHeight = parseInt(tmpSpan.offsetHeight, 10);
    document.body.removeChild(tmpSpan);

    if(tmpHeight <= 80) {  // Account for about a 10px buffer
        metaHeight = 95;
    }
    else {  // Account for about a 10px buffer + 15px bottom pos. for arrows
        metaHeight = (tmpHeight - 80) + 105;
    }

    var topPoint = ($D.getViewportHeight() / 2) - (imgScale[1] / 2) + aClient.yScroll();
    topPoint = topPoint - metaHeight < 0 ? 0 : topPoint - metaHeight;

    var leftPoint = ($D.getViewportWidth() / 2) - (imgScale[0] / 2) + aClient.xScroll() - 10;

    var moveBox = new $M('aBox', {
        width: {to: (imgScale[0] + 20)},
        height: {to: imgScale[1]},
        points: {to:
                [
                    leftPoint, topPoint
                ]
        }
    }, 0.3);
    moveBox.onStart.subscribe(function() {
        $D.setStyle('aBox', 'display', 'block');

        var hideLoad = new $A('aLoadImg', {opacity: {to: 0}}, 0.3);
        var sizeImage = new $A('aImg', {width: {to: imgScale[0]}, height: {to: imgScale[1]}}, 0.3);

        hideLoad.onComplete.subscribe(function() { $D.setStyle('aLoadImg', 'display', 'none'); });
        hideLoad.animate();
        sizeImage.animate();
    });
    moveBox.onComplete.subscribe(function() {
        var imgReg = YAHOO.util.Dom.getRegion('aImgHolder');
        var hdHeight = imgReg.top - parseFloat(document.getElementById('aBox').style.top);
        var imgOffset = (imgReg.bottom - imgReg.top) - imgScale[1]; // Winds up as the margin + padding of aImgHolder

        $D.setStyle('aBox', 'height', imgScale[1] + imgOffset + hdHeight + metaHeight + 'px');
        $D.setStyle('aContainer', 'height', imgScale[1] + imgOffset + hdHeight + 'px');
        $D.setStyle('aBoxMeta', 'width', imgScale[0] + 'px');
        $D.addClass('aBoxMeta', 'aOpen');
        $('aImg').setAttribute('width', imgScale[0]);
        $('aImg').setAttribute('height', imgScale[1]);
        $D.setStyle('aImg', 'visibility', 'visible');
        $D.setStyle('aInfoTitle', 'visibility', 'visible');

        var fadeImg = new $A('aImg', {opacity: {from: 0, to: 1}}, 0.3);
        fadeImg.onComplete.subscribe(function() {
            var showMeta = new $A('aBoxMeta', {opacity: {from: 0, to: 1}, height: {to: metaHeight}}, 0.2);
            showMeta.onComplete.subscribe(function() {
                YAHOO.util.Dom.setStyle('aCount', 'filter', '');
            });
            showMeta.animate();
            YAHOO.util.Dom.setStyle('lightbox_share', 'visibility', 'visible');
            $D.setStyle('aCloseButton', 'visibility', 'visible');
        });
        fadeImg.animate();
    });

    var lbImage = $('aImg');
    // In Safari, if aImg's src is also the aPreload's src, onload will never fire.
    if(lbImage.src == aPreload.src) {
        moveBox.animate();
    }
    else {
        setTimeout(function() {
            lbImage.onload = function() {
                moveBox.animate();
            }
            lbImage.src = aPreload.src;
        }, 300);
    }
};

/*
 *  YAHOO.widget.aEffect.aResizeBoxEl()
 *    Initialized after new image is completed loading. Resizes a box for a non-image element.
 */
YAHOO.widget.aEffect.prototype.aResizeBoxEl = function(aPreload, anEl) {
    $D.addClass('aBox', 'swf');
    var metaHeight = 80;    // Standard height for "meta" information at bottom of lightbox.

    // Calculate the height of our description node to make sure we center things properly
    var tmpSpan = document.createElement('span');
    tmpSpan.style.visibility = 'hidden';
    document.body.appendChild(tmpSpan);
    tmpSpan.innerHTML = $('aInfo').innerHTML;

    if(aPreload.width == 0 || isNaN(aPreload.width)) {
        // Something is wrong here. Bail out and try a width of 100px, otherwise we'll get a ridiculous result
        tmpSpan.style.width = '100px';
    }
    else {
        tmpSpan.style.width = aPreload.width + 'px';
    }

    tmpSpan.style.display = 'block';
    tmpSpan.style.position = 'absolute';
    tmpSpan.style.left = '-5000px';

    var tmpHeight = parseInt(tmpSpan.offsetHeight, 10);
    document.body.removeChild(tmpSpan);

    if(tmpHeight < 30) {
        metaHeight = 80;
    }
    else if(tmpHeight >= 30 && tmpHeight <= 90) {  // Account for about a 10px buffer
        metaHeight = (80 - tmpHeight + 10) + 80;
    }
    else if(tmpHeight > 0) {
        metaHeight = tmpHeight + 60;
    }

    var imgScale = YAHOO.awesomebox.scaleImage(aPreload);

    var topPoint = ($D.getViewportHeight() / 2) - (imgScale[1] / 2) + aClient.yScroll() - metaHeight;
    topPoint = topPoint < 0 ? 0 : topPoint;

    var moveBox = new $M('aBox', {
        width: {to: (aPreload.width + 30)},
        height: {to: (aPreload.height + 90 + metaHeight)},
        points: {to: [
            ($D.getViewportWidth() / 2) - (aPreload.width / 2) + aClient.xScroll() - 10,
            topPoint
        ]
        }
    }, 0.3);
    moveBox.onStart.subscribe(function() {
        $D.setStyle('aBox', 'display', 'block');

        var hideLoad = new $A('aLoadImg', {opacity: {to: 0}}, 0.3);
        var sizeBox = new $A('aDiv', {width: {to: aPreload.width}, height: {to: aPreload.height}}, 0.3);

        hideLoad.onComplete.subscribe(function() { $D.setStyle('aLoadImg', 'display', 'none'); });
        hideLoad.animate();
        sizeBox.animate();
    });
    moveBox.onComplete.subscribe(function() {
        var prHeight = aPreload.height;
        var prWidth = aPreload.width;

        $D.setStyle('aDiv', 'opacity', '1');
        $D.setStyle('aInfoTitle', 'visibility', 'visible');
        $D.setStyle('lightbox_share', 'visibility', 'visible');
        $D.setStyle('aCloseButton', 'visibility', 'visible');
        $D.setStyle('aImg', 'width', '0');
        $D.setStyle('aImg', 'height', '0');
        $D.setStyle('aBoxMeta', 'width', prWidth + 30 + 'px');
        $D.addClass('aBoxMeta', 'aOpen');
        $D.setStyle('aDiv', 'visibility', 'visible');
        $D.setStyle('aDiv', 'display', 'block');
        var showMeta = new $A('aBoxMeta', {opacity: {from: 0, to: 1}, height: {to: 80}}, 0.2);

        if(anEl.href.indexOf('.swf') > 0) {
            $D.setStyle('aDiv', 'width', prWidth + 'px');
            $D.setStyle('aDiv', 'height', prHeight + 'px');

            showMeta.onComplete.subscribe(function() {
                setTimeout(function() {
                    var fo = new FlashObject(anEl.href + '?' + Math.round(Math.random() * 100000),
                            anEl.rel + '' + Math.round(Math.random()), prWidth, prHeight, '#FFF');
                    fo.addParam('allowScriptAccess', 'sameDomain');
                    fo.addParam('wMode', 'transparent');
                    fo.write('aDiv');

                    var imgReg = YAHOO.util.Dom.getRegion('aImgHolder');
                    var hdHeight = imgReg.top - parseFloat(document.getElementById('aBox').style.top);
                    var imgOffset = (imgReg.bottom - imgReg.top) - prHeight; // Winds up as the margin + padding of aImgHolder
                    $D.setStyle('aContainer', 'height', hdHeight + imgOffset + prHeight + 'px');
                }, 10);
            });
        }
        else {
            showMeta.onComplete.subscribe(function() {
                $D.setStyle('aDiv', 'width', prWidth + 30 + 'px');
                $D.setStyle('aDiv', 'height', prHeight + 30 + 'px');

                setTimeout(function() {
                    var fo = new FlashObject('/static/flash/mediabar/nikonvideo.swf?' + Math.round(Math.random() * 100000),
                            anEl.rel + '' + Math.round(Math.random()), prWidth + 30, prHeight + 45, '#FFF');
                    fo.addParam('allowScriptAccess', 'sameDomain');
                    fo.addVariable('path', anEl.href);
                    fo.addVariable('title', '');
                    fo.addVariable('close', 'YAHOO.awesomebox.close');
                    fo.addVariable('showClose', false);
                    fo.addParam('wMode', 'transparent');
                    fo.write('aDiv');

                    var imgReg = YAHOO.util.Dom.getRegion('aImgHolder');
                    var hdHeight = imgReg.top - parseFloat(document.getElementById('aBox').style.top);
                    var imgOffset = (imgReg.bottom - imgReg.top) - prHeight; // Winds up as the margin + padding of aImgHolder
                    $D.setStyle('aContainer', 'height', hdHeight + imgOffset + prHeight + 'px');
                }, 10);
            });
        }
        showMeta.animate();
    });
    moveBox.animate();
};

/*
 *  YAHOO.widget.aEffect.aClose
 *    Closes #aBox and #aOverlay. Invoked via pressing 'x', clicking the 'X' image or #aOverlay
 */
YAHOO.widget.aEffect.prototype.aClose = function() {
    var that = $('aImg');
    $D.removeClass('aBoxMeta', 'variant');
    if(document.getElementById('container_lbVariants')) {
        document.getElementById('container_lbVariants').parentNode.removeChild(document.getElementById('container_lbVariants'));
        document.getElementById('variant_label').style.display = 'none';
        ColorVariantManager.resetEnlargeImg();
    }

    var hideMeta = new $A('aBoxMeta', {height: {to: 0}, opacity: {to: 0}}, 0.2);
    var fadeBox = new $M('aBox', {opacity: {to: 0}}, 0.3);

    fadeBox.onStart.subscribe(function() { $('aDiv').innerHTML = ''; });

    fadeBox.onComplete.subscribe(function() {
        var hideOverlay = new $A('aOverlay', {opacity: {to: 0}}, 0.3);
        hideOverlay.onStart.subscribe(function() {
            selects = document.getElementsByTagName("select");
            for(i = 0; i != selects.length; i++) {
                $D.setStyle(selects[i], 'visibility', 'visible');
            }
            $D.removeClass('aBoxMeta', 'aOpen');
            $D.removeClass('aBox', 'swf');
            $D.removeClass('aBox', 'image');
            $D.setStyle('aBox', 'display', 'none');
            $D.setStyle('aInfoTitle', 'visibility', 'hidden');
            $D.setStyle('lightbox_share', 'visibility', 'hidden');
            $D.setStyle('aImg', 'opacity', '0');
            $D.setStyle('aImg', 'visibility', 'hidden');
            $D.setStyle('aDiv', 'visibility', 'hidden');
            $D.setStyle('aDiv', 'display', 'none');
            $D.setStyle('aDiv', 'opacity', '0');
            $D.setStyle('aOverlay', 'display', 'none');
            $D.setStyle('aOverlay', 'height', '0px');
            $D.setStyle('aLoadImg', 'display', 'none');
        });
        hideOverlay.onComplete.subscribe(function() {
            var w = $D.getStyle('aDiv', 'width');
            var h = $D.getStyle('aDiv', 'height');

            $D.setStyle('aImg', 'width', w);
            $D.setStyle('aImg', 'height', h);

            $D.setStyle('aDiv', 'width', '0');
            $D.setStyle('aDiv', 'height', '0');
        });
        hideOverlay.animate();
    });
    hideMeta.animate();
    fadeBox.animate();
    $E.removeListener('aNextButton', 'click');
    $E.removeListener('aPrevButton', 'click');
};

/*
 * YAHOO.widget.aEffect.aAwesome
 *   This is awesome. Pay no attention to it.
 */
YAHOO.widget.aEffect.prototype.aAwesome = function() {
    return true;
};

/*
 *  YAHOO.awesomebox()
 *    Non-animating functions, initialized on window load completion.
 */
YAHOO.awesomebox = function() {
    return {
        /*
         *  init()
         *    Creates the markup, checks for direct image link, adds event listeners.
         */
        init : function() {
            if(!document.getElementsByTagName) {
                return;
            }

            /*
             *  Awesome Box Markup
             *
             <div id="aOverlay" title="Click to Close"></div>
             <div id="aBox">
             <div id="aImgHolder">
             <img id="aImg" />
             <div id="aDiv" />
             </div>
             <div id="aBoxMeta">
             <a class="aButton" href="javascript:void(0)" id="aNextButton"></a>
             <a class="aButton" href="javascript:void(0)" id="aPrevButton"></a>
             <a class="aButton" href="javascript:void(0)" id="aCloseButton"></a>
             <h1 id="aInfoTitle"></h1>
             <p id="aCount"></p>
             <div id="aInfo"></div>
             </div>
             </div>
             <img src="images/aBox-loading.gif" id="aLoadImg" />
             */

            var aBody = document.getElementsByTagName("body").item(0);

            var aOverlay = document.createElement('div');
            $(aOverlay).setAttribute('id', 'aOverlay');
            $(aOverlay).setAttribute('title', 'Click to Close');
            aBody.appendChild(aOverlay);
            $D.setStyle('aOverlay', 'opacity', '0');

            var aBox = document.createElement('div');
            $(aBox).setAttribute('id', 'aBox');
            aBody.appendChild(aBox);
            $D.addClass('aBox', 'l-e');
            $D.setStyle('aBox', 'opacity', '0');
            $D.setXY('aBox', [($D.getViewportWidth() / 2) - 21, ($D.getViewportHeight() / 2) - 21])
            $D.setStyle('aBox', 'display', 'none');

            var aContainer = document.createElement('div');
            $(aContainer).setAttribute('id', 'aContainer');

            var aCloseButton = document.createElement('a');
            $(aCloseButton).setAttribute('id', 'aCloseButton');
            $(aCloseButton).setAttribute('href', 'javascript:void(0)');
            aContainer.appendChild(aCloseButton);
            $D.addClass(aCloseButton, 'aButton');

            var aInfoTitle = document.createElement('h5');
            $(aInfoTitle).setAttribute('id', 'aInfoTitle');
            aContainer.appendChild(aInfoTitle);

            // If AddThis has been disabled for this page,
            // we should make sure it is disabled here as well
            var lightboxShare = document.createElement('div');
            lightboxShare.setAttribute('id', 'lightbox_share');
            //lightboxShare.innerHTML = '<a id="lightbox_printLink" href="javascript:YAHOO.awesomebox.printImage();" class="std">Print</a>';
            if(document.getElementById('addThis_breadcrumb')) {    // If this Element is present, AddThis is enabled
                lightboxShare.innerHTML += "<a class=\"addThis-Link\" onclick=\"return addthis_sendto();\" onmouseover=\"return addthis_open(this, '', '[URL]', '[TITLE]');\" href=\"http://www.addthis.com/bookmark.php\" onmouseout=\"addthis_close();\">Share</a>";
                //'<a id="lightbox_addThisLink" href="http://www.addthis.com/bookmark.php" onmouseout="addthis_close();" onclick="return addthis_sendto();"><img height="16" width="125" border="0" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Share"/></a>';
            }
            else {
                YAHOO.util.Dom.addClass(lightboxShare, 'no_addthis');
            }
            aContainer.appendChild(lightboxShare);

            var aImgHolder = document.createElement('div');
            $(aImgHolder).setAttribute('id', 'aImgHolder');
            aContainer.appendChild(aImgHolder);

            var aImg = document.createElement('img');
            $(aImg).setAttribute('id', 'aImg');
            aImgHolder.appendChild(aImg);
            $D.setStyle('aImg', 'opacity', '0');
            $D.setStyle('aImg', 'visibility', 'hidden');

            var aDiv = document.createElement('div');
            $(aDiv).setAttribute('id', 'aDiv');
            aImgHolder.appendChild(aDiv);
            $D.setStyle('aDiv', 'opacity', '0');
            $D.setStyle('aDiv', 'visibility', 'hidden');

            aBox.appendChild(aContainer);

            var aBoxMeta = document.createElement('div');
            $(aBoxMeta).setAttribute('id', 'aBoxMeta');
            aBox.appendChild(aBoxMeta);

            var aInfo = document.createElement('div');
            $(aInfo).setAttribute('id', 'aInfo');
            aBoxMeta.appendChild(aInfo);

            var aNextButton = document.createElement('a');
            $(aNextButton).setAttribute('id', 'aNextButton');
            aBoxMeta.appendChild(aNextButton);
            $(aNextButton).setAttribute('href', 'javascript:void(0)');
            $D.addClass(aNextButton, 'aButton');

            var aPrevButton = document.createElement('a');
            $(aPrevButton).setAttribute('id', 'aPrevButton');
            aBoxMeta.appendChild(aPrevButton);
            $(aPrevButton).setAttribute('href', 'javascript:void(0)');
            $D.addClass(aPrevButton, 'aButton');

            var aCountContainer = document.createElement('div');
            $(aCountContainer).setAttribute('id', 'aCountContainer');

            var variantLabel = document.createElement('label');
            $(variantLabel).setAttribute('id', 'variant_label');
            aCountContainer.appendChild(variantLabel);

            var aCount = document.createElement('label');
            $(aCount).setAttribute('id', 'aCount');
            aCountContainer.appendChild(aCount);
            aBoxMeta.appendChild(aCountContainer);
            $D.setStyle(aCount, 'opacity', '0');

            var preloadLoading = new Image();
            preloadLoading.src = aLoadImgSrc;

            var aLoadImg = document.createElement('img');
            $(aLoadImg).setAttribute('id', 'aLoadImg');
            aBody.appendChild(aLoadImg);
            $(aLoadImg).setAttribute('src', preloadLoading.src);
            $D.setStyle('aLoadImg', 'opacity', '0');

            var atLink = document.getElementById('lightbox_addThisLink');
            if(atLink) {
                YAHOO.util.Event.addListener(atLink, 'mouseover', function() {
                    OmnitureHelper.setAddThisEvents();
                    var tStr = "";
                    if(document.getElementById('lightbox_itemTitle')) {
                        tStr = document.getElementById('lightbox_itemTitle').innerHTML;
                    }
                    return addthis_open(this, '', window.location.href, tStr);
                });
            }

            /*
             *  Hash Check
             *    Checks the URL on page load for #filename and attempts to load it
             *
             */
            if(window.location.href.indexOf('showAsset') != -1) {
                var asset = window.location.href.match(/showAsset=([^&]*)&?/)[1];

                // generate an ID for the body if it doesn't exist
                if(document.body.id != '' || document.body.id != null) {
                    var body = $D.generateId(document.body);
                } else {
                    var body = document.body.id;
                }

                var allItems = YAHOO.util.Selector.query('ul.carousel-list li a');

                for(var i = 0; i < allItems.length; i++) {
                    if(allItems[i].href.indexOf(asset) > -1) {
                        var matchedItem = allItems[i];
                        var tmpId = matchedItem.id.substr(matchedItem.id.lastIndexOf('_') + 1);
                        tmpId = parseInt(tmpId.substr(0, tmpId.lastIndexOf('-')));

                        mcTabs.set('activeIndex', (tmpId - 1));
                        this.itemID = 'selectedImg_' + tmpId;

                        if(asset.indexOf('swf') > 0 || asset.indexOf('mp3') > 0 || asset.indexOf('flv') > 0) {
                            if(!isSafari) {
                                this.initLoadSwf(matchedItem);
                            }
                            else {
                                this.initLoadSafari(matchedItem);
                            }
                        }
                        else {    // img
                            this.initLoadImg(matchedItem);
                        }
                    }
                }
            }


            $E.on(aOverlay, 'click', this.close);
            $E.on(aCloseButton, 'click', this.close);
        },

        /***
         * Sets the 'onclick' handler for an object
         * @param {Object} o Object whose handler we're setting
         */
        setClickAction : function(o, obj) {
            // Remove any previous listeners attached to this Element.
            $E.removeListener(o, 'click');

            // This function has new entry points due to the various Media Center conditions (there may not always be
            // a carousel of thumbs, etc. We should ensure that this is a valid file type before proceeding.
            var fileType = o.href.substr(o.href.lastIndexOf('.') + 1).toLowerCase();

            if(fileType in aClient.aTypes) {
                if(fileType == 'swf' || fileType == 'mp3' || fileType == 'flv') {
                    if(!isSafari) {
                        $E.addListener(o, 'click', function(e) {
                            YAHOO.util.Event.preventDefault(e);
                            obj.loadSwf(e, this);
                        });
                    }
                    else {
                        $E.addListener(o, 'click', function(e) {
                            YAHOO.util.Event.preventDefault(e);

                            obj.loadSafari(e, this);
                        });
                    }
                }
                else {    // img
                    $E.addListener(o, 'click', function(e) {
                        YAHOO.util.Event.preventDefault(e);
                        obj.loadImg(e, this);
                    });
                }
            }
        },

        /***
         * Adds a given asset to a URL, complete with that asset's selected tab
         */
        setUrl : function(asset, tab, title) {
            var hashParams = "#" + 'showAsset=' + asset + "&tab=" + tab;
            var hashPosition = window.location.href.indexOf('#');

            if(hashPosition < 0) {
                window.location.href = window.location.href + hashParams;
            }
            else {
                window.location.href = window.location.href.substr(0, hashPosition) + hashParams;
            }

            // Update AddThis link
            var atLink = document.getElementById('lightbox_addThisLink');
            if(atLink) {
                atLink.href = atLink.href.replace('{sUrl}', window.location.href).replace('{sTitle}', title);
            }
        },

        loadSafari : function(e, newSwf) {
            $E.stopEvent(e);
            var sz;

            if(e.target.parentNode.getAttribute('size')) {
                sz = e.target.parentNode.getAttribute('size');
            } // moz, safari, etc.
            else {
                var m = e.target.parentNode.className.match(/\bsize_(\d\d\d\d?x\d\d\d\d?)\b/);
                if(m) {
                    sz = m[1];
                }
                else {
                    sz = null;
                }
            }

            if(sz == null || sz == 'undefined') {
                sz = '480x360';
            }
            var dim = sz.split('x');

            var aItemTitle = '';
            var aItemDesc = '';
            var tmpStr = '';

            if(newSwf.getAttribute('title')) {
                tmpStr = newSwf.getAttribute('title');
                aItemTitle = (tmpStr == 'null' || tmpStr == null) ? '' : tmpStr;
            }

            if(newSwf.getAttribute('data-fulldescription')) {
                tmpStr = newSwf.getAttribute('data-fulldescription');
                aItemDesc = (tmpStr == 'null' || tmpStr == null) ? '' : tmpStr;
            }

            var tmpHeight = 0;
            var hasInfo = (aItemTitle + aItemDesc).length > 0;

            if(hasInfo) {
                var htmlStr = '<h4 id="lightbox_itemTitle">' + aItemTitle + '</h4><label>' + aItemDesc + '</label>'

                var tmpEl = document.createElement('span');
                tmpEl.style.position = 'absolute';
                tmpEl.style.left = '-5000px';
                tmpEl.style.width = parseInt(dim[0]) + 20 + 'px';
                document.body.appendChild(tmpEl);
                tmpEl.innerHTML = htmlStr;

                tmpHeight = tmpEl.offsetHeight + 20;    // Give it a 20px bottom pad.

                document.body.removeChild(tmpEl);
            }

            if(newSwf.href.indexOf('.swf') > 0) {
                tmpHeight += 20;

                var pWin = window.open('/static/html/swf_frame.html?file=' + newSwf.href + '&sz=' + sz + '&title=' + newSwf.getAttribute('title'),
                        'nMedia',
                        'resizable=1,width=' + (parseInt(dim[0]) + 20) + ',height=' + (parseInt(dim[1]) + tmpHeight));
                if(hasInfo) {
                    testOpenInterval = setInterval(function() {
                        if(pWin.document && pWin.document.getElementById('aDescription')) {
                            clearInterval(testOpenInterval);
                            var pDoc = pWin.document;
                            pDoc.getElementById('aDescription').innerHTML = htmlStr;
                            pDoc.getElementById('aDescription').className = '';
                        }
                    }, 150);
                }
            }
            else {
                tmpHeight += 55;

                var pWin = window.open('/static/flash/mediabar/video_frame.html?file=' + newSwf.href + '&sz=' + sz,
                        'nMedia',
                        'resizable=1,width=' + parseInt(parseInt(dim[0]) + 50) + ',height=' + parseInt(parseInt(dim[1]) + tmpHeight));
                if(hasInfo) {
                    testOpenInterval = setInterval(function() {
                        if(pWin.document && pWin.document.getElementById('aDescription')) {
                            clearInterval(testOpenInterval);
                            var pDoc = pWin.document;
                            pDoc.getElementById('aDescription').innerHTML = htmlStr;
                            pDoc.getElementById('aDescription').className = '';
                        }
                    }, 150);
                }
            }
        },

        /*
         *  initLoadSafari
         *    Safari-friendly version of initLoadSwf below.
         */
        initLoadSafari : function(el) {
            if(el.getAttribute('size')) {
                sz = el.getAttribute('size');
            } // moz, safari, etc.
            else {
                var m = el.className.match(/\bsize_(\d\d\d\d?x\d\d\d\d?)\b/);
                if(m) {
                    sz = m[1];
                }
                else {
                    sz = null;
                }
            }

            if(sz == null || sz == 'undefined') {
                sz = '480x360';
            }
            var dim = sz.split('x');

            var aItemTitle = '';
            var aItemDesc = '';
            var tmpStr = '';

            if(newSwf.getAttribute('title')) {
                tmpStr = newSwf.getAttribute('title');
                aItemTitle = (tmpStr == 'null' || tmpStr == null) ? '' : tmpStr;
            }

            if(newSwf.getAttribute('data-fulldescription')) {
                tmpStr = newSwf.getAttribute('data-fulldescription');
                aItemDesc = (tmpStr == 'null' || tmpStr == null) ? '' : tmpStr;
            }

            var tmpHeight = 0;
            var hasInfo = (aItemTitle + aItemDesc).length > 0;

            if(hasInfo) {
                var htmlStr = '<h4 id="lightbox_itemTitle">' + aItemTitle + '</h4><label>' + aItemDesc + '</label>'

                var tmpEl = document.createElement('span');
                tmpEl.style.position = 'absolute';
                tmpEl.style.left = '-5000px';
                tmpEl.style.width = parseInt(dim[0]) + 20 + 'px';
                document.body.appendChild(tmpEl);
                tmpEl.innerHTML = htmlStr;

                tmpHeight = tmpEl.offsetHeight;

                document.body.removeChild(tmpEl);
            }

            if(newSwf.href.indexOf('.swf') > 0) {
                tmpHeight += 20;

                var pWin = window.open('/static/html/swf_frame.html?file=' + newSwf.href + '&sz=' + sz + '&title=' + newSwf.getAttribute('title'),
                        'nMedia',
                        'resizable=1,width=' + (parseInt(dim[0]) + 20) + ',height=' + (parseInt(dim[1]) + tmpHeight));
                if(hasInfo) {
                    testOpenInterval = setInterval(function() {
                        if(pWin.document && pWin.document.getElementById('aDescription')) {
                            clearInterval(testOpenInterval);
                            var pDoc = pWin.document;
                            pDoc.getElementById('aDescription').innerHTML = htmlStr;
                            pDoc.getElementById('aDescription').className = '';
                        }
                    }, 150);
                }
            }
            else {
                tmpHeight += 55;

                var pWin = window.open('/static/flash/mediabar/video_frame.html?file=' + newSwf.href + '&sz=' + sz,
                        'nMedia',
                        'resizable=1,width=' + parseInt(parseInt(dim[0]) + 50) + ',height=' + parseInt(parseInt(dim[1]) + tmpHeight));
                if(hasInfo) {
                    testOpenInterval = setInterval(function() {
                        if(pWin.document && pWin.document.getElementById('aDescription')) {
                            clearInterval(testOpenInterval);
                            var pDoc = pWin.document;
                            pDoc.getElementById('aDescription').innerHTML = htmlStr;
                            pDoc.getElementById('aDescription').className = '';
                        }
                    }, 150);
                }
            }
        },

        loadSwf : function(e, newSwf) {
            var sz;
            var itemID = "";

            // Hide the "print" link. Can't print these guys!
            //document.getElementById('lightbox_printLink').style.display = 'none';

            // Grab the filetype
            var fileType = newSwf.href.substr(newSwf.href.lastIndexOf('.') + 1);

            if(e.srcElement) {
                var srcEl = e.srcElement;
                if(srcEl.tagName.toLowerCase() == 'img') {
                    srcEl = srcEl.parentNode;
                }
                if(srcEl.getAttribute('size')) {
                    sz = srcEl.getAttribute('size');
                }
            }
            else {
                if(e.target.parentNode.getAttribute('size')) {
                    sz = e.target.parentNode.getAttribute('size');
                } // moz, safari, etc.
            }

            if(sz == null || sz == 'undefined') {
                sz = '480x360';
            }

            $E.stopEvent(e);

            aPreload = new Image();
            aPreload.width = sz.split('x')[0];
            aPreload.height = sz.split('x')[1];

            if(newSwf) {
                var that = newSwf;
                if(that.id.match(/^(link_|enlarge_|enlargeLink_|play_link_)(.*)/)) {
                    YAHOO.awesomebox.itemID = that.id.match(/^(link_|enlarge_|enlargeLink_|play_link_)(.*)/)[2];
                }
                else if(YAHOO.util.Dom.hasClass(that, 'read_more')) { // Is this a "read more" link?
                    YAHOO.awesomebox.itemID = that.parentNode.id.match(/^(summary_)(.*)/)[2];
                }
                itemID = YAHOO.awesomebox.itemID;
                this.itemID = itemID;
            }
            else {
                var that = this;
                itemID = YAHOO.awesomebox.itemID;
            }

            var aInfoTitle = '';
            var aInfo = '';
            var aItemTitle = '';
            var aItemDesc = '';
            var tmpStr = '';

            // Group title = innerHTML of the em tag inside the currently active tab in the media center tabview
            aInfoTitle = YAHOO.util.Selector.query('ul.yui-nav li.selected a em', 'mc_tabbed_content', true).innerHTML;

            /* Clicking next/previous gives a "newImg" variable that references that particular
             carousel link. This has a set title/description that we'll use.

             Clicking a link directly means that title/description need to be pulled from the
             appropriate HTMLElements.

             Also, Safari likes to convert a null value into the string "null," so we account for that as well.
             */
            if(newSwf.getAttribute('title')) {
                tmpStr = newSwf.getAttribute('title');
                aItemTitle = (tmpStr == 'null' || tmpStr == null) ? '&nbsp;' : tmpStr;
            }

            if(newSwf.getAttribute('data-fulldescription')) {
                tmpStr = newSwf.getAttribute('data-fulldescription');
                aItemDesc = (tmpStr == 'null' || tmpStr == null) ? '&nbsp;' : tmpStr;
            }

            var aInfo = '<h4 id="lightbox_itemTitle">' + aItemTitle + '</h4><label>' + aItemDesc + '</label>';
            if(! (fileType in aClient.noDownloadLink)) {
                aInfo += '<br/><a href="' + that.href + '" class="std">' + nikon.utils.locale.get("Global.Download") + '</a>';
            }

            if($D.hasClass('aBoxMeta', 'aOpen')) {
                setTimeout(function() {
                    $('aInfoTitle').innerHTML = aInfoTitle;
                    $('aInfo').innerHTML = aInfo;
                }, 250);
            } else {
                $('aInfoTitle').innerHTML = aInfoTitle;
                $('aInfo').innerHTML = aInfo;
            }

            var resizeBox = new YAHOO.widget.aEffect(that);
            resizeBox.aResizeBoxEl(aPreload, that);

            var fadeOverlayIn = new YAHOO.widget.aEffect();
            fadeOverlayIn.aShowOverlay();

            $D.setStyle('aNextButton', 'visibility', 'hidden');
            $D.setStyle('aPrevButton', 'visibility', 'hidden');
            $D.setStyle('aCount', 'opacity', '0');

            // Update URL with currently loaded image's information for sharing, preloading, etc.
            var currentTab = YAHOO.awesomebox.itemID.substr(YAHOO.awesomebox.itemID.indexOf('_') + 1);
            YAHOO.awesomebox.setUrl(that.href.substr(that.href.lastIndexOf('/') + 1), currentTab, aInfoTitle);
        },

        /*
         *  initLoadSwf
         *    Loads a media player item (flv movie, mp3, etc.) on the "init" of the page as specified in URL parameter "showAsset."
         */
        initLoadSwf : function(el) {
            var sz;
            // Hide the "print" link. Can't print these guys!
            //document.getElementById('lightbox_printLink').style.display = 'none';

            // Grab the filetype
            var fileType = el.href.substr(el.href.lastIndexOf('.') + 1);

            if(el.getAttribute('size')) {
                sz = el.getAttribute('size');
            }
            else {
                var m = el.className.match(/\bsize_(\d\d\d\d?x\d\d\d\d?)\b/);
                if(m) {
                    sz = m[1];
                }
                else {
                    sz = null;
                }
            }

            if(sz == null || sz == 'undefined') {
                sz = '480x360';
            }

            aPreload = new Image();
            aPreload.width = sz.split('x')[0];
            aPreload.height = sz.split('x')[1];

            var aInfoTitle = '';
            var aInfo = '';
            var aItemTitle = '';
            var aItemDesc = '';
            var tmpStr = '';

            // Group title = innerHTML of the em tag inside the currently active tab in the media center tabview
            aInfoTitle = YAHOO.util.Selector.query('ul.yui-nav li.selected a em', 'mc_tabbed_content', true).innerHTML;

            /* Clicking next/previous gives a "newImg" variable that references that particular
             carousel link. This has a set title/description that we'll use.

             Clicking a link directly means that title/description need to be pulled from the
             appropriate HTMLElements.
             */
            if(el.getAttribute('title')) {
                tmpStr = el.getAttribute('title');
                aItemTitle = (tmpStr == 'null' || tmpStr == null) ? '&nbsp;' : tmpStr;
            }

            if(el.getAttribute('data-fulldescription')) {
                tmpStr = el.getAttribute('data-fulldescription');
                aItemDesc = (tmpStr == 'null' || tmpStr == null) ? '&nbsp;' : tmpStr;
            }

            var aInfo = '<h4 id="lightbox_itemTitle">' + aItemTitle + '</h4><label>' + aItemDesc + '</label>';
            if(! (fileType in aClient.noDownloadLink)) {
                aInfo += '<br/><a href="' + el.href + '" class="std">' + nikon.utils.locale.get("Global.Download") + '</a>';
            }

            if($D.hasClass('aBoxMeta', 'aOpen')) {
                setTimeout(function() {
                    $('aInfoTitle').innerHTML = aInfoTitle;
                    $('aInfo').innerHTML = aInfo;
                }, 250);
            } else {
                $('aInfoTitle').innerHTML = aInfoTitle;
                $('aInfo').innerHTML = aInfo;
            }

            var resizeBox = new YAHOO.widget.aEffect(el);
            resizeBox.aResizeBoxEl(aPreload, el);

            var fadeOverlayIn = new YAHOO.widget.aEffect();
            fadeOverlayIn.aShowOverlay();

            $D.setStyle('aNextButton', 'visibility', 'hidden');
            $D.setStyle('aPrevButton', 'visibility', 'hidden');
            $D.setStyle('aCount', 'opacity', '0');
        },

        /*
         *  loadImg()
         *    Gets information for new image and invokes appropriate actions.
         */
        loadImg : function(e, newImg) {
            var fadeOverlayIn = new YAHOO.widget.aEffect();
            fadeOverlayIn.aShowOverlay();

            // Show the "print" link in case it's been hidden.
            //document.getElementById('lightbox_printLink').style.display = 'block';

            var itemID = "";
            if(newImg) {
                var that = newImg;
                // that, in our case, will be the link clicked on to trigger this event.
                // Its ID will appear in the form of [enlarge|link]_[itemID]
                if(that.id.match(/^(link_|enlarge_|enlargeLink_)(.*)/)) {
                    YAHOO.awesomebox.itemID = that.id.match(/^(link_|enlarge_|enlargeLink_)(.*)/)[2];
                }
                else if(YAHOO.util.Dom.hasClass(that, 'read_more')) { // Is this a "read more" link?
                    YAHOO.awesomebox.itemID = that.parentNode.id.match(/^(summary_)(.*)/)[2];
                }
                itemID = YAHOO.awesomebox.itemID;
                this.itemID = itemID;
            } else {
                var that = this;
                itemID = YAHOO.awesomebox.itemID;
            }
            $E.stopEvent(e);

            aPreload = new Image();
            aPreload.onload = function() {
                clearInterval(window.imageLoad);
                setTimeout(function() {
                    var aInfoTitle = '';
                    var aItemTitle = '';
                    var aItemDesc = '';
                    var tmpStr = '';

                    // Group title = innerHTML of the em tag inside the currently active tab in the media center tabview
                    aInfoTitle = YAHOO.util.Selector.query('ul.yui-nav li.selected a em', 'mc_tabbed_content',
                            true).innerHTML;

                    /* Clicking next/previous gives a "newImg" variable that references that particular
                     carousel link. This has a set title/description that we'll use.

                     Clicking a link directly means that title/description need to be pulled from the
                     appropriate HTMLElements.
                     */
                    if(newImg.getAttribute('title')) {
                        tmpStr = newImg.getAttribute('title');
                        aItemTitle = (tmpStr == 'null' || tmpStr == null) ? '&nbsp;' : tmpStr;
                    }

                    if(newImg.getAttribute('data-fulldescription')) {
                        tmpStr = newImg.getAttribute('data-fulldescription');
                        aItemDesc = (tmpStr == 'null' || tmpStr == null) ? '&nbsp;' : tmpStr;
                    }

                    var aInfo = '<h4 id="lightbox_itemTitle">' + aItemTitle + '</h4><label>' + aItemDesc + '</label>';

                    if($D.hasClass('aBoxMeta', 'aOpen')) {
                        setTimeout(function() {
                            $('aInfoTitle').innerHTML = aInfoTitle;
                            $('aInfo').innerHTML = aInfo;
                            var resizeBox = new YAHOO.widget.aEffect(that);
                            resizeBox.aResizeBox(aPreload);
                        }, 250);
                    } else {
                        $('aInfoTitle').innerHTML = aInfoTitle;
                        $('aInfo').innerHTML = aInfo;
                        var resizeBox = new YAHOO.widget.aEffect(that);
                        resizeBox.aResizeBox(aPreload);
                    }

                    if(!that.getAttribute('rel')) {
                        $D.setStyle('aNextButton', 'visibility', 'hidden');
                        $D.setStyle('aPrevButton', 'visibility', 'hidden');
                        $D.setStyle('aCount', 'opacity', '0');
                    } else {
                        $D.setStyle('aCount', 'opacity', '1');
                        $E.removeListener('aNextButton', 'click');
                        $E.removeListener('aPrevButton', 'click');
                    }

                    if(that.getAttribute('rel')) {
                        YAHOO.awesomebox.loadNeighbors(that);
                    }
                    // What about an enlarge image button click?
                    else if(that.id.indexOf('enlargeLink') > -1) {
                        var linkId = 'link_' + that.id.substr('enlargeLink_'.length);
                        var linkEl = document.getElementById(linkId);
                        if(linkEl.getAttribute('rel')) {
                            // Set counter opacity and reset link events
                            $D.setStyle('aCount', 'opacity', '1');
                            $E.removeListener('aNextButton', 'click');
                            $E.removeListener('aPrevButton', 'click');

                            YAHOO.awesomebox.loadNeighbors(linkEl);
                        }
                    }
                    else if(YAHOO.util.Dom.hasClass(that, 'read_more')) {
                        var linkId = 'link_' + that.parentNode.id.substr('summary_'.length);
                        var linkEl = document.getElementById(linkId);
                        if(linkEl.getAttribute('rel')) {
                            // Set counter opacity and reset link events
                            $D.setStyle('aCount', 'opacity', '1');
                            $E.removeListener('aNextButton', 'click');
                            $E.removeListener('aPrevButton', 'click');

                            YAHOO.awesomebox.loadNeighbors(linkEl);
                        }
                    }

                    // Update URL with currently loaded image's information for sharing, preloading, etc.
                    // as well as tab index, which we shift back to zero-indexed
                    var currentTab = YAHOO.awesomebox.itemID.substr(YAHOO.awesomebox.itemID.indexOf('_') + 1);
                    YAHOO.awesomebox.setUrl(that.href.substr(that.href.lastIndexOf('/') + 1), currentTab, aInfoTitle);
                }, 10);
            };
            aPreload.src = that.getAttribute('href');

            // Set a 20-second timer just in case we have a 404 image. If the image hasn't loaded by then,
            // we'll scrap the whole thing.
            clearInterval(window.imageLoad);
            window.imageLoad = setInterval(function() {
                if(aPreload.src == document.getElementById('aImg').src) {
                    clearInterval(window.imageLoad);
                    return false;
                }
                else {
                    YAHOO.awesomebox.close();
                    aPreload.src = '';
                    alert(nikon.utils.locale.get("Global.MissingItem"));
                }
            }, 20000);
        },

        /*
         *  initLoadImg
         *    Loads an image on the "init" of the page as specified in URL parameter "showAsset."
         */
        initLoadImg : function(el) {
            var fadeOverlayIn = new YAHOO.widget.aEffect();
            var newImg = el;
            fadeOverlayIn.aShowOverlay();

            // Show the "print" link in case it's been hidden.
            //document.getElementById('lightbox_printLink').style.display = 'block';

            aPreload = new Image();
            aPreload.onload = function() {
                clearInterval(window.imageLoad);
                var aInfoTitle = '';
                var aItemTitle = '';
                var aItemDesc = '';
                var tmpStr = '';

                // Instead of fishing these values out of HTML, we can directly access them from
                // our loaded link's properties.
                if(newImg.getAttribute('rel')) {
                    tmpStr = newImg.getAttribute('rel');
                    aInfoTitle = (tmpStr == 'null' || tmpStr == null) ? '&nbsp;' : tmpStr;
                }

                if(newImg.getAttribute('title')) {
                    tmpStr = newImg.getAttribute('title');
                    aItemTitle = (tmpStr == 'null' || tmpStr == null) ? '&nbsp;' : tmpStr;
                }

                if(newImg.getAttribute('data-fulldescription')) {
                    tmpStr = newImg.getAttribute('data-fulldescription');
                    aItemDesc = (tmpStr == 'null' || tmpStr == null) ? '&nbsp;' : tmpStr;
                }

                var aInfo = '<h4 id="lightbox_itemTitle">' + aItemTitle + '</h4><label>' + aItemDesc + '</label>';

                $('aInfoTitle').innerHTML = aInfoTitle;
                $('aInfo').innerHTML = aInfo;

                var resizeBox = new YAHOO.widget.aEffect(el);
                resizeBox.aResizeBox(aPreload);

                if(!el.getAttribute('rel')) {
                    $D.setStyle('aNextButton', 'visibility', 'hidden');
                    $D.setStyle('aPrevButton', 'visibility', 'hidden');
                    $D.setStyle('aCount', 'opacity', '0');
                } else {
                    $D.setStyle('aCount', 'opacity', '1');
                    $E.removeListener('aNextButton', 'click');
                    $E.removeListener('aPrevButton', 'click');
                }

                if(el.getAttribute('rel')) {
                    YAHOO.awesomebox.loadNeighbors(el);
                }
            };
            aPreload.src = el.getAttribute('href');

            // Set a 20-second timer just in case we have a 404 image. If the image hasn't loaded by then,
            // we'll scrap the whole thing.
            clearInterval(window.imageLoad);
            window.imageLoad = setInterval(function() {
                if(aPreload.src == document.getElementById('aImg').src) {
                    clearInterval(window.imageLoad);
                    return false;
                }
                else {
                    YAHOO.awesomebox.close();
                    aPreload.src = '';
                    alert(nikon.utils.locale.get("Global.MissingItem"));
                }
            }, 20000);
        },

        /*
         *  loadNeighbors()
         *    Invoked via load(), finds and preloads next and previous image.
         */
        loadNeighbors : function(that) {
            var imgRefs = aClient.photos;
            var mGroup = aClient.getGroup(that.rel);

            if(mGroup.mediaType != 'mixed' && mGroup.items && mGroup.items.length > 0) {
                var photoSet = mGroup.items;
                var key = aClient.isInGroup(that.rel, that.href);

                setTimeout(function() {
                    $('aCount').innerHTML = 'Image ' + (key + 1) + ' of ' + photoSet.length;
                    $D.setStyle('aCount', 'visibility', 'visible');
                }, 300);

                if(key != photoSet.length - 1) {
                    var next = new Image();
                    next.src = photoSet[key + 1].getAttribute('href');
                    $D.setStyle('aNextButton', 'visibility', 'visible');
                } else {
                    $D.setStyle('aNextButton', 'visibility', 'hidden');
                }
                if(key != 0) {
                    var prev = new Image();
                    prev.src = photoSet[key - 1].getAttribute('href');
                    $D.setStyle('aPrevButton', 'visibility', 'visible');
                } else {
                    $D.setStyle('aPrevButton', 'visibility', 'hidden');
                }
                $E.addListener('aNextButton', 'click', this.loadImg, photoSet[key + 1], true);
                $E.addListener('aPrevButton', 'click', this.loadImg, photoSet[key - 1], true);
            }
            else {
                $D.setStyle('aCount', 'visibility', 'hidden');
                $D.setStyle('aNextButton', 'visibility', 'hidden');
                $D.setStyle('aPrevButton', 'visibility', 'hidden');
            }
        },

        /***
         * Shows el's content in a plain, old overlay.
         * @param {HTMLElement|String} el Element whose content we'd like to overlay.
         */
        showOverlay : function(el) {
            el = YAHOO.util.Dom.get(el);    // Ensure el is an HTMLElement

            var w = el.getAttribute('data-width');
            var h = el.getAttribute('data-height');

            if(!document.getElementById('mb_overlay')) {
                var d = document.createElement('div');
                d.id = "mb_overlay";
                d.className = "liquidPop pop singleCol";
                d.innerHTML = '<div class="hd"><span class="l"> </span> ' +
                              '<div class="m"><a id="mb_overlay_close" class="closeIcon" href="javascript:void(0)"> </a><h3 class="nkYellow">{popupTitle}</h3></div> ' +
                              '<span class="r"> </span></div>' +
                              '<div class="container_bd"><div class="l"><div class="r"><div class="bd">{popupContent}</div></div></div></div>' +
                              '<div class="ft"><span class="l"> </span><div class="m"> </div><span class="r"> </span></div>';

                document.body.insertBefore(d, document.body.firstChild);
            }

            var overlay = document.getElementById('mb_overlay');

            if(YAHOO.util.Dom.getStyle(overlay, 'display') == "block") {
                this._resetOverlay();
            }

            //overlay.style.visibility = "hidden";
            YAHOO.util.Dom.setStyle(overlay, 'opacity', '0');
            YAHOO.util.Dom.setStyle(overlay, 'display', 'block');

            overlay.innerHTML = overlay.innerHTML
                    .replace('{popupTitle}', el.title)
                    .replace('{popupContent}', document.getElementById(el.id + '_content').innerHTML);

            var bd = YAHOO.util.Selector.query('div.container_bd div.bd', overlay, true);

            if(w) {
                bd.style.width = w + "px";
                overlay.style.width = bd.offsetWidth + "px";
            }
            else {
                // Determine if overlayed content has a width > 357px default. If so, increase overlay size.
                if(bd.firstChild.offsetWidth > 357) {
                    bd.style.width = bd.firstChild.offsetWidth + "px";
                    overlay.style.width = bd.offsetWidth + "px";
                }
            }
            if(h) {
                bd.style.height = h + "px";
            }

            YAHOO.util.Dom.setXY(overlay,
                    [($D.getViewportWidth() / 2) - (overlay.offsetWidth / 2), ($D.getViewportHeight() / 2) - (overlay.offsetHeight / 2)]);
            overlay.style.display = "none";
            YAHOO.util.Event.addListener('mb_overlay_close', 'click', this.hideOverlay, this);
            this._animOverlay(overlay);
        },
        /***
         * Animation for showing the overlay.
         * @param {HTMLElement} overlay Overlay HTMLElement.
         */
        _animOverlay : function(overlay) {
            overlay.style.display = "block";

            var anim = new YAHOO.util.Anim(overlay, {
                opacity: { to: 0.99}
            },
                    0.25,
                    YAHOO.util.Easing.easeIn);

            anim.animate();
        },
        /***
         * "Resets" overlay, setting its content back to a "template"-able state and its
         * display to "none."
         */
        _resetOverlay : function() {
            var overlay = document.getElementById('mb_overlay');

            YAHOO.util.Dom.setStyle('mb_overlay', 'display', 'none');
            YAHOO.util.Selector.query('div.hd h3', overlay, true).innerHTML = "{popupTitle}";
            YAHOO.util.Selector.query('div.container_bd div.bd', overlay, true).innerHTML = "{popupContent}";
        },
        /***
         * Hides that plain, old overlay.
         */
        hideOverlay : function(e, obj) {
            var anim = new YAHOO.util.Anim("mb_overlay", {
                opacity: { to: 0}
            },
                    0.25,
                    YAHOO.util.Easing.easeIn);

            anim.onComplete.subscribe(function() {
                // Reset all content.
                obj._resetOverlay();
            });

            anim.animate();
        },
        /*
         *  scaleImage()
         * Returns proportional values for height and width of image, scaled if necessary.
         *
         * Sorry for the magic number 140. It's the sum of the padding/heights of div#aImgHolder and div#aBoxMeta.
         * As the latter may be set to 0 via a script, we can't dynamically pull it, thus the hardcoded value.
         */
        scaleImage : function(aImage) {
            var ttlReg = YAHOO.util.Dom.getRegion('aInfoTitle');
            var ttlOffset = ttlReg.bottom - ttlReg.top + parseInt(YAHOO.util.Dom.getStyle('aInfoTitle', 'marginTop'));
            var sHeight = aImage.height;
            var sWidth = aImage.width;
            if(aImage.width > $D.getViewportWidth()) {
                sWidth = $D.getViewportWidth() - 20;
                sHeight = aImage.height * (sWidth / aImage.width);
                if(sHeight + 140 + ttlOffset > ($D.getViewportHeight() - 20)) {
                    sHeight = $D.getViewportHeight() - 140 - ttlOffset;
                    sWidth = aImage.width * (sHeight / aImage.height);
                }
            } else if(aImage.height + 140 + ttlOffset > $D.getViewportHeight()) {
                sWidth = aImage.width * (($D.getViewportHeight() - 140 - ttlOffset) / aImage.height);
                sHeight = $D.getViewportHeight() - 140 - ttlOffset;
                if(sWidth > ($D.getViewportWidth() - 20)) {
                    sWidth = aImage.width * (sHeight / aImage.height);
                    sHeight = aImage.height * (sWidth / aImage.width);
                }
            }
            return [Math.floor(sWidth), Math.floor(sHeight)];
        },

        /*
         *  close()
         *    Calls YAHOO.widget.aEffect.aClose() and resets the #filename to #close.
         *    Not the most elegant solution.
         */
        close : function() {
            var aClose = new YAHOO.widget.aEffect();
            aClose.aClose();

            // Clear "is asset loaded?" interval
            if(window.imageLoad) {
                clearInterval(window.imageLoad);
            }

            // Remove asset's url
            if(window.location.href.match(/tab=([^&]*)&?/)) {
                var currentTab = window.location.href.match(/tab=([^&]*)&?/)[1];
                window.location.href = window.location.href.substr(0,
                        window.location.href.indexOf('#')) + '#tab=' + currentTab;
            }
        },

        awesome : function() {
            var aAwesome = new YAHOO.widget.aEffect();
            aAwesome.aAwesome();
        },
        printImage : function() {
            var pWin = window.open('/static/html/le_print_frame.html');
            testOpenInterval = setInterval(function() {
                if(pWin.document && pWin.document.getElementById('printImage')) {
                    clearInterval(testOpenInterval);
                    var pDoc = pWin.document;
                    var pImg = pDoc.getElementById('printImage');
                    pImg.onload = function() {
                        pWin.print();
                    }
                    pImg.src = $('aImg').src;
                    pDoc.getElementById('aBox').innerHTML = '<div id="aInfo">' + $('aInfo').innerHTML + '</div>';
                }
            }, 150);
        }
    }
}();

/*
 *  Start up the processes on window load.
 */
/*
 window.onload = function(){
 YAHOO.awesomebox.init();
 };
 */
YAHOO.util.Event.onDOMReady(YAHOO.awesomebox.init, YAHOO.awesomebox, true);

