/* messaging */

// check URL for language param
// swap language param and redirect

function langToggle(url){
    url = url.toString();
    var language = url.match('/en/');
    if (language != null) {
        url = url.replace('/en/', "/fr/");
    }
    else {
        url = url.replace('/fr/', "/en/");
    };
    window.location = url;
};

// 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
        $('#ChallengePopup .secondaryOverlay').css({
            height: $('#ChallengePopup .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();
        });
    }
    
    
}

function selectReplacement(target){
    var select = {
        replace: replaceSelect, // replace select method
        options: attachOptions, // attach options to select method
        maxHeight: 300
    }
    
    // run select replacement on targeted elements
    $(target).each(function(){
        // select attributes
        select.current = $(this);
        select.id = select.current.attr('id');
        select.val = select.current.val();
        select.text = select.current.find(':selected').text();
        select.current.width = select.current.outerWidth();
        // replacement options for custom input 
        select.replace(select);
    })
    
    // replace select
    function replaceSelect(select){
        select.current.hide();
        select.replacement = '<div style="width:' + (select.current.width + 35) + 'px" class="selectWrapper" rel="' + select.id + '"><a style="width:' + (select.current.width) + 'px" class="select">' + select.text + '</a><div class="arrow"></div></div>';
        select.current.after(select.replacement);
        $('body').append(select.options(select.current));
    }
    
    
    // grab option groups
    function attachOptions(current){
        if (current.find('optgroup').length > 0) {
            var optGroups = [];
            current.find('optgroup').each(function(i){
                optGroups[i++] = '<li>' + $(this).attr('label') + '<ul>' + getOptions(current) + '</ul></li>';
            })
            return '<ul style="width:' + (select.current.width + 35) + 'px" class="selectOptions ' + select.id + '" rel="' + select.id + '">' + optGroups.join('') + '</ul>';
        }
        else {
            return '<ul style="width:' + (select.current.width + 35) + 'px" class="selectOptions ' + select.id + '" rel="' + select.id + '">' + getOptions(current) + '</ul>';
        }
        
        function getOptions(target){
            var options = [];
            target.find('option').each(function(e){
                options[e++] = '<li><a href="#' + $(this).val() + '"data-value="' + $(this).val() + '">' + $(this).text() + '</a></li>'
            })
            return options.join('');
        }
    }
    
    // select functionality    
    $('.selectWrapper').live('click', function(){
        select.current = $(this);
        select.current.offset = select.current.offset();
        select.current.options = $('ul.selectOptions[rel=' + $(this).attr('rel') + ']');
        
        // set vertical placement of options.
        // if options are long or run off the page modify placement/scrolling properties
        select.current.options.css({
            display: 'block', // enable options for placement/scroll check
            left: -99999,
            top: -99999 // hide off the page
        }).attr('state', 'active');
        
        // add scroll bar if options height exceed select.maxHeight value (default: 300px)
        if (select.current.options.outerHeight() > select.maxHeight) {
            select.current.options.css({
                height: select.maxHeight,
                'overflow-y': 'scroll'
            })
        }
        // align options to top of select if options height + replacement select offset is 
        // greater than the document height.
        if (select.current.offset.top + select.current.options.outerHeight() > $(document).height()) {
            select.current.options.css({
                left: select.current.offset.left,
                top: select.current.offset.top - select.current.options.outerHeight()
            });
        }
        else {
            select.current.options.css({
                left: select.current.offset.left,
                top: select.current.offset.top + select.current.outerHeight()
            });
        }
    });
    
    $('.selectOptions').live('click', function(e) {
        // FIX: open link in new window
        var linkUrl = $(e.target).attr('data-value');
        var linkTitle = $(e.target).innerHTML;
        if (linkUrl) {
            window.open(linkUrl, linkTitle);
        }

        // FIX: do not change drop-down selection
        //        $('.selectWrapper[rel="' + $(this).attr("rel") + '"] a').text($(e.target).text());
        //        $('select#' + $(this).attr("rel")).val($(e.target).attr('data-value'));

        $(this).hide();
        return false;
    });
    
    
    
    // hide drop down on external click
    var checkExternalClick = function(e){
        $('.selectOptions').each(function(){
            if ($(this).attr('state') == 'active') {
                select.options = $('.selectOptions[state="active"]');
                select.options.offset = select.options.offset();
                select.options.width = select.options.outerWidth();
                select.options.height = select.options.outerHeight();
                // if mouse x/y coordinates are less or greater than the option containers
                // boundaries hide the option container.            
                if (e.pageX > (select.options.offset.left + select.options.width) || e.pageX < select.options.offset.left || e.pageY < select.options.offset.top || e.pageY > (select.options.offset.top + select.options.height)) {
                    select.options.hide().attr('state', 'inactive')
                }
            }
        })
    };
    $(document).mousedown(checkExternalClick);
}

// 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 boxSlide(props){

}

function getYOffset(){
    var pageY;
    if (typeof(window.pageYOffset) == 'number') {
        pageY = window.pageYOffset;
    }
    else {
        pageY = document.documentElement.scrollTop;
    }
    return pageY;
}

//open out going links (http:// prefix) in a new window
function openHTTPlinksInNewWindow(){
    $('a[href^="http://"]').each(function(){
        $(this).attr({
            target: "_blank",
            title: $(this).attr('title') + ' - Opens in a new window.'
        });
    });
}

function enlargeImage(trigger, iframe, target){
    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'
            })
        });
        enlargedNtCard.css({
            display: 'block',
            margin: 0,
            top: offset.top - (enlargedNtCard.outerHeight() - relContainer.outerHeight()) / 2,
            left: offset.left - (enlargedNtCard.outerWidth() - relContainer.outerWidth()) / 2
        });
    }
    
    
}


function tabsNav(options){

    // tab properties
    var tab = {
        navContainer: $('ul.tabs'),
        active: false,
        panelId: location.hash,
        panel: $('.infoDetails'),
        panelContainer: $('.expandable'),
        css: {
            hide: {
                display: 'none',
                opacity: 0
            },
            show: {
                display: "block"
            }
        },
        animation: {
            opacity: 1
        }
    }
    
    if ($('.tabs.IAG_nav').length > 0 && checkBrowser() == 'IE6') {
        tab.navContainer.find('a').hover(function(){
            if ($(this).attr('class') != 'active') {
                $(this).find('.transparency, strong').addClass('active')
            }
        }, function(){
            if ($(this).attr('class') != 'active') {
                $(this).find('.transparency, strong').removeClass('active')
            }
        })
        
    }
    
    
    // remove opacity if IE7/6 - filter cuts off elements 
    // with a negative offset of the container
    if (checkBrowser() == 'IE7') {
        delete tab.css.hide.opacity;
        delete tab.animation.opacity;
    }
    else 
        if (checkBrowser() == 'IE6') {
            tab.css.hide.position = 'relative';
            tab.css.hide.top = 0;
            delete tab.css.hide.opacity;
            delete tab.animation.opacity;
        }
    
    // get me some triggers.
    tab.trigger = tab.navContainer.find('a')
    
    // check to see if tabbed navigation exists
    // if so... set that sucker up.
    if (tab.trigger.length > 0) {
        // setting marker to first if there is no
        // hash value (history marker)
        var deeplink = false;
        $('div.infoDetails').each(function(){
            if (tab.panelId.replace('#', '') == $(this).attr('id')) {
                deeplink = true;
            }
        })
        if (tab.panelId.length < 1 || deeplink == false) {
            tab.panelId = 'first';
        }
        // show resize panels
        resizeAndShowPanels(tab)
        
        // setup click functionality
        tab.trigger.click(function(e){
            tab.trigger.removeClass('active')
            tab.active = $(this).attr('active');
            if (tab.active != 'true') {
                tab.panelId = $(this).attr('href');
                resizeAndShowPanels(tab);
            }
        });
    }
    
    
    
    function resizeAndShowPanels(tab){
    
        // show first panel
        if (tab.panelId == 'first') {
            // reset panels
            tab.panel.css(tab.css.hide);
            
            // set height of parent container to the panels height
            tab.panelContainer.css({
                'height': tab.panel.eq(0).outerHeight() + 35
            });
            
            // show panel
            tab.panel.eq(0).css(tab.css.show).animate(tab.animation, 600, 'linear');
            
            // set active state to the first nav tab
            if ($('.tabs.IAG_nav').length < 1) {
                tab.trigger.eq(0).attr({
                    'active': 'true',
                    'class': 'active'
                });
            }
        }
        else {
            // adjust panel container height to fit the active panels contents
            tab.panelContainer.css({
                'height': $(tab.panelId).outerHeight() + 35
            }, 200, 'swing');
            
            // set active state for tab nav
            tab.trigger.removeAttr('active').removeClass('active');
            tab.navContainer.find('a[href="' + tab.panelId + '"]').attr({
                'active': 'true',
                'class': 'active'
            });
            
            // reset panels
            tab.panel.css(tab.css.hide);
            
            // show active panel
            $(tab.panelId).css(tab.css.show).animate(tab.animation, 600, 'linear');
            
        }
    }
};


function carousel(){
    if ($('#carousel').length > 0) {
    
        var c_props = {
            carousel: $('#carousel'),
            slideSpeed: 300,
            numPerClick: 2
        };
        
        c_props.prev_btn = c_props.carousel.siblings('a.prev');
        c_props.next_btn = c_props.carousel.siblings('a.next');
        c_props.itemContainer = c_props.carousel.find('ul');
        c_props.itemWidth = c_props.itemContainer.find('li').width();
        c_props.itemLength = c_props.itemContainer.find('li').length;
        c_props.containerWidth = c_props.itemWidth * c_props.itemLength;
        c_props.itemsVisible = c_props.carousel.width() / c_props.itemWidth;
        c_props.itemContainer.width(c_props.itemWidth * c_props.itemLength);
        c_props.endoflist = (c_props.itemsVisible * c_props.itemWidth) - c_props.itemContainer.width();
        
        // attach events
        attachClickingEvents(c_props);
    }
    
    
    function attachClickingEvents(c_props){
        var offset = c_props.itemContainer.position();
        var animating;
        c_props.prev_btn.click(function(){
            c_props.next_btn.css({
                'opacity': 1,
                'cursor': 'pointer'
            });
            if (animating != true && offset.left != 0) {
                animating = true;
                offset = c_props.itemContainer.position();
                c_props.itemContainer.stop().animate({
                    'left': (offset.left + (c_props.itemWidth * c_props.numPerClick))
                }, c_props.slideSpeed, 'swing', function(){
                    animating = false;
                    offset = c_props.itemContainer.position();
                    
                })
            }
            if (offset.left >= (c_props.itemWidth * c_props.numPerClick) * -1) {
                c_props.prev_btn.css({
                    'opacity': .3,
                    'cursor': 'default'
                });
            }
            return false;
        })
        c_props.next_btn.click(function(){
            c_props.prev_btn.css({
                'opacity': 1,
                'cursor': 'pointer'
            });
            if (animating != true && offset.left > c_props.endoflist) {
                animating = true;
                offset = c_props.itemContainer.position();
                c_props.itemContainer.stop().animate({
                    'left': +(offset.left - (c_props.itemWidth * c_props.numPerClick))
                }, c_props.slideSpeed, 'swing', function(){
                    animating = false;
                    offset = c_props.itemContainer.position();
                    
                })
            }
            if (offset.left <= c_props.endoflist + (c_props.itemWidth * c_props.numPerClick)) {
                c_props.next_btn.css({
                    'opacity': .3,
                    'cursor': 'default'
                });
            }
            return false;
        })
    }
}


// 
function addDivider(element, divider, startIndex, endIndex){
    if (divider == undefined) 
        divider = $('<li>|</li>');
    var dividerElement = $(divider);
    if (startIndex == undefined) 
        startIndex = 0;
    if (endIndex == undefined) {
        $(element + ':gt(' + startIndex + ')').before(dividerElement);
    }
    else {
        for (i = startIndex; i <= endIndex; i++) {
            $(element).eq(i).before(dividerElement);
        }
    }
}

function deepLinker(menuWrapper){
    var deepLink = location.pathname;
    $(menuWrapper + ' a[href="' + deepLink + '"]').attr({
        'active': 'true',
        'class': 'active'
    });
}

function tooltips(){

    // create tool tip
    var tooltip = '<table id="ToolTip"><tr><td class="top_leftCnr">&nbsp;</td><td class="top">&nbsp;</td><td class="top_rightCnr">&nbsp;</td></tr><tr><td class="left">&nbsp;</td><td class="content">&nbsp;</td><td class="right">&nbsp;</td></tr><tr><td class="bot_leftCnr">&nbsp;</td><td class="bot"><img src="/SiteCollectionImages/McCain.ca/common/tooltip/tip.png.gif" width="23" height="17"></td><td class="bot_rightCnr">&nbsp;</td></tr>    </table>';
    
    
    $('body').append(tooltip);
    tooltip = $('#ToolTip')
    
    // tooltip (this is for ie6
    tooltip.css('display', 'none')
    
    var timeOut;
    var delayTime = 400;
    var offset = {};
    
    // delay function
    function hideToolTip(trigger, delayTime){
        if (delayTime == false) {
            resetToolTip(trigger);
        }
        else {
            timeOut = setTimeout(function(){
                resetToolTip(trigger);
            }, delayTime)
        }
    }
    
    function resetToolTip(trigger){
        $('.tip_trigger[state="active"], .ms-rteCustom-tooltip_trigger[state="active"]').attr('title', tooltip.find('td.content').text());
        tooltip.css({
            'display': 'none'
        }).find('td.content').empty();
    }
    
    function manageToolTip(_this, offset){
        $('.tip_trigger, .ms-rteCustom-tooltip_trigger').attr('state', 'inactive')
        $(_this).attr('state', 'active')
        tooltip.find('td.content').text($(_this).attr('title'))
        tooltip.css({
            'display': 'block',
            'top': offset.y - (tooltip.height() - 5),
            'left': offset.x - 45
        });
        $(_this).attr('title', '');
    }
    
    // mouse over tool tip trigger
    $('.tip_trigger[title], .ms-rteCustom-tooltip_trigger[title]').mouseover(function(e){
        clearTimeout(timeOut);
        offset.xy = $(this).offset();
        offset.x = parseInt(e.pageX);
        offset.y = parseInt(offset.xy.top);
        if (tooltip.css('display') != 'block') {
            manageToolTip(this, offset);
        }
        else 
            if ($(this).attr('state') == 'inactive' && tooltip.css('display') == 'block') {
                hideToolTip(this, false);
                manageToolTip(this, offset);
            }
    });
    
    // mouse out tool tip trigger
    $('.tip_trigger[title], .ms-rteCustom-tooltip_trigger[title]').mouseout(function(){
        clearTimeout(timeOut);
        var trigger = this;
        // set a delay on hiding the tooltip
        hideToolTip(trigger, delayTime)
        // if the user rolls over tooltip, clear the timeout.
        tooltip.mouseover(function(){
            clearTimeout(timeOut);
        });
        // hide tool tip on mouse out.
        tooltip.mouseout(function(){
            clearTimeout(timeOut);
            hideToolTip(trigger, delayTime);
        });
    });
}

function setIndeticalHeight(element, target){
    $(element).height($(target).outerHeight());
}

function toggleAccordian(trigger){
    $(trigger).siblings('div.QandA').slideToggle();
    $(trigger).toggleClass('open')
}

function createVideoPlayer(target, currVideoPath){
    var flashvars = {};
    flashvars.videoPath = currVideoPath;
    var params = {};
    params.wmode = "transparent";
    var attributes = {};
    attributes.id = target;
    swfobject.embedSWF("/SiteCollectionImages/McCain.ca/swfs/videoPlayer.swf", target, "500", "417", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
}

function secondaryPopup(){
    // hide selects in IE6
    if (checkBrowser() == 'IE6' && $('#ChallengePopup').length > 0) {
        $('#ChallengePopup iframe').contents().find('body').addClass('hideSelect')
    }
    
    $('#ChallengePopup .secondaryOverlay').css({
        height: $('#ChallengePopup .popContent .inner').height()
    })
    
    $('.closeSecondaryPop').click(function(){
        $(this).closest('.secondaryPopup').hide();
        $('.secondaryOverlay').hide();
        $('#ChallengePopup iframe').contents().find('body').removeClass('hideSelect')
        return false;
    });
    
    $('.ms-rteCustom-IngredientChallenge_Disclaimer_popup_trigger').click(function(){
        if (checkBrowser() == 'IE6' && $('#ChallengePopup').length > 0) {
            $('#ChallengePopup iframe').contents().find('body').addClass('hideSelect')
        }
        $('#ChallengePopup .secondaryOverlay').css({
            height: $('#ChallengePopup .popContent').outerHeight()
        }).show();
        $('#LegalDisclaimer').show();
        
        return false;
    })
    
    $('.ms-rteCustom-IngredientChallenge_Instructions_popup_trigger').click(function(){
        if (checkBrowser() == 'IE6' && $('#ChallengePopup').length > 0) {
            $('#ChallengePopup iframe').contents().find('body').addClass('hideSelect')
        }
        $('#ChallengePopup .secondaryOverlay').css({
            height: $('#ChallengePopup .popContent').outerHeight()
        }).show();
        $('#IG_usage').show();
        return false;
    })
}

function landingAnimStart(){
    var cookieName = location.pathname;
    if (readCookie(cookieName) == "true") {
        landingAnimComplete();
        return false;
    }
    else {
        createCookie(cookieName, "true", 0)
        var targetContainer = $('div.content');
        $(targetContainer).append('<div class="overlay" id="Animation"></div>');
        $('#Animation').css({
            width: targetContainer.outerWidth(),
            height: targetContainer.outerHeight()
        })
        return true;
    }
}

function landingAnimComplete(){
    $('#ctl00_PlaceHolderMain_IntroMediaControl, #Animation').animate({
        opacity: 0
    }, 500, 'swing', function(){
        $(this).remove();
    });
}

// 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 resizeOverlay(){
    $('div.overlay').css({
        height: $(document).height() + 100
    });
}

function pageSetup(){
    //  match sub nav height height to main content height
    setIndeticalHeight('div.nav_col', 'div.mainContent');
    // attach target="_blank" to out going links
    //openHTTPlinksInNewWindow();
    // add pipes to Ancillary nav
    //addDivider('#AncillaryNavigation li', '<li>|</li>');
    // Toggle language
    /*
    $('a.langToggle').click(function(){
        langToggle(window.location);		
        return false;
    });
    */
    // initiate tool tips
    tooltips();
    // initiate tabs
    tabsNav();
    // initiate productCarousel
    carousel();
    // initiate image enlarger
    $('.btn_enlarge').click(function(){
        enlargeImage(this);
        return false;
    })
    // custom select elements
    selectReplacement('select.replace')
    
    secondaryPopup();
    
    // IE6 needs a rattle to get home pods to sit in their correct position.
    if (checkBrowser() == 'IE6') {
        // rattle!!!
        $('ul.product').css('bottom', '15px')
    }
}


$(document).ready(function(){
    // set iframe heights
    // setiFrameHeight()
    // initial page setup
    pageSetup();
    
    // popup ingreient challenge panel when an elememt 
    //with the class .IC_pop is clicked
    $('.IC_pop, .ms-rteCustom-IngredientChallenge_popup_trigger').click(function(){
        showFullOverlay({
            'popUpId': '#ChallengePopup',
            'container': 'body',
            'opacity': 1,
            'color': '#000',
            'fadeTime': 500,
            'slidePopUp': true,
            'yOffset': 50,
            'zIndex': 999
        });
        
        //$('#ChallengePopup div.disclaimer').
        
        
        return false;
    });
    
    $('.J_pop, .ms-rteCustom-JoinOurJourney_popup_trigger').click(function(){
        showFullOverlay({
            'popUpId': '#JourneyPopup',
            'container': 'div.content',
            'opacity': .5,
            'color': '#000',
            'fadeTime': 500,
            'slidePopUp': true,
            'yOffset': 50,
            'zIndex': 999
        });
        return false;
    });
    
    $('.Ask_pop, .ms-rteCustom-AskUs_popup_trigger').click(function(){
        showFullOverlay({
            'popUpId': '#AskUs',
            'container': 'div.content',
            'opacity': .5,
            'color': '#000',
            'fadeTime': 500,
            'slidePopUp': true,
            'yOffset': 50,
            'zIndex': 999
        });
        
        return false;
    });
    
    
    $('.showVideo, .ms-rteCustom-TV_Spot_popup_trigger').click(function(){
        showFullOverlay({
            'popUpId': '#Video',
            'container': 'div.content',
            'opacity': .75,
            'color': '#000',
            'fadeTime': 500,
            'slidePopUp': true,
            'yOffset': 50,
            'zIndex': 999,
            'video': {
                'v_target': 'videoPlayer',
                'v_path': $(this).attr('href')
            }
        });
        
        return false;
        
        /*
         var path = $(this).attr('href')
         document.getElementById('videoPlayer2').playVideo(path);
         return false;
         */
    });
    
    
    
    $('.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;
    });
    
    $('a.formHint').click(function(){
        var hint = $(this).attr('href');
        $(hint).slideToggle()
        return false;
    });
    
    $('.accordian .trigger').click(function(){
        toggleAccordian(this);
    });
    
    // open mccain country site in new window
    $('#CountrySelector').change(function(){
        window.open(this.value);
    })
    
    // open mccain country site in new window
    $('#CountrySelector_fr').change(function(){
        window.open(this.value);
    })
    
});
