/* PAGE-SPECIFIC Initializations */
var initializations = {

    '/': function () {
        HERSHEYS.dot_com.Flash.homepageBar();
    },
    'our-story': function () {

        var altContent = function () {

            upSpeed = 300;
            downSpeed = 100;
            selected = null;
            $("#story_nav li").each(function (i) {
                $(this).find("a").hover(function () {
                    if (selected == $(this).attr("title"))
                        return false;
                    $("#popup_" + (i + 1)).stop(true, false).animate({ height: "340px" }, upSpeed).animate({ height: "330px" }, downSpeed);
                }, function () {
                    if (selected == $(this).attr("title"))
                        return false;
                    $("#popup_" + (i + 1)).stop(true, false).animate({ height: "340px" }, downSpeed).animate({ height: "0" }, upSpeed);
                });
                $(this).find("a").click(function () {
                    if ($(this).attr("title") == "Hershey Timeline") {
                        $(".simply-scroll-container").show();
                        HERSHEYS.Dot_Com.trackStory("timeline");
                    } else {
                        $(".simply-scroll-container").hide();
                        HERSHEYS.Dot_Com.trackStory($(this).attr("title").toLowerCase());
                    }
                    if (selected == $(this).attr("title"))
                        return false;
                    if (selected != null)
                        $("#popup_" + (i + 1)).stop(true, false).animate({ height: "340px" }, downSpeed).animate({ height: "0" }, upSpeed);
                    selected = $(this).attr("title");
                });
            });
            $("#back").click(function () {
                $(this).parent().animate({ scrollTop: "0" }, 500);
                return false;
            });
            $("#story_4").scroll(function () {
                offset = $(this).scrollTop();
                $(".clear").text(offset);
                if (offset > 1170)
                    $("#back").fadeIn(500);
                else {
                    $("#back").fadeOut(200);
                }
            });

            $(".vscroller").simplyScroll({
                className: 'vert',
                horizontal: false,
                frameRate: 20,
                speed: 10
            });

            HERSHEYS.TabbedBrowsing.init({
                navSelector: '#story_nav a',
                contentSelector: '.story_content'
            });
        };

        HERSHEYS.dot_com.Flash.story(altContent);

    },

    "promotions-and-celebrations/smores": function () {

        HERSHEYS.Carousel.init({
            'slideDistance': 160,
            'numVisible': 5,
            'firstItem': 2,
            'showTitle': true
        });

    },
    "promotions-and-celebrations/pure-smores": function () {

        HERSHEYS.TabbedBrowsing.init({
            navSelector: '.tabnav .tabitem',
            contentSelector: '.carousel ul',
            callback: function () {
                HERSHEYS.Carousel.init({
                    'carouselItem': '.tab-content-active li',
                    'slideDistance': 160,
                    'numVisible': 5,
                    'firstItem': 2,
                    'showTitle': true,
                    'carouselContainer': 'ul.tab-content-active',
                    'resetValues': true
                });
            }
        });



        $('.carousel a').bind('click', function () {

            if (!$(this).parent().hasClass('active-carousel-item')) return false;

            /* wipe out omniture recipe id each time */
            if (typeof OMNITURE_RECIPE_ID != 'undefined') OMNITURE_RECIPE_ID = null;

            var data = $(this).attr('dataurl');

            var section = $('.tabnav li.active').attr('title').toLowerCase();
            var page = $(this).siblings('.title').html().toLowerCase();

            HERSHEYS.Analytics.doPureSmoresView(section, page);

            if (data) {
                $('.content_top').addClass('smoresLoading');
            }

            $('#smorescontentpanel').load(data, function () {

                setTimeout(function () { $('.content_top').removeClass('smoresLoading'); }, 400);

                $('.pane-title').bind('click', function () {
                    $('.pane').removeClass('pane-active');
                    $(this).parent().addClass('pane-active');
                    return false;
                });

                $('.button_print').bind('click', function () {
	
					HERSHEYS.Analytics.doAssetInteraction('PDF', $(this).attr("assetname"));
					
                    window.print(); return false;
                });


				$('.download').bind('click', function () {
					HERSHEYS.Analytics.doAssetInteraction('PDF', $(this).attr("assetname"));
                });


				$('ul.prep-methods a').bind('mouseover', function(){
				    $('ul.prep-methods li').removeClass('active');
				    $(this).parents('li').addClass('active');
				}).bind('mouseleave', function(){
				    $('ul.prep-methods li').removeClass('active');
				});

            });

            return false;
        });


        $(HERSHEYS.Carousel).bind("SlideStart", function (e, data) {
            setTimeout(function () {
                $(data).parents('a').click();
            }, 500);
        });




        $('.tabnav li.item4 a, #buildYourOwn').bind('click', function () {

            $('body').addClass('buildYourOwnSmore');

            $('.content_bottom').css('visibility', 'hidden');

            $('#content').append("<div id='flash_wrap_outer' style='position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;'><div id='flash_wrap'></div></div>");

            var flashvars = {};
            var attributes = {};
            var param = {};

            flashvars.wmode = 'transparent';
            flashvars.account = HERSHEYS.Analytics.getAccount();
            param.wmode = 'transparent';
            param.base = '.';

            swfobject.embedSWF("/assets/swf/dot_com/smores/preloader.swf",
								"flash_wrap", "830", "550", "10.0.0",
								"/assets/swf/expressInstall.swf", flashvars, param, attributes, function (e) {
								    if (e.success) {

								    } else {
								        alert('You need flash to build your own S\'More!');
								        $('body').removeClas('buildYourOwnSmore');
								    }

								});
            return false;

        });

        $('.content_bottom').css('visibility', 'visible');

    },
    "ads-and-videos": function () {
        HERSHEYS.Carousel.init({
            'slideDistance': 348
        });
    },

    "contact/faq": function () {

        HERSHEYS.TabbedBrowsing.init({
            navSelector: '.faq .faqs_set .question',
            contentSelector: '.faq .faqs_set .answer'
        });

        HERSHEYS.TabbedBrowsing.init({
            navSelector: '.faq .threeCol a',
            contentSelector: '.faq .faqs_set'
        });

    }

};

HERSHEYS.Dot_Com = {};

if(!IS_MOBILE){

	HERSHEYS.Utility.doPageInits(initializations);

}
	
function closeLightbox(){ $('body').removeClass('buildYourOwnSmore');$('#flash_wrap_outer').remove();$('.content_bottom').css('visibility', 'visible'); $.fancybox.close();}

HERSHEYS.Dot_Com.trackStory = function(marc_brown){
    HERSHEYS.Analytics.doPageView('our story', marc_brown);
};
HERSHEYS.Dot_Com.trackHomepage = function(marc){
	
	if (marc == 'start'){
		s.events = s.linkTrackEvents = "event15,event18";
		s.eVar36 = s.prop26 = "hersheys:Interaction:chocolate bar";
		s.eVar38 = s.prop29 = "hersheys:Interaction:chocolate bar:unwrap start";
		s.linkTrackVars = "events,eVar36,eVar38";
		s.tl(true,'o','chocolate bar unwrap start');
	}else if (marc == 'complete'){
		s.events = s.linkTrackEvents = "event16,event18";
		s.eVar36 = s.prop26 = "hersheys:Interaction:chocolate bar";
		s.eVar38 = s.prop29 = "hersheys:Interaction:chocolate bar:unwrap complete";
		s.linkTrackVars = "events,eVar36,eVar38";
		s.tl(true,'o','chocolate bar unwrap complete');
	}
	
};




$(document).ready(function(){

	if(!IS_MOBILE){
		
	    /* To Track About Hershey Story Module */
	    $('.pure-products #pod_1 a').bind('click', function () {
	        var linkname = $('.pure-products #pod_1 a').attr('class');
	        s.tl(this, 'o', linkname);
	    });

		$('body').css('overflow', 'hidden');

		if ($('body').hasClass('autoScroll')){
			HERSHEYS.dot_com.Scroll.init('#content');
		}
	
		$('.search_container a').wrap('<h2 />');
	
		/* Enable leaving notice binding */
		HERSHEYS.Utility.leavingNotice({
			'transparency' : HERSHEYS.transparency,
			'title' : 'HERSHEYS.COM!'
		});
	
		/* Get the content height and set it */
		if ($('body').hasClass('noAutoSize')){
		
		}else{
			HERSHEYS.dot_com.Size.container();
		}
	
		HERSHEYS.transparency.init();	
		HERSHEYS.EmailRecipe.init('dotcom');
		HERSHEYS.KitchensSignup.init('#kitchensSignup');
	
	
	
		HERSHEYS.Utility.fakeActiveNav({
			'wrapperSelector' : 'div#nav a'
		});	
	
		/* Wire up search result button to field and search result page. */
		HERSHEYS.Utility.stealSearchButton({
			'site' : ''
		});
	
		$('.display_toggle').bind('click', function(){
		
			$(this).toggleClass('option_b');
		
			$('#content').scrollLeft(0);

		
				if ($.browser.ie){
					if ($(this).hasClass('option_b')){
						$('.scrollMe').css('width' , 7736); // 7728 7260
						$(".product_grid").removeClass('product_grid').addClass('product_scroll');
						$('div.product_grid_grouping').removeClass('product_grid_grouping').addClass('product_scroll_grouping');
						$(".product_bar_grid").removeClass('product_bar_grid').addClass('product_bar_scroll');
						$(".product_bag_grid").removeClass('product_bag_grid').addClass('product_bag_scroll');
						$(".product_bottle_grid").removeClass('product_bottle_grid').addClass('product_bottle_scroll');
					}else{
						$('.scrollMe').css('width' , 3180);
						$(".product_scroll").removeClass('product_scroll').addClass('product_grid');
						$(".product_bar_scroll").removeClass('product_bar_scroll').addClass('product_bar_grid');
						$(".product_bag_scroll").removeClass('product_bag_scroll').addClass('product_bag_grid');
						$(".product_bottle_scroll").removeClass('product_bottle_scroll').addClass('product_bottle_grid');
						$(".product_scroll_grouping").removeClass('product_scroll_grouping').addClass('product_grid_grouping');
					}
			
				}else{	
					if ($(this).hasClass('option_b')){
						$('div.product_grid_grouping').removeClass('product_grid_grouping').addClass('product_scroll_grouping');
						$(".product_grid").switchClass('product_grid', 'product_scroll', 1000);
						$(".product_bar_grid").switchClass('product_bar_grid', 'product_bar_scroll', 1000);
						$(".product_bag_grid").switchClass('product_bag_grid', 'product_bag_scroll', 1000);
						$(".product_bottle_grid").switchClass('product_bottle_grid', 'product_bottle_scroll', 1000);
						$('.scrollMe').css('width' , 7736); // 7728 7260
					}else{
						$(".product_scroll").switchClass('product_scroll', 'product_grid', 1000);
						$(".product_bar_scroll").switchClass('product_bar_scroll', 'product_bar_grid', 1000);
						$(".product_bag_scroll").switchClass('product_bag_scroll', 'product_bag_grid', 1000);
						$(".product_bottle_scroll").switchClass('product_bottle_scroll', 'product_bottle_grid', 1000);
						$(".product_scroll_grouping").switchClass('product_scroll_grouping', 'product_grid_grouping', 1000);
						$('.scrollMe').css('width' , 3180);
			
					}
				}

	
		
			return false;
		});

		$('.closer_look').fancybox({
			cyclic : true,
			padding: 0,
			onStart : function(){
				HERSHEYS.Analytics.doPageView('take a closer look', name);
			}
		});
	
		HERSHEYS.ShareThis.init({viewAnimation : 'fade'});
		
		
		if (typeof CURRENT_PROMOTION_ID != 'undefined'){
			switch(CURRENT_PROMOTION_ID){
				case 'cstore-free-gas-promo':
				
					$('#pr_wrapper').append('<div id="people_on_car"><img src="/assets/images/pr_images/cstore/peopleoncar.png" /></div>');
					$('#pr_nav_home a').addClass('active').unbind().bind('click', function(){
					
						window.location.reload();
						return false;
					});
				
				break;
			}
		}
		
	}else{
		/* Mobile initializations */
	}
	
});



if(!IS_MOBILE){
	$(window).bind('resize', function(){ 

	//	HERSHEYS.transparency.on(200);

		HERSHEYS.Utility.throttle(function(){
			$('.transparency, #content').stop();
			HERSHEYS.dot_com.Size.container();
			setTimeout(function(){
	//			HERSHEYS.transparency.off(200);
			}, 500);
		
		}, 300);
		
	});
}

HERSHEYS.dot_com = (function(){	
			
	var containers = { 
		content 	: 'content',
		nav 		: 'nav',
		footer 		: 'footer',
		scrollArea	: 'scrollMe'
	};
	
	var getContainerHeight = function(){

		if ($('body').hasClass('size-fixed')){ 
			$.each($('body').attr('class').split(' '), function(i,v){
				var height = v.split('fixed-');
				if (height.length > 1){
					return height[1] * 1;
				}
			});
		}
	
		if ($('body').hasClass('size-0')){ return 0;}
		if ($('body').hasClass('size-0b')){ return 470;}
		if ($('body').hasClass('size-1')){ return 519;}
		if ($('body').hasClass('size-1b')){ return 530;}
		if ($('body').hasClass('size-2')){ return 564;}
		if ($('body').hasClass('size-3')){ return 626;}
		if ($('body').hasClass('size-4')){ return 700;}
		if ($('body').hasClass('size-5')){ return 900;}
		
		return 519;
		
	};
	
	
	// Handle the sizing of components for full screen effect
	var Sizing = {		
		// sizeContent: assign a set height and width to the content region to maximize space
		// typically called on init & resize
		// "containerIn" : optionally pass in a reference to the container
			container : function(containerIn){
				
				// Do we have a reference to our container already? 
				// Use it! Otherwise, grab it from the private config
				var container = containerIn || $('#' + containers['content']);
				
				// The container height, in our case, is going to be the
				// WINDOW HEIGHT - "TOP" - "BOTTOM"
				// or
				// The min content height set in the private config
				var height =  $(window).height() - $('#' + containers.nav).height() - $('#' + containers.footer).height() - 80;
				
				var bottomPanel = $('#bottom_panel');
				
				if (bottomPanel.length) height = height - bottomPanel.height() - 50;
				
				if (height < getContainerHeight()){
					$('body').css('overflow-y' , 'auto');
					height = getContainerHeight();
				}else{
					$('body').css('overflow' , 'hidden');
				}
				
			//	$('body').css('overflow', 'hidden');
				
			//	$('.content_top').animate({'height': height - $('.content_bottom').height()});
				
				container.animate({'height': height, 'width' : $(window).width()});
		}
		
	};
	
//	getContainerHeight();
	
	var Scrolling = {
		scrollContainer : '#content',
		scrollInterval : false,
		controls : {
			'forward' : $('<div class="scroll_wrap" id="scroll_right"><a class="horz_scroll_arrow replace">&rarr;</a></div>'),
			'back' : $('<div class="scroll_wrap" id="scroll_left"><a class="horz_scroll_arrow replace" id="back">&larr;</a></div>').hide()
		},
		init : function(container){
			var that = this;
			
			this.scrollContainer = container || '#content';
			Scrolling.controls.forward.bind('mouseover', this.forward).
									   bind('mouseout', {'direction' : 'forward'}, function(){
										if (!that.doingAutoscroll){
											clearInterval(Scrolling.scrollInterval);  
											$(Scrolling.scrollContainer).stop();}}).
									   bind('click', function(){
										clearInterval(Scrolling.scrollInterval);  
										$(Scrolling.scrollContainer).stop();
										Scrolling.doScrollClick(1);
									});
			Scrolling.controls.back.bind('mouseover', this.back).
									bind('mouseout', {'direction' : 'back'}, function(){
										if (that.doingAutoscroll) return false;
										
										clearInterval(Scrolling.scrollInterval);  
										$(Scrolling.scrollContainer).stop();}).
								 	bind('click', function(){
										clearInterval(Scrolling.scrollInterval);  
										$(Scrolling.scrollContainer).stop();
										Scrolling.doScrollClick(-1);
									});
			
			Scrolling.transparencies = {};					
			Scrolling.transparencies.left = $('<div class="trans_left trans_wrap"></div>').hide();
			Scrolling.transparencies.right = $('<div class="trans_right trans_wrap"></div>');
				
			
			
			
			setTimeout(function(){
			//		Scrolling.transparencies.left.css({'height' : $('#' + containers.content).height()});
			//		Scrolling.transparencies.right.css({'height' : $('#' + containers.content).height()});
				
				$('body').append(Scrolling.controls.forward, Scrolling.controls.back, Scrolling.transparencies.left,Scrolling.transparencies.right);
			},500);
			var _this = this;
		},
		stop : function(e){		
			$('.' + containers['scrollArea']).stop();	
			
			/*Attempted to have it slow to a halt. Two problems. 1) can have a swing that slows down 2) hard to have it start the slow down from the full speed
			var slowDownRate = 50;
			var adjust = e.data.direction == 'forward' ? slowDownRate * -1 : slowDownRate;
			var newLeft = $('#' + containers['scrollArea']).css('left').split('px')[0] * 1 + adjust;
			$('#' + containers['scrollArea']).animate({'left' : newLeft}, 1000, 'swing');
			*/
		},
		forward : function(){
			Scrolling.controls.back.fadeIn(); 
			Scrolling.transparencies.left.fadeIn(); 			
			Scrolling.doScroll(1);
		},
		back : function(){
			Scrolling.controls.forward.fadeIn();
			Scrolling.doScroll(-1);
		},
		autoScroll: function(direction){
			return true;
			
			direction = direction || 1;
			
			var amount = direction ? 1000 : 0;
			
			var time = 1000;
			var scrollMe = $(Scrolling.scrollContainer);
			
			var that = this;
			that.doingAutoscroll = true;
		 	scrollMe.stop().animate({scrollLeft :  amount}, time,'swing', function(){
				that.doingAutoscroll = false;
			});
		},
		doScrollClick : function(where){
	
	
			var time = 800;
			var amount = 1500 * where;
			var scrollMe = $(Scrolling.scrollContainer);
			var current = scrollMe.scrollLeft();
	
		 	scrollMe.animate({scrollLeft :  current+= amount}, time,'swing', function(){
				if (scrollMe.scrollLeft() == 0){
					Scrolling.controls.back.hide();
					Scrolling.transparencies.left.hide();
				}
			});
		},
		doScroll : function(where){


			var time = 800;
			var amount = 400 * where;
			var scrollMe = $(Scrolling.scrollContainer);
			var current = scrollMe.scrollLeft();

		 	scrollMe.animate({scrollLeft :  current+= amount}, time,'linear', function(){
				if ($(this).scrollLeft() == 0){
					Scrolling.controls.back.hide();
					Scrolling.transparencies.left.hide();
				}
			});

			var _this = this;	
			Scrolling.scrollInterval = setInterval(function(){
			    var slide = scrollMe;
			    var current = slide.scrollLeft();
			    slide.animate({scrollLeft :  current+= amount}, time,'linear', function(){
					var newPosition = slide.scrollLeft();
				
					if (newPosition == 0){
						Scrolling.controls.back.fadeOut();
					}
				
					if (current + amount != newPosition){
			 			//clearInterval(Scrolling.scrollInterval);
						if (newPosition == 0){
						//	Scrolling.controls.back.fadeOut();
						}else{
						//	Scrolling.controls.forward.fadeOut();
						}
					} 
			})}, time);
		
		}
	};
	
	var Flash = {
		
		homepageBar : function(){
				var flashvars = {};
				var attributes = {};
				var param = {wmode : 'transparent'};

				flashvars.swfpath = "/assets/swf/dot_com/HersheysBar.swf";
				flashvars.animationpath = "/assets/swf/dot_com/HersheysBarUnwrapped.swf";
				flashvars.offsetX = 0;
				flashvars.offsetY = -10;
				flashvars.wmode = 'transparent';

				swfobject.embedSWF("/assets/swf/dot_com/HersheysBarLoader.swf", 
									"flash_wrap", "100%", "100%", "10.0.0", 
									"/assets/swf/expressInstall.swf",flashvars, param, attributes);				
			/*
				$('#content').bind('touchstart', function(e){

					$('.trace').html((e.targetTouches[0].pageX)).show();

				});	
			*/
				$('#content').swipe({
					     swipeLeft: function() {$('#flash_wrap').animate({'opacity' : '1'}) },
					     swipeRight: function() {$('#flash_wrap').animate({'opacity' : '0'})}
				});	
		},
		homepageDrops : function(){
			
				$('.content_bottom').hide();
			
				var flashvars = {};
				var attributes = {};
				var param = {wmode : 'transparent'};

				flashvars.videopath = "../../videos/dot_com/home_drops.mp4";
				flashvars.wmode = 'transparent';

				swfobject.embedSWF("/assets/swf/dot_com/HersheysDrops.swf", 
									"flash_wrap", "100%", "100%", "10.0.0", 
									"/assets/swf/expressInstall.swf",flashvars, param, attributes,function(e){								
										if (e.success){
											
										}else{
											$('.content_bottom').show();
											$('#flash_wrap_holder').addClass('dropshomepagebg');
											$('#flash_wrap').hide();
										}
										
									});
		},
		story : function(altContent) {
				var flashvars = {};
					var attributes = {};
					var param = {wmode : 'transparent'};

					flashvars.datapath = "/xml/dot_com_ourStory.xml";
					flashvars.fontpath = "/assets/swf/dot_com/OurStoryFonts.swf";
					flashvars.swfpath = "/assets/swf/dot_com/OurStory.swf";

					swfobject.embedSWF("/assets/swf/dot_com/OurStoryLoader.swf", 
										"flash_wrap", "100%", "100%", "10.0.0", 
										"/assets/swf/expressInstall.swf",flashvars, param, attributes, function(e){
											
											if (e.success){
												
											}else{
												altContent();
												$('#alt_content_wrap').show();
											}
											
										});
		},
		videoComplete : function(){
			// used as an end result of the homepageDrops sequence. is called via the swf?
			setTimeout(function(){
				$('#flash_wrap_holder').fadeOut(1000, function(){
					$(this).css({'width' : 1024, 'margin' : 'auto'}).html('<a href="/pure-products/hersheys-drops/milk-chocolate.aspx?ICID=HER1398" class="red_button_large button" style="position: absolute; top: 174px; left: 95px;"><span>Learn More</span></a>').addClass('dropshomepagebg').fadeIn();
					$('.content_bottom').fadeIn();
				});		
			}, 500);
		}
	};
		
	return {	
		Size : Sizing,
		Get : {
			container : function(){
				return $('#' + containers['content']);
			}
		},
		Scroll : Scrolling,
		Flash : Flash
	}	
})();



