/* PAGE-SPECIFIC Initializations */
HERSHEYS.Company = {};




HERSHEYS.Company.leftNavBind = function(){
	$('.top-leftnav').removeClass('active');
	$('.top-leftnav').bind('click', HERSHEYS.Company.leftNavBind);
	$(this).toggleClass("active");//.find('a:first').toggleClass('active');

	$(this).unbind();
	return false;
	$('.top-leftnav').bind('click',HERSHEYS.Company.leftNavBind);
}
HERSHEYS.Company.carouselinit = function(){
	HERSHEYS.TabbedBrowsing.init({
		navSelector : '.button_nav li a',
		contentSelector : '.drop_content_block',
		transition : 'slide'
	});
}



HERSHEYS.Company.storyinit = function(){
	/*story module*/
    var currentChapter = 1;
	var currentSection = 0;
	if($("#story-1-0").html() == ""){
		currentSection = 1;
	}else{
		currentSection = 0;
	}
    var numOfChapters = $(".select_chapter a").length;
    var allStories = $(".story");
    function hideStories() {
        //hide all stories
        allStories.hide();
        //remove active
        //$(".select_chapter li").removeClass("active");
        $(".select_section li").removeClass("active");
    }
    function checkDisabled() {
        //alert(currentChapter+' '+currentSection);
        if ((currentChapter == 1) && (currentSection == 0)) {
            $("#story-back").unbind().attr("id", "story-back-disabled");
        } else {
            $("#story-back-disabled").attr("id", "story-back");
        }
        if ((currentChapter == numOfChapters) && (currentSection == $(".select_section_inner ul:last li").length)) {
            $("#story-next").unbind().attr("id", "story-next-disabled");
        } else {
            $("#story-next-disabled").attr("id", "story-next");
        }
    }
    function addActiveClass() {
        $(".select_chapter li:nth-child(" + (currentChapter) + ")").addClass("active");
        $("#select_section_" + currentChapter + " li:nth-child(" + (currentSection + 1) + ")").addClass("active");
    }
    checkDisabled();
    $(".select_chapter a").bind('click', function () {
        //hide all stories and show chapter
        hideStories();
        $(".select_chapter").find("li").removeClass("active");
        currentSection = 0;
        currentChapter = $(this).index(".select_chapter a") + 1;
        $(".select_section").hide();
        $("#select_section_" + currentChapter).fadeIn();
		if($("#story-" + currentChapter + "-0").html() == ""){
			$("#story-" + currentChapter + "-1").fadeIn();
			currentSection = 1;
		}else{
			$("#story-" + currentChapter + "-0").fadeIn();
		}

        checkDisabled();
        addActiveClass();
        return false;
    });
    $(".select_section a").bind('click', function () {
        hideStories();

        currentChapter = $(".select_chapter li:nth-child(" + (currentChapter) + ")").index(".select_chapter  li") + 1;
        currentSection = $(this).index("#select_section_" + currentChapter + " li a") + 1;
        //alert(currentChapter+' '+currentSection);
        //show clicked story based on section
		if($.browser.msie){
			$("#story-" + currentChapter + "-" + currentSection).show();
		}else{
			$("#story-" + currentChapter + "-" + currentSection).fadeIn();
		}
        checkDisabled();
        addActiveClass();
        return false;
    });
    $("#story-next").live('click', function () {
        hideStories();

        if (currentSection >= $("#select_section_" + currentChapter + " li").length) {
            $(".select_chapter li").removeClass("active");
            currentChapter++;
			if($("#story-" + currentChapter + "-0").html()==""){
				currentSection = 1;
			}else{
				currentSection = 0;
			}
            //$(".select_chapter li:nth-child("+currentChapter+")").addClass("active");
            $(".select_section").hide();
            $("#select_section_" + currentChapter).fadeIn();
        } else {
            currentSection++;
        }
		if($.browser.msie){
			$("#story-" + currentChapter + "-" + currentSection).show();
		}else{
			$("#story-" + currentChapter + "-" + currentSection).fadeIn();
		}
        checkDisabled();
        addActiveClass();
        return false;
    });
    $("#story-back").live('click', function () {
        hideStories();
		
		if($("#story-" + currentChapter + "-0").html() != ""){
			if (currentSection <= 0) {
				$(".select_chapter").find("li").removeClass("active");
				currentChapter--;
				currentSection = $("#select_section_" + currentChapter + " li").length;
				//$(".select_chapter li:nth-child("+currentChapter+")").addClass("active");
				$(".select_section").hide();
				$("#select_section_" + currentChapter).fadeIn();
			} else {
				currentSection--;
			}
		}else{
			if (currentSection <= 1) {
				$(".select_chapter").find("li").removeClass("active");
				currentChapter--;
				currentSection = $("#select_section_" + currentChapter + " li").length;
				//$(".select_chapter li:nth-child("+currentChapter+")").addClass("active");
				$(".select_section").hide();
				$("#select_section_" + currentChapter).fadeIn();
			} else {
				currentSection--;
			}
		}
		if($.browser.msie){
			$("#story-" + currentChapter + "-" + currentSection).show();
		}else{
			$("#story-" + currentChapter + "-" + currentSection).fadeIn();
		}
        checkDisabled();
        addActiveClass();
        return false;
    });
}

HERSHEYS.Company.searchjobinit = function(){
	$('.btn').click(function(event) {
		var divHeight = $(this).next('ul').height();
		if ($(this).hasClass('active')) {
			$(this).next('ul').stop().animate({ height: '1px' }, 400, function() {
				$(this).css('left', '-999em');
				$(this).css('height', 'auto');
				$(this).prev().removeClass('active')
			})
		} else {
			$(this).next('ul').css('left', 'auto');
			$(this).next('ul').css('height', '1px');
			$(this).next('ul').stop().animate({ height: divHeight }, 400)
			
			$(this).addClass('active')
		}
		event.preventDefault();
		});
}

HERSHEYS.Company.initializations = {

    '/': function () {
        HERSHEYS.Carousel.init({
            'slideDistance': 135,
            'carouselSelector': '#brand_carousel',
            'navClass': 'pager',
			'disableAnimation': true
        });

        var expanded = false;
        $(".togglePopup").bind('click', function () {
            var index = $(".togglePopup").index(this);
            if (expanded) {
                $("#popup_slider").animate({ top: '+=128' }, function () { expanded = false; }).removeClass("expanded");
                $(this).css({ "background-position": "0px -355px", height: "16px" });
                //$(".topBar").toggleClass("unwrapped");
                $(".topBar .info:eq(" + index + ")").fadeOut();
            } else {
                $("#popup_slider").animate({ top: '-=128' }, function () { expanded = true; }).addClass("expanded");
                $(this).css({ "background-position": "88px -370px", height: "13px" });
                //$(".topBar").toggleClass("unwrapped");
                $(".topBar .info:eq(" + index + ")").fadeIn();
            }
            return false;
        });
        $(document).ready(function () {
            var featureNum = Math.floor(Math.random() * 9);
            var selectedItem = $(".topBar-content:eq(" + featureNum + ")");
			
            selectedItem.show();
            $("body").addClass("home" + featureNum);
        });
        /*setInterval(function(){
        var active = $('.topBar-content:visible');
        var siblings = active.siblings('.topBar-content');
        var featureNum = Math.floor(Math.random() * siblings.length);
        var selectedItem =$(".topBar-content:eq("+featureNum+")");

        active.fadeOut(2000);
        selectedItem.fadeIn(2000,function(){
        //add body class for backgroundimage
        $("body").removeClass("body home0 home1 home2 home3 home4 home5 home6 home7 home8 home").addClass("home"+featureNum);
        });
        if(expanded){
        //if panel is open, fade the info as well
        selectedItem.children(".info").fadeIn(2000);
        }
        }, 15000);*/
    },
    'brands/iconic-brands': HERSHEYS.Company.carouselinit,
    'brands/category': HERSHEYS.Company.carouselinit,
    'brands/special-nutrition': function(){
		HERSHEYS.Company.carouselinit();
		$("#kosher-product-nutrition").click(function(){
			$(".snutrition_nav_2 a").click();
		});
		$("#sugar-free-product-nutrition").click(function(){
			$(".snutrition_nav_4 a").click();
		});
		$("#100-calorie-product-nutrition").click(function(){
			$(".snutrition_nav_5 a").click();
		});
	},
    'brands/alphabetical-listing': function(){
		HERSHEYS.Company.carouselinit();
		$("#prod-2853 a").attr({"href":"http://www.dagobachocolate.com/","target":"_blank"});
		$("#prod-2855 a").attr({"href":"http://www.scharffenberger.com/","target":"_blank"});
	},

    "brands/hersheys-kisses/filled-with-caramel": function () {
		fbContent = '<div id="alert-wrapper">';
		fbContent += '<div id="alert">';
		fbContent += "<h1>Consumer Alert</h1>";
		fbContent += '<div class="seperator"></div>';
		fbContent += "<p>";
		fbContent += "As of March 1, 2011, The Hershey Company will begin producing the HERSHEY'S KISSES Milk Chocolates filled with Cherry Cordial Cr&egrave;me and HERSHEY'S KISSES Milk Chocolates filled with Caramel on a line that manufactures peanut-containing products. As a result, we want to inform our consumers that the following allergen statement is being added to the packages: ALLERGY INFORMATION: MANUFACTURED ON THE SAME EQUIPMENT THAT PROCESSES <b>PEANUTS</b>.<br /><br />";
		fbContent += "During a transition period, both the original and relocated products will continue to be in the marketplace. The labels accurately reflect the ingredient and allergen information for the products. Consumers, therefore, should read the labels carefully. It should be noted that the products also continue to contain milk and soy lecithin.<br /><br />";
		fbContent += "For more information, please contact The Hershey Company at (800) 468-1714.";
		fbContent += "</p>";
		fbContent += "</div>"
		fbContent += "</div>"
		$(".cl_l:eq(0)").prepend('<a href="#alert" class="consumer-alert">Consumer Alert: HERSHEY\'S KISSES Milk<br />Chocolates filled with Caramel</a><br /><br />');
		$("body").append(fbContent);
		$("a.consumer-alert").fancybox();
    },


    'about-hershey/our-story/milton': HERSHEYS.Company.storyinit,
    'about-hershey/our-story/hersheys-history': HERSHEYS.Company.storyinit,

    'careers/working-at-hersheys/locations': function () {
        HERSHEYS.TabbedBrowsing.init({
            navSelector: '.tab_nav li a',
            contentSelector: '.tab_content'
        });
    },
	
    'careers/benefits': HERSHEYS.Company.searchjobinit,
    'careers/workforce-diversity': HERSHEYS.Company.searchjobinit,
    'careers/values': HERSHEYS.Company.searchjobinit,
    'careers/community-involvement': HERSHEYS.Company.searchjobinit,
	
	
    'brands': function () {
        //stylish select
        $("#product-select").sSelect();

        HERSHEYS.Carousel.init({
            'slideDistance': 147,
            'numVisible': 5,
            'firstItem': 2,
            'carouselSelector': '#brand_carousel',
            'navClass': 'pager',
            'disableAnimation': true
        });

        /* Brand carousel */
        setInterval(function () {
            var active = $('.banner_img:visible');
            var siblings = active.siblings('.banner_img');
            var selectedItem = $(siblings[Math.floor(Math.random() * siblings.length)]);

            active.fadeOut(2000);
            selectedItem.fadeIn(2000);
        }, 8000);
    },
    'contact-us/frequently-asked-questions': function () {
        HERSHEYS.TabbedBrowsing.init({
            navSelector: 'a.question',
            contentSelector: 'div.answer'
        });
		var showing = new Array;
        $(".view-all-questions").bind("click", function () {
            var index = $(".view-all-questions").index(this) - 1;
			var qContainer = $(".question-container:eq(" + index + ") .answer");
			if(showing[index]){
				$(this).text("+ View all answers");
				qContainer.hide();
				showing[index] = false;
			}else{
				$(this).text("- Hide all answers");
				qContainer.show();
				showing[index] = true;
			}

            return false;
        });
        var hash = window.location.hash;
        if (hash == "#h2_nutrition-faq") {
            if ($(hash).length != 0) {
                if ($.browser.opera) { $('html').animate({ scrollTop: $(hash).offset().top - 50 }, 500); } else $('html,body').animate({ scrollTop: $(hash).offset().top - 50 }, 500);
            }
        }
    },
    'nutrition-and-wellness/nutrition-information': function () {
        $(document).ready(function () {
            $('.fancy_modal').fancybox({
                'autoDimensions': false,
                'width': 600,
                'height': 500,
                'padding': 0
            });
        });
    },
    'investors/stock-information/subscribe-to-our-financial-alerts': function () {

        $('#content .form_wrap .submit').bind('click', function () {


            var alerts = $('#content .form_wrap input:checked');

            if (!alerts.length) {
                $('.form_status').html('Please select an alert to subscribe to from above. <br />').fadeIn();
                return false;
            } /*else if (email == '' || !filter.test(email)){
		        html += 'Please enter a valid email';
		    }*/
            else {

                /*html = 'Your request to subscribe <b>' + email +'</b> to the following list(s) has been submitted: <br><br>';

                alerts.each(function(i,v){
                var title = $(this).next().html();
                html += '<em>'+title+'</em><br />';
                });

                html +=    '<br><br> An e-mail with user validation has been sent to <b>' + email + '</b>.'+
                '<br>To complete the process, please follow the instructions within the e-mail.';
                */
                return true;
            }
        });
    },
    'investors/stock-information/stock-fundamentals': function () {
        //$('.tabTableContent').addClass('hidden');
        $('.tabHeader').bind('click', function () {
            $(this).parent().next('.tabTableContent').slideToggle();
            return false;
        });
    },
    'investors/stock-information/dividend-history' : function(){
    	$("tr.total td:nth-child(4n),tr.total td:nth-child(5n)").css("background-color","#96BC22");
    },
    /*'contact-us/contact-us-form-step-2' : function(){
    $("#submit_contactStep2").bind('click',function(){
    $(".form-container").hide();
    $("#contact-us-complete").show();
    return false;
    }).submit(function(){
    return false;
    });
    },*/
    'contact-us/locate-hard-to-find-products': function () {
        $("form").attr("action", "/contact-us/locate-hard-to-find-products.aspx#table_product_results");
        if ($("#table_product_results").length > 0) {
            $('#table_product_results table').attr("cellspacing", 0);
        }
    },
	/*'contact-us/contact-us-form-step-2' : function(){
		

	},*/
	"newsroom/subscribe-to-hersheys/step-2" : function(){
		$('input[name=top_priorities], input[name=activities]').bind('click', function(){
		  	if ($(this).siblings(':checked').length + 1 > 3){
		        alert('You may only select three '+ $(this).attr('name').replace('_', ' ') + "'s");
		        return false;    
			}
		});
	},
    'about-hershey/our-story/making-our-chocolate': function () {
        $('.video_playlist_external a').bind('click', function () {
            //alert('external playlist click');
            HERSHEYS.Video.doPlay($(this));


            var title = $(this).attr('title');
            var id = $(this).attr('class');
            var poster = $(".video_playlist a").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;
        });
    }
};
HERSHEYS.Utility.doPageInits(HERSHEYS.Company.initializations);

$(document).ready(function () {
	//HERSHEYS.Company.leftNavBind();	


	//$('.investors #content a').addClass('override_leaving');
	
	HERSHEYS.Utility.leavingNotice({
		'transparency' : HERSHEYS.transparency,
		'title' : 'The Hershey Company'
	});
	
    //timeline
    var timeline = $(".time");
    var timePoint = timeline.find("li");
    timePoint.find("a").bind("click", function () {
        timePoint.removeClass("active");
        $(this).parent().addClass("active");

        var timeYear = $(this).text();
        var timeExcerpt = $(this).siblings().text();
        $("h4#year").text(timeYear);
        $("p#excerpt").text(timeExcerpt);

        return false;
    });
	// Careers stylish select
	$('.form select').sSelect();
	
	$(".careers form").submit(function(e) {
	   e.preventDefault();
		//if ($("select").val() != '--Select Location--') {
			if ( document.getElementById('job-selection').selectedIndex > 0 ){
			// works because it is acting on a reference of the window.location object
			// thus the copy has all of the properties and methods by inheritance!
			window.location.href = $("select").val();
			} else {
			alert('Please select an option');
			}
	});
	
	//community_accordian
	$(".community_accordian").accordion({ 
		collapsible: true,
		active: 999,
		header: 'h3',
		navigation: true,
		icons: { 'header': 'toggle-collapsed', 'headerSelected': 'toggle-open' },
		autoHeight: false 	
	});
	$(".community_accordian").bind('accordionchange', function(event, ui) {
	  //$(body, html).animate({scrollTop: $(ui.newHeader).offset().top}, 1000);
		$.scrollTo( ui.newHeader, 1000 );
	});
	//scrollTo top of the accordian 
	  //$(this).stop(true, true).animate(800);
	  
	//_old_ faq accordian
	var FAQAccordian = $("#faq");
	FAQAccordian.find('a').bind("click", function(e){
		$(this).parent().find(".answer").slideToggle();
		$(this).parent().toggleClass("active");
		return false;
	});
	//partner section background randomization
	if($(".partners").length != 0){
		var BGnum = Math.floor(Math.random() * 2);
		$("body").addClass("partners"+BGnum);
	}
	//search disabled
	var searchSubmit = $(".search_submit");
	var searchTextBox = $(".searchTextBox");
	
	function checkSearch(){
		if((searchTextBox.val() == "Search Hershey's Sites")||(searchTextBox.val() == "")){
			searchSubmit.addClass("disabled").attr('disabled','disabled');
		}else{
			searchSubmit.removeClass("disabled").removeAttr('disabled');
		}
	}
	checkSearch();
	searchTextBox.bind('focus keypress blur', function(){
		checkSearch();
	});
	/* Wire up search result button to field and search result page. */
	HERSHEYS.Utility.stealSearchButton({});

	// TRACK DOWNLOADS
	function trackOmniDownload(pDownloadType, pCategory) {
	    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,eVar6"; //Defining the list of variables that will be sent in the server call	
	    s.eVar6 = s.prop17 = pDownloadType + ":" + pCategory
	    s.linkTrackEvents = "event21";
	    s.events = "event21"; 	//Passing the value into s.events

	    s.tl(true, 'o', 'download'); //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
	    }
	}

	$('a[href*=pdf]').attr('target', '_blank');
	$('a[href*=pdf]').bind('click', function () {
	    var title = $(this).html();
	    title = title.split('<img')[0] || $(this).attr('title') || 'Missing Link Title';

	    trackOmniDownload('PDF', title);
	});

	$('a.audio_right').attr('target', '_blank');
	$('a.audio_right').bind('click', function () {
	    var title = $(this).html();
	    title = title.split('<img')[0] || $(this).attr('title') || 'Missing Link Title';

	    trackOmniDownload('Audio', title);
	});

	$('a[href*=.doc]').attr('target', '_blank');
	$('a[href*=doc]').bind('click', function () {
	    var title = $(this).html();
	    title = title.split('<img')[0] || $(this).attr('title') || 'Missing Link Title';

	    trackOmniDownload('Doc', title);
	});

	/* To Track About Hershey Story Module */
	$('.about #story_module a, a#story-next, a#story-back').bind('click', function () {
	    var linkname = $('.content .story:visible').attr('id');
	    s.pageName = s.prop1 = 'thehersheycompany:about hershey:our story:' + s.pageName.split(':')[3] + ':' + linkname;
	    s.channel = s.prop2 = 'thehersheycompany:about hershey';
	    s.prop3 = 'thehersheycompany:about hershey:our story';
	    s.prop4 = 'thehersheycompany:about hershey:our story:' + s.pageName.split(':')[3] + ':' + linkname;
	    s.t();
	});

	/* To track Brand Category Selection */
	$('.brands-category #category_button_nav a').bind('click', function () {
	    var linkname = $(this).attr('id');
	    s.pageName = s.prop1 = 'thehersheycompany:brands:category:' + s.pageName.split(':')[3] + ':' + linkname;
	    s.channel = s.prop2 = 'thehersheycompany:brands';
	    s.prop3 = 'thehersheycompany:brands:category';
	    s.prop4 = 'thehersheycompany:brands:category:' + s.pageName.split(':')[3] + ':' + linkname;
	    s.t();
	});

	/* To track Contact Us */
	$('.contact-form input.submit_contactStep2').bind('click', function () {
	    s.events = s.linkTrackEvents = "event16";
	    s.eVar36 = s.prop26 = 'thehersheycompany:contact us';
	    s.linkTrackVars = "events,eVar36";
	    s.tl(this, 'o', 'contact form submission');
	});

	/* To track Registrations Complete */
	$('.contact-us-step2 span#subscribe-step-3 a').bind('click', function () {
	    s.events = s.linkTrackEvents = "event16,event29";
	    s.eVar36 = s.prop26 = 'thehersheycompany:subscribe to hersheys';
	    s.linkTrackVars = "events,eVar36";
	    s.tl(this, 'o', 'site registration');
	});

	// This is a fix to change the phone number ONLY for the three Hersheys milkshake products.	
	if($("#prod-1984").length || $("#prod-1986").length || $("#prod-1987").length){
		$('.nutrition_section').find('td').html('Nutrition information for this flavor is not available online at this time. Please consult the package label or call us at (800) 242-2423 for further information.');
		$('.ingredients_section').find('td').html('Ingredients information for this flavor is not available online at this time. Please consult the package label or call us at (800) 242-2423 for further information.');			
	}
});

