$(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();
		
		
		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();
				}
			});
			
			/* Promotion Popup Binds */
					var fancyconfig = {
						'padding' : 0,	
						'opacity' : true,
						'transitionIn' : 'elastic',
						'transitionOut' : 'elastic',
						'scrolling' : 'no', 
						'onStart': function() {
							if($('.pr_page').length) { $('#fancybox-wrap').addClass('pr_fancybox'); }
							if($('.pr_fancybox_noborder').length) { $('#fancybox-outer').addClass('pr_fancybox_noborder'); }
						}
					};
					var standardPopupConfig = fancyconfig;

					standardPopupConfig.onComplete = function() {
						var popupMainWrapper = $("#fancybox-wrap #pr_rules .pr_jscroll");
					 	if($(".pr_hallfame #fancybox-wrap #pr_rules .pr_jscroll").length > 0) { popupMainWrapper.jScrollPane({scrollbarWidth: 7, scrollbarMargin: 20}); }
						if($(".pr_tropicsweep #fancybox-wrap #pr_rules .pr_jscroll").length > 0) { popupMainWrapper.jScrollPane({scrollbarWidth: 18, scrollbarMargin: 20, showArrows: true}); }
					};
					$('.pr_modal_popup').fancybox(standardPopupConfig);

					var registerLinkConfig = fancyconfig;

					registerLinkConfig.onStart =  function() {
						if($('.pr_page').length) { $('#fancybox-wrap').addClass('pr_fancybox'); }
						if($('.pr_fancybox_noborder').length) { $('#fancybox-outer').addClass('pr_fancybox_noborder'); }
					};
					registerLinkConfig.onComplete = function() {
						/* insert webservice call here */
						var webserviceReturn = {
							'status' : 1,
							'text' : 'dob'
						};
						if (webserviceReturn.status){
			                $('.pr_form_container').hide();
			                $('#pr_form_' + webserviceReturn.text).show();
							setTimeout(function(){$('#pr_link_register').click(); }, 200);
						}else{
					         alert("there has been a problem!");
					    }
					};
					$('#pr_nav_register .pr_modal_popup').unbind().fancybox(registerLinkConfig);
			
		

			$('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%';
				}
			}
		});
	}
});

var HERSHEYS = {};

HERSHEYS.CURRENT_PAGE = (function(pageIn){
	
	// ----------------------------------------- LIVE
	var split = pageIn.split('.com/');

	// ----------------------------------------- QA
	if (split.length != 2) { 
		split = pageIn.split('.qa.jplhosting.net/');
	}

	// ----------------------------------------- DEV
	if (split.length != 2) { 
		split = pageIn.split('.dev/');
	}

	// ----------------------------------------- LOCAL
	if (split.length != 2) { 
		split = pageIn.split('.test/');
	}
	
	if (split.length != 2){ return 'ERROR';}
	
	return split[1].split('#')[0].split('?')[0].split('.aspx')[0] || '/';

})(window.location.href);

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
	};

	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){
	
		$(HERSHEYS.Carousel).trigger("SlideStart", carousel+" "+item+":eq("+currentDisplay+") img");
		
		
		
		$(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();		

	};

	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);
			

			carousel = $(this.config.carouselSelector);				
			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){
					$(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('ul').append(item);
			}
			
			prevButton.addClass(this.config.navClass).bind('click', this, this.doPrevious);
			nextButton.addClass(this.config.navClass).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('ul').position();
				if (Math.round(scroller_pos.left) === 0){
					carousel.find('ul').css('left', (-(that.config.slideDistance*(totalItems)))+'px');
				}
				if(currentDisplay <= 0){
					currentDisplay = totalItems-1;
				} else {
					currentDisplay--;
				}
				that.animateSize();
				carousel.find('ul').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('ul').position();
				var totalCarouselWidth = (-(that.config.slideDistance*(totalItems)));
				
				//IE hack, if slide distance is greater than 250px, 
				//add one more pixel to overall carousel length
				if(that.config.slideDistance >= 250){
					if($.browser.msie && $.browser.version < 8){
						totalCarouselWidth = totalCarouselWidth+1;
					}
				}
				//alert(Math.round(scroller_pos.left)+" end:"+totalCarouselWidth);
				if (Math.round(scroller_pos.left) == totalCarouselWidth){
					carousel.find('ul').css('left', 0);
				}
				if(currentDisplay >= totalItems-1){
					currentDisplay = 0;
				} else {
					currentDisplay++;
				}
				that.animateSize();
				carousel.find('ul').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'
		
	};
	
	function show(which){
		
	}
	
	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);
				}
				
				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();
					$(this.contentItems[index]).show();
			}
			
			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.Analytics = (function () {

    var areDebugging = false;
    var showAllEvents = false;//$.cookie('HERSHEYS_showAllEvents');


    /* GLOBAL DROPDOWN AND FOOTER TRACKING */

    var GLOBAL_CAMPAIGN_TRACKING = {

        globalShareCodes: {

            /* ALL ON CLICK */
            'mixx-link' 	: 'HER1387',
            'del-link' 		: 'HER1388',
            'reddit-link' 	: 'HER1389',
            'stumble-link' 	: 'HER1390',
            'myspace-link' 	: 'HER1391',
            'twitterk-link' : 'HER1392',
            'digg-link' 	: 'HER1393',
            'facebook-link' : 'HER1394'

        }

    };


    var callTracking = function (msg) {
        if (showAllEvents) console.log('Analytics: ' + msg);
    };

    $(HERSHEYS.Carousel).bind('AllItemsSeen', function (e, data) {
        callTracking('Carousel AllItemsSeen Being Called');
    });
    $(HERSHEYS.Carousel).bind('SlideStart', function (e, data) {
        callTracking('Carousel SlideStart Being Called - "' + $(data).attr('alt') + '"');
    });
    $(HERSHEYS.TabbedBrowsing).bind('NewItemShowing', function (e, data) {
        callTracking('TabbedBrowsing NewItemShowing Being Called - "' + $(data).attr('title') + '"');
    });
    $(HERSHEYS.TabbedBrowsing).bind('AllItemsSeen', function () {
        callTracking('TabbedBrowsing AllItemsSeen Being Called');
    });


    var trackInternalCampaign = function (pTrackCode) {

        var s = s_gi(s_account);
        s.templtv = s.linkTrackVars;          /*Saving the original state of the variables*/
        s.templte = s.linkTrackEvents;         /*Saving the original state of the variables*/
        s.linkTrackVars = "events,eVar2";      /*Defining the list of variables that will be sent in the server call*/
        s.eVar2 = pTrackCode + ":" + s.pageName; // Tracking code will be provided by Kendra
        s.linkTrackEvents = "event9";
        s.events = "event9";              //Passing in the value into s.events

        s.tl(true, 'o', 'internal campaign clicks');   //Server call

        if (s.templtv) {
            s.linkTrackVars = s.templtv;    //reassigning the variables to the original state
        }

        if (s.templte) {
            s.linkTrackEvents = s.templte;   //reassigning the variables to the original state
        }
    };

    var shareTracking = function (pTrackCode) {
	
        var s = s_gi(s_account);
        s.templtv = s.linkTrackVars; /*Saving the original state of the variables*/
        s.templte = s.linkTrackEvents; /*Saving the original state of the variables*/
        s.linkTrackVars = "events,eVar2"; /*Defining the list of variables that will be sent in the server call*/
        s.eVar2 = pTrackCode + ":" + s.pageName;
        s.linkTrackEvents = "event7,event9";
        s.events = "event7,event9"; 	//Passing the value into s.events

        s.tl(true, 'o', 'clicks to share widget');   //Server call	

        if (s.templtv) {
            s.linkTrackVars = s.templtv;     //reassigning the variables to the original state
        }
        if (s.templte) {
            s.linkTrackEvents = s.templte;   //reassigning the variables to the original state
        }

    };

    var addToURL = function (href, code) {
		
	 	if (href.indexOf('?') == -1) {
			if (href.indexOf('#') != -1) {
				return href.replace('#', '?' + code + '#');
			}else{
            	return href + '?' + code;
			}
        } else {
			if (href.indexOf('#') != -1) {
				return href.replace('#', '&' + code + '#');
			}else{
            	return href + '&' + code;
			}
        }
        return;
    };

    var CONFIG = false;

    return {
        debug: function () { areDebugging = true; console.log('Debugging enabled.'); },
        showAllEvents: function () {
            $.cookie('HERSHEYS_showAllEvents', 1);
            showAllEvents = true;
            console.log('Now showing everything that can be bound to.');
        },
        /*
        devAccount = 'devaccount',
        liveAccount = 'liveaccount',
	
        appendCampaignCodes = {
        'HG_ID=HER123' : 'a#homepage_link1',
        'HG_ID=HER456' : 'a#homepage_link2',
        'HG_ID=HER789' : 'a#homepage_link3'	
        },
	
        clickCampaignCodes = {
        'pie123' : 'a#homepage_link1',
        'pie456' : 'a#homepage_link2',
        'pie789' : 'a#homepage_link3'	
        }
        */
        init: function (config) {

            CONFIG = config;

            $(document).ready(function () {
                $.each(CONFIG.clickCampaignCodes, function (code, selector) {
	
                    var link = $(selector);

                    if (link) {
                        link.bind('click', function () {
                            trackInternalCampaign(code);
                        });
                    }
                });

                $.each(CONFIG.appendCampaignCodes, function (i, v) {
                    var link = $(v);

                    if (link.length) {

                        var href = link.attr("href");

                        if (!href) {
                            if (showAllEvents) console.log('Analytics: Bad campaign code request: ' + v);
                        } else {
                            link.attr('href', addToURL(href, i));
                        }
                    }

                });

				$('.share-links').live('click', function(){
					
					var code = GLOBAL_CAMPAIGN_TRACKING.globalShareCodes[$(this).attr('id')];
					if (code) HERSHEYS.Analytics.doShareTracking(code);
				});
				
				/* To Track Recipe Prints */     
				    $('a.print_recipe').live('click', function () {
						if (!OMNITURE_RECIPE_ID) return true;
						
				        s.events = s.linkTrackEvents = "event5";
				        s.eVar10 = s.prop30 = OMNITURE_RECIPE_ID;
				        s.products = ";" + OMNITURE_RECIPE_ID;
				        s.linkTrackVars = "events,eVar10,products";
				        s.tl(this, 'o', 'recipe print clicks');
				    });
				

                $('.gh a, .gf a').each(function () {
                    var code = $(this).attr('omni');
                    if (code) {
                        var wholeCode = 'ICID=' + code;
                        var href = $(this).attr('href');

                        $(this).attr('href', addToURL(href, wholeCode));
                    }
                });

                $("a#estore_header").bind('click', function () {
                    trackInternalCampaign('ICID=HER1361');
                });
				$("a#gh_retailer_dropdown").bind('click', function () {
                    trackInternalCampaign('ICID=HER1344');
                });
				$("a#gh_hersheypa").bind('click', function () {
                    trackInternalCampaign('ICID=HER1343');
                });


                $(HERSHEYS.Video).bind('Milestone', function (e, data) {

                    switch (data.percent) {

						case 0:
                            HERSHEYS.Analytics.trackVideo(data.title, 'start');
                            break;

						case 100:
                            HERSHEYS.Analytics.trackVideo(data.title, 'complete');
                            break;
                    }

                });

            });

            return this;

        },
		doShareTracking : function(code){
			shareTracking(code);
		},
        getAccount: function () {
			
            if (href.indexOf("www.hersheys.com") != -1 || href.indexOf("www.thehersheycompany.com") != -1 || href.indexOf("www.m.hersheys.com") != -1 || href.indexOf("www.m.thehersheycompany.com") != -1) {
                return CONFIG.liveAccount;
            }
            else {
                return CONFIG.devAccount;
            }

        },
        getBusinessUnit: function () {

            return CONFIG.businessUnit;

        },
        getDomain: function () {

            return CONFIG.domain;

        },

        getTempLinkInternalFilters: function () {

            return CONFIG.tempLinkInternalFilters;
        },

        doProductView: function (productName) {

            s.pageName = s.prop3 = s.prop4 = s.prop1 = 'hersheys:' + this.getBusinessUnit().toLowerCase() + ':products:product detail';
            s.products = ';' + productName.replace(/-/g, ' ');
            s.events = "event3,prodView";
            s.prop2 = this.getDomain().toLowerCase() + ':' + this.getBusinessUnit().toLowerCase() + ':products';
            s.channel = 'hersheys:' + this.getBusinessUnit().toLowerCase() + ':products';
            s.t();

        },

        doPageView: function (channel, pageName) {

            s.pageName = this.getDomain().toLowerCase() + ':' + this.getBusinessUnit().toLowerCase() + ':' + channel.toLowerCase().replace(/-/g, ' ') + ':' + pageName.toLowerCase().replace(/-/g, ' ');
            s.channel = s.prop2 = this.getDomain().toLowerCase() + ':' + this.getBusinessUnit().toLowerCase() + ':' + channel.toLowerCase().replace(/-/g, ' ');
            s.prop3 = s.prop4 = s.prop1 = s.pageName.toLowerCase().replace(/-/g, ' ');
            s.t();

        },

        doPrintAdView: function (channel, pageName) {

            s.pageName = this.getDomain().toLowerCase() + ':' + this.getBusinessUnit().toLowerCase() + ':' + channel.toLowerCase().replace(/-/g, ' ') + ':' + pageName.toLowerCase().replace(/-/g, ' ');
            s.channel = s.prop2 = this.getDomain().toLowerCase() + ':' + this.getBusinessUnit().toLowerCase() + ':' + channel.toLowerCase().replace(/-/g, ' ');
            s.prop3 = s.prop4 = s.prop1 = s.pageName.toLowerCase().replace(/-/g, ' ');
            s.prop26 = s.eVar36 = this.getBusinessUnit().toLowerCase() + ':PrintAdView:' + pageName.toLowerCase().replace(/-/g, ' ');
            s.events = 'event15,event16';
            s.t();

        },

        trackVideo: function (videoID, action) {
			
			if (typeof s_gi != 'function') return false;
			
            /* We must split the video id by an underscore - the first half should be the type, the second half should be the video name */

            var videoSplit = videoID.split('_');

            var videoCategory = videoSplit.length == 2 ? videoSplit[0].replace(/-/g, ' ') : 'Unclassified';
            var videoName = videoSplit.length == 2 ? videoSplit[1].replace(/-/g, ' ') : videoID;

            var s = s_gi(s_account);
            s.templtv = s.linkTrackVars; /*Saving the original state of the variables*/
            s.templte = s.linkTrackEvents; /*Saving the original state of the variables*/
            s.linkTrackVars = "events,eVar36"; /*Defining the list of variables that will be sent in the server call*/
            s.eVar36 = s.prop26 = this.getBusinessUnit().toLowerCase() + ':' + videoCategory + ':' + videoName;

            switch (action) {
                case "start":
                    s.linkTrackEvents = "event15";
                    s.events = "event15"; 	//Passing the value into s.events
                    break;
                case 'complete':
                    s.linkTrackEvents = "event16";
                    s.events = "event16"; 	//Passing the value into s.events
                    break;
            }

            s.tl(true, 'o', s.eVar36 + ' ' + action);   //Server call	

            if (s.templtv) {
                s.linkTrackVars = s.templtv;     //reassigning the variables to the original state
            }
            if (s.templte) {
                s.linkTrackEvents = s.templte;   //reassigning the variables to the original state
            }
        },

		trackRecipeView : function(opts){
			
			var contextType = "Category not found";
			var contextValue = "Category not found";
			
			if (window.location.href.indexOf('/recipes-by-type/') != -1){		
				contextType = 'Type';
				var split = window.location.href.split('/');
				contextValue = split[split.length - 1].split('.aspx')[0];			
			}else if (window.location.href.indexOf('/recipes-by-occasion/') != -1){
				contextType = 'Occasion';
				var split = window.location.href.split('/');
				contextValue = split[split.length - 1].split('.aspx')[0];
			}else if (window.location.href.indexOf('searchresults.aspx') != -1){
					contextType = 'Search';				
					var split = window.location.href.split('KW=');
					if (split.length > 1)
						contextValue = split[1];
			}				
			
			s.pageName = this.getBusinessUnit().replace(/ /g,'').toLowerCase() + ':recipes:detail';
		  	s.products =" ;" + opts['recipeID'] + ";;;;;eVar9=" + contextType + "|eVar4=" + contextValue + ",;" + opts['associatedProducts'].replace(/,/g,";;;event22=1,;") + ";;;event22=1";
		  	s.events = "event4,event22";
		    s.channel = s.prop2 = this.getBusinessUnit().replace(/ /g,'').toLowerCase() + ':recipes';
			s.prop3 = this.getBusinessUnit().replace(/ /g,'').toLowerCase() + ':recipes:' + contextType.toLowerCase();
			s.prop4 = s.prop1 = this.getBusinessUnit().replace(/ /g,'').toLowerCase() + 'recipes:'+ contextType.toLowerCase() + ':' + contextValue.toLowerCase();
			s.prop30 = s.eVar10 = opts['recipeID'];
		
        	s.t();
			
		},
		
		IsLoggedIn : function(){
			return HERSHEYS.IsLoggedIn;
		}

    };

})();

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.stealSearchButton = function(opts){
	
	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;
	});
};

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 = '/latino/kitchens/AjaxServices.ashx';
	
	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);
			
		},
		'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]"
			],
				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:text[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'));
					}
				});
			});
		},
		
		
		/* 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;}};}
