/**
 * @author Adam McIntyre
 * @author adam.mcintyre@molecular.com
 *
 * Misc. Nikon Utilities
 * NOTE: If you're minifying this, make sure to catch all the conditional compilation.
 */

/****
 * Singleton for adding flyout rollovers to little icon images.
 */
IconRollovers = function() {
    return{
        addIconRollovers : function(container) {
            var icons = YAHOO.util.Dom.getElementsByClassName('iconRollover', 'img', container);
            var obj = this;
            for(i = 0; i < icons.length; i++) {
                var el = icons[i];

                YAHOO.util.Event.addListener(el, 'mouseover', obj.showOverlay);
                YAHOO.util.Event.addListener(el, 'mouseout', obj.hideOverlay);
            }
        },
        showOverlay : function() {
            var el = this;
            var xy = YAHOO.util.Dom.getXY(el);
            var ov = document.getElementById('overlay_iconRollover');
            if(ov == null) {
                // Create page's glossary overlay
                ov = document.createElement('div');
                ov.id = 'overlay_iconRollover';
                ov.className = 'pop_glossary';

                var tmpHtml = '<div class="hd"><div class="rnd le_bg"></div><h3 class="nkYellow">&nbsp;</h3></div>';
                tmpHtml += '<div class="bd"><div class="definition">&nbsp;</div></div>';
                tmpHtml += '<div class="ft le_bg">&nbsp;</div><div class="corner le_bg tl">&nbsp;</div>';

                ov.innerHTML = tmpHtml;
                document.body.appendChild(ov)
            }

            YAHOO.util.Selector.query('h3', ov, true).innerHTML = el.alt;
            YAHOO.util.Selector.query('div.definition', ov, true).innerHTML = el.title;

            // Do we need to shift the overlay to any particular side of the screen?
            var shiftLeft = (xy[0] + ov.offsetWidth) > YAHOO.util.Dom.getViewportWidth(); // Shift right or left?
            var shiftTop = (xy[1] + ov.offsetHeight) > YAHOO.util.Dom.getViewportHeight(); // Shift up or down?

            var cEl = YAHOO.util.Selector.query('div.corner', ov, true);

            if(shiftLeft && shiftTop) {
                cEl.className = "corner le_bg br";

                var newX = xy[0] - ov.offsetWidth - el.offsetWidth + cEl.offsetWidth;
                var newY = xy[1] - ov.offsetHeight - el.offsetHeight + (cEl.offsetWidth / 2);
                YAHOO.util.Dom.setXY(ov, [newX, newY]);
            }
            else if(! shiftLeft && shiftTop) {
                cEl.className = "corner le_bg bl";

                var newX = xy[0] + el.offsetWidth + cEl.offsetWidth;
                var newY = xy[1] - ov.offsetHeight - el.offsetHeight + (cEl.offsetWidth / 2);
                YAHOO.util.Dom.setXY(ov, [newX, newY]);
            }
            else if(shiftLeft && ! shiftTop) {
                cEl.className = "corner le_bg tr";

                var newX = xy[0] - ov.offsetWidth - el.offsetWidth + cEl.offsetWidth;
                var newY = xy[1] + el.offsetHeight + (cEl.offsetWidth / 2);
                YAHOO.util.Dom.setXY(ov, [newX, newY]);
            }
            else {
                cEl.className = "corner le_bg tl";

                var newX = xy[0] + el.offsetWidth + cEl.offsetWidth;
                var newY = xy[1] + el.offsetHeight + (cEl.offsetWidth / 2);
                YAHOO.util.Dom.setXY(ov, [newX, newY]);
            }
        },
        hideOverlay : function(e, el) {
            var ov = document.getElementById('overlay_iconRollover');
            ov.style.left = "-5000px";
        }
    }
}();

/****
 * addRollover -- Adds a rollover to an image/object
 * @param {Object} anId ID of object to add rollover to
 * @see swapImages
 */
function addRollover(anId) {
    /*@cc_on
     document.getElementById(anId).attachEvent('onmouseover',swapImages);
     document.getElementById(anId).attachEvent('onmouseout',swapImages);
     return true;
     @*/
    document.getElementById(anId).addEventListener('mouseover', swapImages, false);
    document.getElementById(anId).addEventListener('mouseout', swapImages, false);
}

/***
 * Swaps two images for a rollover effect. Expects image names in the form of name.gif and name_on.gif
 * @param {Object} e Event that triggers this function call
 */
function swapImages(e) {
    if(!e) {
        e = window.event;
    }
    if(e.target) {
        var o = e.target;
    }
    else {
        var o = e.srcElement;
    }

    // Safari check
    if(o.nodeType == 3) {
        o = o.parentNode;
    }

    if(!o.src) {
        return false;
    }    // Just in case we hit an a tag, etc.
    if(o.src.indexOf('_on') < 0) {
        o.src = (o.src.substr(0, o.src.length - 4) + '_on' + o.src.substr(o.src.length - 4));
    }
    else {
        o.src = o.src.substr(0, o.src.length - 7) + o.src.substr(o.src.length - 4);
    }

}

/***
 * Swaps two images for a rollover effect. Expects image names in the form of name.gif and name_on.gif.
 * Added via an inline event (onmouseover and onmouseout).
 * @param {Object} o Object triggering Event
 */
function inline_swapImages(o) {
    if(!o.src) {
        return false;
    }    // Just in case we hit an a tag, etc.
    if(o.src.indexOf('_on') < 0) {
        o.src = (o.src.substr(0, o.src.length - 4) + '_on' + o.src.substr(o.src.length - 4));
    }
    else {
        o.src = o.src.substr(0, o.src.length - 7) + o.src.substr(o.src.length - 4);
    }

}


/***
 *  Builds an even/odd style tabular setting by applying "even" and "odd" classNames to a series of rows
 *  of a given className, rowName. Note that due to array indexing, index 0 = row 1.
 *  Require's YUI's YAHOO and Dom utilities.

 *  @param {String} rowName The className shared by all items we want to apply this treatment to.
 */
function evenOddRowClass(rowName) {
    var els = YAHOO.util.Dom.getElementsByClassName(rowName);
    for(var i = 0; i < els.length; i++) {
        if(i % 2 == 0) {
            YAHOO.util.Dom.addClass(els[i], 'odd');
        }
        else {
            YAHOO.util.Dom.addClass(els[i], 'even');
        }
    }
}

/***
 * Formats a series of modules to a grid, a la Template G.
 *
 * @param {Number} totalModules The total number of modules in our grid.
 */
function formatGrid() {
    var els = YAHOO.util.Dom.getElementsByClassName('lens');
    for(var i = 1; i <= els.length; i += 2) {
        var leftEl = document.getElementById('body_' + i);
        var rightEl = document.getElementById('body_' + (i + 1));

        if(rightEl) {
            var leftHt = leftEl.offsetHeight;
            var rightHt = rightEl.offsetHeight;

            if(leftHt > rightHt) {
                leftEl.style.height = leftHt + 'px';
                rightEl.style.height = leftHt + 'px';
            }
            else {
                leftEl.style.height = rightHt + 'px';
                rightEl.style.height = rightHt + 'px';
            }
        }
    }
}

/***
 * Prepares a page / document for printing, ensuring that any product detail tabs are displayed
 */
function preparePrint() {
    if(typeof YAHOO === 'object') {
        var contentBlocks = YAHOO.util.Dom.getElementsByClassName('tabContent', 'div', 'tabContentBlock')
        for(var i = 0; i < contentBlocks.length; i++) {
            if(!(contentBlocks[i].style.display == 'block')) {
                contentBlocks[i].className = "noD";
                contentBlocks[i].style.display = "block";
            }
        }
    }

    var pWin = window.open('/static/html/print_frame.html');
    testOpenInterval = setInterval(function() {
        if(pWin.document) {
            clearInterval(testOpenInterval);
            setTimeout(function() {
                pWin.document.getElementById('body_content').innerHTML = document.body.innerHTML.replace(/<script\b[^>]*>([\s\S])*?<\/script>/ig,
                        function() { return arguments[1]}).replace(/on(load|mouseover|click|mouseout)="(.*?)"/ig, '');
                pWin.print();
            }, 200);
        }
    }, 150);
}

/***
 * Opens a print-this-page version of a product detail page.
 */
function productPrint() {
    var l = location.href.replace(location.hash, '');
    if(l.indexOf('?') == -1) {
        l = l + '?';
    } else {
        l = l + '&';
    }

    l = l + 'mode=print';

    var pwin = window.open(l);
}

/***
 * Opens a print-this-page version of an article detail page.
 * Ostensibly, this is the same as productPrint above, but I'm separating them out as I'd imagine this will likely change.
 */
function prepareLePrint() {
    if(window.location.href.indexOf('#') > -1) {
        var urlParts = window.location.href.split('#');

        if(urlParts[1].indexOf('?') > 0) {  // Make sure params are set before the hash. This shouldn't be the case.
            var params = urlParts[1].split('?');
            window.open(urlParts[0] + '?' + params[1] + '&mode=print' + '#' + params[0]);
        }
        else if(urlParts[0].indexOf('?') > 0) {
            window.open(urlParts[0] += '&mode=print' + '#' + urlParts[1]);
        }
        else {
            window.open(urlParts[0] += '?mode=print' + '#' + urlParts[1]);
        }
    }
    else if(window.location.href.indexOf('?') > 0) {
        window.open(window.location.href + '&mode=print');
    }
    else {
        window.open(window.location.href + '?mode=print');
    }
}

/***
 * Horizontally center a container based on its firstChild's width.
 * Assumes firstChild has an ID in the form of "firstChild_PARENTID"
 */
function horizCenter(cn) {
    var nd = document.getElementById(cn);
    var fc = document.getElementById('firstChild_' + cn);

    nd.style.width = fc.offsetWidth + 'px';
}

/***
 * Clears a text input of default text
 * @param {Object} el Input we're working with
 * @param {String} txt Default text to compare against
 */
function clearInput(el, txt) {
    if(el.value == txt) {
        el.value = '';
        el.style.color = '#000';
    }

}

/***
 * Fades in inEl while fading out outEl. Requires YUI utilities on page.
 * @param {HTMLElement|String} inEl Element to fade in
 * @param {HTMLElement|String} outEl Element to fade out
 */
function fadeSwap(inEl, outEl) {
    if(typeof inEl == 'string') {
        inEl = document.getElementById(inEl);
    }
    if(typeof outEl == 'string') {
        outEl = document.getElementById(outEl);
    }

    var anim = new YAHOO.util.Anim(inEl, {
        opacity : { to : 1 }
    },
            0.25,
            YAHOO.util.Easing.easeIn);

    var f = function() {
        new YAHOO.util.Anim(outEl, {
            opacity : { to : 0 }
        },
                0.25,
                YAHOO.util.Easing.easeOut).animate();
    }
    anim.onStart.subscribe(f);
    anim.animate();
}

/***
 * Formats a series of titles with the className "wrap", adding a <br/> at the appropriately matched
 * place if the string is longer than charNumber characters.
 *
 * Requires YUI's Yahoo and DOM modules.
 *
 * @param {String} regExStr The regex we will use to find the match
 * @param {Number} charNumber The minimum number of characters each title must have before rule is applied
 */
function formatWrap(regExStr, charNumber) {
    var els = YAHOO.util.Dom.getElementsByClassName('wrap');
    var reg = eval(regExStr);

    for(var i = 0; i < els.length; i++) {
        var h = els[i].innerHTML;
        if(h.length > charNumber) {
            var m = reg.exec(h);
            if(m) {
                var mStr = m[0];
                var idx = h.indexOf(mStr);
                els[i].innerHTML = h.substr(0, idx + mStr.length) + '<br/>' + h.substr(idx + mStr.length);
            }
        }
    }
}

/***
 * Loads a specific product detail page tab, based on a URL parameter called "tab".
 */
function loadProductTab() {
    var m = document.location.href.match(/tab=([^&]*)&?/);
    if(m) {
        var param = m[1];
        var tabs = tabView.get('tabs');

        for(var i = 0; i < tabs.length; i++) {
            if(param.replace("%20", " ").toLowerCase() == tabs[i].get('href').substr(1).toLowerCase()) {
                tabView.set('activeIndex', i);
            }
        }
    }
}

/***
 * Handles a Learn-And-Explore, Component 39 sort
 * @param {HTMLElement} el Select Element whose onchange Event triggered this call.
 */
function handeSort(el) {
    var val = el.options[el.selectedIndex].value;
    var sUrl = window.location.href;
    sUrl = sUrl.indexOf('?') > 0 ? sUrl : sUrl + '?';

    // Is there already a sort? If so, replace it, otherwise forge ahead...
    if(sUrl.indexOf('sort=') > 0) {
        window.location.href = sUrl.replace(/sort=([^&]*)/, function($0, $1) { return 'sort=' + val });
    }
    else {
        window.location.href = sUrl + "&sort=" + val;
    }
}

/**
 * Function to create level promo boxes when  bottom links wrap
 */
function nikonMultilingual_init() {
    //promo leveling
    levelContent('top_l', 'div');
    levelContent('promo_links', 'div', 'bottom');
    // We'll hijack promo_summary levelling to add in a few Omniture events... +ajm
    levelContent('promo_summary', 'div', null, function(el) {
        var pNode = YAHOO.util.Dom.getAncestorByClassName(el, 'product_view');
        if(pNode && pNode.getAttribute('data-pid') && pNode.getAttribute('data-pName')) {
            OmnitureHelper.setProdViewEvent([pNode.getAttribute('data-pid'),pNode.getAttribute('data-pName').replace(/'/ig,
                    '&#39;').replace(/"/ig, '&quot;')]);
        }
    });

    //template D and H
    levelContent('abstract', 'div');
    levelContent('listItem_inner', 'div');
}
YAHOO.util.Event.onDOMReady(nikonMultilingual_init);

/***
 * Occasionally, Interwoven gives an extra right margin to elements, which causes them to wrap in IE6. This fixes that
 * problem. See article detail pages for implementation (component 40).
 *
 */
function fixIEwrap(el) {
    if(typeof YAHOO != 'undefined' && YAHOO.env.ua.ie > 0 && YAHOO.env.ua.ie < 7) {
        el = YAHOO.util.Dom.get(el);
        var maxWidth = parseInt(YAHOO.util.Dom.getStyle(el, 'width'), 10)

        var pNode = el.parentNode.parentNode;
        YAHOO.util.Dom.setStyle(pNode, 'marginRight', '0');

        var pWidth = parseInt(YAHOO.util.Dom.getStyle(pNode, 'width'), 10);
        if(maxWidth > pWidth) {
            YAHOO.util.Dom.setStyle(pNode, 'width', maxWidth);
        }
        else {
            maxWidth = pWidth;
        }

        pNode = pNode.parentNode;
        YAHOO.util.Dom.setStyle(pNode, 'marginRight', '0');

        if(maxWidth > parseInt(YAHOO.util.Dom.getStyle(pNode, 'width'), 10)) {
            YAHOO.util.Dom.setStyle(pNode, 'width', maxWidth);
        }
        else {
            maxWidth = parseInt(YAHOO.util.Dom.getStyle(pNode, 'width'), 10);
        }

        if(parseInt(YAHOO.util.Dom.getStyle(pNode, 'width'), 10) > 950) {
            YAHOO.util.Dom.setStyle(pNode, 'width', '996px');
        }
        else {
            // Could be an extra div or two in here...
            var pNode = pNode.parentNode;

            YAHOO.util.Dom.setStyle(pNode, 'marginRight', '0');
            var pWidth = parseInt(YAHOO.util.Dom.getStyle(pNode, 'width'), 10);
            if(maxWidth > pWidth) {
                YAHOO.util.Dom.setStyle(pNode, 'width', maxWidth);
            }
            else if(pWidth > 950) {
                YAHOO.util.Dom.setStyle(pNode, 'width', '996px');
            }

            if(YAHOO.util.Dom.getStyle(pNode.parentNode, 'width').toLowerCase() != 'auto' &&
               parseInt(YAHOO.util.Dom.getStyle(pNode.parentNode, 'width'), 10) > 950) {
                YAHOO.util.Dom.setStyle(pNode.parentNode, 'width', '996px');
            }
            pNode = pNode.parentNode;

            while(pNode.parentNode.tagName.toLowerCase() != 'body') {
                YAHOO.util.Dom.setStyle(pNode, 'marginRight', '0');
                if(maxWidth > parseInt(YAHOO.util.Dom.getStyle(pNode, 'width'), 10)) {
                    YAHOO.util.Dom.setStyle(pNode, 'width', maxWidth);
                }

                if(parseInt(YAHOO.util.Dom.getStyle(pNode.parentNode, 'width'), 10) > 950) {
                    YAHOO.util.Dom.setStyle(pNode.parentNode, 'width', '996px');
                }
                pNode = pNode.parentNode;
            }
        }
        if(el.parentNode.style.display == 'none') {
            el.parentNode.style.display = 'block';
        }
    }
}

/***
 * Evens out the tab heights on an L&E component 38 so that content sections are as tall as the tabs next to them.
 *
 */
function fixTabHeights(e, o) {
    if(! e.prevValue) {
        var bd = YAHOO.util.Selector.query('div.bd', o.get('contentEl'), true);
        var tabHeight = YAHOO.util.Selector.query('ul.yui-nav', 'related_tabbed_content', true).offsetHeight;

        if(bd.offsetHeight < tabHeight) {
            var topPadding = parseInt(YAHOO.util.Dom.getStyle(bd, 'paddingTop'), 10);
            var btmPadding = parseInt(YAHOO.util.Dom.getStyle(bd, 'paddingBottom'), 10);

            YAHOO.util.Dom.setStyle(bd, 'height', (tabHeight - topPadding - btmPadding) + 'px');
            if(o.get('contentEl').parentNode.offsetHeight <= tabHeight) {
                YAHOO.util.Dom.setStyle(o.get('contentEl').parentNode, 'height',
                        o.get('contentEl').offsetHeight + 'px');
            }
        }
    }
}

/***
 * Closes up the gap created when Interwoven enforces a min-height on an element that's not being shown.
 * @param {String} (Optional) elId ID of Element we'd like to close up
 */
function closeNoContentGap(elId) {
    if(! elId) {
        elId = 'contentBuffer__'
    }
    var el = document.getElementById(elId);
    var pEl = el.parentNode;

    if(pEl && pEl.style.height != '') {
        pEl.style.height = '0px';
    }
    if(pEl && pEl.style.minHeight != '') {
        pEl.style.minHeight = '0px';
    }
}

/***
 * Sets the height of an L&E article to 25 pixels greater than the height of the media center, if it
 * is shorter. It also checks for three-line titles and adds appropriate padding.
 */
function fixArticleHeight() {
    var aEl = document.getElementById('container_article');
    var mEl = document.getElementById('media_center');

    if(mEl) {
        if(aEl.offsetHeight <= (mEl.offsetHeight + mEl.offsetTop)) {
            YAHOO.util.Event.onDOMReady(function() {
                setTimeout(function() {aEl.style.height = mEl.offsetHeight + mEl.offsetTop + 40 + 'px'}, 100);
            });
        }
    }
    if(typeof YAHOO !== 'undefined') {
        if(YAHOO.util.Dom.hasClass('article_header', 'hd_light')) {
            var hdEl = document.getElementById('article_header');
            var el = YAHOO.util.Selector.query('h1', hdEl, true);
            // If there are more than two lines of text (the height is twice the line-height...)
            var hdHeight = parseInt(YAHOO.util.Dom.getStyle(el, 'height'), 10);
            if(isNaN(hdHeight)) {
                hdHeight = el.offsetHeight;
            }
            var lnHeight = parseInt(YAHOO.util.Dom.getStyle(el, 'lineHeight'), 10);
            if(hdHeight >= (4 * lnHeight)) {
                YAHOO.util.Dom.addClass(hdEl, 'hd_doublePad');
            }
            else if(hdHeight >= (3 * lnHeight)) {
                YAHOO.util.Dom.addClass(hdEl, 'hd_pad');
            }
        }
    }
}

/**
 * @author Ryan Mulloy
 * @author ryan.mulloy@molecular.com
 */
var countrytimeoutHolder = null;

function showCountries() {
    YAHOO.util.Dom.setStyle("countrySelector", 'display', "block");
    return false;
}

function hoverCountries() {
    clearTimeout(countrytimeoutHolder);
}

function hideCountries() {
    countrytimeoutHolder = setTimeout(function() {
        YAHOO.util.Dom.setStyle("countrySelector", 'display', "none")
    },
            500);
}

/***
 * "Levels" content of a given className and Element type, setting all matched Elements to the height of the
 * tallest matched Element.
 *
 * @param {String} className CSS class we're looking to match on.
 * @param {String} elemType Type of Elements we're looking to match.
 * @param {String} align (Optional) Optional alignment to specify. If "bottom," Elements will be padded from the top to align content at the bottom of height.
 * @param {Function} cb (Optional) Optional callback function to run once an Element has been levelled.
 */
function levelContent(className, elemType, align, cb) {
    var els = YAHOO.util.Dom.getElementsByClassName(className, elemType);
    var highestHeight = 0;
    var heightsArray = [];
    if(els.length > 1) {//make sure there is actually more than one element to level

        //first we need a baseline to find the highest height
        for(var i = 0; i < els.length; i++) {
            var thisHeight = els[i].offsetHeight;
            //add thisHeight to height collection
            heightsArray[i] = thisHeight;

            if(thisHeight > highestHeight) {
                highestHeight = thisHeight;
            }
        }
        //now we need to reloop and adjust each div
        for(var i = 0; i < els.length; i++) {
            //compare the height of this div and the highest div, and then add the delta to the height.

            if(align == 'middle') {
                var delta = highestHeight - heightsArray[i];
                var halfDelta = Math.round(delta / 2);
                YAHOO.util.Dom.setStyle(els[i], 'padding-top', halfDelta + "px");
                if(delta % 2) {
                    YAHOO.util.Dom.setStyle(els[i], 'padding-bottom', halfDelta + "px");
                } else {
                    YAHOO.util.Dom.setStyle(els[i], 'padding-bottom', (halfDelta + 1) + "px");
                }
            } else if(align == 'bottom') {
                //var delta = highestHeight - heightsArray[i];
                //YAHOO.util.Dom.setStyle(els[i], 'padding-top', delta + "px");
                YAHOO.util.Dom.setStyle(els[i], 'height', highestHeight + "px");
            } else {
                YAHOO.util.Dom.setStyle(els[i], 'height', highestHeight + "px");
            }

            if(cb) {
                cb(els[i]);
            }
        }
    }
}

// Target DD_belatedPNG fix at IE6 only. Borrowed this Object detection snippet from Paul Irish.
if(YAHOO.env.ua.ie > 0 && YAHOO.env.ua.ie < 7) {
    YAHOO.util.Event.addListener(window, 'load', function() {
        if(typeof DD_belatedPNG !== 'undefined') {
            DD_belatedPNG.fix('h1.shifted, h2.shifted, h3.shifted, h4.shifted, div#hero img, div#list.product div.bd div.container img.product, div.promo_bw div.mid_c img.promoImg, table tr td img.png, img.camera, li.pv-item img.product');
        }
    });
}

function resetForms() {} // No-op; Google Mini likes to call this undefined function.

