var HERSHEYS = {
    CURRENT_PAGE: (function (pageIn) {
        //alert('CURRENT_PAGE: pageIn: ' + pageIn);
        //alert('domain: ' + document.domain);
        //alert('hostname: ' + location.hostname);
        //var split = pageIn.split('.com/');

        //var split = pageIn.split('.test/');
        //alert(split[1] + ", " + split[1].split('#')[0] + ", " + split[1].split('#')[0].split('?')[0] + ", " + split[1].split('#')[0].split('?')[0].split('.aspx')[0]);

        var split = pageIn.split(location.hostname + '/');
        //alert(split[1] + ", " + split[1].split('#')[0] + ", " + split[1].split('#')[0].split('?')[0] + ", " + split[1].split('#')[0].split('?')[0].split('.aspx')[0]);

        if (split.length != 2) {
            //return 'ERROR'; 
            return 'celebrate/404.htm'; //TODO: timmy: will this work? - if we want to go with season-specific 404 pages, use HERSHEYS.CURRENT_SEASON (e.g. 'celebrate/ + HERSHEYS.CURRENT_SEASON + /404.htm')
        }
        
        //return split[1].split('#')[0].split('?')[0].split('.aspx')[0] || '/';
        
        return split[1].split('#')[0];

    })(window.location.href)
};

if (typeof IS_MOBILE == 'undefined') var IS_MOBILE = false;

$(document).ready(function () {

    HERSHEYS.transparency = new HERSHEYS.Utility.Transparency({
        'opacity': '.6',
        'color': '#000000'
    });

    if (!IS_MOBILE) {

        /* Bind global nav elements */
        HERSHEYS.GlobalHeader.bind();
        HERSHEYS.Utility.inputPlaceholder();

        if (typeof CURRENT_PROMOTION_ID != 'undefined')
            HERSHEYS.Promotions.initBinds();

        HERSHEYS.globalBinds = function () {

            $('.fancy_modal').fancybox({ 'padding': 0, 'opacity': true, 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'scrolling': 'no' });
            $('.popupImage').fancybox();
            $('.modal_popup').fancybox();
            $('.button_print').bind('click', function () { window.print(); });

            $('.video_playlist a').bind('click', function () {

                HERSHEYS.Video.doPlay($(this));


                var title = $(this).attr('title');
                var id = $(this).attr('id');
                var poster = $(this).find('img').attr('src').replace('_thumb', '');
                var videoUrl = $(this).attr('filename');

                $('#video_title').html(title);

                var videoPlayer = PInstance[0];
                videoPlayer.setTitle(title);
                videoPlayer.setID(id);
                videoPlayer.setFile(videoUrl + ".mp4", false);
                if (navigator.userAgent.indexOf("Firefox") > 0) videoPlayer.setFile(videoUrl + ".ogv", false);
                videoPlayer.setPlay();
                videoPlayer.setActiveItem(1);
                videoPlayer.setPlayerPoster(poster);

                return false;
            });
            $(".scroller").simplyScroll({
                className: 'vert',
                horizontal: false,
                frameRate: 20,
                speed: 10
            });
            $('.submit_search').bind('click', function () {
                $('form:first').submit();
                return false;
            });
            /* Contact Form */
            $('.formOptionGroupASelector').unbind().bind('change', function () {

                if ($(this).attr('value') == "Product Concern and Availability") {
                    //$('.formOptionGroupA').hide();
                    $('#productInformation').show();
                } else {
                    $('.formOptionGroupA').hide();
                    $('#commentWrapper').show();
                }
            });
            $('a[externalSite]').bind('mouseenter', function (e) {

                var element = $('#preview_popup_instance');

                if (!element.length) {
                    element = $('<div id="preview_popup_instance" style="position: absolute; background-image: url(/assets/images/dot_com/external_preview.png); width: 225px; height: 171px; z-index: 99999">');
                    $('body').append(element);
                    element.append('<div id="preview_popup_inside">');
                }

                $(document).mousemove(function (e) {
                    var element = $('#preview_popup_instance');
                    element.css({
                        'left': e.pageX - 100,
                        'top': e.pageY - 180
                    });
                });

                element.css({
                    'left': e.pageX - 100,
                    'top': e.pageY - 180
                });

                var siteBG = $(this).attr('externalSite');
                if (siteBG) {
                    $('#preview_popup_inside').css(
			        { 'background-image': 'url(/assets/images/dot_com/preview_overlay_' + siteBG + '.gif)',
			            'height': '100%'
			        });
                }


            }).bind('mouseleave', function () {

                if ($.browser.msie) {
                    $('#preview_popup_instance').remove();
                } else {
                    $('#preview_popup_instance').fadeOut('fast', function () { $(this).remove(); });
                }
            });
        };

        HERSHEYS.globalBinds();

        $(HERSHEYS).trigger(HERSHEYS.CURRENT_PAGE + '_loaded');

    } else {

        $('.fancy_modal').fancybox({
            'padding': 0
			, 'margin': 5
			, 'modal': true
			, 'opacity': true
			, 'transitionIn': 'elastic'
			, 'transitionOut': 'elastic'
			, 'scrolling': 'no'
			, 'overlayOpacity': 0
        });
        $('.modal_popup').fancybox({
            'autoScale': false,
            'onStart': function () {
                if (IS_SCROLL) {
                    var headerH = document.getElementById('header').offsetHeight,
						footerH = document.getElementById('footer').offsetHeight,
						wrapperH = window.innerHeight - headerH - footerH;
                    document.getElementById('fancybox-overlay').style.height = (wrapperH + 100) + 'px';
                } else {
                    document.getElementById('fancybox-overlay').style.height = '100%';
                }
            }
        });
    }
});

HERSHEYS.EmailRecipe = (function(){
	
	var config = {
		
		'formSelector'  : '.modal_form',
		'submitSelector' : '#sendToFriend',
		'parentSelector' : '#share_recipe',
		'loadingSelector' : '.modal_loading',
		'successSelector' : '.modal_success',	
		'sendAgainSelector' : '#sendAgain',			
		'groupClass' : '.modal_panel',	
		'errors'	: '.sharerrors', 			
		'url' : '?form=blah'
				
	};
	
	var resetData = function(parent){
		
		parent.find('input:text').each(function(){
			$(this).attr('value',$(this).attr('placeholder'));
		});
		parent.find(config['groupClass']).hide();
		parent.find(config['formSelector']).show();
		parent.find(config['errors']).hide();
		
		$.fancybox.resize();
	};
	
	return {
		
		init : function(src){
			
			var parent = $(config['parentSelector']);
			
			
			resetData(parent);
			
			$(config['submitSelector']).live('click', function(){
				
				parent.find(config['groupClass']).hide();
				parent.find(config['loadingSelector']).show();
				
				$.fancybox.resize();
				
				var emailList = $('input#friendEmail').attr('value');
			    var nameList = $('input#friendName').attr('value');
			    var yourName = $('input#yourName').attr('value');
			    var yourEmail = $('input#yourEmail').attr('value');
			    var recipeID = $(this).attr('recipeid') || 0;
				
				
				HERSHEYS.Services.shareRecipe({
					'name' : yourName,
					'email' : yourEmail,
					'friendname' : nameList,
					'friendemail' : emailList,
					'recipeid' : recipeID,
					'src'	: src ? src : false,

					'success' : function(returns){

						parent.find(config['groupClass']).hide();
						parent.find(config['successSelector']).show();
						$.fancybox.resize();

					},
					'failure' : function(){

						alert('Sorry, there was an error sending your request. Please try again!');
						parent.find(config['groupClass']).show();
						parent.find(config['loadingSelector']).hide();
						$.fancybox.resize();
						
					}
				});
				
				return false;		
			});

			$(config['sendAgainSelector']).bind('click', function(){
				resetData(parent);
				return false;	
			});
		}
		
		
	};
	
})();
HERSHEYS.KitchensSignup = (function(){
	
	var config = {
		
		'parentSelector' : '#kitchens_signup',
		'successSelector' : '.modal_success',	
		'groupClass' : '.modal_panel',	
		'url' : '?form=blah'	
	};
	
	
	
	return {
		
		init : function(triggerSelector){
			
			var parent = $(config['parentSelector']);

			$('#submit_dob').bind('click', function(){
				
				HERSHEYS.Services.agecheck({
					year : $('#dob_year').attr('value'),
					month : $('#dob_month').attr('value'),
					day : $('#dob_day').attr('value'),
					
					success : function(){ 
						$('#subscribe_dob').hide();
						$('#subscribe_email').show();
					},
					failure : function(){
						$('#subscribe_dob').hide();
						$('#subscribe_failure').show();
					}
				});
				
				return false;
				
			});
			
			$('#kitchensSignup').bind('click', function(){
				
				if (!HERSHEYS.Utility.validate('email', $('#email').attr('value'))) return false;
				
				HERSHEYS.Services.subscribe({
					
					email : $('#email').attr('value'),
					
					success : function(){ 
						$('#subscribe_email').hide();
						$('#subscribe_success').show();
					},
					failure : function(){
						alert('Sorry, there was an error subscribing you. Please try again!');
					}
				});
				
				return false;
				
			});
	
		}	
	};
	
})();
HERSHEYS.GlobalHeader = (function () {

    var gh = '.gh';
    var subnavs = '.gh_subnav';
    var brandsLinks = '.toggle_all_brands';

    return {

        bind: function () {

            var that = this;

            $(gh).find('li')
					.bind('mouseover', function () {
					    clearTimeout(that.hideDelay);
					    $(this).addClass('active');
					    $(this).find(subnavs).show();
					    $(this).siblings().find(subnavs).hide();        // hide any subnavs that may be visible
					    $(this).siblings().removeClass('active');       // remove active state from wrapper to get change down arrow
					});
            $(gh).bind('mouseout', function () {
                that.hideDelay = setTimeout(function () {
                    $(subnavs).hide();
                    $(gh + ' .active').removeClass('active');
                }, 10);
            });

            $(subnavs)
				    .bind('mouseover', function () {
				        $(this).show();
				    });

            /* Bind Toggle All Brands link in header drop down */
            $(brandsLinks).bind('mouseover click', function () {
                HERSHEYS.Utility.slideAlternate({
                    'slideMe': '#gh_find_hersheys_sites .slideMe',
                    'howMuch': 700
                });
            });
        }
    };

})();
HERSHEYS.Carousel = (function () {
    /* Carousel Object - instantiate with optional selectors, but definite amount to slide */

    /* triggers: 
    'SlideStart' - passes handle to new item
    'SlideComplete' - passes handle to new item
    'AllItemsSeen' - passes handle to new item
    */

    var defaults = {
        carouselSelector: '.carousel',
        carouselItem: '.item',
        slideDistance: 348,
        navClass: 'carousel_pager',
        numVisible: 3,
        firstItem: 1,
        showTitle: false,
        animationLength: 400,
        disableAnimation: false,
        carouselContainer: 'ul',
        resetValues: false
    };

    var totalItems = 0,
		carousel = null,
		currentDisplay = 1,
		prevButton = $('<a href="#" id="carousel_prev" title="previous item">Previous</a>'),
		nextButton = $('<a href="#" id="carousel_next" title="next item">Next</a>'),
		numClicks = 0;

    var doAnimation = function (carousel, item, length) {




        $(carousel + " " + item + ":not(:eq(" + currentDisplay + ")) img, " + carousel + " li.flow_item:not(:eq(" + currentDisplay + ")) img").animate({ width: '70%', top: '15px' }, length);
        $(carousel + " " + item + ":not(:eq(" + currentDisplay + ")) .title, " + carousel + " li.flow_item:not(:eq(" + currentDisplay + ")) .title").hide();

        $(carousel + " " + item + ":eq(" + currentDisplay + ") img, " + carousel + " li#flow_item_" + (currentDisplay % totalItems) + " img").animate({ width: '100%', top: '0px' }, length, function () { $(HERSHEYS.Carousel).trigger("SlideComplete", $(this)); });
        $(carousel + " " + item + ":eq(" + currentDisplay + ") .title, " + carousel + " li#flow_item_" + (currentDisplay % totalItems) + " .title").fadeIn();

        $(carousel + " " + item + ":not(:eq(" + currentDisplay + ")), " + carousel + " li.flow_item:not(:eq(" + currentDisplay + "))").removeClass('active-carousel-item');
        $(carousel + " " + item + ":eq(" + currentDisplay + "), " + carousel + " li#flow_item_" + (currentDisplay % totalItems) + "").addClass('active-carousel-item');

        $(HERSHEYS.Carousel).trigger("SlideStart", carousel + " " + item + ":eq(" + currentDisplay + ") img");


    };

    var initReset = function (that) {
        currentDisplay = that.config.firstItem;
        carousel.find(that.config.carouselContainer).css('left', 0);
        carousel.find(that.config.carouselItem + " img, li.flow_item img").css({ width: '70%', top: '15px' });
    }

    return {
        sliding: false,
        numClicks: 0,
        animateSize: function () {
            if (this.config.disableAnimation) {
                var item = this.config.carouselItem;
                var carousel = this.config.carouselSelector;
                $(HERSHEYS.Carousel).trigger("SlideStart", carousel + " " + item + ":eq(" + currentDisplay + ") img");
                $(HERSHEYS.Carousel).trigger("SlideComplete", carousel + " " + item + ":eq(" + currentDisplay + ") img");
                return false;
            }
            doAnimation(this.config.carouselSelector, this.config.carouselItem, this.config.animationLength);

        },
        init: function (opts) {
            this.config = HERSHEYS.Utility.assignConfig('Carousel', defaults, opts);

            //Remove flow items
            $(this.config.carouselSelector).find('.flow_item').remove();

            carousel = $(this.config.carouselSelector);

            //Reset values if user requested
            if (this.config.resetValues) { initReset(this); }

            totalItems = carousel.find(this.config.carouselItem).length;
            if (!totalItems) { console.warn("Carousel: No items found for selector '" + this.config.carouselSelector + ' ' + this.config.carouselItem + "'"); }
            if (totalItems < 3) { $.error("Carousel: carousel must have at least 3 items, " + totalItems + " found!"); return false; }

            //Add navigation items
            carousel.before(prevButton, nextButton);

            if (this.config.showTitle) {
                $.each(carousel.find(this.config.carouselItem), function (i, v) {
                    if ($(v).find('.title').length < 1) {
                        $(v).append('<span class="title hidden">' + $(v).find('img').attr('alt') + '</span>');
                    }
                });
            }

            //Add flow items
            for (i = 0; i < this.config.numVisible; i++) {
                var item = $('<li class="flow_item" id="flow_item_' + i + '"></li>').html($(this.config.carouselItem + ":eq(" + i + ")").html());
                carousel.find(this.config.carouselContainer).append(item);
            }

            prevButton.addClass(this.config.navClass).unbind('click').bind('click', this, this.doPrevious);
            nextButton.addClass(this.config.navClass).unbind('click').bind('click', this, this.doNext);


            currentDisplay = this.config.firstItem;

            //Initialize sizes of carousel items
            this.animateSize();

        },
        doPrevious: function (e) {

            var that = e.data;

            that.numClicks++;

            if (that.numClicks == totalItems - 1 || that.numClicks == -1 * (totalItems - 1)) {
                $(HERSHEYS.Carousel).trigger("AllItemsSeen");
            }

            if (!that.sliding) {
                that.sliding = true;
                var scroller_pos = carousel.find(that.config.carouselContainer).position();
                //alert(currentDisplay);
                if (currentDisplay === that.config.firstItem) {
                    carousel.find(that.config.carouselContainer).css('left', (-(that.config.slideDistance * (totalItems))) + 'px');
                }
                if (currentDisplay <= 0) {
                    currentDisplay = totalItems - 1;
                } else {
                    currentDisplay--;
                }
                that.animateSize();
                carousel.find(that.config.carouselContainer).animate({ left: "+=" + that.config.slideDistance }, that.config.animationLength, function () {
                    that.sliding = false;

                });
            }
            return false;
        },
        doNext: function (e) {


            var that = e.data;

            that.numClicks++;

            if (that.numClicks == totalItems - 1) {
                $(HERSHEYS.Carousel).trigger("AllItemsSeen");
            }

            if (!that.sliding) {
                that.sliding = true;
                /*var scroller_pos = carousel.find(that.config.carouselContainer).position();
                var totalCarouselWidth = (-(that.config.slideDistance * (totalItems)));
                var scrollPosLeft = Math.round(scroller_pos.left);*/

                if (currentDisplay == that.config.firstItem) {
                    carousel.find(that.config.carouselContainer).css('left', 0);
                }
                if (currentDisplay >= totalItems - 1) {
                    currentDisplay = 0;
                } else {
                    currentDisplay++;
                }
                that.animateSize();
                carousel.find(that.config.carouselContainer).animate({ left: "-=" + that.config.slideDistance }, that.config.animationLength, function () {
                    that.sliding = false;
                });
            }
            return false;
        }

    };
})();
HERSHEYS.TabbedBrowsing = (function () {

    /* Triggers:
    'NewItemShowing' - passes clean title name of tab,
    'TabClick' - passes in reference to which was clicked,
    'DeepLinked' - passed index of the deep link item to show
    */

    /* 
    Usesage: 

    $(document).ready(function(){
    HERSHEYS.TabbedBrowsing.init();	
    });

    OR, to configure manually:

    $(document).ready(function(){
    HERSHEYS.TabbedBrowsing.init({
    navSelector : '.tabbedBrowsing .nav a',
    contentSelector : '.tabbedBrowsing .tabbedContent',
    nextSelector : '.tabbedNext'
    });	
    });

    - handle the showing and hiding
    - add "active" class to current item
    - will add location hash (the title of the nav with spaces turned to dashses),
    - upon page load will show the proper content and add nav.
    - sends all analytics info based on the title
    - if nextSelector or previousSelector are defined, they will be bound to handle forward and backwards navigation

    HTML structure looks like this:

    <div class="tabbedBrowsing"> 
    <ul class="nav">
    <li><a href="#" title="Human readable title of nav item">Nav 1</a></li>
    <li><a href="#" title="Nav 2 Name">Nav 2</a></li>
    <li><a href="#" title="Nav 3 Name">Nav 3</a></li>
    <li><a href="#" title="Nav 4 Name">Nav 4</a></li>
    </ul>
	
    <div class="tabbedContent">Content 1</div>
    <div class="tabbedContent">Content 2</div>
    <div class="tabbedContent">Content 3</div>
    <div class="tabbedContent">Content 4</div>
	
    </div>
    */


    var defaults = {

        wrapperSelector: '.tabbedBrowsing',

        navSelector: '.nav a',

        contentSelector: '.tabbedContent',

        nextSelector: false,

        previousSelector: false,

        ignoreShow: false,

        parentActive: false,

        autoRotate: false,

        transition: 'hide',

        tabContentClass: 'tab-content-active',

        expanded: false,

        callback: function () { }

    };

    function show(which) {

    }

    function doCallback(callbackFn) {
        if (typeof callbackFn == 'function') {
            callbackFn.call(this);
        }
    }

    var ItemsSeen = [];

    return {

        init: function (opts) {

            this.config = HERSHEYS.Utility.assignConfig('TabbedBrowsing', defaults, opts);
            this.navItems = $(this.config.navSelector);
            this.contentItems = $(this.config.contentSelector);
            this.jumpToIndex = 0;
            this.currentIndex = 0;

            var that = this;

            if (!this.config.ignoreShow) {
                if (!this.contentItems.length) { $.error("TabbedBrowsing: no content items found for selector '" + this.config.contentSelector + "'"); }
                this.contentItems.hide();
            }

            $.each(this.navItems, function (i, v) {

                var title = $(v).attr('title');

                if (!title) {
                    console.warn('No title provided for tabbedBrowsing element (index: ' + i + '). Please add one for analytics and location.hash');
                }

                if (title == HERSHEYS.Utility.titleHash(location.hash, 'fromHash')) {
                    that.jumpToIndex = i;
                    if (that.config.parentActive) {
                        $(v).parent().addClass('active');
                    } else {
                        $(v).addClass('active');
                    }
                }
            });

            ItemsSeen[this.jumpToIndex] = true;

            if (!this.navItems.length) { $.error("TabbedBrowsing: no nav items found for selector '" + this.config.navSelector + "'"); }

            if (this.config.nextSelector) {

                var nextButton = $(this.config.nextSelector);

                if (!nextButton.length) { $.error("TabbedBrowsing: no next button found for selector '" + this.config.nextSelector + "'"); }

                nextButton.bind('click', function () {
                    var next = 0;
                    $.each(that.navItems, function (i, v) {
                        if (that.config.parentActive) {
                            if ($(v).parent().hasClass('active') && i < that.navItems.length - 1) {
                                next = i + 1;
                            }
                        } else {
                            if ($(v).hasClass('active') && i < that.navItems.length - 1) {
                                next = i + 1;
                            }
                        }
                    });
                    $(that.navItems[next]).click();
                    return false;
                });

                this.nextbutton = nextButton;

            }

            if (this.config.previousSelector) {

                var previousButton = $(this.config.previousSelector);

                if (!previousButton.length) { $.error("TabbedBrowsing: no previous button found for selector '" + this.config.previousSelector + "'"); }

                previousButton.bind('click', function () {
                    var next = that.navItems.length - 1;
                    $.each(that.navItems, function (i, v) {
                        if (that.config.parentActive) {
                            if ($(v).parent().hasClass('active') && i !== 0) {
                                next = i - 1;
                            }
                        } else {
                            if ($(v).hasClass('active') && i !== 0) {
                                next = i - 1;
                            }
                        }
                    });
                    $(that.navItems[next]).click();
                    return false;
                });
            }

            this.navItems.bind('click', function () {

                $(HERSHEYS.TabbedBrowsing).trigger('TabClick', $(this));
                $(HERSHEYS.TabbedBrowsing).trigger('NewItemShowing', $(this));

                var cleanTitle = HERSHEYS.Utility.titleHash($(this).attr('title'));

                location.hash = '/' + cleanTitle;

                if (that.config.parentActive) {
                    that.navItems.parent().removeClass('active');
                    $(this).parent().addClass('active');
                } else {
                    that.navItems.removeClass('active');
                    $(this).addClass('active');
                }

                var index = $(this).index(that.config.navSelector);

                if (!that.config.ignoreShow) {
                    that.show(index, cleanTitle);
                }

                //Execute Click Callback Function
                if (that.config.callback) {
                    doCallback(that.config.callback);
                }

                if (that.config.expanded) {
                    $(that.config.navSelector).each(function (i) {
                        $(this).text($(this).text().replace('[-]', '[+]'));
                    }); 
                    var question = $(this).text();
                    question = question.replace('[+]', '[-]');


                    $(this).text(question);
                }

                return false;
            });

            if (this.config.autoRotate) {
                setInterval(function () {
                    that.nextbutton.click();
                }, this.config.autoRotate);
            }

            //	if (this.config.ignoreShow){
            $(this.navItems[this.jumpToIndex]).click();
            //	}

            $(HERSHEYS.TabbedBrowsing).trigger('DeepLinked', this.jumpToIndex);
        },
        show: function (index, cleanTitle) {

            ItemsSeen[index] = true;

            if (this.config.transition == 'fade') {
                this.contentItems.fadeOut(2000);
                $(this.contentItems[index]).fadeIn(2000);
            } else if (this.config.transition == 'slide') {

                var _this = this;

                $(this.contentItems[this.currentIndex]).slideUp(500, function () {
                    $(_this.contentItems[index]).slideDown(500);
                });
            } else {
                this.contentItems.hide();
                if (this.contentItems.hasClass(this.config.tabContentClass)) { this.contentItems.removeClass(this.config.tabContentClass); }
                $(this.contentItems[index]).show().addClass(this.config.tabContentClass);
            }

            this.currentIndex = index;

            if (ItemsSeen.length && ItemsSeen.length == this.navItems.length) {
                var seenAll = true;

                $.each(ItemsSeen, function (i, v) { if (!v) seenAll = false; });

                if (seenAll) {
                    $(HERSHEYS.TabbedBrowsing).trigger('AllItemsSeen');
                    ItemsSeen = false;
                }
            }
        }

    };

})();
HERSHEYS.Rotator = (function(){
	
	/* triggers: 
		'NewItem' - passes handle to new item
		'AllItemsSeen' - passes handle to new item
	*/
	
	var defaults = {
		
		wrapperSelector : '.rotator_wrapper',
		
		nextSelector : '.rotator_next',
		
		prevSelector : '.rotator_prev',
		
		contentSelector : '.rotator_content',
		
		autoRotate : false,
		
		fadeLength : 400
		
	};
	
	return {
		
		init : function(opts){
			this.config = HERSHEYS.Utility.assignConfig('Rotator', defaults, opts);
			
			var that = this;
			
			var nextButton = $(this.config.nextSelector);
						
			var prevButton = $(this.config.prevSelector);
			
			
			this.allItems = $(this.config.contentSelector);
			if (!this.allItems.length) {console.warn("Rotator: No content items found for selector '"+this.config.contentSelector+"'");}
			
			nextButton.bind('click', function(){that.next(); return false;});
			prevButton.bind('click', function(){that.prev(); return false;});
			
			if (this.config.autoRotate){
				setInterval(function(){
					that.next();
				}, this.config.autoRotate);
			}
					
		},
		
		next : function(e){
			
			var current = $(this.config.contentSelector).filter('.active:first');
			if (!current.length) {
				current = $(this.config.contentSelector).filter(':first');
			}

			var next = current.next(this.config.contentSelector);

			if (!next.length) {
				next = $(this.config.contentSelector).filter(':first');
				$(HERSHEYS.Rotator).trigger('AllItemsSeen', next);
			}

			$(this.config.contentSelector).removeClass('active').fadeOut(this.config.fadeLength);
			next.addClass('active').fadeIn(this.config.fadeLength);
			
			$(HERSHEYS.Rotator).trigger('NewItem', next);
			
		},
		
		prev : function(e){

			var current = $(this.config.contentSelector).filter('.active:first');
			var prev = current.prev(this.config.contentSelector);

			if (!prev.length) {
				prev = $(this.config.contentSelector).filter(':last');
			//	$(HERSHEYS.Rotator).trigger('AllItemsSeen', prev);
			}

			$(this.config.contentSelector).removeClass('active').hide();
			prev.addClass('active').show();

			$(HERSHEYS.Rotator).trigger('NewItem', prev);

		}
		
	};
	
	
	
})();
HERSHEYS.Promotions = (function(){
	
	var USE_WEBSERVICE = true;
	var MISSING_FIELDS_NOTICE = "Be sure all required fields are entered";
	var standardFancyBoxConfig = {
		'padding' : 0,	
		'opacity' : true,
		'scrolling' : 'no', 
		'titleShow' : false,
		'onStart': function() {
			if($('.pr_page').length) { $('#fancybox-wrap').addClass('pr_fancybox'); }
			if($('.pr_fancybox_noborder').length) { $('#fancybox-outer').addClass('pr_fancybox_noborder'); }		
		}
	};	
	var doWebserviceCall = function (config, data, location, customCallback) {
			
		wipeOutStatus();
		showAjaxLoading();
		
		$.ajax({
			type: "POST",
			data: $.toJSON({'config' : config, 'data' : data}),
			dataType: "json",
			url: location,
			contentType: "application/json; charset=utf-8",
			success: function(data){
					webserviceReturn = data.d;
					
					
					if (typeof customCallback == 'function'){
						customCallback(data.d);
						return false;
					}
					
					if (webserviceReturn.status){
						
						$('.pr_form:visible :input').each(function(){
							$(this).attr("value", '');	
							
							if ($('body').hasClass('pr_fancy_labels')){
								$(this).siblings('label').show().css('opacity', 1);
							}
						});				
						
						if (webserviceReturn.data){
							
							$.each(webserviceReturn.data, function(i,v){
								$('input[name=' + i + ']').attr('value', v);
								$('select[name=' + i + ']').attr('value', v);
								$('.pr_fancy_labels #pr_regstep_' + webserviceReturn.text + ' label').hide();
							});							
							
						}					
						
						if (webserviceReturn.isLoggedIn){
							$('.pr_member_controls').fadeIn();
						}else{
							$('.pr_member_controls').fadeOut();
						}
						
						switch(webserviceReturn.status){					
							case 1:
								/* This means the webservice was a success, do the next step of the process */
								doPromoRegStep(webserviceReturn.text);
							break;
							
							case 2:
								/* This means the webservice was a success, but don't continue on, show the message */
								$('.pr_status_messages').html(webserviceReturn.text);
								hideAjaxLoading();
							break;
							
						}								                
					}else{
						$('.pr_error_messages').html(webserviceReturn.text).fadeIn();
						hideAjaxLoading();
				    }
			},
			error: function(data){
				$('.pr_error_messages').html('There was an error submitting your request!').fadeIn();
				hideAjaxLoading();
			}
		});		
	};
	
	var doPromoRegStep = function(which){
		
		$(HERSHEYS.Promotions).trigger('DoingRegStep_'+which);
		
		wipeOutStatus();
		
		$('.pr_regstep_container').hide();
        $('#pr_regstep_' + which).show().css('visibility', 'hidden');	
		$('#pr_link_register').attr('title', which).click();
		
	};
	var wipeOutStatus = function(){
		$('.pr_error_messages').html('');
		$('.pr_status_messages').html('');
	};
	var getPromoID = function(){
		return typeof CURRENT_PROMOTION_ID == 'undefined' ? 'UNDEFINED_PROMOTION_ID' : CURRENT_PROMOTION_ID;	
	};
	var getInstantWinType = function(){
		return typeof CURRENT_INSTANTWIN_TYPE == 'undefined' ? '' : CURRENT_INSTANTWIN_TYPE
	}
	var showAjaxLoading = function(){
		$('#pr_loading_screen').fadeIn();
		$.fancybox.showActivity();
	};
	var hideAjaxLoading = function(){
		$('#pr_loading_screen').fadeOut();
		$.fancybox.hideActivity();
	};
	var validatePromoField = function(field){
		
		var value = $.trim(field.val());
		
		if (field.hasClass('required') && value == ""){
			return false;
		}
		
		if (field.hasClass('email') && !HERSHEYS.Utility.validate('email', value)){
			return false;
		}
		
		if (field.attr('matchfield') && value == ""){
			return false;
		}
		
		if (field.attr('matchfield') && !($('#' + field.attr('matchfield')).val() == field.val())){
		   return false;
		}
		
		return true;
		
	};
	
	var drawDevNav = function(){
	
		$('body').prepend('<div id="promoDebugNav" class="" style="padding: 10px; text-align: center; background-color: white; position: relative; z-index: 9999;"></div>');
	
		$('div[id^=pr_regstep_]').each(function(){
			
			var key = $(this).attr('id').split('pr_regstep_')[1];

			$('#promoDebugNav').append('<a style="color: black;" class="pr_regstep_link" rel="'+key+'" href="#">' +key+ '</a> &nbsp;&nbsp;&nbsp;');

		});
		
		$('#promoDebugNav').append('<hr>');
		
		$('.pr_modal_popup:not(a[href=#pr_register_init])').each(function(){
			
			var key = $(this).attr('href').split('#')[1];
			
			if (!$('#promoDebugNav a[href=#'+key+']').length)
				$('#promoDebugNav').append('<a style="color: black;" class="pr_modal_popup" href="#'+key+'">' +key+ '</a> &nbsp;&nbsp;')
		});
		
	};
	
	var ajaxBinds = function(){
		
		$('.pr_form input[type=submit]').unbind('click').bind('click', function(){
		
			
		    var config = {
				'promoKey': getPromoID(), 'instantWinType': getInstantWinType()
			};			
		    var data = {
			};

			var successfullSubmit = true;

			$(this).parents(".pr_form").find(':input:not([type=submit], [type="hidden"]), .pr_serialize').each(function(){
				
				if($(this).is(':visible') || $(this).hasClass("pr_serialize")){
							
					var value = $.trim($(this).val());
				
				    data[$(this).attr('name')] = $(this).val();
				
					if (validatePromoField($(this))){
						$(this).removeClass('error');
					}else{
						$(this).addClass('error');
						successfullSubmit = false;
					}
					
				}
			});
			
			if (successfullSubmit){
				if (USE_WEBSERVICE){
					var action = typeof data['action'] == 'undefined' ? "/services/Promotions.asmx/AgeCheck" : data['action'];
					
					action = $(this).parents(".pr_form").attr('action');
				
					if(!action){
						$.error('Every div class="pr_form" MUST have action="webserviceURL"');
					}else{
						doWebserviceCall(config, data, action);
					}
				}else{			
					doPromoRegStep($('.pr_regstep_container:visible').next().attr('id').split('pr_regstep_')[1]);
				}
			}else{
				wipeOutStatus();
				$('.pr_error_messages').html(MISSING_FIELDS_NOTICE).fadeIn();
				$('#pr_loading_screen').fadeOut();
				$.fancybox.hideActivity();
			}

			return false;

		});
		
		$('.pr_regstep_link').bind('click', function(){			
			HERSHEYS.Promotions.jumpToStep($(this).attr('rel'));
			return false;
		});
		
		$('#pr_refresh_captcha').bind('click', function(){
			$('.pr_form_captcha img').attr('src', '/services/captcha.aspx?' + Math.random() + '" />');
			return false;
		});
		
		$('.pr_form input[type!=submit]').unbind('keydown').bind('keydown', function(event){ 
			if(event.keyCode == 13){ 	
				$(this).parents('.pr_form').find(':submit').click(); 				
				return false; 			  
			}
		});
		
		//Toggle Confirm Field Handling
		$('input[matchfield]').each(function(n) { 
						
			var triggerId = $(this).attr('matchfield');   
			var target = $(this).parents('.pr_form_field');
			var changed = false;
			var originalVal = $("#" + triggerId).val();
			var currentVal;
			
			$("#" + triggerId).unbind('keyup').bind('keyup', function(){

				currentVal = $(this).val();
							
				if(currentVal != originalVal && !changed) {
					$(this).unbind('keyup');			
					target.addClass('pr_showconf');
					target.css('visibility','visible');
					changed = true;
				}
			});
		});
		
		$('.cancel_fancybox').bind('click', function(){		
			$.fancybox.close();
			return false;			
		});
		
		$('#pr_regstep_tell_a_friend .pr_button2 input').bind('click', function () {
			HERSHEYS.Analytics.trackPromotionEvent('tell_a_friend_submit_button', $(this));
		});
		$('#pr_share_it a').bind('click', function () {
			HERSHEYS.Analytics.trackPromotionEvent('share_it_links', $(this));
		});
		if ($.browser.msie && $.browser.version.substr(0,1)<7) {
			if (typeof DD_belatedPNG != 'undefined'){
				DD_belatedPNG.fix('div, a, img');
			}
		}
		
	};
			
	return {
		
		jumpToStep : function(which){		
			doPromoRegStep(which);			
		},
		webservice: function (config, data, serviceURL, callback) {
			doWebserviceCall(config, data, serviceURL, callback);
		},
		initBinds : function(){			
				
				var PR_JSCROLL_CONFIG = {		
					scrollbarWidth 		: typeof PR_JSCROLL_scrollbarWidth == 'undefined' || PR_JSCROLL_scrollbarWidth == "" ? 7 : PR_JSCROLL_scrollbarWidth,
					scrollbarMargin 	: typeof PR_JSCROLL_scrollbarMargin == 'undefined' || PR_JSCROLL_scrollbarMargin == "" ? 20 : PR_JSCROLL_scrollbarMargin,
					scrollbarShowArrows : typeof PR_JSCROLL_scrollbarShowArrows == 'undefined' || PR_JSCROLL_scrollbarShowArrows == "" ? false : PR_JSCROLL_scrollbarShowArrows
				};
				
				if (window.location.href.indexOf('?debug') != -1){
					drawDevNav();
				}

				var standardPopupConfig = standardFancyBoxConfig;

				standardPopupConfig.onComplete = function() {
			
					if($(".pr_jscroll").length > 0) { $("#fancybox-wrap .pr_jscroll").jScrollPane({scrollbarWidth: PR_JSCROLL_CONFIG['scrollbarWidth'], scrollbarMargin: PR_JSCROLL_CONFIG['scrollbarMargin'], showArrows: PR_JSCROLL_CONFIG['scrollbarShowArrows']}); }
					
					
					$('.pr_regstep_container').css('visibility', 'visible');
					$('#pr_loading_screen').fadeOut();										
				};
				
			
				
				ajaxBinds();
				
				$('.pr_modal_popup').fancybox(standardPopupConfig);
				
				$('.pr_modal_popup').bind('click', function(){
					HERSHEYS.Analytics.trackPromotionPage($(this).attr('title'));
				});
				
				/* Takeover function of registration link to handle webservice check first */
				$('#pr_nav_register .pr_modal_popup, .pr_registerinit_link').unbind('click').bind('click', function(){
					$.fancybox.showActivity();
					doWebserviceCall({ 'promoKey': getPromoID(), 'instantWinType': getInstantWinType() }, {}, "/services/Promotions.asmx/RegInit");
					return false;
				});
				
				/* Takeover function of tell a friend link to handle webservice check first */
				/* Notice here, I am passing in an optional function that will override the typical "doRegStep" functionality*/
				$('a[rel=tell_a_friend]').unbind('click').bind('click', function(){
					$.fancybox.showActivity();
					doWebserviceCall({ 'promoKey': getPromoID(), 'instantWinType': getInstantWinType() }, {}, "/services/Promotions.asmx/GetActiveProfileInfo", function (dataIn) {
						/* We have a logged in user, pre-populate the firstname and last name fields of tell a friend */
						if (dataIn.data){
							$('#tellfriend_firstname').attr('value', dataIn.data['FirstName']);
							$('#tellfriend_lastname').attr('value', dataIn.data['LastName']);
						}
						HERSHEYS.Promotions.jumpToStep('tell_a_friend');
						setTimeout(function(){
							$('#tellfriend_friendsname').focus();
						},500);
						
					});
					return false;
				});
				
				
				$('.pr_loggedin_edit_profile_link').bind('click', function(){
					doWebserviceCall({}, {}, "/services/Promotions.asmx/EditProfile");
				    return false;
				});

				$('.pr_loggedin_logout_link').bind('click', function(){
					doWebserviceCall({}, {}, "/services/Promotions.asmx/LogOut");
				    return false;
				});
					
		}
	};
})();

HERSHEYS.ShareThis = (function(){
	/* ShareThis Object - instantiate with optional selectors */
	
	/* triggers: 
		'shareWrapper' - passes element wrapper
		'sources' - passes which share sites to use (defaults to all)
		'viewAnimation' - passes which animation to use for share dropdown. Either 'slide' or 'fade'
	*/
	
	var defaults = {		
		shareWrapper : '.share_wrap',
		sources : {
				
				'Mixx' : 'mixx',
				'Del.icio.us' : 'del',
				'reddit' : 'reddit',
				'StumbleUpon' : 'stumble',
				'myspace' : 'myspace',
				'twitter' : 'twitter',
				'digg' : 'digg',
				'Facebook' : 'facebook'
			
			},
		viewAnimation : 'slide'
	};

	return {
		
		init : function(opts){
			
			this.config = HERSHEYS.Utility.assignConfig('ShareThis', defaults, opts);
			
			var timeout, 
				container = $(this.config.shareWrapper),
				link = $('<a class="share_button">Share</a>'),
				drop = $('<div class="drop_down" style="display:none;"></div>'),
				dropDown = container.find('div.drop_down'),
				that = this;
			
			if (!container.length){ $.error("ShareThis: no wrapper found for selector "+this.config.shareWrapper+"!");return false;}
			
			if(that.config.viewAnimation == 'fade'){
				link.toggle(
					function(){
						drop.fadeIn('fast');
						return false;
					},
					function(){
						drop.fadeOut('fast');
						return false;
					});
			}else{
				link.bind('click', function(){drop.slideToggle();return false;});
			}

			drop.mouseout(function(){
				timeout = setTimeout(function(){
					drop.fadeOut('fast');
				},1000);
			}).mouseover(function(){
				clearTimeout(timeout);
			});
			
			// url string variables
			var P_URL = $(document.location).attr('href');
			var P_TITLE = $('title').text();

			P_TITLE = escape(P_TITLE);
			P_URL = escape(P_URL);
			
			$.each(this.config.sources, function(i,v){
				
				drop.append('<li><a class="share-links" id="'+ v +'-link" href="'+ assignURLstrings(v) +'">'+ i +'</a></li>');
				
			});
			/*drop.find('li a').each(function(){
				var service = $(this).attr('href');
				$(this).attr({
					target: '_blank',
					href: assignURLstrings(service)
				});
			});*/
			
			drop.find("li").wrapAll("<ul></ul>");
			container.append(link);
			container.append(drop);
			
			// send to correct url
			function assignURLstrings(service) {

				if (service == 'del') { return 'http://del.icio.us/post?url=' + P_URL + '&amp;title=' + P_TITLE; }
				else if (service == 'digg') { return 'http://digg.com/submit?phase=2&amp;url=' + P_URL + '&amp;title=' + P_TITLE; }
				else if (service == 'facebook') { return 'http://www.facebook.com/share.php?u=' + P_URL + '&amp;t=' + P_TITLE; }
				else if (service == 'mixx') { return 'http://www.mixx.com/submit?page_url=' + P_URL + '&amp;title=' + P_TITLE; }
				else if (service == 'myspace') { return 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + P_URL + '&amp;t=' + P_TITLE; }
				else if (service == 'reddit') { return 'http://reddit.com/submit?url=' + P_URL + '&amp;title=' + P_TITLE; }
				else if (service == 'stumble') { return 'http://www.stumbleupon.com/submit?url=' + P_URL + '&amp;title=' + P_TITLE; }
				else if (service == 'twitter') { return 'http://www.twitter.com/home?status=' + P_URL; }
			}
			
		}

	};
})();

HERSHEYS.Video = {	
	'videoPlayer' : false,
	'doPlay' : function(source){
		    if (typeof PInstance == 'undefined') var PInstance = false;
			
            this.videoPlayer = this.videoPlayer || (PInstance && PInstance[0]) || false;
			
			if (!this.videoPlayer){
				return true;
			}
		
			var title 		= source.attr('title');
			var id 			= source.attr('id');
			var poster		= source.find('img').attr('src').replace('_thumb', '');
			var videoUrl 	= source.attr('filename');
			
			$('#video_title').html(title);

			this.videoPlayer.setTitle(title);
			this.videoPlayer.setID(id);
			this.videoPlayer.setFile(videoUrl+".mp4", false);
			this.videoPlayer.setFile(videoUrl+".ogv", false);
			this.videoPlayer.setPlay();
			this.videoPlayer.setActiveItem(1);
			this.videoPlayer.setPlayerPoster(poster);
			
	}
};
HERSHEYS.Services = (function(){
	
	var WEB_SERVICE_URL = '/celebrate/services/AjaxServices.ashx'; //TODO: timmy: are we using this global.js? or the one under hersheys.com?
	
	var doService = function(which, post, opts){	
		var success 		= opts['success'] || function(){};
		var failure 		= opts['failure'] || function(){};
		$.post(WEB_SERVICE_URL + '?method=' + which, post,  function(data){
		        if (data == 1){
					success();
				}else{
					failure();
				}
		});
	};
	
	return {		
		'login' : function(opts){
						
		    var username 		= opts['username'];
		    var password 		= opts['password'];
			var keepLoggedIn 	= opts['keepLoggedIn'] || 'false';

			var success 		= opts['success'] || function(){};
			var failure 		= opts['failure'] || function(){};
			
			if (!username || !password) {
				failure();
				return false;
			}		

			$.get(WEB_SERVICE_URL + '?method=login&handle='+ username + '&password=' + password + '&keeploggedin=' + keepLoggedIn, function(data){
			        if (data == 1){
						HERSHEYS.IsLoggedIn = true;
						success({'username' : username});
					}else{
						failure();
					}
			});
		},	
		'addToGroceryList' : function(opts){

			var rID 	= opts['recipeID'] || 'false';


			var success 		= opts['success'] || function(){};
			var failure 		= opts['failure'] || function(){};

			$.get(WEB_SERVICE_URL + '?method=addtogrocerylist&recipeid=' + rID, function(data){
				
			        if (data == 1){
			
						success({'recipeID' : rID});
			
					}else{
			
						failure();
			
					}
			});
			
		},
		'saveToRecipeBox' : function(opts){
			
			var rID 	= opts['recipeID'] || 'false';


			var success 		= opts['success'] || function(){};
			var failure 		= opts['failure'] || function(){};
			
			$.get(WEB_SERVICE_URL + '?method=savetorecipebox&recipeid=' + rID, function(data){
			        if (data == 1){
						success({'recipeID' : rID});
					}else{
						failure();
					}
			});
			
		},
		'reviewRecipe' : function(opts){
			
			var post = {
				
					recipeID 		: opts['recipeID'] 			|| 0,
					reviewtext 		: opts['reviewtext'] 		|| '',
					overallrating	: opts['overallrating'] 	|| 0,
					tasterating 	: opts['tasterating'] 		|| 0,
					difficultyrating : opts['difficultyrating'] || 0,
					apperancerating	: opts['apperancerating'] 	|| 0	
					
			};
			
			var success 		= opts['success'] || function(){};
			var failure 		= opts['failure'] || function(){};
			
			$.post(WEB_SERVICE_URL + '?method=submitreview', post, function(data){
				
			        if (data == 1){
						success({'ratingDetails' : post});
					}else{
						failure();
					}
			});
			
		},
		'agecheck' : function(opts){
			
				var post = {

						month 		: opts['month'] || 0,
						day 		: opts['day'] 	|| '',
						year		: opts['year'] 	|| 1
				};
				
				var success 		= opts['success'] || function(){};
				var failure 		= opts['failure'] || function(){};
				
				$.get(WEB_SERVICE_URL + '?method=agecheck&year='+post['year'] + '&day=' + post['day'] + '&month=' + post['month'], function(data){

				        if (data == 1){
							success();
						}else{
							failure();
						}
				});
			
		},
		'subscribe' : function(opts){
			
				var post = {

						email 		: opts['email'] || 0
				};
				
				var success 		= opts['success'] || function(){};
				var failure 		= opts['failure'] || function(){};
				
				$.get(WEB_SERVICE_URL + '?method=subscribe&newskitchen=y&email='+post['email'], function(data){

				        if (data == 1){
							success();
						}else{
							failure();
						}
				});
			
		},
		'inviteFriends' : function(opts){
			
				var post = {

						name 			: opts['name'] 		|| 0,
						email 			: opts['email'] 	|| 0,
						friendname		: opts['friendName'] || 0,
						friendemail		: opts['friendEmail'] || 0,
						comment			: opts['comment'] || 0
				};
				
				doService('invitefriend', post, opts);
			
		},
		'shareRecipe' : function(opts){
			
				var post = {
					
						name 			: opts['name'] 			|| 0,
						email 			: opts['email'] 		|| 0,
						friendname		: opts['friendname']	|| 0,
						friendemail		: opts['friendemail'] 	|| 0,
						recipeid		: opts['recipeid'] 		|| '',
						src				: opts['src'] 			|| 'empty'
				};
				
				doService('sharerecipe', post, opts);
			
		},
		'shareArticle' : function(opts){
			
				var post = {
					
						name 			: opts['name'] 			|| 0,
						email 			: opts['email'] 		|| 0,
						friendname		: opts['friendname']	|| 0,
						friendemail		: opts['friendemail'] 	|| 0,
						articlepath		: opts['articlepath'] 	|| ''
				};
				
				doService('sharearticle', post, opts);
			
		},
		'getReviews' : function(opts){
			
				var post = {

						page 		: opts['page'] || 0,
						numPerPage 	: opts['numPerPage'] || 0,
						orderby		: opts['orderby'] || 0
				};
				
				doService('getreviews', post, opts);
			
		},
		'getComments' : function(opts){
			
				var post = {
							page 		: opts['page'] || 0,
							numPerPage 	: opts['numPerPage'] || 0,
							orderby		: opts['orderby'] || 0
				};
								
				doService('getcomments', post, opts);
			
		}
	};
})();

HERSHEYS.Utility = {
    doPageInits: function (initializations) {
        $.each(initializations, function (i, v) {
            $(HERSHEYS).bind(i + '_loaded', function () {
                v();
            });
        });
    },
    validate: function (type, value) {

        switch (type) {

            case 'email':
                var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
                break;

        }

        if (value == '' || !filter.test(value)) {
            return false;
        }

        return true;
    },
    titleHash: function (input, type) {


        type = type || 'toHash';

        if (type == 'toHash') {
            return input.replace(/ /g, '-');
        } else {
            return input.replace(/-/g, ' ').replace('#/', '');
        }

    },
    assignConfig: function (namespace, defaults, opts) {
        /* 
        namespace:String - Object funtion that's calling it for error reporting
        defaults:Object - Key/Value of default config
        opts:Object -	  opts handed to initialation of namespace function

        return:Object - throws warning if opts contains keys that don't exist in defaults.
        */
        if (!opts) return defaults;

        var config = {};

        $.each(defaults, function (i, v) {
            config[i] = v;
        });

        $.each(opts, function (i, v) {
            if (typeof config[i] != 'undefined') {
                config[i] = v;
            } else {
                console.warn(namespace + ': "' + i + '" is not a valid configuration param!');
            }
        });

        return config;

    },
    throttle: function (functionIn, length) {
        // I'm going to start asking you to run a function over and over.
        // When I don't ask for it for X miliseconds, give it to me!
        length = length || 200;
        if (HERSHEYS.Utility.throttleTimeout) clearInterval(HERSHEYS.Utility.throttleTimeout);
        HERSHEYS.Utility.throttleTimeout = setTimeout(functionIn, length);
    },
    leavingNotice: function (configIn) {

        configIn = configIn || {};

        if (configIn['transparency']) {
            var transparency = configIn['transparency'];
        } else {
            transparency = { 'on': function () { return true; }, 'off': function () { return true; } };
        }

        var title = '<span style="color: black;">You are leaving: </span>' + configIn['title'] + '!';
        var body = configIn['body'] || 'You are about to leave for another site that may contain things for adults as well as kids. <strong>Do you want to leave or stay?</that>';
        var footer = configIn['footer'] || 'KIDS - <b>Listen Up</b> Before you give out any information about yourself online, <b>always</b> ask your parent or guardian first. Never give out your full name, address or phone number because strangers don\'t need to know that!';

        var markup = '<h2>' + title + '</h2>';
        markup += '<p>' + body + '</p><hr />';


        var content = $('<div>').addClass('inner').html(markup);

        var links = {
            go: $('<a class="override_leaving modal_button leaving_go" target="_blank"><span>I Want To Go There</span></a>'),
            stay: $('<a>').attr('href', '#').addClass('modal_button leaving_stay').html('<span>I Want To Stay On<br /><strong>' + configIn['title'] + '</strong></span>')
        }


        content.append(links.stay, links.go, $('<div class="cl"></div><hr /><div class="modal_wrapper"><p>' + footer + '</p></div>'));

        var dialogue = $('<div>').attr({ 'id': 'leavingNotice' }).addClass('modal_bg rall shadow').hide().html(content);


        links.stay.bind('click', function () {
            transparency.off();
            dialogue.fadeOut();
            return false;
        });
        links.go.bind('click', function () {
            transparency.off();
            dialogue.fadeOut();
        });


        $('body').append(dialogue);

        var whitelistArr = [
				".override_leaving"
				, "a[href*=hersheycompany]"
				, "a[href*=hersheys.com]"
				, "a[href*=hersheysstore]"
				, "a[href*=hersheyskitchens.com]"
				, "a[href*=web.servicebureau.net]"
				, "a[href*=jobs-hersheys.icims.com]"
				, "a[href*=hersheystrackandfield.com]"
				, "a[href*=hersheyschocolateworld.com]"
				, "a[href*=dagobachocolate.com]"
				, "a[href*=scharffenberger.com]"
				, "a[href*=regen2recover.com]"
				, "a[href*=hersheypa.com]"
				, "a[href*=themoderationnation.com]"
				, "a[href*=TheModerationNation.com]"
				, "a[href*=hersheysbliss.com]"
				, "a[href*=CelebrateWithHersheys.com]"
				, "a[href*=hersheys.icims.com]"
				, "a[href*=ice-breakers.com]"
				, "a[href*=reeses.com]"
				, "a[href*=hersheycookies.com]"
				, "a[href*=HersheyCookies.com]"
				, "a[href*=twizzlers.com]"
				, "a[href*=thehersheylegacy.com]"
				, "a[href*=hersheykitchens.com]"
				, "a[href*=HersheyCenterforHealthandNutrition.com]"
				, "a[href*=hersheycanada.com]"
				, "a[href*=hersheysjapan.com]"
				, "a[href*=mounds.com]"
				, "a[href*=almondjoy.com]"
				, "a[href*=kisses.com]"
				, "a[href*=hersheyskiss.com]"
				, "a[href*=kitkatusa.com]"
				, "a[href*=yorkpeppermintpattie.com]"
				, "a[href*=corporate-ir.net]"
                , "a[href*=hersheyschina.com]"
                , "a[href*=trackandfield.com]"
                , "a[href*=jsc.com]"
                , "a[href*=pipe33.com]"
			],
				promptBumper = [
				'a[href^=http://www.facebook.com]:not(".override_leaving")'
				, 'a[href^=http://www.mixx.com]:not(".override_leaving")'
				, 'a[href^=http://del.icio.us]:not(".override_leaving")'
				, 'a[href^=http://reddit.com]:not(".override_leaving")'
				, 'a[href^=http://www.stumbleupon.com]:not(".override_leaving")'
				, 'a[href^=http://www.myspace.com]:not(".override_leaving")'
				, 'a[href^=http://www.twitter.com]:not(".override_leaving")'
				, 'a[href^=http://digg.com]:not(".override_leaving")'
				, 'a[href^=http://facebook.com]:not(".override_leaving")'
			],
				whitelistArrStr = whitelistArr.join(", "),
				promptBumperStr = promptBumper.join(", ");

        //whitelist
        $('a[href*=http]:not("' + whitelistArrStr + '"),' + promptBumperStr + '').live('click', function () {

            transparency.on();
            links.go.attr('href', $(this).attr('href'));

            var left = (($(window).width() - dialogue.width()) / 2);
            var top = (($(window).height() - dialogue.height()) / 2);

            dialogue.css({ 'left': left, 'top': top }).fadeIn();
            return false;
        });
    },
    slideAlternate: function (opts) {
        /* Make a div twice as long as it's container and call 
        slideAlternate({
        'slideMe' : '#slideMeSelectorString',
        'howMuch' : int for the size of your container, or amount you'd like to go back and forth.
        });
        */
        opts = opts || {};
        if (!(opts['slideMe'] && opts['howMuch'])) {
            console.warn('Missing params in Utility.slideAlternate');
            return false;
        }

        var slide = $(opts['slideMe']);

        if (slide.css('left') == -1 * opts['howMuch'] + 'px') {
            slide.animate({ 'left': '0px' }, 1000, 'swing');
        } else {
            slide.animate({ 'left': -1 * opts['howMuch'] + 'px' }, 1000, 'swing');
        }
    },
    /* Function for automatically showing active states. Simply needs to be executed at page load */
    fakeActiveNav: function (configIn) {

        var config = {
            'wrapperSelector': configIn['wrapperSelector'] || 'div#nav a, .nav a',
            'activeClass': configIn['activeClass'] || 'active',
            'activeSelector': configIn['activeSelector'] || 'parent'
        };



        var currentPage = HERSHEYS.CURRENT_PAGE;

        $(config['wrapperSelector']).each(function () {

            var thisLink = $(this).attr('href').split('.aspx')[0].replace(/\//g, '');


            if (currentPage.indexOf(thisLink) != -1) {

                if (config['activeSelector'] == 'parent') {
                    $(this).parent().addClass(config['activeClass']);
                } else if (config['activeSelector'] == 'parent parent') {
                    $(this).parent().parent().addClass(config['activeClass']);
                } else if (config['activeSelector'] == 'this parent') {
                    $(this).parent().parent().parent().addClass(config['activeClass']);
                    $(this).addClass(config['activeClass']);
                } else {
                    $(this).addClass(config['activeClass']);
                }

            }

        });

        $(config['wrapperSelector']).bind('click', function () {
            if (config['activeSelector'] == 'parent') {
                $(config['wrapperSelector']).parent().removeClass(config['activeClass']);
                $(this).parent().addClass(config['activeClass']);
            } else {
                $(config['wrapperSelector']).removeClass(config['activeClass']);
                $(this).addClass(config['activeClass']);
            }
        });

    },
    inputPlaceholder: function () {

        $('input[placeholder]').each(function () {
            var placeholder = $(this).attr('placeholder');
            var value = $.trim($(this).attr('value'));

            if (value == "") {
                $(this).attr('value', placeholder);
            }

            $(this).bind('focus', function () {
                if ($(this).attr('value') == $(this).attr('placeholder')) {
                    $(this).attr('value', '');
                }
            }).bind('blur', function () {
                if ($.trim($(this).attr('value')) == '') {
                    $(this).attr('value', $(this).attr('placeholder'));
                }
            });
        });
    },
    stealSearchButton: function (opts) {

        //alert(HERSHEYS.CURRENT_SEASON); //stealSearchButton function is called by dot_com.js, but I don't think we're using that file for celebrate seasons...
        //TODO: timmy: if this function is being called, it could affect the path to searchresults.aspx sine we have that page under each season-specific directory (e.g. halloween)

        var site = opts['site'] || '';
        if (site !== '')
            site = site + '/';

        /* Steal Search button */
        $('.searchTextBox').bind('keypress', function (e) {
            //if entered is pressed in text input
            if (e.keyCode == "13") {
                window.location = '/' + site + 'searchresults.aspx?KW=' + $('.searchTextBox').attr('value') + '&site=' + site.split('/')[0];
                return false;
            }
        });
        $('#search_wrap .submit, .search_wrap .submit, .search_wrap .search, .search_wrap #search, .search_submit').bind('click', function (e) {
            window.location = '/' + site + 'searchresults.aspx?KW=' + $('.searchTextBox').attr('value') + '&site=' + site.split('/')[0];
            return false;
        });
    },
    /* Transparency object - instantiation adds it to body, hide and show methods available. */
    Transparency: function (config) {
        config = config || {};

        /* 	Optional config params:
        background-color, opacity, background.
        Usage: instantiate, run the init() to build, style and place HIDDEN transparency in body
        Then, call on(), off().
        */
        var hideMethod = config['hideMethod'] || 'fadeOut';
        var fadeLength = config['fadeLength'] || 400;

        this.namespace = config['namespace'] || '_trans_div_';
        this.css = {
            'background': config['background-image'] || 'none',
            'background-color': config['background-color'] || '#eeeeee',
            'opacity': config['opacity'] || '.4',

            'position': 'fixed',
            'height': '100%',
            'width': '100%',
            'display': 'none',
            'top': 0, 'left': 0
        };

        this.isHidden = true;

        this.init = function () {
            this.element = $('<div>').attr('id', '#' + this.namespace).css(this.css);

            var _this = this;
            this.element.bind('click', function () {
                _this.onClick();
            });
            $('body').append(this.element);
        };

        this.addCallBack = function (f) {
            if (typeof f != 'function') $.error('Expecting function, given: "' + typeof (f) + '"');

            alert('function given');
        }

        this.on = function (fadeLength) {

            if (this.element && this.isHidden) {
                this.element.fadeTo(fadeLength, this.css.opacity);
            }
        };
        this.off = function (fadeLength) {
            if (this.element) {
                this.element.fadeOut(fadeLength);
            }
        };

        this.onClick = function (f) {
            f = f || function () {

            };

            f();
        };

    }
};

//if (typeof console != 'object'){var console = { error : function(){return true}, warn : function(){return true;}};}
