/**
 * @author Adam McIntyre
 * Builds the Media Bar / Carousel / Lightbox combo on the product 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

 Merged from production - 02 JUL 2010
 */
var aClient = {};
aClient.photos = [];
aClient.allAssets = {};
aClient.groups = {};
aClient.noDisplayaltTerms = {'Enlarge Image' : true};  // Array of alt terms to ignore

/*
 *  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 aTypes = {'jpg':true, 'gif':true, 'png':true, 'bmp':true, 'flv':true, 'mp3':true, 'wav':true}; // types of images to place in Awesome Box

    if(lbItem.href.substr(lbItem.href.lastIndexOf('.') + 1) in aTypes) {
        this.photos.push(lbItem);
        this.addToGroup(lbItem);
        YAHOO.awesomebox.setClickAction(lbItem, YAHOO.awesomebox);
    }
};

/***
 * 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
 */
aClient.addToGroup = function(lbItem) {
    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);
    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;
};

function CarouselWidget(cId, replaceImgId, size, numVisible, scrollInc) {
    var configOpts =
    {
        "numVisible":                numVisible || 2,
        "animationSpeed":            0.35,
        "scrollInc":                 scrollInc || numVisible || 2,
        "navMargin":                 0,
        "revealAmount":              0,
        "firstVisible":              1,
        "size":                      size || 4,
        "prevElement":               cId + "-prev",
        "nextElement":               cId + "-next"
        //"loadNextHandler":           animateNodes,
        //"loadPrevHandler":           animateNodes,
        //"loadInitHandler":           initImages
    };

    var carousel = new YAHOO.extension.Carousel(cId, configOpts);

    var navId = cId + "-navigation";
    var obj = this;

    var mousedOver = false;          // is the mouse currently over the element?

    this.replaceImgId = replaceImgId;

    this.getCarouselEl = function() { return carousel._carouselElemID; };
    this.getNav = function() { return document.getElementById(navId); };
    this.setMousedOver = function() { mousedOver = !mousedOver; };

    this.getCarousel = function() { return carousel; };

    this.scrollable = (size > numVisible) ? true : false;

    var _wireChildActions = function() {
        var anchors = YAHOO.util.Selector.query('ul.carousel-list li a', cId);

        YAHOO.util.Dom.batch(anchors, function(o) {
            // Product views swap the current product image.
            // Are we in a product view? If so, wire that in.
            if(o.getAttribute('rel') &&
               o.getAttribute('rel').toLowerCase().indexOf('product views') != -1) {
                YAHOO.util.Event.addListener(o, 'click', function(e) {
                    YAHOO.util.Event.preventDefault(e);
                    var curEl = this;

                    // Fade in loader, fade out current image
                    fadeSwap('loader', 'swapTarget');

                    setTimeout(function() {
                        obj.swapImages(obj, curEl);
                        obj.swapEnlargeButtons(obj, curEl);
                        obj.setHighlighted(curEl);

                        var im = new Image();
                        im.onload = function() {
                            setTimeout(function() { fadeSwap('swapTarget', 'loader'); }, 10);
                        };
                        im.src = curEl.href;
                    }, 100);

                    // And, while we're at it, fire off the Omniture "prodView" event.
                    OmnitureHelper.setMBProdView();
                });

                // Add the appropriate enlarge image button to lightbox control.
                var enlargeEl = document.getElementById(o.id.substr(o.id.indexOf('_') + 1));
                if(enlargeEl) {
                    var oId = document.getElementById(o.id.substr(o.id.indexOf('_') + 1));
                    aClient.addItem(oId);

                    new $A(oId, {
                        opacity : { to : .99 }
                    },
                            0.15).animate();
                }
            }
            else {
                YAHOO.util.Event.addListener(o, 'click', function(e) {
                    obj.setHighlighted(this);
                });
                aClient.addItem(o);
            }
        });
    };

    var init = function() {
        _wireChildActions();
        obj._configureNav();
    };

    init();


    YAHOO.util.Event.onDOMReady(function() {
        var els = YAHOO.util.Selector.query('div#carousel_ProductViews ul.carousel-list li:first-child');

        if(els.length > 0) {
            YAHOO.util.Dom.addClass(els[0], 'selected');
            YAHOO.util.Dom.addClass(els[0].parentNode, 'selected');

            setTimeout(function() {
                Carousels.highlighted = els[0];
                Carousels.current = els[0].parentNode;
            }, 100);
        }
    });

}

CarouselWidget.prototype.swapImages = function(obj, linkObj) {
    YAHOO.util.Dom.get(obj.replaceImgId).src = linkObj.href;
};

CarouselWidget.prototype.swapEnlargeButtons = function(obj, linkObj) {
    if(Carousels.highlighted) {
        var oldIdStr = 'enlargeImage_' + Carousels.highlighted.id.substr(27);
        YAHOO.util.Dom.addClass(oldIdStr, 'noD');

        var newIdStr = 'enlargeImage_' + linkObj.id.substr(18);
        YAHOO.util.Dom.removeClass(newIdStr, 'noD');
    }
    else {
        YAHOO.util.Dom.addClass('enlargeImage_1', 'noD');

        var newIdStr = 'enlargeImage_' + linkObj.id.substr(18);
        YAHOO.util.Dom.removeClass(newIdStr, 'noD');
    }
}

CarouselWidget.prototype.setHighlighted = function(obj) {
    // Remove selected from current selections
    YAHOO.util.Dom.removeClass(Carousels.highlighted, 'selected');
    YAHOO.util.Dom.removeClass(Carousels.current, 'selected');

    // Add to new selections
    YAHOO.util.Dom.addClass(obj.parentNode, 'selected');
    YAHOO.util.Dom.addClass(this.getCarousel().carouselList, 'selected');

    Carousels.highlighted = obj.parentNode;
    Carousels.current = this.getCarousel().carouselList;

    // Calculate currently clicked image number and update the nav counters
    var id = obj.parentNode.id;
    var num = id.substr(id.indexOf('item-') + 5);
    this._setCurrentNumber(num);
}

CarouselWidget.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';
            }
        }
    }
}

CarouselWidget.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');
};

CarouselWidget.prototype._getNavInfo = function() {
    var rt = {};
    rt.xy = YAHOO.util.Dom.getXY(this.getNav());
    rt.h = this.getNav().offsetHeight;
    return rt;
};

CarouselWidget.prototype._setShowNavEvent = function() {
    //YAHOO.util.Event.addListener(this.getCarouselEl()+"-container",'mouseover',this.handleShowNavigation,this);
    YAHOO.util.Event.addListener(this.getNav(), 'mousemove', this.handleShowNavigation, this);
};

CarouselWidget.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();
};

CarouselWidget.prototype._fadeInNav = function(e, o) {
    var anim = new YAHOO.util.Anim(this.getNav(),
    { opacity : { to : 1 } },
            0.25,
            YAHOO.util.Easing.easeOut
            );

    anim.animate();
};

CarouselWidget.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();
};

CarouselWidget.prototype._setHideNavEvent = function() {
    //YAHOO.util.Event.addListener(this.getCarouselEl()+"-container",'mouseout',this.handleHideNavigation,this);
    YAHOO.util.Event.addListener(this.getNav(), 'mouseout', this.handleHideNavigation, this);
};

CarouselWidget.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();
    }
};

CarouselWidget.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();
};

CarouselWidget.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
 *  ***************************************
 */

// Moved the aClient declaration out to CarouselWidget.js -- A

/*
 *  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() {
        $D.setStyle('aLoadImg', 'display', 'block');
        $D.setXY('aLoadImg', [
            ($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');
            });
            hideMeta.animate();
        }
    });
    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) {
    // 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');
    }

    var metaHeight = 40;    // Standard height for "meta" information at bottom of lightbox.

    if(document.getElementById('container_colors')) {
        ColorVariantManager.setSelectedEl(this.oEl);
        if($D.hasClass(this.oEl, 'enlargeImg')) {
            $D.addClass('aBoxMeta', 'variant');
            metaHeight = 62;
            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 = nikon.utils.locale.get("Global.Labels.selectColor") + ': <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 moveBox = new $M('aBox', {
        width: {to: (imgScale[0] + 20)},
        height: {to: (imgScale[1] + 70)},
        points: {to:
                [
                    ($D.getViewportWidth() / 2) - (imgScale[0] / 2) + aClient.xScroll() - 10,
                    ($D.getViewportHeight() / 2) - (imgScale[1] / 2) + aClient.yScroll() - 60
                ]
        }
    }, 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() {
        $D.setStyle('aBox', 'height', imgScale[1] + 130 + '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');

        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();
            $D.setStyle('aCloseButton', 'visibility', 'visible');
        });
        fadeImg.animate();
    });
    if($D.hasClass('aBoxMeta', 'aOpen')) {
        setTimeout(function() {
            $('aImg').setAttribute('src', aPreload.src);
            setTimeout(function() {
                moveBox.animate();
            }, 10);
        }, 300);
    } else {
        $('aImg').setAttribute('src', aPreload.src);
        setTimeout(function() { moveBox.animate(); }, 10);
    }
};

/*
 *  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) {
    var moveBox = new $M('aBox', {
        width: {to: (aPreload.width + 30)},
        height: {to: (aPreload.height + 85)},
        points: {to: [
            ($D.getViewportWidth() / 2) - (aPreload.width / 2) + aClient.xScroll() - 10,
            ($D.getViewportHeight() / 2) - (aPreload.height / 2) + aClient.yScroll() - 10
        ]
        }
    }, 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', 'width', prWidth + 30 + 'px');
        $D.setStyle('aDiv', 'height', prHeight + 30 + 'px');
        $D.setStyle('aDiv', 'opacity', '1');
        $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: 40}}, 0.2);

        showMeta.onComplete.subscribe(function() {
            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('closeButton',
                        '/static/images/' + nikon.utils.locale.get("Global.locale") + '/buttons/btn_flash_close_on.png');
                fo.addVariable('closeButtonHover',
                        '/static/images/' + nikon.utils.locale.get("Global.locale") + '/buttons/btn_flash_close_off.png');
                fo.addVariable('volLabel',
                        '/static/images/' + nikon.utils.locale.get("Global.locale") + '/icons/icon_flash_sound.png');
                fo.addVariable('close', 'YAHOO.awesomebox.close');
                fo.addVariable('showClose', true);
                fo.write('aDiv');
            }, 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.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.setStyle('aBox', 'display', 'none');
            $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('aDiv', 'width', '0');
            $D.setStyle('aDiv', 'height', '0');
            $D.setStyle('aOverlay', 'display', 'none');
            $D.setStyle('aOverlay', 'height', '0px');
            $D.setStyle('aLoadImg', 'display', 'none');
            $D.setStyle('aCloseButton', 'visibility', 'hidden');
        });
        hideOverlay.onComplete.subscribe(function() {
            $('aDiv').innerHTML = '';
        });
        hideOverlay.animate();
    });
    hideMeta.animate();
    fadeBox.animate();
    $E.removeListener('aNextButton', 'click');
    $E.removeListener('aPrevButton', 'click');
    $E.removeListener(document, 'keypress');
};

/*
 * 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="#next" id="aNextButton"></a>
             <a class="aButton" href="#prev" id="aPrevButton"></a>
             <a class="aButton" href="#close" id="aCloseButton"></a>
             <h1 id="aInfoTitle"></h1>
             <p id="aCount"></p>
             <p id="aInfo"></p>
             </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');
            if(typeof nikonLabel === 'undefined') {
                $(aBox).className = 'en_US';
            }
            else {
                $(aBox).className = nikon.utils.locale.get("Global.cssClass");
            }
            aBody.appendChild(aBox);
            $D.setStyle('aBox', 'opacity', '0');
            $D.setXY('aBox', [($D.getViewportWidth() / 2) - 21, ($D.getViewportHeight() / 2) - 21])
            $D.setStyle('aBox', 'display', 'none');

            var aCloseButton = document.createElement('a');
            $(aCloseButton).setAttribute('id', 'aCloseButton');
            $(aCloseButton).setAttribute('href', 'javascript:void(0);');
            aBox.appendChild(aCloseButton);
            $D.addClass(aCloseButton, 'aButton');

            var aInfoTitle = document.createElement('h5');
            $(aInfoTitle).setAttribute('id', 'aInfoTitle');
            aBox.appendChild(aInfoTitle);

            var aImgHolder = document.createElement('div');
            $(aImgHolder).setAttribute('id', 'aImgHolder');
            aBox.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');

            var aBoxMeta = document.createElement('div');
            $(aBoxMeta).setAttribute('id', 'aBoxMeta');
            aBox.appendChild(aBoxMeta);

            var aNextButton = document.createElement('a');
            $(aNextButton).setAttribute('id', 'aNextButton');
            aBoxMeta.appendChild(aNextButton);
            $(aNextButton).setAttribute('href', '#next');
            $D.addClass(aNextButton, 'aButton');

            var aPrevButton = document.createElement('a');
            $(aPrevButton).setAttribute('id', 'aPrevButton');
            aBoxMeta.appendChild(aPrevButton);
            $(aPrevButton).setAttribute('href', '#prev');
            $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 aInfo = document.createElement('p');
            $(aInfo).setAttribute('id', 'aInfo');
            aBoxMeta.appendChild(aInfo);

            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');

            /*
             *  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 allMBItems = aClient.photos;
                for(var i = 0; i < allMBItems.length; i++) {
                    if(allMBItems[i].href.indexOf(asset) > -1) {
                        if(asset.indexOf('swf') > 0 || asset.indexOf('mp3') > 0 || asset.indexOf('flv') > 0) {
                            if(!isSafari) {
                                this.initLoadSwf(allMBItems[i]);
                            }
                            else {
                                this.initLoadSafari(allMBItems[i]);
                            }
                        }
                        else {    // img
                            this.initLoadImg(allMBItems[i]);
                        }
                    }
                }
                /*

                 var loadImg = window.location.href.split('#')[1];
                 loadImg = loadImg.substr(0,loadImg.indexOf('&'));
                 var loadType = loadImg.split('&boxType=')[1];

                 for(i = 0; i < imgArray.length; i++) {
                 var imgUrl = imgArray[i].getAttribute('href').split('/');
                 if(imgUrl[imgUrl.length-1].split('.')[0] == loadImg) {
                 if(loadType == 'img'){

                 $E.onAvailable(body, this.loadImg, $(imgArray[i]), true);
                 }
                 else{
                 $E.onAvailable(body, this.loadSwf, $(imgArray[i]), true);
                 }
                 }
                 }
                 */
            }


            $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) {
            var fileType = o.href.substr(o.href.lastIndexOf('.') + 1).toLowerCase();

            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);

                    // Fire appropriate Omniture event
                    var ttl = o.title ? o.title.replace(' ', '-') : '';
                    OmnitureHelper.setMediaBarThumbClickEvents(fileType, o.href, ttl);
                });
            }
        },

        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');

            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]) + 55));
        },

        /*
         *  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');

            window.open('/static/flash/mediabar/video_frame.html?file=' + el.href + '&sz=' + sz, 'nMedia',
                    'resizable=1,width=' + parseInt(parseInt(dim[0]) + 50) + ',height=' + parseInt(parseInt(dim[1]) + 55));
        },

        loadSwf : function(e, newSwf) {
            var sz;

            if(e.srcElement) {
                if(e.srcElement.parentNode.getAttribute('size')) {
                    sz = e.srcElement.parentNode.getAttribute('size');
                }
                else {
                    var m = e.srcElement.parentNode.className.match(/\bsize_(\d\d\d\d?x\d\d\d\d?)\b/);
                    if(m) {
                        sz = m[1];
                    }
                    else {
                        sz = null;
                    }
                }
            }
            else {
                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';
            }

            $E.stopEvent(e);
            $E.removeListener(document, 'keypress');

            aPreload = new Image();
            aPreload.width = sz.split('x')[0];
            aPreload.height = sz.split('x')[1];

            if(newSwf) {
                var that = newSwf;
            } else {
                var that = this;
            }

            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');

            var aInfoTitle = '';
            var aInfo = '';

            if(that.getAttribute('title') != null) {
                var aInfoTitle = that.getAttribute('title');
            }

            if($D.hasClass('aBoxMeta', 'aOpen')) {
                setTimeout(function() {
                    $('aInfoTitle').innerHTML = aInfoTitle;
                    $('aInfo').innerHTML = aInfo;
                }, 250);
            } else {
                $('aInfoTitle').innerHTML = aInfoTitle;
                $('aInfo').innerHTML = aInfo;
            }

            $E.addListener(document, 'keypress', function(e) {
                $E.stopEvent(e);
                switch($E.getCharCode(e)) {
                    case (120) : YAHOO.awesomebox.close();
                        break;
                    case (97) : YAHOO.awesomebox.awesome();
                        break;
                }
            });
        },

        /*
         *  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;

            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 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');

            var aInfoTitle = '';
            var aInfo = '';

            if(el.getAttribute('title') != null) {
                var aInfoTitle = el.getAttribute('title');
            }

            if($D.hasClass('aBoxMeta', 'aOpen')) {
                setTimeout(function() {
                    $('aInfoTitle').innerHTML = aInfoTitle;
                    $('aInfo').innerHTML = aInfo;
                }, 250);
            } else {
                $('aInfoTitle').innerHTML = aInfoTitle;
                $('aInfo').innerHTML = aInfo;
            }

            $E.addListener(document, 'keypress', function(e) {
                $E.stopEvent(e);
                switch($E.getCharCode(e)) {
                    case (120) : YAHOO.awesomebox.close();
                        break;
                    case (97) : YAHOO.awesomebox.awesome();
                        break;
                }
            });
        },

        /*
         *  loadImg()
         *    Gets information for new image and invokes appropriate actions.
         */
        loadImg : function(e, newImg) {
            var fadeOverlayIn = new YAHOO.widget.aEffect();
            fadeOverlayIn.aShowOverlay();

            if(newImg) {
                var that = newImg;
            } else {
                var that = this;
            }

            $E.stopEvent(e);
            $E.removeListener(document, 'keypress');

            aPreload = new Image();
            aPreload.onload = function() {
                setTimeout(function() {
                    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');
                    }
                    var aInfoTitle = '';
                    var aInfo = '';

                    if(that.getAttribute('title') != null) {
                        var aInfoTitle = that.getAttribute('title');
                    }
                    if(
                            that.getElementsByTagName('img')[0] &&
                            that.getElementsByTagName('img')[0].getAttribute('title') != null
                            ) {
                        var aInfoTitle = that.getElementsByTagName('img')[0].getAttribute('title');
                    }
                    if(
                            that.getElementsByTagName('img')[0] &&
                            that.getElementsByTagName('img')[0].getAttribute('alt') != null &&
                            !(that.getElementsByTagName('img')[0].getAttribute('alt') in aClient.noDisplayaltTerms)
                            ) {
                        var aInfo = that.getElementsByTagName('img')[0].getAttribute('alt');
                    }

                    if($D.hasClass('aBoxMeta', 'aOpen')) {
                        setTimeout(function() {
                            $('aInfoTitle').innerHTML = aInfoTitle;
                            $('aInfo').innerHTML = aInfo;
                        }, 250);
                    } else {
                        $('aInfoTitle').innerHTML = aInfoTitle;
                        $('aInfo').innerHTML = aInfo;
                    }

                    if(that.getAttribute('rel')) {
                        YAHOO.awesomebox.loadNeighbors(that);
                    }
                    $E.addListener(document, 'keypress', function(e) {
                        $E.stopEvent(e);
                        switch($E.getCharCode(e)) {
                            case (120) : YAHOO.awesomebox.close();
                                break;
                            case (97) : YAHOO.awesomebox.awesome();
                                break;
                        }
                    });
                }, 10);
            };
            aPreload.src = that.getAttribute('href');
        },

        /*
         *  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();
            fadeOverlayIn.aShowOverlay();

            aPreload = new Image();
            aPreload.onload = function() {
                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');
                }
                var aInfoTitle = '';
                var aInfo = '';

                if(el.getAttribute('title') != null) {
                    var aInfoTitle = el.getAttribute('title');
                }
                if(
                        el.getElementsByTagName('img')[0] &&
                        el.getElementsByTagName('img')[0].getAttribute('title') != null
                        ) {
                    var aInfoTitle = el.getElementsByTagName('img')[0].getAttribute('title');
                }
                if(
                        el.getElementsByTagName('img')[0] &&
                        el.getElementsByTagName('img')[0].getAttribute('alt') != null &&
                        !(that.getElementsByTagName('img')[0].getAttribute('alt') in aClient.noDisplayaltTerms)
                        ) {
                    var aInfo = el.getElementsByTagName('img')[0].getAttribute('alt');
                }

                if($D.hasClass('aBoxMeta', 'aOpen')) {
                    setTimeout(function() {
                        $('aInfoTitle').innerHTML = aInfoTitle;
                        $('aInfo').innerHTML = aInfo;
                    }, 250);
                } else {
                    $('aInfoTitle').innerHTML = aInfoTitle;
                    $('aInfo').innerHTML = aInfo;
                }

                if(el.getAttribute('rel')) {
                    YAHOO.awesomebox.loadNeighbors(el);
                }
                $E.addListener(document, 'keypress', function(e) {
                    $E.stopEvent(e);
                    switch($E.getCharCode(e)) {
                        case (120) : YAHOO.awesomebox.close();
                            break;
                        case (97) : YAHOO.awesomebox.awesome();
                            break;
                    }
                });
            };
            aPreload.src = el.getAttribute('href');
        },

        /*
         *  loadNeighbors()
         *    Invoked via load(), finds and preloads next and previous image.
         */
        loadNeighbors : function(that) {
            var imgRefs = aClient.photos;
            var photoSet = aClient.getGroup(that.rel).items;
            var key = aClient.isInGroup(that.rel, that.href);

            setTimeout(function() {
                $('aCount').innerHTML = nikon.utils.locale.get("Global.Image") + ' ' + (key + 1) + ' ' + nikon.utils.locale.get("Global.Labels.of") + ' ' + photoSet.length;
            }, 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);
            $E.addListener(document, 'keypress', function(e) {
                $E.stopEvent(e);
                switch($E.getCharCode(e)) {
                    // 110 = n, 112 = p
                    case (110) :
                        if(key != photoSet.length - 1) {
                            YAHOO.awesomebox.loadImg('', photoSet[key + 1]);
                        }
                        break;
                    case (112) :
                        if(key != 0) {
                            YAHOO.awesomebox.loadImg('', photoSet[key - 1]);
                        }
                        break;
                }
            });
        },

        /***
         * 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)-20, ($D.getViewportHeight()/2)-20])
            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);

            /*
             var ow = overlay.offsetWidth;
             var oh = overlay.offsetHeight;

             overlay.style.width = "20px";
             overlay.style.height = "20px";
             overlay.style.overflow = "hidden";
             overlay.style.visibility = "visible";


             var anim = new $M(overlay, {
             width: { to: ow },
             height: { to: oh },
             opacity: { from: 0, to: 0.99 },
             points: {to:
             [
             ($D.getViewportWidth()/2)-(ow/2)+aClient.xScroll(),
             ($D.getViewportHeight()/2)-(oh/2)+aClient.yScroll()
             ]
             }
             }, 0.3);
             */

            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.
         */
        scaleImage : function(aImage) {
            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 + 100 > ($D.getViewportHeight() - 20)) {
                    sHeight = $D.getViewportHeight() - 120;
                    sWidth = aImage.width * (sHeight / aImage.height);
                }
            } else if(aImage.height + 100 > $D.getViewportHeight()) {
                sWidth = aImage.width * (($D.getViewportHeight() - 120) / aImage.height);
                sHeight = $D.getViewportHeight() - 120;
                if(sWidth > ($D.getViewportWidth() - 20)) {
                    sWidth = aImage.width * (sHeight / aImage.height);
                    sHeight = aImage.height * (sWidth / aImage.width);
                }
            }
            var scaleAtts = new Array(Math.floor(sWidth), Math.floor(sHeight));
            return scaleAtts;
        },

        /*
         *  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();
            /*
             if(window.location.href.indexOf('#') != -1) {
             var url = window.location.href.split('#')[0];
             } else {
             var url = window.location.href;
             }
             */
        },

        awesome : function() {
            var aAwesome = new YAHOO.widget.aEffect();
            aAwesome.aAwesome();
        }
    }
}();

/*
 *  Start up the processes on window load.
 */
window.onload = function() {
    YAHOO.awesomebox.init();

    if(document.getElementById('mediaBar')) {
        var mb_fc = YAHOO.util.Dom.getFirstChild(document.getElementById('mediaBar'));
        var mb_container = YAHOO.util.Dom.getNextSibling(mb_fc);

        YAHOO.util.Dom.setStyle(mb_container, 'visibility', 'visible');
        YAHOO.util.Dom.setStyle(mb_container, 'opacity', '0');

        var anim = new YAHOO.util.Anim(mb_container, {
            opacity : { to : 1.0 }
        },
                0.20,
                YAHOO.util.Easing.easeIn
                );
        var f = function() {
            new YAHOO.util.Anim('loader_mediaBar', {
                opacity : { to : 0 }
            },
                    0.15,
                    YAHOO.util.Easing.easeOut).animate();

            var colorEls = YAHOO.util.Dom.getElementsByClassName('color');
            if(colorEls.length > 0) {
                YAHOO.util.Event.addListener(colorEls, 'click', function() {
                    ColorVariantManager.detailClick(this);
                });
                YAHOO.util.Dom.setStyle('container_colors', 'filter', '');
            }
        }
        anim.onStart.subscribe(f);
        anim.onComplete.subscribe(function() {
            YAHOO.util.Dom.setStyle('loader_mediaBar', 'visibility', 'hidden');
            var el = document.getElementById('loader_mediaBar');
            el.parentNode.removeChild(el);

            if(document.getElementById('container_colors')) {
                YAHOO.util.Dom.setStyle('container_colors', 'display', 'block');
                new YAHOO.util.Anim('container_colors', {
                    opacity : { to : .99 }
                },
                        0.15,
                        YAHOO.util.Easing.easeIn).animate();
            }
        });
        anim.animate();
    }
    else {
        if(document.getElementById('container_colors')) {
            var colorEls = YAHOO.util.Dom.getElementsByClassName('color');
            if(colorEls.length > 0) {
                YAHOO.util.Event.addListener(colorEls, 'click', function() {
                    ColorVariantManager.detailClick(this);
                });
                YAHOO.util.Dom.setStyle('container_colors', 'filter', '');
            }

            YAHOO.util.Dom.setStyle('container_colors', 'display', 'block');
            var anim = new YAHOO.util.Anim('container_colors', {
                opacity : { to : .99 }
            },
                    0.15,
                    YAHOO.util.Easing.easeIn).animate();
        }
    }
};
//YAHOO.util.Event.onDOMReady(YAHOO.awesomebox.init, YAHOO.awesomebox, true);

// Fix a timing error in IE. Possibly due to large images not loading in time causing body not to be "closed?"
//YAHOO.util.Event.onAvailable('body',YAHOO.awesomebox.init, YAHOO.awesomebox, true);

/**
 * Manages "color variant" behavior.
 * @author Adam J. McIntyre
 */

ColorVariantManager = function() {
    var currentEl = selectedEl = originalVariantId = '';
    var variants = templates = [];

    return{
        /***
         * Handles switching between swatches/variants on a flyout i.e. on CDSC category page.
         * @param {HTMLElement} el Element clicked on to initiate action.
         */
        categoryClick : function(el) {
            var els = YAHOO.util.Dom.getElementsByClassName('color', 'div', el.parentNode, function(o) {
                if(o == el) {    // If this is the clicked element, highlight, swap content, etc.
                    YAHOO.util.Dom.addClass(o, 'selected');
                    var dataEl = YAHOO.util.Dom.getLastChild(el);
                    var flyoutId = dataEl.getAttribute('data-parentId');
                    var variantId = dataEl.id.substr(dataEl.id.lastIndexOf('_') + 1);

                    // Show a loading image while the new product loads
                    document.getElementById('item_' + flyoutId + '_img').src = '/static/images/icons/blank.gif';
                    var im = new Image();
                    im.onload = function() {
                        document.getElementById('item_' + flyoutId + '_img').src = im.src;
                    };
                    im.src = dataEl.getAttribute('data-image');

                    document.getElementById('data_price_' + flyoutId).innerHTML = dataEl.getAttribute('data-price');
                    document.getElementById('data_color_' + flyoutId).innerHTML = dataEl.getAttribute('data-label');

                    document.getElementById('data_url_' + flyoutId).href = dataEl.getAttribute('data-href');
                    document.getElementById('data_url_ft_' + flyoutId).href = dataEl.getAttribute('data-href');
                }
                else {
                    YAHOO.util.Dom.removeClass(o, 'selected');
                }
            });
        },

        /***
         * Handles switching between swatches/variants on a product detail page.
         * @param {HTMLElement} el Element clicked on to initiate action.
         */
        detailClick : function(el) {
            YAHOO.util.Dom.removeClass(currentEl, 'selected');
            YAHOO.util.Dom.addClass(el, 'selected');
            currentEl = el;

            var v = this.getVariant(el.id.substr(el.id.lastIndexOf('_') + 1));

            // Begin swapping out images with the new variant

            // Front view. Buffer with a loading image.
            var fo = new YAHOO.util.Anim('swapTarget',
            { opacity : { to : 0 }
            },
                    0.10);

            fo.onStart.subscribe(function() { YAHOO.util.Dom.setStyle('loader', 'opacity', '0.99')});
            fo.animate();

            // Which product view do we display?
            var idx = Carousels.highlighted.id.substr(Carousels.highlighted.id.lastIndexOf('-') + 1);
            idx--;    // Shift this to zero-based array index.

            // Store current view from product views below. Start as view front as a default.
            var currentPv = v.ViewFront;

            // Enlarge image and media bar views.
            var enlargeEls = YAHOO.util.Dom.getElementsByClassName('enlargeImg', 'a', 'hero');
            var mbEls = YAHOO.util.Dom.getElementsByClassName('ProductViews', 'li', 'mediaBar');
            var count = 0;
            var grp = aClient.getGroup('Product Views');

            for(var i in v.productViews) {
                // Enlarge images
                var portStr = '';
                if(document.location.port) {
                    portStr = ':' + document.location.port;
                }
                enlargeEls[count].href = document.location.protocol + '//' + document.location.hostname + portStr + v.productViews[i].large;

                // Update lightbox group with this category
                /* 12/9 - I added hostname + port as it seemed to be needed. Otherwise, it would look for images starting at the root. */
                grp[document.location.protocol + '//' + document.location.hostname + portStr + v.productViews[i].large] = count;
                grp.items[count] = enlargeEls[count];

                // Media bar + thumb
                var mbEl = YAHOO.util.Dom.getFirstChild(mbEls[count]);
                mbEl.href = v.productViews[i].view;
                YAHOO.util.Dom.getFirstChild(mbEl).src = v.productViews[i].thumb;

                // Capture as current view,
                // excluding representativeView/viewfront as this is a special case
                if(count == idx) {
                    currentPv = v.productViews[i].view;
                }
                count++;
            }

            // Display it
            var im = new Image();
            im.onload = function() {
                var tg = document.getElementById('swapTarget');
                tg.src = currentPv;

                var fi = new YAHOO.util.Anim('swapTarget',
                { opacity : { to : 0.99 }
                },
                        0.10);

                fi.onStart.subscribe(function() { YAHOO.util.Dom.setStyle('loader', 'opacity', '0')});
                fi.animate();
            }
            im.src = currentPv;

            // Swap textual elements.
            if(document.getElementById('label_price')) {
                document.getElementById('label_price').innerHTML = v.price;
            }
            document.getElementById('label_productNumber').innerHTML = nikon.utils.locale.get("ProductDetail.Hero.ProductNumber") + ' ' + v.productNumber;

            // Swap appropriate WTB section
            if(v.nikonMall) {
                document.getElementById('buttons_wtb').innerHTML = this.processTemplate('mall', v);
            }
            else if(v.wtbUrl) {
                document.getElementById('buttons_wtb').innerHTML = this.processTemplate('wtb', v);
            }
            else {
                document.getElementById('buttons_wtb').innerHTML = "";
            }
        },

        /***
         * Handles highlighting swatches/variants on a product detail page via mouseover.
         * @param {HTMLElement} el Element clicked on to initiate action.
         */
        detailMouseover : function(el) {
            var v = this.getVariant(el.id.substr(el.id.lastIndexOf('_') + 1));

            document.getElementById('color_label').innerHTML = v.name;
            document.getElementById('lg_swatch').innerHTML = '<img src="' + v.swatchUrl + '" alt="' + v.name + '">';
        },

        /***
         * Handles highlighting swatches/variants on a product detail page via mouseout.
         * @param {HTMLElement} el Element clicked on to initiate action.
         */
        detailMouseout : function(el) {
            var v = this.getVariant(el.id.substr(el.id.lastIndexOf('_') + 1));

            document.getElementById('color_label').innerHTML = "";
            document.getElementById('lg_swatch').innerHTML = "";
        },

        /***
         * Handles "color" clicks from the variant block in the lightbox.
         * @param {String} variantId ID of variant that was clicked on.
         */
        lightboxClick : function(variantId) {
            var v = this.getVariant(variantId);

            this.swapEnlargeImg(v);

            // Set 'selected' state
            var els = YAHOO.util.Dom.getElementsByClassName('color', 'div', 'container_lbVariants');
            for(var i = 0; i < els.length; i++) {
                if(els[i].id.indexOf(variantId) > -1) {
                    YAHOO.util.Dom.addClass(els[i], 'selected');
                }
                else {
                    YAHOO.util.Dom.removeClass(els[i], 'selected');
                }
            }

            // Swap current displayed image
            document.getElementById('aImg').src = selectedEl.href;

            // Set text labels
            document.getElementById('label_colorName').innerHTML = v.name;
            document.getElementById('variant_label').innerHTML = v.name + '&nbsp;';
        },

        /***
         * Swaps 'enlarge image' views, especially used when using variants in the product views lightbox
         * @param {String|Variant} variant Variant or ID of variant that was clicked on.
         */
        swapEnlargeImg : function(variant) {
            if(typeof variant != 'object') {
                variant = this.getVariant(variant);
            }

            var enlargeEls = YAHOO.util.Dom.getElementsByClassName('enlargeImg', 'a', 'hero');
            var count = 0;
            var grp = aClient.getGroup('Product Views');

            for(var i in variant.productViews) {
                // Enlarge
                var portStr = '';
                if(document.location.port) {
                    portStr = ':' + document.location.port;
                }
                enlargeEls[count].href = document.location.protocol + '//' + document.location.hostname + portStr + variant.productViews[i].large;

                // Update lightbox group with this category
                /* 12/9: Tie this to an absolute URL as well. */
                grp[document.location.protocol + '//' + document.location.hostname + portStr + variant.productViews[i].large] = count;
                grp.items[count] = enlargeEls[count];

                count++;
            }
        },

        /***
         * Resets enlarge images to original state.
         */
        resetEnlargeImg : function() {
            this.swapEnlargeImg(originalVariantId);
        },

        /***
         * Sets original color's ID to id.
         * @param {String} id
         */
        setOriginalColor : function(id) {
            originalVariantId = id;
        },

        /***
         * Sets the 'selected' element from a lightbox view so we can retrieve it later.
         * Lives as this.oEl in YAHOO.widget.aEffect.prototype.aResizeBox function.
         * @param {HTMLElement} el Element we've selected.
         */
        setSelectedEl : function(el) {
            selectedEl = el;
        },

        /***
         * Adds a variant to variants array for tracking and management.
         * @param {String} id ID of variant to add.
         * @param {Object} o Variant Object to add.
         */
        addVariant : function(id, o) {
            variants[id] = o;
            return this;
        },

        /***
         * Retrieves a variant Object of given id.
         * @param {String} id ID of variant to return.
         * @return {Object}
         */
        getVariant : function(id) {
            return variants[id] || null;
        },

        /***
         * Returns all variants
         */
        getAllVariants : function() {
            return variants;
        },

        /***
         * Sets the currently selected el to that given by ID
         * @param {String} id ID of HTMLElement
         */
        setCurrentEl : function(id) {
            currentEl = id;
        },

        /***
         * Adds an HTML template for use.
         * @param {String} id Template's ID
         * @param {String} html String version of template's HTML.
         */
        addTemplate : function(id, html) {
            templates[id] = html;
        },

        /***
         * Retrieves template with given ID.
         * @param {String} id ID of template we're interested in.
         */
        getTemplate : function(id) {
            return templates[id];
        },

        /***
         * Runs a given template against a variant, returning the resultant HTML.
         * @param {String} tId ID of template to use
         * @param {Object} variant Variant to use for substitution.
         */
        processTemplate : function(tId, variant) {
            var html = this.getTemplate(tId);

            for(var i in variant) {
                html = html.replace('[' + i + ']', variant[i]).replace('&amp;', '&');
            }
            return html;
        }
    }
}();

