﻿$(document).ready(function() {

    /* Layout: User Experience */
    setupDropdownMenu();
    setupSelectMenu();
    setupHeaderForms();
    setupRequestACatalog();

    /* Component JavaScript */
    setupFontScale();
    setupShowHide();
    setupShowModal();
    setupCarousel();
    setupMediaGallery();

    /* General Functions */
    setupPrivacyPolicyModal();
    setupDynamicTrackingCode();

    // Because IE sucks with standards, we need to create our own 'placeholder' functionality
    if ($.browser.msie) {
        setupPlaceholdersForIE($("[id$='Email_Forms_p_Persistent_p_Header_p_Wrapper_p'] input"));
        setupPlaceholdersForIE($("[id$='Search_Forms_p_Persistent_p_Header_p_Wrapper_p'] input"));
    }
});



/********************************************************* Global Variables ********************************************************/
var animateTime = 1000;
var carouselOnHold = false;



/***************************************************** Layout: User Experience *****************************************************/

/* Dropdown Menu */
function setupDropdownMenu() {
    $.tools.tooltip.addEffect("slidedownup",
	    function(done) {
            this.getTip().slideDown(300).show();
	    },
	    function(done) {
	        this.getTip().slideUp(300, function() {
	            $(this).hide();
	            done.call();
	        });
	    }
	);

    // Since 'this' in the tooltip function is not what we need, we must
    // seperate out each menu by using the 'each()' function
    $("[id$='NavItem_navContainer_p']").each(function(index, val) {
        var $current = new Array();
        $current[index] = $(this);

        $current[index].find("div.navSubHead").tooltip({
            tip: $current[index].find("[id$='divLevelThree']"),
            relative: true,
            position: 'bottom center',
            offset: [0, 0],
            effect: 'slidedownup',
            onBeforeShow: function() {
                $(this).addClass('navActive');
                $current[index].addClass('hover');
            },
            onBeforeHide: function() {
                $(this).removeClass('navActive');
                $current[index].removeClass('hover');
            }
        });
    });
}

/* Hero Select Menu Setup */
function setupSelectMenu() {
    if ($("[id$='SelectMenu_p']").length > 0) {
        $("[id$='SelectMenu_p']").selectmenu({
            style: 'dropdown',
            width: 331,
            menuWidth: 330,
            maxHeight: 250,
            select: function() {
                var val = this.value;
                if (val.toLowerCase().indexOf("optgroup") == -1) {
                    window.location = val;
                }
            }
        });
    }
}

/* Header Email/Search Form User Experience */
function setupHeaderForms() {
    var headerForms = { animateTime: function() { return 650; }, delayTime: function() { return 655; } };

    $("[id$='Email_Forms_p_Persistent_p_Header_p_Wrapper_p'] img").click(function() {
        $divEmail = $("[id$='Email_Forms_p_Persistent_p_Header_p_Wrapper_p']");
        $divSearch = $("[id$='Search_Forms_p_Persistent_p_Header_p_Wrapper_p']");

        $imgEmail = $(this);
        $imgSearch = $divSearch.find("img");
        $inputEmail = $divEmail.find("div.slideout");
        $inputSearch = $divSearch.find("div.slideout");

        if ($inputEmail.css("display") == "none") {
            $imgEmail.css("top", "-100%");
            $imgSearch.css("top", "0");

            $inputSearch.hide("slide", { direction: "right" }, headerForms.animateTime());
            setTimeout(function() {
                $imgSearch.css("top", "");
                $divEmail.removeClass("hiddenForm").addClass("currentForm");
                $divSearch.removeClass("currentForm").addClass("hiddenForm");
                $inputEmail.show("slide", { direction: "left" }, headerForms.animateTime());
            }, headerForms.delayTime());
        }
    });

    $("[id$='Search_Forms_p_Persistent_p_Header_p_Wrapper_p'] img").click(function() {
        $divEmail = $("[id$='Email_Forms_p_Persistent_p_Header_p_Wrapper_p']");
        $divSearch = $("[id$='Search_Forms_p_Persistent_p_Header_p_Wrapper_p']");

        $imgEmail = $divEmail.find("img");
        $imgSearch = $(this);
        $inputEmail = $divEmail.find("div.slideout");
        $inputSearch = $divSearch.find("div.slideout");

        if ($inputSearch.css("display") == "none") {
            $imgEmail.css("top", "0");
            $imgSearch.css("top", "-100%");

            $inputEmail.hide("slide", { direction: "left" }, headerForms.animateTime());
            setTimeout(function() {
                $imgEmail.css("top", "");
                $divEmail.removeClass("currentForm").addClass("hiddenForm");
                $divSearch.removeClass("hiddenForm").addClass("currentForm");
                $inputSearch.show("slide", { direction: "right" }, headerForms.animateTime());
            }, headerForms.delayTime());
        }
    });
}

/* Request a Catalog */
function setupRequestACatalog() {
    if ($("[id$='RequestCatalog']").length > 0) {
        $("[id$='Button_RequestCatalog_p']").toggle(function() {
            $(this).addClass("active");
            $("[id$='Content_RequestCatalog_p']").show("blind", null, 350);
        }, function() {
            $(this).removeClass("active");
            $("[id$='Content_RequestCatalog_p']").hide("blind", null, 350);
        });
    }
}


/****************************************************** Component JavaScript *******************************************************/
/* Font Scale/Resize */
function setupFontScale() {
    var itemsToChange = "[id$='Left_Area_p_Content_p_Wrapper_p'] p, [id$='Left_Area_p_Content_p_Wrapper_p'] span, [id$='Left_Area_p_Content_p_Wrapper_p'] ul, [id$='Left_Area_p_Content_p_Wrapper_p'] ol, [id$='Left_Area_p_Content_p_Wrapper_p'] li, [id$='Left_Area_p_Content_p_Wrapper_p'] h1, [id$='Left_Area_p_Content_p_Wrapper_p'] h2, [id$='Left_Area_p_Content_p_Wrapper_p'] h3, [id$='Left_Area_p_Content_p_Wrapper_p'] h4, [id$='Left_Area_p_Content_p_Wrapper_p'] h5, [id$='Left_Area_p_Content_p_Wrapper_p'] h6, div.mediagallery-carousel-group-item,"
                      + "[id$='Right_Area_p_Content_p_Wrapper_p'] p, [id$='Right_Area_p_Content_p_Wrapper_p'] span, [id$='Right_Area_p_Content_p_Wrapper_p'] ul, [id$='Right_Area_p_Content_p_Wrapper_p'] ol, [id$='Right_Area_p_Content_p_Wrapper_p'] li, [id$='Right_Area_p_Content_p_Wrapper_p'] h1, [id$='Right_Area_p_Content_p_Wrapper_p'] h2, [id$='Right_Area_p_Content_p_Wrapper_p'] h3, [id$='Right_Area_p_Content_p_Wrapper_p'] h4, [id$='Right_Area_p_Content_p_Wrapper_p'] h5, [id$='Right_Area_p_Content_p_Wrapper_p'] h6, [id$='Right_Area_p_Content_p_Wrapper_p'] div.title, [id$='Right_Area_p_Content_p_Wrapper_p'] div.content, div.mediagallery-carousel-group-item,"
                      + "[id$='Wide_Area_p_Content_p_Wrapper_p'] p, [id$='Wide_Area_p_Content_p_Wrapper_p'] span, [id$='Wide_Area_p_Content_p_Wrapper_p'] ul, [id$='Wide_Area_p_Content_p_Wrapper_p'] ol, [id$='Wide_Area_p_Content_p_Wrapper_p'] li, [id$='Wide_Area_p_Content_p_Wrapper_p'] h1, [id$='Wide_Area_p_Content_p_Wrapper_p'] h2, [id$='Wide_Area_p_Content_p_Wrapper_p'] h3, [id$='Wide_Area_p_Content_p_Wrapper_p'] h4, [id$='Wide_Area_p_Content_p_Wrapper_p'] h5, [id$='Wide_Area_p_Content_p_Wrapper_p'] h6, div.mediagallery-carousel-group-item";
    var scale = 4;
    var fontLevel = 1;

    $reset = $("[id$='Reset_FontResize_p']");
    $upActive = $("[id$='ActiveIncrease_FontResize_p']");
    $upDeactive = $("[id$='DeactiveIncrease_FontResize_p']");
    $downActive = $("[id$='ActiveDecrease_FontResize_p']");
    $downDeactive = $("[id$='DeactiveDecrease_FontResize_p']");

    $upActive.fontscale(itemsToChange, "up", { unit: "px", increment: scale });
    $downActive.fontscale(itemsToChange, "down", { unit: "px", increment: scale });
    $reset.fontscale(itemsToChange, "reset");

    if ($.cookie('fontscale') != null) {
        var currentLevel = $.cookie('fontscale').split('&')[0].replace('delta=', '');
        fontLevel = parseInt(currentLevel) / scale + 1;

        if (fontLevel >= 4) {
            $upActive.hide();
            $upDeactive.show();
        }
        else if (fontLevel <= 0) {
            $downActive.hide();
            $downDeactive.show();
        }
    }

    $upActive.click(function() {
        if (fontLevel >= 4) {
            $upActive.hide();
            $upDeactive.show();
        }
        else fontLevel++;
        $downActive.show();
        $downDeactive.hide();
    });
    $downActive.click(function() {        
        if (fontLevel <= 0) {
            $downActive.hide();
            $downDeactive.show();
        }
        else fontLevel--;
        $upActive.show();
        $upDeactive.hide();
    });
    $reset.click(function() {
        fontLevel = 1;
        $upActive.show();
        $upDeactive.hide();
        $downActive.show();
        $downDeactive.hide();
    });
}

/* Show/Hide */
function setupShowHide() {
    var $showHide = $("[id$='ShowHide']");

    if ($showHide.length > 0) {
        var $toggleShowHide = $("[id$='Toggle_ShowHide_p']");
        
        if($toggleShowHide.length > 0) {
            $toggleShowHide.click(function() {
                var $controller = $(this).closest("[id$='ShowHide']").find("[id$='Controller_ShowHide_p']");
                var $dynamic = $(this).closest("[id$='ShowHide']").find("[id$='Dynamic_ShowHide_p']");

                if ($controller.hasClass("open")) {
                    $controller.removeClass("open");
                    $controller.addClass("closed");
                    $dynamic.hide("blind", null, animateTime);
                }
                else {
                    $controller.removeClass("closed");
                    $controller.addClass("open");
                    $dynamic.show("blind", null, animateTime);

                    // If it has a carousel within, make sure it is resized correctly
                    if ($controller.closest("div.carousel-container").length > 0) {
                        setTimeout(function() {
                            setScrollableHeight($controller.closest("div.carousel-container"));
                        }, animateTime);
                    }
                }
            });
        }
    }
}

function setupShowModal() {
    var $showHide = $("[id$='ShowHide']");

    if ($showHide.length > 0) {
        var $modalShowHide = $showHide.find("[id$='Modal_ShowHide_p']");        
        if($modalShowHide.length > 0) {
            $modalShowHide.find("[id$='lnkModalShow']").fancybox({
                'padding': 15,
                'autoScale': true,
                'transitionIn': 'none',
                'transitionOut': 'none',
                'width': 700,
                'showCloseButton': true
            });
        }
    }
}


/* Carousel */
function setupCarousel() {
    if($("[id$='Content_Circular_p_Carousel_p']").length > 0) {
        $("[id$='Content_Circular_p_Carousel_p']").each(function(idx) {
            var $container = new Array();
            $container[idx] = $(this).closest("div.carousel-container");
            $nav = $container[idx].find("[id$='Nav_Circular_p_Carousel_p']");

            $nav.find('div.next').click(function() {
                if (!carouselOnHold) {
                    carouselOnHold = true;
                    updateScrollable($(this), $container[idx], 'next', false)
                }
            });
            $nav.find('div.prev').click(function() {
                if (!carouselOnHold) {
                    carouselOnHold = true;
                    updateScrollable($(this), $container[idx], 'prev', false)
                }
            });

            $allItems = $container[idx].find('.scrollableItem');

            $pages = $nav.find("div.pages");
            if ($pages.hasClass("withSlash"))
                $pages.html("1 / " + $allItems.length);
            else
                $pages.html("1 of " + $allItems.length);

            if ($container[idx].hasClass("resize")) {
                setScrollableHeight($container[idx]);
            }
        });
    }
}

function setScrollableHeight($container) {
    var intervalIdx = 0;

    var scrollableInterval = setInterval(function() {
        if (intervalIdx < 5) {
            $container.find('.scrollableItem.active').each(function() {
                var myHeight = $(this).height() + 20;
                var container = $(this).parents('.scrollableContainer');
                $(container).animate({
                    height: myHeight
                }, 'fast');
            });
            intervalIdx++;
        }
        else {
            clearInterval(scrollableInterval);
        }
    }, 500);
}

function updateScrollable(navItem, $parent, direction, noncircular) {
   var container = $parent.find('.scrollableContainer');
    var allItems = $(container).find('.scrollableItem');
    var itemCount = $(allItems).length;
    var visibleItem = $(container).find('.scrollableItem.active');
    var visibleItemIndex = $(visibleItem).index();
    var navContainer = $(container).find('.scrollableNav');
    var navPrev = $(navContainer).find('.prev');
    var navNext = $(navContainer).find('.next');
    var nextItemIndex = 0;

    if (direction == 'next') {
        nextItemIndex = (itemCount - 1 == visibleItemIndex) ? 0 : (visibleItemIndex + 1);
    }
    else {
        nextItemIndex = (visibleItemIndex == 0) ? (itemCount - 1) : (visibleItemIndex - 1);
    }
    var nextItem = allItems[nextItemIndex];

    if ($parent.hasClass("resize")) {
        $(visibleItem).fadeOut('fast', function() {
            $(this).removeClass('active');
            var thisHeight = $(nextItem).height();
            var newContainerHeight = thisHeight;
            $(container).animate({
                height: newContainerHeight
            }, 'fast', function() {
                updateScrollable_FadeIn(nextItem, nextItemIndex, itemCount, navContainer, navPrev, navNext, noncircular);
            });
        });
    }
    else {
        $(visibleItem).fadeOut('fast', function() {
            $(this).removeClass('active');
            var thisHeight = $(nextItem).height();
            var newContainerHeight = thisHeight;

            updateScrollable_FadeIn(nextItem, nextItemIndex, itemCount, navContainer, navPrev, navNext, noncircular);
        });
    }

    $pages = $parent.find("div.pages");
    if ($pages.hasClass("withSlash"))
        $pages.html((nextItemIndex + 1) + " / " + itemCount);
    else
        $pages.html((nextItemIndex + 1) + " of " + itemCount);
}

function updateScrollable_FadeIn(nextItem, nextItemIndex, itemCount, navContainer, navPrev, navNext, noncircular) {
    $(nextItem).fadeIn('fast', function() {
        $(this).addClass('active');
        $(navContainer).find('.index').html(nextItemIndex + 1);
        if (nextItemIndex == 0) {
            if (noncircular)
                $(navPrev).addClass('disabled');
        }
        else {
            if (noncircular)
                $(navPrev).removeClass('disabled');
        }
        if (nextItemIndex == itemCount - 1) {
            if (noncircular)
                $(navNext).addClass('disabled');
        }
        else {
            if (noncircular)
                $(navNext).removeClass('disabled');
        }
        carouselOnHold = false;
    });
}

/* Media Gallery */
function setupMediaGallery() {
    // Setup Photos
    if ($("[id$='Photo_Item_p_MediaGalley_p']").length > 0) {
        $("[id$='Photo_Item_p_MediaGalley_p']").fancybox({
            'titleShow': true,
            'titlePosition': 'inside',
            'showNavArrows': true,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            type: 'image'
        });
    }

    // Setup Videos
    if ($("[id$='Video_Item_p_MediaGalley_p']").length > 0) {
        $("[id$='Video_Item_p_MediaGalley_p']").click(function() {
	        $.fancybox({
	            'titlePosition': 'inside',
		        'autoScale': false,
		        'showNavArrows': true,
		        'transitionIn': 'none',
		        'transitionOut': 'none',
		        'title': this.title,
		        'width': 680,
		        'height': 495,
		        'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
		        'type': 'swf',
		        'swf': {
		   	        'wmode': 'transparent',
			        'allowfullscreen': 'true'
		        }
	        });

	        return false;
        });
    }
}

/* overwrite */
function setupVideoTracking(destination) {
   $("[id$='Video_Item_p_MediaGalley_p']").click(function() {
       _gaq.push(['_trackPageview', '/tracking/videos/' + destination]);
       return false;
   });
}


/******************************************************** General Functions ********************************************************/
function setupPrivacyPolicyModal() {
    if ($("[id$='hlPrivacyPolicy']").length > 0) {
        $("[id$='hlPrivacyPolicy']").fancybox({
            'padding': 0,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'height': 400,
            'width': 650,
            'showCloseButton': true,
            'type': 'iframe'
        });
    }
}

function setupPlaceholdersForIE($input) {
    if ($input.attr("placeholder").length > 0) {
        $input.val($input.attr("placeholder"));
        $input.focusin(function() {
            if ($input.val() == $input.attr("placeholder"))
                $input.val("");
        });
        $input.focusout(function() {
            if ($input.val() == "")
                $input.val($input.attr("placeholder"));
        });
    }
}

function setupDynamicTrackingCode() {
    $dynamicTrackingCodes = $("a[dynamictrackingcode]");
    
    if($dynamicTrackingCodes.length > 0) {
        $dynamicTrackingCodes.each(function() {
        var $url = window.location.protocol + "//" + window.location.host + $(this).attr("dynamictrackingcode");
            
            $(this).click(function() {
                $("[id$='ifmTrackingCodeDynamic']").attr("src", $url);
            });
        });
    }    
}
