(function($) {
    $.fn.outerHTML = function() {
        var cloned = $(this).clone();
        cloned.wrap('<div></div>')

        var html = cloned.parent().html();
        cloned.remove();
        return html;
    }
})(jQuery);

function initializeTooltips() {
    var index = 1;
    var tooltipTemplate = $('#hiddenContainer .tooltip');
    var toolTipsContainer = $('#tooltips');

    $('a.tip_trigger, a.ms-rteCustom-tooltip_trigger').each(function(i, a) {

        var a = $(a).removeClass('tip_trigger').removeClass('ms-rteCustom-tooltip_trigger').addClass('tip');

        var tooltipId = 'tip' + index;
        index++;

        var tooltip = tooltipTemplate.clone();
        tooltip.addClass(tooltipId);
        tooltip.find('.tip-content .p').append(a.attr('title'));

        a.attr('title', '');
        a.attr('id', tooltipId);
        a.click(function() { return false; });
        
        toolTipsContainer.append(tooltip);
    });
}

function toggleAccordian(trigger) {
    $(trigger).siblings('div.QandA').slideToggle();
    $(trigger).toggleClass('open')
}

$(document).ready(function() {
    //init meganav
    window.mccain.MegaNav.init('.nav-wrapper');

    //Generate tooltips html
    initializeTooltips();
    //init any tooltips on the page
    mccain.utils.ToolTip.init();

    // Setup sites list
    $('.footer-dropdown select').change(function() {
        window.location = $(this).val();
    });

    // Setup global search box    
    var searchGlobal = function() {
    var searchURL = "/Pages/SearchResults.aspx?k=" + $(':input[id$="globalSearchInput"]').val();

        if (window.location.href.toLowerCase().indexOf("/fr-ca/") != -1) {
            searchURL = "/fr-ca" + searchURL;
        } else {
            searchURL = "/en-ca" + searchURL;
        }

        window.location = searchURL;

        return false;
    }
    $('#globalSearchButton').click(searchGlobal);
    $('#globalSearchButton').submit(searchGlobal);
    $('#SearchBoxWrapper :input[id$="globalSearchInput"]').keypress(function(event) {
        if (event.which == 13) {
            event.preventDefault();
            searchGlobal();
        }
    });


    $('.closePop').live('click', function() {
        hideFullOverlay('.popup', this);
        // if closing the flash video player popup
        if ($('#videoPlayer').length > 0) {
            // replace flash object with DIV
            $('#videoPlayer').replaceWith('<div id="videoPlayer"></div>');
            //document.getElementById('videoPlayer').killVideo();
        }
        return false;
    });


    $('.closeImg').live('click', function() {
        $(this).closest('.popup').remove();
        return false;
    });

    // Migrated js
    $('a.formHint').click(function() {
        var hint = $(this).attr('href');
        $(hint).slideToggle()
        return false;
    });
    
    $('.accordian .trigger').click(function() {
        toggleAccordian(this);
    });

    $('#site-footer a[href$="#window"]').attr("target", "_blank");

    $('.IF_pop, .ms-rteCustom-IngredientFinder_popup_trigger, a.btn-primary[href$="/#IngredientFinder"]').click(function() {
        showFullOverlay({
            'popUpId': '#IngredientFinder',
            'container': 'body',
            'opacity': .5,
            'color': '#000',
            'fadeTime': 500,
            'slidePopUp': true,
            'yOffset': 10,
            'zIndex': 999
        });

        return false;
    });

    // initiate product detail image enlarger
    $('#NutritionalFacts .btn_enlarge').live('click', function() {
        enlargeImage(this);
        return false;
    });

    // initiate ingredient finder image enlarger
    $('#NFcards .btn_enlarge').live('click', function() {
        enlargeImage(this, false, false, true);
        return false;
    });

    secondaryPopup();
});

// check brower
function checkBrowser() {
    var browser;
    if (window.XMLHttpRequest) {
        if (document.expando) {
            browser = 'IE7';
        }
        else {
            browser = 'moz, safari, chrome'
        }
    }
    else {
        browser = 'IE6';
    }
    return browser;
}

function setiFrameHeight(_this) {
    // height setter

    function heightSetter(_this) {
        _this.css({
            'height': _this.contents().find("body").outerHeight()
        });
        // reset secondary overlay for ingredient challenge
        $('#IngredientFinder .secondaryOverlay').css({
            height: $('#IngredientFinder .popContent .inner').outerHeight()
        });
    }
    // loop through all iframes and attach ready and load events

    var _this = $(_this);
    if (_this.attr('setHeight')) {
        _this.css('height', _this.attr('setHeight'))
        resizeOverlay();
    }
    else {

        // on ready set iframe height
        _this.ready(function() {
            heightSetter(_this)
            resizeOverlay();
        });
        // on load set iframe height
        _this.load(function() {
            //alert('load')
            heightSetter(_this);
            resizeOverlay();
        });
    }
}

// shows full window overlay.
//will also block user from interacting with page elements with a lesser z-index
function showFullOverlay(s) {

    //$('select').addClass("hide_select"); // This is for IE6 only
    // define properites if settings are missing
    s.popUpId = $(s.popUpId);
    s.container = s.container || 'body';
    s.opacity = s.opacity || .5;
    s.color = s.color || '#000';
    s.fadeTime = s.fadeTime || 500;
    s.slidePopUp = s.slidePopUp || false;
    s.zIndex = s.zIndex || 999;
    s.yOffset = s.yOffset || 60;
    s.overlay = $('<div class="overlay"><div>');

    // wrap container in jQuery object
    s.container = $(s.container);
    s.container.offset = s.container.offset();

    setiFrameHeight(s.popUpId.find('iframe'));

    // offset popup
    if (getYOffset() >= s.container.offset.top) {
        s.yOffset = (getYOffset() + s.yOffset) - s.container.offset.top
    }

    // expand container if the popup plus it's y offset is larger
    if (s.container.outerHeight() < (s.yOffset + s.popUpId.outerHeight())) {
        s.container.attr('resetTo', s.container.height() - 200);
        s.container.css({
            'height': s.yOffset + s.popUpId.outerHeight() + 200
        });
    }

    // set offset based on slidePopUp settings
    if (s.slidePopUp == true) {
        s.yOffsetStart = -(s.popUpId.outerHeight());
    }
    else {
        s.yOffsetStart = s.yOffset;
    }

    // append overlay to container
    s.container.append(s.overlay);

    // show overlay
    s.overlay.css({
        'display': "block",
        'height': s.container.outerHeight(),
        'width': s.container.outerWidth(),
        'opacity': 0,
        'background': s.color
    }).animate({
        'opacity': s.opacity
    }, s.fadeTime, 'swing');

    // show popup settings
    var showPopup = {
        'css': {
            'display': "block",
            'top': s.yOffsetStart,
            'opacity': 0
        },
        'animation': {
            'top': s.yOffset,
            'opacity': 1
        }
    }

    // remove opacity if IE7/6 - filter cuts off elements
    // with a negative offset of the container
    if (checkBrowser() == 'IE7' || checkBrowser() == 'IE6') {
        delete showPopup.css.opacity
        delete showPopup.animation.opacity
    }

    // move popUp to target container
    s.popUpId.appendTo(s.container)

    //show popup
    setTimeout(function() {
        s.popUpId.css(showPopup.css).animate(showPopup.animation, s.fadeTime, 'swing', function() {
            /* set video if path exists */
            if (s.video) {
                createVideoPlayer(s.video.v_target, s.video.v_path);
            }

            s.popUpId.find('iframe').css({
                opacity: 0,
                visibility: 'visible'
            }).animate({
                opacity: 1
            })
            /* IE6 won't display it's select elements within the iFrame when it's container
            * has been negatively indented off the page. The only solution is to recreate the selects
            * and replace the dead selects with the newly created elements. This works but it is insane.
            * IE6 is insane...
            */
            /*
            if (checkBrowser() == 'IE6') {
            var ie6_clone = {}
            s.popUpId.find('iframe').contents().find('select').each(function(){
            ie6_clone.name = $(this).attr('name');
            ie6_clone.id = $(this).attr('id');
            ie6_clone.elements = $(this).html();
            $(this).after('<select name="' + ie6_clone.name + '" id="' + ie6_clone.id + '">' + ie6_clone.elements + '</select>');
            $(this).remove()
            })
            }
            */
        })
    }, s.fadeTime / 2.5)

};


// hide overlay/popup
function hideFullOverlay(noticeID, trigger) {

    $('div.overlay').css({
        display: "none"
    }).remove();
    var popup = {}
    popup.current = $(trigger).closest(noticeID);

    // iFrame browser problemos
    if (checkBrowser() == 'IE6' || checkBrowser() == 'IE7') {
        popup.hide = {
            display: "none"
        };
    }
    else {
        popup.hide = {
            top: -99999
        };
    }

    var iframeHeight = popup.current.css(popup.hide).find('iframe').css('height')
    popup.current.css(popup.hide).find('iframe').css({
        visibility: 'hidden'
    }).attr('setHeight', iframeHeight)


    // reset container height
    var container = $(noticeID).closest('div[resetTo]');
    if (checkBrowser() == 'IE6') {
        container.css({
            'height': container.attr('resetTo')
        })
    }
    else {
        container.css({
            'height': 'auto'
        })
    }
};

function getYOffset() {
    var pageY;
    if (typeof (window.pageYOffset) == 'number') {
        pageY = window.pageYOffset;
    }
    else {
        pageY = document.documentElement.scrollTop;
    }
    return pageY;
}


function resizeOverlay() {
    $('div.overlay').css({
        height: $(document).height() + 100
    });
}

function setIndeticalHeight(element, target) {
    $(element).height($(target).outerHeight());
}


function secondaryPopup() {
    // hide selects in IE6
    if (checkBrowser() == 'IE6' && $('#IngredientFinder').length > 0) {
        // $('#IngredientFinder').addClass('hideSelect');
    }

    $('#IngredientFinder .secondaryOverlay').css({
        height: $('#IngredientFinder .popContent .inner').height()
    });

    $('#IngredientFinder .secondaryOverlay').css({
        height: $('#IngredientFinder .popContent .inner').height()
    });

    $('.closeSecondaryPop').click(function() {
        $(this).closest('.secondaryPopup').hide();
        $('.secondaryOverlay').hide();
        $('#IngredientFinder').removeClass('hideSelect')
        return false;
    });

    $('.ms-rteCustom-IngredientChallenge_Disclaimer_popup_trigger, .IF_disclaimer').click(function() {
        if (checkBrowser() == 'IE6' && $('#IngredientFinder').length > 0) {
            $('#IngredientFinder').addClass('hideSelect');
        }

        $('#IngredientFinder .secondaryOverlay').css({
            height: $('#IngredientFinder .popContent').outerHeight()
        }).show();


        $('#IngredientFinder #LegalDisclaimer').show();

        return false;
    })

    $('.ms-rteCustom-IngredientChallenge_Instructions_popup_trigger, .IF_instructions').click(function() {
        if (checkBrowser() == 'IE6' && $('#IngredientFinder').length > 0) {
            $('#IngredientFinder').addClass('hideSelect')
        }
        $('#IngredientFinder .secondaryOverlay').css({
            height: $('#IngredientFinder .popContent').outerHeight()
        }).show();
        $('#IF_usage').show();
        return false;
    });
}


function setIngredientFinderCookie() {
    if (readCookie('IngredientFinder') == "true") {
        $('#IngredientFinder #LegalDisclaimer, #IngredientFinder div.secondaryOverlay').hide();
    }
    else {
        createCookie('IngredientFinder', "true", 0);
    }
};

// Create, Read, and Delete cookie functions
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else
        var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ')
            c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0)
            return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function enlargeImage(trigger, iframe, target, IngFinder) {
    var relContainer, offset, iframeOffset, enlargedNtCard;
    trigger = $(trigger);

    if ($('#' + trigger.attr('rel') + '_enlarged').css('display') != 'block') {

        //update image path to point to the large image
        if (iframe) {
            enlargedNtCard = $('#' + iframe + ' iframe').contents().find('#' + trigger.attr('rel')).clone();
            // relational container
            relContainer = $('#' + iframe + ' iframe').contents().find('[target=' + trigger.attr('rel') + ']');
            iframeOffset = $('#' + iframe + ' iframe').offset();
            offset = target;

            offset.top = offset.top + iframeOffset.top
            offset.left = offset.left + iframeOffset.left

        }
        else {
            enlargedNtCard = $('div#' + trigger.attr('rel')).clone()
            // relational container
            relContainer = $('[target=' + trigger.attr('rel') + ']');
            offset = relContainer.offset();
        }


        enlargedNtCard.addClass('nt_enlarged popup').attr({
            'enlarged': trigger.attr('rel'),
            'id': trigger.attr('rel') + '_enlarged'
        })
        enlargedNtCard.append('<a href="#closer" class="closeImg">Close [x]</a>');
        enlargedNtCard.appendTo('body');


        // position container
        enlargedNtCard = $('#' + trigger.attr('rel') + '_enlarged');
        // enlargedNtCard.draggable();
        enlargedNtCard.mouseover(function() {
            enlargedNtCard.css({ // cursor: 'move'
        })
    });

    var NFcard_CSS = {
        display: 'block',
        margin: 0,
        top: offset.top - (enlargedNtCard.outerHeight() - relContainer.outerHeight()) / 2,
        left: offset.left - (enlargedNtCard.outerWidth() - relContainer.outerWidth()) / 2
    }


    if (IngFinder) {
        switch (trigger.siblings('.nutrionalInfo').attr('id')) {
            case 'ntFacts_1':
                NFcard_CSS.left = NFcard_CSS.left - 50;
                break;
            case 'ntFacts_2':
                // stay centered
                break;
            case 'ntFacts_3':
                NFcard_CSS.left = NFcard_CSS.left + 50;
                break;
            default:

        }
    }


    enlargedNtCard.css(NFcard_CSS);
}
}

