var 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/');
		}
        if (split.length != 2) {
            split = pageIn.split('.dev2/');
        }

		// ----------------------------------------- LOCAL
		if (split.length != 2) { 
			split = pageIn.split('.test/');
		}

		// ----------------------------------------- SET ERROR
		if (split.length != 2) { return 'ERROR'; }
		
		return split[1].split('#')[0].split('?')[0].split('.aspx')[0] || '/';
	})(window.location.href)
};

if (typeof IS_MOBILE == 'undefined') var IS_MOBILE = false;

// ----------------------------------------------------------------------------------------- UPDATE AJAX REQUESTS TO POST OVER SSL
function HostURL() {
	var domain = window.location.hostname;
	
	// ONLY RETURN DOMAIN NAME IF WE'RE NOT ON LOCAL, DEV, QA OR TEST
	if (domain.indexOf('.test') > 0 || domain.indexOf('.com') == -1) { 
		return '';
	} else { 
		return 'https://' + domain;
	}
}

$(document).ready(function(){

	HERSHEYS.transparency = new HERSHEYS.Utility.Transparency({
		'opacity' : '.6',
		'color' : '#000000'
	});

	if(!IS_MOBILE){

		/* Bind global nav elements */
		HERSHEYS.GlobalHeader.bind();
		HERSHEYS.Utility.inputPlaceholder();		
		
		if (typeof CURRENT_PROMOTION_ID != 'undefined')
			HERSHEYS.Promotions.initBinds();	
		
		HERSHEYS.globalBinds = function(){
			
			$('.fancy_modal').fancybox({'padding' : 0,	'opacity' : true,'transitionIn' : 'elastic','transitionOut' : 'elastic','scrolling' : 'no'});
			$('.popupImage').fancybox();
			$('.modal_popup').fancybox();
			$('.button_print').bind('click', function(){window.print();	});
		
			$('.video_playlist a').bind('click', function(){
			
				HERSHEYS.Video.doPlay($(this));
			
				
				var title = $(this).attr('title');
				var id = $(this).attr('id');
				var poster = $(this).find('img').attr('src').replace('_thumb', '');
				var videoUrl = $(this).attr('filename');
			
				$('#video_title').html(title);
			
				var videoPlayer = PInstance[0];
				videoPlayer.setTitle(title);
				videoPlayer.setID(id);
				videoPlayer.setFile(videoUrl+".mp4", false);
				if(navigator.userAgent.indexOf("Firefox") > 0) videoPlayer.setFile(videoUrl+".ogv", false);
				videoPlayer.setPlay();
				videoPlayer.setActiveItem(1);
				videoPlayer.setPlayerPoster(poster);
				
				return false;
			});	
			$(".scroller").simplyScroll({
				className: 'vert',
				horizontal: false,
				frameRate: 20,
				speed: 10
			});
			$('.submit_search').bind('click', function(){
				$('form:first').submit();
				return false;
			});			
			/* Contact Form */
			$('.formOptionGroupASelector').unbind().bind('change', function(){

				if ($(this).attr('value') == "Product Concern and Availability"){
					//$('.formOptionGroupA').hide();
					$('#productInformation').show();
				}else{
					$('.formOptionGroupA').hide();
					$('#commentWrapper').show();
				}
			});				
			$('a[externalSite]').bind('mouseenter', function(e){

			   var element = $('#preview_popup_instance');

			    if (!element.length){
			       element = $('<div id="preview_popup_instance" style="position: absolute; background-image: url(/assets/images/dot_com/external_preview.png); width: 225px; height: 171px; z-index: 99999">');
			        $('body').append(element);
			        element.append('<div id="preview_popup_inside">');
			    }

			     $(document).mousemove(function(e){
			        var element = $('#preview_popup_instance');
			        element.css({
			           'left' : e.pageX - 100, 
			            'top' : e.pageY - 180
			        });
			     }); 

			     element.css({
			        'left' : e.pageX - 100, 
			        'top' : e.pageY - 180
			     });

			    var siteBG = $(this).attr('externalSite');
			    if (siteBG){
			        $('#preview_popup_inside').css(
			        {'background-image' : 'url(/assets/images/dot_com/preview_overlay_' + siteBG + '.gif)',
			        'height' : '100%'
			       });
			    }


			}).bind('mouseleave', function(){

				if ($.browser.msie) {
				 	$('#preview_popup_instance').remove();
				}else{
					$('#preview_popup_instance').fadeOut('fast', function(){$(this).remove();});
				}
			});	
		};
		
		HERSHEYS.globalBinds();
		
		$(HERSHEYS).trigger(HERSHEYS.CURRENT_PAGE + '_loaded'); 

	} else {
	
		$('.fancy_modal').fancybox({
			'padding' : 0
			, 'margin' : 5
			, 'modal' : true
			, 'opacity' : true
			,'transitionIn' : 'elastic'
			,'transitionOut' : 'elastic'
			,'scrolling' : 'no'
			, 'overlayOpacity' : 0
		});
		$('.modal_popup').fancybox({
			'autoScale' : false,
			'onStart': function(){
				if(IS_SCROLL){
					var headerH = document.getElementById('header').offsetHeight,
						footerH = document.getElementById('footer').offsetHeight,
						wrapperH = window.innerHeight - headerH - footerH;
					document.getElementById('fancybox-overlay').style.height = (wrapperH+100) + 'px';
				}else{
					document.getElementById('fancybox-overlay').style.height = '100%';
				}
			}
		});
	}
});

HERSHEYS.EmailRecipe = (function(){
	
	var config = {
		
		'formSelector'  : '.modal_form',
		'submitSelector' : '#sendToFriend',
		'parentSelector' : '#share_recipe',
		'loadingSelector' : '.modal_loading',
		'successSelector' : '.modal_success',	
		'sendAgainSelector' : '#sendAgain',			
		'groupClass' : '.modal_panel',	
		'errors'	: '.sharerrors', 			
		'url' : '?form=blah'
				
	};
	
	var resetData = function(parent){
		
		parent.find('input:text').each(function(){
			$(this).attr('value',$(this).attr('placeholder'));
		});
		parent.find(config['groupClass']).hide();
		parent.find(config['formSelector']).show();
		parent.find(config['errors']).hide();
		
		$.fancybox.resize();
	};
	
	return {
		
		init : function(src){
			
			var parent = $(config['parentSelector']);
			
			
			resetData(parent);
			
			$(config['submitSelector']).live('click', function(){
				
				parent.find(config['groupClass']).hide();
				parent.find(config['loadingSelector']).show();
				
				$.fancybox.resize();
				
				var emailList = $('input#friendEmail').attr('value');
			    var nameList = $('input#friendName').attr('value');
			    var yourName = $('input#yourName').attr('value');
			    var yourEmail = $('input#yourEmail').attr('value');
			    var recipeID = $(this).attr('recipeid') || 0;
				
				
				HERSHEYS.Services.shareRecipe({
					'name' : yourName,
					'email' : yourEmail,
					'friendname' : nameList,
					'friendemail' : emailList,
					'recipeid' : recipeID,
					'src'	: src ? src : false,

					'success' : function(returns){

						parent.find(config['groupClass']).hide();
						parent.find(config['successSelector']).show();
						$.fancybox.resize();

					},
					'failure' : function(){

						alert('Sorry, there was an error sending your request. Please try again!');
						parent.find(config['groupClass']).show();
						parent.find(config['loadingSelector']).hide();
						$.fancybox.resize();
						
					}
				});
				
				return false;		
			});

			$(config['sendAgainSelector']).bind('click', function(){
				resetData(parent);
				return false;	
			});
		}
		
		
	};

})();
HERSHEYS.AskExpert = (function () {
    var config = {
        'parentSelector': '#ask_expert'
    }

    return {
        init: function (triggerSelector) {

            var parent = $(config.parentSelector);
            var submit_link = $("#age_check_submit", parent);
            var question_submit_link = $('#question_submit');
            var form_msg = $('#form_msg', parent);

            if (question_submit_link != undefined) {
                question_submit_link.bind("click", function () {
                    if (form_msg != undefined) form_msg.hide();

                    var data = {
                        firstName: $('#first_name', parent).val()
                        , lastName: $('#last_name', parent).val()
                        , email: $('#email', parent).val()
                        , question: $('#question', parent).val()
                        , callback: function (data) {
                            if (data == "1") {
                                $('#vThankYou', parent).show();
                                $('#vAskQuestion', parent).hide();
                            } else {
                                if (form_msg != undefined) {
                                    form_msg.text(data);
                                    form_msg.show();
                                }
                            }
                        }
                    };

                    var firstNameReq = $('#firstNameReq');
                    var lastNameReq = $('#lastNameReq');
                    var emailReq = $('#emailReq');
                    var questionReq = $('#questionReq');
                    var canSubmit = true;
                    var emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[A-Za-z]{2,4}$/

                    firstNameReq.css('color', '');
                    lastNameReq.css('color', '');
                    emailReq.css('color', '');
                    questionReq.css('color', '');

                    if (data.firstName == '') {
                        canSubmit = false;
                        firstNameReq.css('color', '#ffff00');
                    }
                    if (data.lastName == '') {
                        canSubmit = false;
                        lastNameReq.css('color', '#ffff00');
                    }
                    if (data.email == '') {
                        canSubmit = false;
                        emailReq.css('color', '#ffff00');
                    } else if (!(emailReg.test(data.email))) {
                        canSubmit = false;
                        emailReq.css('color', '#ffff00');
                    }
                    if (data.question == '') {
                        canSubmit = false;
                        questionReq.css('color', '#ffff00');
                    }

                    if (canSubmit)
                        HERSHEYS.Services.askExpert(data);
                    else
                        form_msg.show();
                });
            }
            if (submit_link != undefined) {
                submit_link.bind("click", function () {
                    //get the dob fields
                    var ddYear, ddMonth, ddDay;
                    ddYear = $("#ddYear", parent).val();
                    ddMonth = $("#ddMonth", parent).val();
                    ddDay = $("#ddDay", parent).val();
					//New
					age = 18;
					dobdate = new Date();
					dobdate.setFullYear(ddYear, ddMonth-1, ddDay);
					currdate = new Date();

                    //check that values have been entered	
					if ( (ddYear == -1) || (ddDay == -1) || (ddMonth == -1) ) {
						  $("#age_required", parent).text("Please enter your birthday information");
						  $("#age_required", parent).show();
						  return;					 
					} else if ((ddYear > 0) && (ddDay > 0) && (ddMonth > 0)) {
						currdate.setFullYear(currdate.getFullYear() - age);						
						if ((currdate - dobdate) < 0){ 				
							$('#vAgeVerification', parent).hide();
							$("#age_msg", parent).show();
							return;
						}
						else {
                    		$('#vAgeVerification', parent).hide();
                        	$('#vAskQuestion', parent).show();
							return;
						}
					}
                    /*
					HERSHEYS.Services.agecheck({
                        year: ddYear
                        , month: ddMonth
                        , day: ddDay
                        , success: function () {
                            $('#vAgeVerification', parent).hide();
                            $('#vAskQuestion', parent).show();
                        }
                        , failure: function () {
                            $('#vAgeVerification', parent).show();
                            $("#ask_expert_form", parent).hide();
                            //$("#age_msg", parent).text("You are not eligible");
                            $("#age_msg", parent).show();
                            $('#vAskQuestion', parent).hide();
                            $('#age_check_submit', parent).hide();
                        }
                    });
					*/
                });
            }

        }
    };
})();

HERSHEYS.KitchensSignup = (function () {

    var config = {

        'parentSelector': '#kitchens_signup',
        'successSelector': '.modal_success',
        'groupClass': '.modal_panel',
        'url': '?form=blah'
    };

    return {

        init: function (triggerSelector) {

            var parent = $(config['parentSelector']);

            $('#submit_dob').bind('click', function () {

                HERSHEYS.Services.agecheck({
                    year: $('#dob_year').attr('value'),
                    month: $('#dob_month').attr('value'),
                    day: $('#dob_day').attr('value'),

                    success: function () {
                        $('#subscribe_dob').hide();
                        $('#subscribe_email').show();
                    },
                    failure: function () {
                        $('#subscribe_dob').hide();
                        $('#subscribe_failure').show();
                    }
                });

                return false;

            });

            $('#kitchensSignup').bind('click', function () {

                if (!HERSHEYS.Utility.validate('email', $('#email').attr('value'))) return false;

                HERSHEYS.Services.subscribe({

                    email: $('#email').attr('value'),

                    success: function () {
                        $('#subscribe_email').hide();
                        $('#subscribe_success').show();
                    },
                    failure: function () {
                        alert('Sorry, there was an error subscribing you. Please try again!');
                    }
                });

                return false;

            });

        }
    };

})();
HERSHEYS.GlobalHeader = (function () {

    var gh = '.gh';
    var subnavs = '.gh_subnav';
    var brandsLinks = '.toggle_all_brands';

    return {

        bind: function () {

            var that = this;

            $(gh).find('li')
					.bind('mouseover', function () {
					    clearTimeout(that.hideDelay);
					    $(this).addClass('active');
					    $(this).find(subnavs).show();
					    $(this).siblings().find(subnavs).hide();        // hide any subnavs that may be visible
					    $(this).siblings().removeClass('active');       // remove active state from wrapper to get change down arrow
					});
            $(gh).bind('mouseout', function () {
                that.hideDelay = setTimeout(function () {
                    $(subnavs).hide();
                    $(gh + ' .active').removeClass('active');
                }, 10);
            });

            $(subnavs)
				    .bind('mouseover', function () {
				        $(this).show();
				    });

            /* Bind Toggle All Brands link in header drop down */
            $(brandsLinks).bind('mouseover click', function () {
                HERSHEYS.Utility.slideAlternate({
                    'slideMe': '#gh_find_hersheys_sites .slideMe',
                    'howMuch': 700
                });
            });
        }
    };

})();
HERSHEYS.Carousel = (function () {
    /* Carousel Object - instantiate with optional selectors, but definite amount to slide */

    /* triggers: 
    'SlideStart' - passes handle to new item
    'SlideComplete' - passes handle to new item
    'AllItemsSeen' - passes handle to new item
    */

    var defaults = {
        carouselSelector: '.carousel',
        carouselItem: '.item',
        slideDistance: 348,
        navClass: 'carousel_pager',
        numVisible: 3,
        firstItem: 1,
        showTitle: false,
        animationLength: 400,
        disableAnimation: false,
        carouselContainer: 'ul',
        resetValues: false
    };

    var totalItems = 0,
		carousel = null,
		currentDisplay = 1,
		prevButton = $('<a href="#" id="carousel_prev" title="previous item">Previous</a>'),
		nextButton = $('<a href="#" id="carousel_next" title="next item">Next</a>'),
		numClicks = 0;

    var doAnimation = function (carousel, item, length) {




        $(carousel + " " + item + ":not(:eq(" + currentDisplay + ")) img, " + carousel + " li.flow_item:not(:eq(" + currentDisplay + ")) img").animate({ width: '70%', top: '15px' }, length);
        $(carousel + " " + item + ":not(:eq(" + currentDisplay + ")) .title, " + carousel + " li.flow_item:not(:eq(" + currentDisplay + ")) .title").hide();

        $(carousel + " " + item + ":eq(" + currentDisplay + ") img, " + carousel + " li#flow_item_" + (currentDisplay % totalItems) + " img").animate({ width: '100%', top: '0px' }, length, function () { $(HERSHEYS.Carousel).trigger("SlideComplete", $(this)); });
        $(carousel + " " + item + ":eq(" + currentDisplay + ") .title, " + carousel + " li#flow_item_" + (currentDisplay % totalItems) + " .title").fadeIn();

        $(carousel + " " + item + ":not(:eq(" + currentDisplay + ")), " + carousel + " li.flow_item:not(:eq(" + currentDisplay + "))").removeClass('active-carousel-item');
        $(carousel + " " + item + ":eq(" + currentDisplay + "), " + carousel + " li#flow_item_" + (currentDisplay % totalItems) + "").addClass('active-carousel-item');

        $(HERSHEYS.Carousel).trigger("SlideStart", carousel + " " + item + ":eq(" + currentDisplay + ") img");


    };

    var initReset = function (that) {
        currentDisplay = that.config.firstItem;
        carousel.find(that.config.carouselContainer).css('left', 0);
        carousel.find(that.config.carouselItem + " img, li.flow_item img").css({ width: '70%', top: '15px' });
    }

    return {
        sliding: false,
        numClicks: 0,
        animateSize: function () {
            if (this.config.disableAnimation) {
                var item = this.config.carouselItem;
                var carousel = this.config.carouselSelector;
                $(HERSHEYS.Carousel).trigger("SlideStart", carousel + " " + item + ":eq(" + currentDisplay + ") img");
                $(HERSHEYS.Carousel).trigger("SlideComplete", carousel + " " + item + ":eq(" + currentDisplay + ") img");
                return false;
            }
            doAnimation(this.config.carouselSelector, this.config.carouselItem, this.config.animationLength);

        },
        init: function (opts) {
            this.config = HERSHEYS.Utility.assignConfig('Carousel', defaults, opts);

            //Remove flow items
            $(this.config.carouselSelector).find('.flow_item').remove();

            carousel = $(this.config.carouselSelector);

            //Reset values if user requested
            if (this.config.resetValues) { initReset(this); }

            totalItems = carousel.find(this.config.carouselItem).length;
            if (!totalItems) { console.warn("Carousel: No items found for selector '" + this.config.carouselSelector + ' ' + this.config.carouselItem + "'"); }
            if (totalItems < 3) { $.error("Carousel: carousel must have at least 3 items, " + totalItems + " found!"); return false; }

            //Add navigation items
            carousel.before(prevButton, nextButton);

            if (this.config.showTitle) {
                $.each(carousel.find(this.config.carouselItem), function (i, v) {
                    if ($(v).find('.title').length < 1) {
                        $(v).append('<span class="title hidden">' + $(v).find('img').attr('alt') + '</span>');
                    }
                });
            }

            //Add flow items
            for (i = 0; i < this.config.numVisible; i++) {
                var item = $('<li class="flow_item" id="flow_item_' + i + '"></li>').html($(this.config.carouselItem + ":eq(" + i + ")").html());
                carousel.find(this.config.carouselContainer).append(item);
            }

            prevButton.addClass(this.config.navClass).unbind('click').bind('click', this, this.doPrevious);
            nextButton.addClass(this.config.navClass).unbind('click').bind('click', this, this.doNext);


            currentDisplay = this.config.firstItem;

            //Initialize sizes of carousel items
            this.animateSize();

        },
        doPrevious: function (e) {

            var that = e.data;

            that.numClicks++;

            if (that.numClicks == totalItems - 1 || that.numClicks == -1 * (totalItems - 1)) {
                $(HERSHEYS.Carousel).trigger("AllItemsSeen");
            }

            if (!that.sliding) {
                that.sliding = true;
                var scroller_pos = carousel.find(that.config.carouselContainer).position();
                //alert(currentDisplay);
                if (currentDisplay === that.config.firstItem) {
                    carousel.find(that.config.carouselContainer).css('left', (-(that.config.slideDistance * (totalItems))) + 'px');
                }
                if (currentDisplay <= 0) {
                    currentDisplay = totalItems - 1;
                } else {
                    currentDisplay--;
                }
                that.animateSize();
                carousel.find(that.config.carouselContainer).animate({ left: "+=" + that.config.slideDistance }, that.config.animationLength, function () {
                    that.sliding = false;

                });
            }
            return false;
        },
        doNext: function (e) {


            var that = e.data;

            that.numClicks++;

            if (that.numClicks == totalItems - 1) {
                $(HERSHEYS.Carousel).trigger("AllItemsSeen");
            }

            if (!that.sliding) {
                that.sliding = true;
                /*var scroller_pos = carousel.find(that.config.carouselContainer).position();
                var totalCarouselWidth = (-(that.config.slideDistance * (totalItems)));
                var scrollPosLeft = Math.round(scroller_pos.left);*/

                if (currentDisplay == that.config.firstItem) {
                    carousel.find(that.config.carouselContainer).css('left', 0);
                }
                if (currentDisplay >= totalItems - 1) {
                    currentDisplay = 0;
                } else {
                    currentDisplay++;
                }
                that.animateSize();
                carousel.find(that.config.carouselContainer).animate({ left: "-=" + that.config.slideDistance }, that.config.animationLength, function () {
                    that.sliding = false;
                });
            }
            return false;
        }

    };
})();




HERSHEYS.TabbedBrowsingInt = (function () {


    var defaults = {

        wrapperSelector: '.tabbedBrowsingInt',

        navSelector: '.navInt a',

        contentSelector: '.tabbedContentInt',

        nextSelector: false,

        previousSelector: false,

        ignoreShow: false,

        parentActive: false,

        autoRotate: false,

        transition: 'hide',

        tabContentClass: 'tab-content-active',

        expanded: false,

        callback: function () { }

    };

    function show(which) {

    }

    function doCallback(callbackFn) {
        if (typeof callbackFn == 'function') {
            callbackFn.call(this);
        }
    }

    var ItemsSeen = [];

    return {

        init: function (opts) {

            this.config = HERSHEYS.Utility.assignConfig('TabbedBrowsingInt', 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("TabbedBrowsingInt: 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 tabbedBrowsingInt 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("TabbedBrowsingInt: no nav items found for selector '" + this.config.navSelector + "'"); }

            if (this.config.nextSelector) {

                var nextButton = $(this.config.nextSelector);

                if (!nextButton.length) { $.error("TabbedBrowsingInt: 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("TabbedBrowsingInt: 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.TabbedBrowsingInt).trigger('TabClick', $(this));
                $(HERSHEYS.TabbedBrowsingInt).trigger('NewItemShowing', $(this));

                var cleanTitle = HERSHEYS.Utility.titleHash($(this).attr('title'));

                location.hash = '/' + cleanTitle;

                if (that.config.parentActive) {
                    that.navItems.parent().removeClass('active');
                    $(this).parent().addClass('active');
                } else {
                    that.navItems.removeClass('active');
                    $(this).addClass('active');
                }

                var index = $(this).index(that.config.navSelector);

                if (!that.config.ignoreShow) {
                    that.show(index, cleanTitle);
                }

                //Execute Click Callback Function
                if (that.config.callback) {
                    doCallback(that.config.callback);
                }

                if (that.config.expanded) {
                    $(that.config.navSelector).each(function (i) {
                        $(this).text($(this).text().replace('[-]', '[+]'));
                    }); 
                    var question = $(this).text();
                    question = question.replace('[+]', '[-]');


                    $(this).text(question);
                }

                return false;
            });

            if (this.config.autoRotate) {
                setInterval(function () {
                    that.nextbutton.click();
                }, this.config.autoRotate);
            }

            //	if (this.config.ignoreShow){
            $(this.navItems[this.jumpToIndex]).click();
            //	}

            $(HERSHEYS.TabbedBrowsingInt).trigger('DeepLinked', this.jumpToIndex);
        },
        show: function (index, cleanTitle) {

            ItemsSeen[index] = true;

            if (this.config.transition == 'fade') {
                this.contentItems.fadeOut(2000);
                $(this.contentItems[index]).fadeIn(2000);
            } else if (this.config.transition == 'slide') {

                var _this = this;

                $(this.contentItems[this.currentIndex]).slideUp(500, function () {
                    $(_this.contentItems[index]).slideDown(500);
                });
            } else {
                this.contentItems.hide();
                if (this.contentItems.hasClass(this.config.tabContentClass)) { this.contentItems.removeClass(this.config.tabContentClass); }
                $(this.contentItems[index]).show().addClass(this.config.tabContentClass);
            }

            this.currentIndex = index;

            if (ItemsSeen.length && ItemsSeen.length == this.navItems.length) {
                var seenAll = true;

                $.each(ItemsSeen, function (i, v) { if (!v) seenAll = false; });

                if (seenAll) {
                    $(HERSHEYS.TabbedBrowsingInt).trigger('AllItemsSeen');
                    ItemsSeen = false;
                }
            }
        }

    };

})();
























HERSHEYS.TabbedBrowsing = (function () {

    /* Triggers:
    'NewItemShowing' - passes clean title name of tab,
    'TabClick' - passes in reference to which was clicked,
    'DeepLinked' - passed index of the deep link item to show
    */

    /* 
    Usesage: 

    $(document).ready(function(){
    HERSHEYS.TabbedBrowsing.init();	
    });

    OR, to configure manually:

    $(document).ready(function(){
    HERSHEYS.TabbedBrowsing.init({
    navSelector : '.tabbedBrowsing .nav a',
    contentSelector : '.tabbedBrowsing .tabbedContent',
    nextSelector : '.tabbedNext'
    });	
    });

    - handle the showing and hiding
    - add "active" class to current item
    - will add location hash (the title of the nav with spaces turned to dashses),
    - upon page load will show the proper content and add nav.
    - sends all analytics info based on the title
    - if nextSelector or previousSelector are defined, they will be bound to handle forward and backwards navigation

    HTML structure looks like this:

    <div class="tabbedBrowsing"> 
    <ul class="nav">
    <li><a href="#" title="Human readable title of nav item">Nav 1</a></li>
    <li><a href="#" title="Nav 2 Name">Nav 2</a></li>
    <li><a href="#" title="Nav 3 Name">Nav 3</a></li>
    <li><a href="#" title="Nav 4 Name">Nav 4</a></li>
    </ul>
	
    <div class="tabbedContent">Content 1</div>
    <div class="tabbedContent">Content 2</div>
    <div class="tabbedContent">Content 3</div>
    <div class="tabbedContent">Content 4</div>
	
    </div>
    */


    var defaults = {

        wrapperSelector: '.tabbedBrowsing',

        navSelector: '.nav a',

        contentSelector: '.tabbedContent',

        nextSelector: false,

        previousSelector: false,

        ignoreShow: false,

        parentActive: false,

        autoRotate: false,

        transition: 'hide',

        tabContentClass: 'tab-content-active',

        expanded: false,

        callback: function () { }

    };

    function show(which) {

    }

    function doCallback(callbackFn, args) {
        if (typeof callbackFn == 'function') {
            callbackFn.call(this, args);
        }
    }

    var ItemsSeen = [];

    return {

        init: function (opts) {

            this.config = HERSHEYS.Utility.assignConfig('TabbedBrowsing', defaults, opts);
            this.navItems = $(this.config.navSelector);
            this.contentItems = $(this.config.contentSelector);
            this.jumpToIndex = 0;
            this.currentIndex = 0;

            var that = this;

            if (!this.config.ignoreShow) {
                if (!this.contentItems.length) { $.error("TabbedBrowsing: no content items found for selector '" + this.config.contentSelector + "'"); }
                this.contentItems.hide();
            }

            $.each(this.navItems, function (i, v) {

                var title = $(v).attr('title');

                if (!title) {
                    console.warn('No title provided for tabbedBrowsing element (index: ' + i + '). Please add one for analytics and location.hash');
                }

                if (title == HERSHEYS.Utility.titleHash(location.hash, 'fromHash')) {
                    that.jumpToIndex = i;
                    if (that.config.parentActive) {
                        $(v).parent().addClass('active');
                    } else {
                        $(v).addClass('active');
                    }
                }
            });

            ItemsSeen[this.jumpToIndex] = true;

            if (!this.navItems.length) { $.error("TabbedBrowsing: no nav items found for selector '" + this.config.navSelector + "'"); }

            if (this.config.nextSelector) {

                var nextButton = $(this.config.nextSelector);

                if (!nextButton.length) { $.error("TabbedBrowsing: no next button found for selector '" + this.config.nextSelector + "'"); }

                nextButton.bind('click', function () {
                    var next = 0;
                    $.each(that.navItems, function (i, v) {
                        if (that.config.parentActive) {
                            if ($(v).parent().hasClass('active') && i < that.navItems.length - 1) {
                                next = i + 1;
                            }
                        } else {
                            if ($(v).hasClass('active') && i < that.navItems.length - 1) {
                                next = i + 1;
                            }
                        }
                    });
                    $(that.navItems[next]).click();
                    return false;
                });

                this.nextbutton = nextButton;

            }

            if (this.config.previousSelector) {

                var previousButton = $(this.config.previousSelector);

                if (!previousButton.length) { $.error("TabbedBrowsing: no previous button found for selector '" + this.config.previousSelector + "'"); }

                previousButton.bind('click', function () {
                    var next = that.navItems.length - 1;
                    $.each(that.navItems, function (i, v) {
                        if (that.config.parentActive) {
                            if ($(v).parent().hasClass('active') && i !== 0) {
                                next = i - 1;
                            }
                        } else {
                            if ($(v).hasClass('active') && i !== 0) {
                                next = i - 1;
                            }
                        }
                    });
                    $(that.navItems[next]).click();
                    return false;
                });
            }

            this.navItems.bind('click', function () {

                $(HERSHEYS.TabbedBrowsing).trigger('TabClick', $(this));
                $(HERSHEYS.TabbedBrowsing).trigger('NewItemShowing', $(this));

                var cleanTitle = HERSHEYS.Utility.titleHash($(this).attr('title'));

                location.hash = '/' + cleanTitle;

                if (that.config.parentActive) {
                    that.navItems.parent().removeClass('active');
                    $(this).parent().addClass('active');
                } else {
                    that.navItems.removeClass('active');
                    $(this).addClass('active');
                }

                var index = $(this).index(that.config.navSelector);

                if (!that.config.ignoreShow) {
                    that.show(index, cleanTitle);
                }

                //Execute Click Callback Function
                if (that.config.callback) {
                    doCallback(that.config.callback, index);
                }

                if (that.config.expanded) {
                    $(that.config.navSelector).each(function (i) {
                        $(this).text($(this).text().replace('[-]', '[+]'));
                    }); 
                    var question = $(this).text();
                    question = question.replace('[+]', '[-]');


                    $(this).text(question);
                }

                return false;
            });

            if (this.config.autoRotate) {
                setInterval(function () {
                    that.nextbutton.click();
                }, this.config.autoRotate);
            }

            //	if (this.config.ignoreShow){
            $(this.navItems[this.jumpToIndex]).click();
            //	}

            $(HERSHEYS.TabbedBrowsing).trigger('DeepLinked', this.jumpToIndex);
        },
        show: function (index, cleanTitle) {

            ItemsSeen[index] = true;

            if (this.config.transition == 'fade') {
                this.contentItems.fadeOut(2000);
                $(this.contentItems[index]).fadeIn(2000);
            } else if (this.config.transition == 'slide') {

                var _this = this;

                $(this.contentItems[this.currentIndex]).slideUp(500, function () {
                    $(_this.contentItems[index]).slideDown(500);
                });
            } else {
                this.contentItems.hide();
				// Added a visibility parameter only for the York site to prevent flickering on the product page
				if(window.location.toString().indexOf("/york") > -1) { 
					this.contentItems.css('visibility', 'visible');
				}
                if (this.contentItems.hasClass(this.config.tabContentClass)) { this.contentItems.removeClass(this.config.tabContentClass); }
                $(this.contentItems[index]).show().addClass(this.config.tabContentClass);
            }

            this.currentIndex = index;

            if (ItemsSeen.length && ItemsSeen.length == this.navItems.length) {
                var seenAll = true;

                $.each(ItemsSeen, function (i, v) { if (!v) seenAll = false; });

                if (seenAll) {
                    $(HERSHEYS.TabbedBrowsing).trigger('AllItemsSeen');
                    ItemsSeen = false;
                }
            }
        }

    };

})();
HERSHEYS.Rotator = (function(){
	
	/* triggers: 
		'NewItem' - passes handle to new item
		'AllItemsSeen' - passes handle to new item
	*/
	
	var defaults = {
		
		wrapperSelector : '.rotator_wrapper',
		
		nextSelector : '.rotator_next',
		
		prevSelector : '.rotator_prev',
		
		contentSelector : '.rotator_content',
		
		autoRotate : false,
		
		fadeLength : 400
		
	};
	
	return {
		
		init : function(opts){
			this.config = HERSHEYS.Utility.assignConfig('Rotator', defaults, opts);
			
			var that = this;
			
			var nextButton = $(this.config.nextSelector);
						
			var prevButton = $(this.config.prevSelector);
			
			
			this.allItems = $(this.config.contentSelector);
			if (!this.allItems.length) {console.warn("Rotator: No content items found for selector '"+this.config.contentSelector+"'");}
			
			nextButton.bind('click', function(){that.next(); return false;});
			prevButton.bind('click', function(){that.prev(); return false;});
			
			if (this.config.autoRotate){
				setInterval(function(){
					that.next();
				}, this.config.autoRotate);
			}
					
		},
		
		next : function(e){
			
			var current = $(this.config.contentSelector).filter('.active:first');
			if (!current.length) {
				current = $(this.config.contentSelector).filter(':first');
			}

			var next = current.next(this.config.contentSelector);

			if (!next.length) {
				next = $(this.config.contentSelector).filter(':first');
				$(HERSHEYS.Rotator).trigger('AllItemsSeen', next);
			}

			$(this.config.contentSelector).removeClass('active').fadeOut(this.config.fadeLength);
			next.addClass('active').fadeIn(this.config.fadeLength);
			
			$(HERSHEYS.Rotator).trigger('NewItem', next);
			
		},
		
		prev : function(e){

			var current = $(this.config.contentSelector).filter('.active:first');
			var prev = current.prev(this.config.contentSelector);

			if (!prev.length) {
				prev = $(this.config.contentSelector).filter(':last');
			//	$(HERSHEYS.Rotator).trigger('AllItemsSeen', prev);
			}

			$(this.config.contentSelector).removeClass('active').hide();
			prev.addClass('active').show();

			$(HERSHEYS.Rotator).trigger('NewItem', prev);

		}
		
	};
	
	
	
})();
HERSHEYS.Promotions = (function () {

    var USE_WEBSERVICE = true;
    var MISSING_FIELDS_NOTICE = "Be sure all required fields are entered";
    var INVALID_EMAIL_NOTICE = "Please enter a valid email address";
    var PASSWORD_MATCH_NOTICE = "The Password & Confirm Password values must match";

    var standardFancyBoxConfig = {
        'padding': 0,
        'opacity': true,
        'scrolling': 'no',
        'titleShow': false,
        'onStart': function () {
            if ($('.pr_page').length) { $('#fancybox-wrap').addClass('pr_fancybox'); }
            if ($('.pr_fancybox_noborder').length) { $('#fancybox-outer').addClass('pr_fancybox_noborder'); }
            if ($("body").attr("class").indexOf("-es") > -1) {
                MISSING_FIELDS_NOTICE = "Aseg&uacute;rese de que todos los campos obligatorios se introducen";
                INVALID_EMAIL_NOTICE = "Por favor escribe un e-mail v&aacute;lido";
                PASSWORD_MATCH_NOTICE = "Contrase&ntilde;a y Confirmar Contrase&ntilde;a deben coincidir";
            }
        }
    };

    var emailValidationFail = false;
    var passwordMatchFail = false;

    var doWebserviceCall = function (config, data, location, customCallback) {

        wipeOutStatus();
        showAjaxLoading();

        $.ajax({
            type: "POST",
            data: $.toJSON({ 'config': config, 'data': data }),
            dataType: "json",
            url: location,
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                webserviceReturn = data.d;


                if (typeof customCallback == 'function') {
                    customCallback(data.d);
                    return false;
                }

                if (webserviceReturn.status) {

                    $('.pr_form:visible :input').each(function () {

                        if ($(this).attr('type') == 'submit') return true;

                        $(this).attr("value", '');

                    });

                    if (webserviceReturn.data) {

                        $.each(webserviceReturn.data, function (i, v) {
                            $('#replace_' + i).html(v);
                            $('input[name=' + i + ']').attr('value', v);
                            $('select[name=' + i + ']').attr('value', v);
                        });

                    }

                    if (webserviceReturn.isLoggedIn || webserviceReturn.text == 'entry_confirmation' || webserviceReturn.text == 'instant_win' || webserviceReturn.text == 'max_entry_confirmation' || webserviceReturn.text == ' repeat_entry_confirmation' || 
                        webserviceReturn.text == 'instant_win#prize1' || webserviceReturn.text == 'instant_win#prize2' || webserviceReturn.text == 'instant_win#prize3') {
                        $('.pr_member_controls').fadeIn();
                    } else {
                        $('.pr_member_controls').fadeOut();
                    }

                    //if we're on the edit profile step, display the address fields based on the user's country...
                    if (webserviceReturn.text == 'edit_profile') {
                        switch (webserviceReturn.data.editprofile_country.toLowerCase()) {
                            //                            case 'united states':               
                            //                                $('div[name=\'pnlEditProfileUsAddress\']').css('display', 'block');               
                            //                                $('div[name=\'pnlEditProfileCanadianAddress\']').css('display', 'none');               
                            //                                break;               
                            //                            default:               
                            //                                $('div[name=\'pnlEditProfileUsAddress\']').css('display', 'none');               
                            //                                $('div[name=\'pnlEditProfileCanadianAddress\']').css('display', 'block');               
                            //                                break;                
                            case 'canada':
                                $('div[name=\'pnlEditProfileUsAddress\']').css('display', 'none');
                                $('div[name=\'pnlEditProfileCanadianAddress\']').css('display', 'block');
                                break;
                            default:
                                $('div[name=\'pnlEditProfileUsAddress\']').css('display', 'block');
                                $('div[name=\'pnlEditProfileCanadianAddress\']').css('display', 'none');
                                break;
                        }
                    }

                    switch (webserviceReturn.status) {
                        case 1:
                            /* This means the webservice was a success, do the next step of the process */
                            doPromoRegStep(webserviceReturn.text);
                            break;

                        case 2:
                            /* This means the webservice was a success, but don't continue on, show the message */
                            $('.pr_status_messages').html(webserviceReturn.text);
                            hideAjaxLoading();
                            break;

                    }
                } else {
                    //only reload the captcha image if that step is visible...
                    if ($('#pr_regstep_form_initiation').css('display') != 'none') {
                        Recaptcha.reload();
                    }
                    errorText = webserviceReturn.text;
                    if ($("body").attr("class").indexOf("-es") > -1 && webserviceReturn.text == "Invalid username and password.")
                        $('.pr_error_messages').html("Usuario y contrase&ntilde;a inv&aacute;lidos.").fadeIn();
                    else
                        $('.pr_error_messages').html(errorText).fadeIn();
                    hideAjaxLoading();
                }
            },
            error: function (data) {

                if ($('#pr_regstep_form_initiation').css('display') != 'none') {
                    Recaptcha.reload();
                }

                $('.pr_error_messages').html('There was an error submitting your request!').fadeIn();
                hideAjaxLoading();
            }
        });
    };

    var doPromoRegStep = function (which) {

		which = 'instant_win#prize1'; //TODO: timmy: remove this...just temporary to assist with testing on DEV
	
        $(HERSHEYS.Promotions).trigger('DoingRegStep', which);

        $(HERSHEYS.Promotions).trigger('DoingRegStep_' + which);

        wipeOutStatus();

        //NEW: for instant winners, web service to return 'instant_win#prize_n' where 'n' is the prize number (e.g. 1, 2 or 3)...
        //     we'll split on the hash (#):
        //     - the left-hand side (e.g. instant_win) indicates which modal to open
        //     - the right-hand side (e.g. prize_1) indicates which <div> within the instant_win modal to display
        var prize = null;

        if (which.split('#').length == 2) {
            prize = which.split('#')[1];
            which = which.split('#')[0];

            //hide the <div> for all 3 instant win prizes to prevent multiple prizes from being displayed upon a win...
            $('#' + getPromoID() + "_prize1").hide();
            $('#' + getPromoID() + "_prize2").hide();
            $('#' + getPromoID() + "_prize3").hide();

            $('#' + getPromoID() + "_" + prize).show(); //show the <div> associated with the prize to be awarded
        }

        $('.pr_regstep_container').hide();
        $('#pr_regstep_' + which).show().css('visibility', 'hidden');
        $('#pr_link_register').attr('title', which).click();

    };
    var wipeOutStatus = function () {
        $('.pr_error_messages').html('');
        $('.pr_status_messages').html('');
    };
    var getPromoID = function () {
        return typeof CURRENT_PROMOTION_ID == 'undefined' ? 'UNDEFINED_PROMOTION_ID' : CURRENT_PROMOTION_ID;
    };
    var getInstantWinType = function () {
        return typeof CURRENT_INSTANTWIN_TYPE == 'undefined' ? '' : CURRENT_INSTANTWIN_TYPE;
    }
    var getPromoPageLanguage = function () {
        return typeof CURRENT_PAGE_LANGUAGE == 'undefined' ? 'en-US' : CURRENT_PAGE_LANGUAGE;
    }
    var showAjaxLoading = function () {
        $('#pr_loading_screen').fadeIn();
        $.fancybox.showActivity();
    };
    var hideAjaxLoading = function () {
        $('#pr_loading_screen').fadeOut();
        $.fancybox.hideActivity();
    };
    var validatePromoField = function (field) {

        var value = $.trim(field.val());

        if (field.hasClass('required') && value == "") {
            return false;
        }

        //TODO: this email validation message will override the required field message ('Be sure all required fields are entered')
        //      - it's shown even when you haven't entered any data in any fields...probably not the best to show it unless there's data entered
        if (field.hasClass('email') && !HERSHEYS.Utility.validate('email', value)) {
            emailValidationFail = true;
            return false;
        }

        if (field.attr('matchfield') && value == "") {
            return false;
        }

        if (field.attr('matchfield') && !($('#' + field.attr('matchfield')).val() == field.val())) {
            //NOTE: if we use 'matchfield' for something other than password/confirm password in other promos, we'll need another error message that is specific to those fields
            passwordMatchFail = true;
            return false;
        }

        return true;

    };

    var drawDevNav = function () {

        $('body').prepend('<div id="promoDebugNav" class="" style="padding: 10px; text-align: center; background-color: white; position: relative; z-index: 9999;"></div>');

        $('div[id^=pr_regstep_]').each(function () {

            var key = $(this).attr('id').split('pr_regstep_')[1];

            $('#promoDebugNav').append('<a style="color: black;" class="pr_regstep_link" rel="' + key + '" href="#">' + key + '</a> &nbsp;&nbsp;&nbsp;');

        });

        $('#promoDebugNav').append('<hr>');

        $('.pr_modal_popup:not(a[href=#pr_register_init])').each(function () {

            var key = $(this).attr('href').split('#')[1];

            if (!$('#promoDebugNav a[href=#' + key + ']').length)
                $('#promoDebugNav').append('<a style="color: black;" class="pr_modal_popup" href="#' + key + '">' + key + '</a> &nbsp;&nbsp;')
        });

    };

    var ajaxBinds = function () {

        $('.pr_form input[type=submit]').unbind('click').bind('click', function () {


            var config = {
                'promoKey': getPromoID(), 'instantWinType': getInstantWinType(), 'promoPageLanguage': getPromoPageLanguage()
            };
            var data = {
        };

        var successfullSubmit = true;

        //This is where the form field values are loaded into 'data' to be sent via the web service...
        $(this).parents(".pr_form").find(':input:not([type=submit], [type="hidden"]), .pr_serialize, #recaptcha_challenge_field').each(function () {

            var isVisible = false;
            /*Below conditional is ridiculous but working - checks either input field or input field pr_form_field parent for visibility - IE6/7 fix*/
            if (($(this).is(':visible')) && ($(this).css('visibility') != 'hidden' && $(this).parents('.pr_form_field').css('visibility') != 'hidden')) {
                isVisible = true;
            }

            if (isVisible || $(this).hasClass("pr_serialize") || $(this).attr("id") == "recaptcha_challenge_field") {

                var value = $.trim($(this).val());

                data[$(this).attr('name')] = $(this).val();

                if (validatePromoField($(this))) {
                    $(this).removeClass('error');
                } else {
                    $(this).addClass('error');
                    successfullSubmit = false;
                }

            }
        });

        if (successfullSubmit) {
            if (USE_WEBSERVICE) {
                var action = typeof data['action'] == 'undefined' ? "/services/Promotions.asmx/AgeCheck" : data['action'];

                action = $(this).parents(".pr_form").attr('action');
                if (action.indexOf('MemberLogin') > -1) {
                    action = HostURL() + action;
                }

                if (!action) {
                    $.error('Every div class="pr_form" MUST have action="webserviceURL"');
                } else {
                    doWebserviceCall(config, data, action);
                }
            } else {
                doPromoRegStep($('.pr_regstep_container:visible').next().attr('id').split('pr_regstep_')[1]);
            }
        } else {
            wipeOutStatus();

            if (emailValidationFail) {
                $('.pr_error_messages').html(INVALID_EMAIL_NOTICE).fadeIn();
            }
            else if (passwordMatchFail) {
                $('.pr_error_messages').html(PASSWORD_MATCH_NOTICE).fadeIn();
            }
            else {
                $('.pr_error_messages').html(MISSING_FIELDS_NOTICE).fadeIn();
            }

            $('#pr_loading_screen').fadeOut();
            $.fancybox.hideActivity();

            //reset 'special' validation flags...
            emailValidationFail = false;
            passwordMatchFail = false;
        }

        return false;

    });

    $('.pr_regstep_link').bind('click', function () {
        HERSHEYS.Promotions.jumpToStep($(this).attr('rel'));
        return false;
    });

    $('#pr_refresh_captcha').bind('click', function () {
        $('.pr_form_captcha img').attr('src', '/services/captcha.aspx?' + Math.random() + '" />');
        return false;
    });

    $('.pr_form input[type!=submit]').unbind('keydown').bind('keydown', function (event) {
        if (event.keyCode == 13) {
            $(this).parents('.pr_form').find(':submit').click();
            return false;
        }
    });

    //Toggle Confirm Field Handling
    $('input[matchfield]').each(function (n) {

        var triggerId = $(this).attr('matchfield');
        var target = $(this).parents('.pr_form_field');
        var changed = false;
        var originalVal = $("#" + triggerId).val();
        var currentVal;

        $("#" + triggerId).unbind('keyup').bind('keyup', function () {

            currentVal = $(this).val();

            if (currentVal != originalVal && !changed) {
                $(this).unbind('keyup');
                target.addClass('pr_showconf');
                target.css('visibility', 'visible');
                changed = true;
            }
        });
    });

    $('.cancel_fancybox').bind('click', function () {
        $.fancybox.close();
        return false;
    });

    $('#pr_regstep_tell_a_friend .pr_button2 input').bind('click', function () {
        HERSHEYS.Analytics.trackPromotionEvent('tell_a_friend_submit_button', $(this));
    });
    $('#pr_share_it a').bind('click', function () {
        HERSHEYS.Analytics.trackPromotionEvent('share_it_links', $(this));
    });
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        if (typeof DD_belatedPNG != 'undefined') {
            DD_belatedPNG.fix('div, a, img');
        }
    }

};

return {

    jumpToStep: function (which) {
        doPromoRegStep(which);
    },
    webservice: function (config, data, serviceURL, callback) {
        doWebserviceCall(config, data, serviceURL, callback);
    },
    initBinds: function () {

        /* Fixing odd URL double encoding */
        var badURL = $("a#twitter-link").attr('href');
        var goodURL = badURL.replace(/%3a/g, ':').replace(/%2f/g, '/');
        $("a#twitter-link").attr('href', goodURL);

        var PR_JSCROLL_CONFIG = {
            scrollbarWidth: typeof PR_JSCROLL_scrollbarWidth == 'undefined' || PR_JSCROLL_scrollbarWidth == "" ? 7 : PR_JSCROLL_scrollbarWidth,
            scrollbarMargin: typeof PR_JSCROLL_scrollbarMargin == 'undefined' || PR_JSCROLL_scrollbarMargin == "" ? 20 : PR_JSCROLL_scrollbarMargin,
            scrollbarShowArrows: typeof PR_JSCROLL_scrollbarShowArrows == 'undefined' || PR_JSCROLL_scrollbarShowArrows == "" ? false : PR_JSCROLL_scrollbarShowArrows
        };

        if (window.location.href.indexOf('?debug') != -1) {
            drawDevNav();
        }

        var standardPopupConfig = standardFancyBoxConfig;

        standardPopupConfig.onComplete = function () {

            if ($(".pr_jscroll").length > 0) { $("#fancybox-wrap .pr_jscroll").jScrollPane({ scrollbarWidth: PR_JSCROLL_CONFIG['scrollbarWidth'], scrollbarMargin: PR_JSCROLL_CONFIG['scrollbarMargin'], showArrows: PR_JSCROLL_CONFIG['scrollbarShowArrows'] }); }


            $('.pr_regstep_container').css('visibility', 'visible');

            /*Edit Profile - Set Confirm Fields to a default of visibility hidden*/
            var confPasswordFields = $('#pr_regstep_edit_profile .pr_form_conf');
            confPasswordFields.each(function () {
                confPasswordFields.removeClass('pr_showconf');
                confPasswordFields.css('visibility', 'hidden');
            });

            /*SUCK IT*/
            if ($('#pr_regstep_form_initiation').css('display') == 'block') {
                //Recaptcha.create("6LegxsMSAAAAAIdHsSSSIkrVVQiZsbXUi4pL0MYW",   //vmldev.com
                //Recaptcha.create("6Lc27sMSAAAAAPZbxtyQ5HuTKd8zRC__nstIvkWt",   //test.new.hersheys.com
                //Recaptcha.create("6Lc17sMSAAAAAKHDqrTflEbB-kUhY3Gkvst0gdA3",    //hersheys.com
                Recaptcha.create("6Lf8NcQSAAAAAAlTzi1f8_N-IK-u3ZHTwEh77u-v",    //hersheysumbraco.herfo.local
							"captcha-insert",
							{
							    theme: "red",
							    callback: Recaptcha.focus_response_field
							}
						);

                //$("#recaptcha_challenge_field").addClass("pr_serialize");
            }

            $('#pr_loading_screen').fadeOut();


        };

        standardPopupConfig.onClosed = function () {
            $('#pr_primarynav a').removeClass('active');
            $('#pr_nav_home a').addClass('active');
        };


        ajaxBinds();

        $('.pr_modal_popup').fancybox(standardPopupConfig);

        $('.pr_modal_popup').bind('click', function () {
            HERSHEYS.Analytics.trackPromotionPage($(this).attr('title'));
        });

        /* Takeover function of registration link to handle webservice check first */
        $('#pr_nav_register .pr_modal_popup, .pr_registerinit_link').unbind('click').bind('click', function () {
            $.fancybox.showActivity();
            doWebserviceCall({ 'promoKey': getPromoID(), 'instantWinType': getInstantWinType(), 'promoPageLanguage': getPromoPageLanguage() }, {}, "/services/Promotions.asmx/RegInit");
            return false;
        });

        /* Takeover function of tell a friend link to handle webservice check first */
        /* Notice here, I am passing in an optional function that will override the typical "doRegStep" functionality*/
        $('a[rel=tell_a_friend]').unbind('click').bind('click', function () {
            $.fancybox.showActivity();
            doWebserviceCall({ 'promoKey': getPromoID(), 'instantWinType': getInstantWinType(), 'promoPageLanguage': getPromoPageLanguage() }, {}, HostURL() + "/services/Promotions.asmx/GetActiveProfileInfo", function (dataIn) {
                /* We have a logged in user, pre-populate the firstname and last name fields of tell a friend */
                if (dataIn.data) {
                    $('#tellfriend_yourname').attr('value', dataIn.data['FirstName'] + ' ' + dataIn.data['LastName']);
                    $('#tellfriend_youremail').attr('value', dataIn.data['Email']);
                }
                HERSHEYS.Promotions.jumpToStep('tell_a_friend');
                setTimeout(function () {
                    $('#tellfriend_friendsname').focus();
                }, 500);

            });
            return false;
        });

        /* Custom call to make sure edit profile isn't standalone and continues to promo entry */
        $('a[rel=edit_incomplete_profile]').unbind('click').bind('click', function () {
            doWebserviceCall({}, {}, "/services/Promotions.asmx/EditIncompleteProfile");
            return false;
        });

        $('.pr_loggedin_edit_profile_link').bind('click', function () {
            doWebserviceCall({}, {}, HostURL() + "/services/Promotions.asmx/EditProfile");
            return false;
        });

        $('.pr_loggedin_logout_link').bind('click', function () {
            doWebserviceCall({}, {}, "/services/Promotions.asmx/LogOut");
            return false;
        });

        $('#pr_primarynav a').bind('click', function () {
            $('#pr_primarynav a').removeClass('active');
            $(this).addClass('active');
        });

        /* Sign-up country change */
        $('#initiation_country').unbind().bind('change', function () {
            //alert('SU: ' + $(this).attr('value'));
            switch ($(this).attr('value').toLowerCase()) {
                //                case 'united states':               
                //                    $('div[name=\'pnlSignUpUsAddress\']').css('display', 'block');               
                //                    $('div[name=\'pnlSignUpCanadianAddress\']').css('display', 'none');               
                //                    break;               
                //                default:               
                //                    $('div[name=\'pnlSignUpUsAddress\']').css('display', 'none');               
                //                    $('div[name=\'pnlSignUpCanadianAddress\']').css('display', 'block');               
                //                    break;                
                case 'canada':
                    $('div[name=\'pnlSignUpUsAddress\']').css('display', 'none');
                    $('div[name=\'pnlSignUpCanadianAddress\']').css('display', 'block');
                    break;
                default:
                    $('div[name=\'pnlSignUpUsAddress\']').css('display', 'block');
                    $('div[name=\'pnlSignUpCanadianAddress\']').css('display', 'none');
                    break;
            }
        });

        /* Edit Profile country change */
        $('#editprofile_country').unbind().bind('change', function () {
            //alert('EP: ' + $(this).attr('value'));
            switch ($(this).attr('value').toLowerCase()) {
                //                case 'united states':               
                //                    $('div[name=\'pnlEditProfileUsAddress\']').css('display', 'block');               
                //                    $('div[name=\'pnlEditProfileCanadianAddress\']').css('display', 'none');               
                //                    break;               
                //                default:               
                //                    $('div[name=\'pnlEditProfileUsAddress\']').css('display', 'none');               
                //                    $('div[name=\'pnlEditProfileCanadianAddress\']').css('display', 'block');               
                //                    break;                
                case 'canada':
                    $('div[name=\'pnlEditProfileUsAddress\']').css('display', 'none');
                    $('div[name=\'pnlEditProfileCanadianAddress\']').css('display', 'block');
                    break;
                default:
                    $('div[name=\'pnlEditProfileUsAddress\']').css('display', 'block');
                    $('div[name=\'pnlEditProfileCanadianAddress\']').css('display', 'none');
                    break;
            }
        });

    }
};
})();

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){ return false; $.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 = P_URL;
			
			$.each(this.config.sources, function(i,v){
				
				drop.append('<li><a class="share-links override_leaving" id="'+ v +'-link" href="'+ assignURLstrings(v) +'">'+ i +'</a></li>');
				
			});
			/*drop.find('li a').each(function(){
				var service = $(this).attr('href');
				$(this).attr({
					target: '_blank',
					href: assignURLstrings(service)
				});
			});*/
			
			drop.find("li").wrapAll("<ul></ul>");
			container.append(link);
			container.append(drop);
			
			// send to correct url
			function assignURLstrings(service) {

				if (service == 'del') { return 'http://del.icio.us/post?url=' + P_URL + '&amp;title=' + P_TITLE; }
				else if (service == 'digg') { return 'http://digg.com/submit?phase=2&amp;url=' + P_URL + '&amp;title=' + P_TITLE; }
				else if (service == 'facebook') { return 'http://www.facebook.com/share.php?u=' + P_URL + '&amp;t=' + P_TITLE; }
				else if (service == 'mixx') { return 'http://www.mixx.com/submit?page_url=' + P_URL + '&amp;title=' + P_TITLE; }
				else if (service == 'myspace') { return 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + P_URL + '&amp;t=' + P_TITLE; }
				else if (service == 'reddit') { return 'http://reddit.com/submit?url=' + P_URL + '&amp;title=' + P_TITLE; }
				else if (service == 'stumble') { return 'http://www.stumbleupon.com/submit?url=' + P_URL + '&amp;title=' + P_TITLE; }
				else if (service == 'twitter') { return 'http://www.twitter.com/home?status=' + P_URL; }
			}
			
		}

	};
})();

HERSHEYS.Video = {	
	'videoPlayer' : false,
	'doPlay' : function(source){
		    if (typeof PInstance == 'undefined') var PInstance = false;
			
            this.videoPlayer = this.videoPlayer || (PInstance && PInstance[0]) || false;
			
			if (!this.videoPlayer){
				return true;
			}
		
			var title 		= source.attr('title');
			var id 			= source.attr('id');
			var poster		= source.find('img').attr('src').replace('_thumb', '');
			var videoUrl 	= source.attr('filename');
			
			$('#video_title').html(title);

			this.videoPlayer.setTitle(title);
			this.videoPlayer.setID(id);
			this.videoPlayer.setFile(videoUrl+".mp4", false);
			this.videoPlayer.setFile(videoUrl+".ogv", false);
			this.videoPlayer.setPlay();
			this.videoPlayer.setActiveItem(1);
			this.videoPlayer.setPlayerPoster(poster);
			
	}
};
HERSHEYS.Services = (function () {

    var WEB_SERVICE_URL = '/AjaxServices.ashx';

    var doService = function (which, post, opts) {
        // SSL WEB_SERVICE_URL FOR APPLICABLE SERVICES
        if (which == 'invitefriend' || which == 'sharerecipe' || which == 'sharearticle') {
            WEB_SERVICE_URL = HostURL() + '/AjaxServices.ashx';
        }

        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(HostURL() + 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(HostURL() + WEB_SERVICE_URL + '?method=subscribe&newskitchen=y&email=' + post['email'], function (data) {

                if (data == 1) {
                    success();
                } else {
                    failure();
                }
            });

        },
        'inviteFriends': function (opts) {

            var post = {

                name: opts['name'] || 0,
                email: opts['email'] || 0,
                friendname: opts['friendName'] || 0,
                friendemail: opts['friendEmail'] || 0,
                comment: opts['comment'] || 0
            };

            doService('invitefriend', post, opts);

        },
        'shareRecipe': function (opts) {

            var post = {

                name: opts['name'] || 0,
                email: opts['email'] || 0,
                friendname: opts['friendname'] || 0,
                friendemail: opts['friendemail'] || 0,
                recipeid: opts['recipeid'] || '',
                src: opts['src'] || 'empty'
            };

            doService('sharerecipe', post, opts);

        },
        'shareArticle': function (opts) {

            var post = {

                name: opts['name'] || 0,
                email: opts['email'] || 0,
                friendname: opts['friendname'] || 0,
                friendemail: opts['friendemail'] || 0,
                articlepath: opts['articlepath'] || ''
            };

            doService('sharearticle', post, opts);

        },
        'askExpert': function (opts) {
            var post = {
                firstName: opts.firstName || ''
                , lastName: opts.lastName || ''
                , email: opts.email || ''
                , question: opts.question || ''
            };

            var cb = opts.callback || function () { };
            var url = HostURL() + WEB_SERVICE_URL + '?method=askexpert';

            /* Send the data using post and put the results in a div */
            $.post(url, post,
              function (data) {
                  cb(data);
                  /*var content = $(data).find('#content');
                  $("#result").empty().append(content);*/
              }
            );
            /*$.get(HostURL() + WEB_SERVICE_URL + '?method=askexpert&firstName=' + opts.firstName + '&password=' + password + '&keeploggedin=' + keepLoggedIn, function (data) {
                if (data == 1) {
                    HERSHEYS.IsLoggedIn = true;
                    success({ 'username': username });
                } else {
                    failure();
                }
            });*/

        },
        '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*=jobs-hersheystest.icims.com]"				
				,"a[href*=hersheystrackandfield.com]"
				,"a[href*=hersheyschocolateworld.com]"
				,"a[href*=dagobachocolate.com]"
				,"a[href*=scharffenberger.com]"
				,"a[href*=regen2recover.com]"
				,"a[href*=hersheypa.com]"
				,"a[href*=themoderationnation.com]"
				,"a[href*=TheModerationNation.com]"
				,"a[href*=hersheysbliss.com]"
				,"a[href*=CelebrateWithHersheys.com]"
				,"a[href*=hersheys.icims.com]"
				,"a[href*=ice-breakers.com]"
				,"a[href*=reeses.com]"
				,"a[href*=hersheycookies.com]"
				,"a[href*=HersheyCookies.com]"
				,"a[href*=twizzlers.com]"
				,"a[href*=thehersheylegacy.com]"
				,"a[href*=hersheykitchens.com]"
				,"a[href*=HersheyCenterforHealthandNutrition.com]"
				,"a[href*=hersheycanada.com]"
				,"a[href*=hersheysjapan.com]"
				,"a[href*=mounds.com]"
				,"a[href*=almondjoy.com]"
				,"a[href*=kisses.com]"
				,"a[href*=hersheyskiss.com]"
				,"a[href*=kitkatusa.com]"
				,"a[href*=yorkpeppermintpattie.com]"
				, "a[href*=corporate-ir.net]"
                , "a[href*=hersheyschina.com]"
                , "a[href*=trackandfield.com]"
				,"a[href*=hersheys.herfo2.dev2]"
				,"a[href*=hersheys.herfo2.test]"
			],
				promptBumper = [
				'a[href^=http://www.facebook.com]:not(".override_leaving")'
				,'a[href^=http://www.mixx.com]:not(".override_leaving")'
				,'a[href^=http://del.icio.us]:not(".override_leaving")'
				,'a[href^=http://reddit.com]:not(".override_leaving")'
				,'a[href^=http://www.stumbleupon.com]:not(".override_leaving")'
				,'a[href^=http://www.myspace.com]:not(".override_leaving")'
				,'a[href^=http://www.twitter.com]:not(".override_leaving")'
				,'a[href^=http://digg.com]:not(".override_leaving")'
				, 'a[href^=http://facebook.com]:not(".override_leaving")'
			],
				whitelistArrStr = whitelistArr.join(", "),
				promptBumperStr = promptBumper.join(", ");
			
			//whitelist
			$('a[href*=http]:not("'+ whitelistArrStr +'"),'+ promptBumperStr +'').live('click', function(){
				
				transparency.on();
				links.go.attr('href', $(this).attr('href'));
				
				var left = (($(window).width() - dialogue.width()) / 2);
				var top = (($(window).height() - dialogue.height()) / 2);
				
				dialogue.css({'left': left, 'top' : top}).fadeIn();
				return false;
			});
		},
		slideAlternate : function(opts){	
			/* Make a div twice as long as it's container and call 
			slideAlternate({
				'slideMe' : '#slideMeSelectorString',
				'howMuch' : int for the size of your container, or amount you'd like to go back and forth.
			});
			*/
				opts = opts || {};
				if (!(opts['slideMe'] && opts['howMuch'])){
					console.warn('Missing params in Utility.slideAlternate');
					return false;
				}

				var slide = $(opts['slideMe']);

				if (slide.css('left') == -1 * opts['howMuch'] + 'px'){
					slide.animate({'left': '0px'}, 1000, 'swing');
				}else{
					slide.animate({'left': -1 * opts['howMuch'] + 'px'}, 1000, 'swing');
				}
		},		
		/* Function for automatically showing active states. Simply needs to be executed at page load */
		fakeActiveNav : function(configIn){
			
			var config = {
				'wrapperSelector' : configIn['wrapperSelector'] || 'div#nav a, .nav a',
				'activeClass'	: configIn['activeClass'] || 'active',
				'activeSelector' : configIn['activeSelector'] || 'parent'
			};
			
		
			
			var currentPage = HERSHEYS.CURRENT_PAGE;
			
			$(config['wrapperSelector']).each(function(){
				
				var thisLink = $(this).attr('href').split('.aspx')[0].replace(/\//g, '');
				
				
				if (currentPage.indexOf(thisLink) != -1){
					
					if (config['activeSelector'] == 'parent'){
						$(this).parent().addClass(config['activeClass']);
					}else if (config['activeSelector'] == 'parent parent'){
						$(this).parent().parent().addClass(config['activeClass']);
					}else if (config['activeSelector'] == 'this parent'){
						$(this).parent().parent().parent().addClass(config['activeClass']);
						$(this).addClass(config['activeClass']);
					}else{
						$(this).addClass(config['activeClass']);
					}
					
				}
				
			});
			
			$(config['wrapperSelector']).bind('click', function(){
				if (config['activeSelector'] == 'parent'){
					$(config['wrapperSelector']).parent().removeClass(config['activeClass']);
					$(this).parent().addClass(config['activeClass']);
				}else{
					$(config['wrapperSelector']).removeClass(config['activeClass']);
					$(this).addClass(config['activeClass']);
				}
			});
			
		},
		inputPlaceholder : function(){
			
			$('input[placeholder]').each(function(){
				var placeholder = $(this).attr('placeholder');
				var value = $.trim($(this).attr('value'));

				if (value == ""){
					$(this).attr('value', placeholder);
				}

				$(this).bind('focus', function(){
					if ($(this).attr('value') == $(this).attr('placeholder')){
						$(this).attr('value', '');
					}
				}).bind('blur', function(){
					if ($.trim($(this).attr('value')) == ''){
						$(this).attr('value', $(this).attr('placeholder'));
					}
				});
			});
		},
		stealSearchButton : function(opts){

			var site = opts['site'] || '';
			if (site !== '') 
				site = site + '/';

			/* Steal Search button */
			$('.searchTextBox').bind('keypress', function(e){
				//if entered is pressed in text input
				if(e.keyCode == "13"){
					window.location = '/' + site + 'searchresults.aspx?KW=' + $('.searchTextBox').attr('value') + '&site=' + site.split('/')[0];
					return false;
				}
			});
			$('#search_wrap .submit, .search_wrap .submit, .search_wrap .search, .search_wrap #search, .search_submit').bind('click', function(e){
				window.location = '/' + site + 'searchresults.aspx?KW=' + $('.searchTextBox').attr('value') + '&site=' + site.split('/')[0];
				return false;
			});
		},
		/* Transparency object - instantiation adds it to body, hide and show methods available. */
		Transparency : function(config){
			config = config || {};
			
			/* 	Optional config params:
					background-color, opacity, background.
				Usage: instantiate, run the init() to build, style and place HIDDEN transparency in body
								Then, call on(), off().
			*/
			var hideMethod = config['hideMethod'] || 'fadeOut';
			var fadeLength = config['fadeLength'] || 400;
			
			this.namespace 	= config['namespace'] || '_trans_div_';
			this.css = {
				'background' : config['background-image'] || 'none',
				'background-color' : config['background-color'] || '#eeeeee',
				'opacity' : config['opacity'] || '.4',
			
				'position' : 'fixed',						
				'height' : '100%',
				'width' : '100%',
				'display' : 'none',
				'top' : 0, 'left' : 0
			};
			
			this.isHidden = true;
			
			this.init = function(){					
				this.element = $('<div>').attr('id', '#' + this.namespace).css(this.css);
				
				var _this = this;
				this.element.bind('click', function(){
					_this.onClick();
				});
				$('body').append(this.element);
			};
			
			this.addCallBack = function(f){
				if (typeof f != 'function') $.error('Expecting function, given: "'+typeof(f)+'"');
				
				alert('function given');
			}
			
			this.on = function(fadeLength){
			
				if (this.element && this.isHidden){
					this.element.fadeTo(fadeLength, this.css.opacity);
				}
			};
			this.off = function(fadeLength){
				if (this.element){
					this.element.fadeOut(fadeLength);
				}
			};
			
			this.onClick = function(f){
				f = f || function(){
					
				};
				
				f();
			};
			
		}
};

//if (typeof console != 'object'){var console = { error : function(){return true}, warn : function(){return true;}};}
