/* 
================================================================================================================================ CREDITS
Notes   : Media Share
================================================================================================================================ BEGIN JAVASCRIPT
*/

/* ============================================================================================================================= COMMON FUNCTIONS */

// ---------------------------------------------------------- WINDOW LOCATION
var url = window.location.toString();

// ---------------------------------------------------------- USER AGENT
var ua = navigator.userAgent.toLowerCase();
var isie = navigator.userAgent.toLowerCase().indexOf('msie');

// ---------------------------------------------------------- GET VALUE OF QUERYSTRING PARAMETER
function getQueryValue(key) {
	key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

	var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
	var qs = regex.exec(window.location.href);
	if (qs == null) {
		return "";
	}
	return qs[1];
}

// ---------------------------------------------------------- REMOVE FILTER AFTER OBJECT IS DONE ANIMATING (CLEARTYPE ISSUES IN IE)
function removeFilter(obj) {
	if ($.browser.msie) {
		$(obj).get(0).style.removeAttribute('filter');
	}
}

// ---------------------------------------------------------- SET COOKIE
function setCookie(name,value,expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = name + " = " + escape(value) + "; path=/" + ((expiredays==null) ? "" : "; expires = " + exdate.toGMTString());
}

// ---------------------------------------------------------- RETRIEVE COOKIE
function getCookie(check_name) {
	var cookies = document.cookie.split( ';' );
	var tmpcookie = cookie_name = cookie_value = '';
	var cookie_found = false;

	for (var i = 0; i < cookies.length; i++ ) {
		tmpcookie = cookies[i].split( '=' );
		cookie_name = tmpcookie[0].replace(" ", "");

		if (cookie_name == check_name) {
			cookie_found = true;
			if (tmpcookie.length > 1) cookie_value = unescape(tmpcookie[1].replace(" ", ""));
		}
	}
	if (!cookie_found) {
		return "none";
	} else {
		return cookie_value;
	}
}

// ---------------------------------------------------------- VALIDATE EMAIL
function validate_email(email) {
	var invalid = ' /:,;';
	if (email == '' || email == null) {
		return false;
	} else {
		if (email.search(/^[\w-_.]*[\w-_.]@[\w].+[\w]+[\w]$/) == -1) {
			return false;
		}
		for (var i = 0; i < invalid.length; i++) {
			badChar = invalid.charAt(i);
			if (email.indexOf(badChar,0) > -1) {
				return false;
			}
		}
	}
	return true;
}

/* ============================================================================================================================= COMMON FLASH FUNCTIONS */

// ---------------------------------------------------------- GLOBAL VAR USED TO STORE FLASH PLAYER OBJECT
var ytplayer = '';

// ---------------------------------------------------------- GOOGLE ANALYTICS TRACKING (FROM WITHIN FLASH)
function google_analytics(str) {
	if (str != '') {
		_gaq.push(['_trackEvent', 'Videos', 'Play', str]);
	}
}

// ---------------------------------------------------------- CROSS-BROWSER FUNCTION TO RETRIEVE FLASH OBJECT FROM DOM
function thisMovie(movieName) {
	if (window.document[movieName]) return window.document[movieName];
	if (navigator.appName.indexOf("Microsoft Internet") == -1) {
		if (document.embeds && document.embeds[movieName]) return document.embeds[movieName]; 
	} else {
		return document.getElementById(movieName);
	} 
}

// ---------------------------------------------------------- YOUTUBE CALLBACK FUNCTION WITHIN FLASH PLAYER
function onYouTubePlayerReady(str) {
	var arrVid = str.split('|'); // [0] = DOM OBJECT ID, [1] = YOUTUBE VIDEO ID
	ytplayer = thisMovie(arrVid[0]);

	// IF OBJECT EXISTS, LOAD AND CUE VIDEO
	if (ytplayer != null) {
		ytplayer.cueVideoById(arrVid[1]);

		if (url.indexOf('video=') > -1) {
			$('.video-playlist li a[href*="' + getQueryValue('video') + '"]').trigger('click');
		}
	}
}

// ---------------------------------------------------------- IF YOUTUBE ISN'T ACCESSIBLE, PLAY LOCAL MP4 FILE
function onJPLPlayerReady(str) {
	var arrVid = str.split('|'); // [0] = DOM OBJECT ID, [1] = YOUTUBE VIDEO ID
	ytplayer = thisMovie(arrVid[0]);
}

/* ============================================================================================================================= FLASH LOAD */

function load_flash() {
	// AVAILABLE FLASHVARS
	// ytAvailable	: if false, YouTube is bypassed and and the local mp4 file is used
	// pathToVideo	: path to video, assumes /lib/vid/
	// dimensions	: width|height of video, assumes 368x288 otherwise (12px added for video controls)
	
	var flashvars = {};
	var params = { base: ".", allowScriptAccess: "always" };
	var attributes = {};
	var alt = '#video-player-alt';
	
	// EXPERT ADVICE VIDEO PLAYER
	if ($('#video-player').length) {		 
		swfobject.embedSWF(
			"/lib/swf/player.swf?enablejsapi=1&playerapiid=video-player|xyIrO6Catwk", 
			"video-player", "368", "288", "9.0.0", "/lib/swf/expressInstall.swf", flashvars, params, attributes
		);

		if ($('#video-player-alt').css('visibility') == 'hidden') {
			$('#video-player-alt').css('visibility','visible');
		}
	}
}

/* ============================================================================================================================= DOM READY, ATTACH EVENT HANDLERS */

$(document).ready(function() {
	/* ------------------------------------------------------------------------------------------------------------------------- DROPDOWN MENUS */
	// USES hoverIntent PLUGIN
	
	if ($('.main-nav').length) {
		$('.main-nav').children('li').children('a').each(function() {
			$(this).hoverIntent(
				function() {
					if ($(this).next('ul').css('display') == 'none') {
						$(this).parent().addClass('active');
						if ($(this).children('img').attr('src') == '/lib/img/nav/topnav-arrow.gif') {
							$(this).children('img').attr('src','/lib/img/nav/topnav-arrow-active.gif');
						}
						if ($(this).parent().hasClass('first')) {
							$(this).parent().next().children('ul').slideUp(200,function() {
								$(this).parent().removeClass('active');
							});
						} else {
							$(this).parent().prev().children('ul').slideUp(200,function() {
								$(this).parent().removeClass('active');
							});
						}
						$(this).next('ul').slideDown(500);
					}
				},
				function(event) {
					if (event.relatedTarget.nodeName != "A" || event.relatedTarget.className == "navlink" || event.relatedTarget.className == "logo" || event.relatedTarget.className == "bean-hdr show-bean-home" || event.relatedTarget.className == "chocolate-hdr show-chocolate-home") {
						$(this).next('ul').slideUp(200, function() {
							$(this).parent().removeClass('active');
							if ($(this).prev().children('img').attr('src') == '/lib/img/nav/topnav-arrow-active.gif') {
								$(this).prev().children('img').attr('src','/lib/img/nav/topnav-arrow.gif');
							}
						});
					}
				}
			);
		});
		$('.main-nav').children('li').children('ul').each(function() {
			$(this).hover(
				function() {
					$(this).parent().addClass('active');
					if ($(this).prev().children('img').attr('src') == '/lib/img/nav/topnav-arrow.gif') {
						$(this).prev().children('img').attr('src','/lib/img/nav/topnav-arrow-active.gif');
					}
					$(this).next('ul').slideDown(500);
				},
				function(event) {
					if (event.relatedTarget.nodeName != "A" || event.relatedTarget.className == "navlink" || event.relatedTarget.className == "logo" || event.relatedTarget.className == "bean-hdr show-bean-home" || event.relatedTarget.className == "chocolate-hdr show-chocolate-home") {
						$(this).slideUp(200, function() {
							$(this).parent().removeClass('active');
							if ($(this).prev().children('img').attr('src') == '/lib/img/nav/topnav-arrow-active.gif') {
								$(this).prev().children('img').attr('src','/lib/img/nav/topnav-arrow.gif');
							}
						});
					}
				}
			);
		});
	}
	
	/* ------------------------------------------------------------------------------------------------------------------------- LOAD ANY FLASH */

	load_flash(); 
	
	/* ------------------------------------------------------------------------------------------------------------------------- INTRO PAGE ANIMATIONS */
	
	if ($('.bean-text').length) {
		$('.bean-text').hover(
			function() {
				if (!$(this).hasClass('noaction')) {
					$('.home-bean-photo').stop().animate({ width: '780px' }, 1000, 'easeOutBack');
					$(this).addClass('bean-text-active');
					$('.bean-copy').css('text-indent','0px');
					$('.chocolate-hdr').parent().css('display','none');
				}
			},
			function() {
				if (!$(this).hasClass('noaction')) {
					$('.bean-copy').css('text-indent','-9999px');
					$('.chocolate-hdr').parent().css('display','block');
					$(this).removeClass('bean-text-active');
					$('.home-bean-photo').stop().animate({ width: '480px' }, 700, 'easeOutBack');
				}
			}
		);
		$('.chocolate-text').hover(
			function() {
				if (!$(this).hasClass('noaction')) {
					$('.home-bean-photo').stop().animate({ width: '180px' }, 1000, 'easeOutBack');
					$(this).addClass('chocolate-text-active');
					$('.chocolate-copy').css('text-indent','0px');
					$('.bean-hdr').parent().css('display','none');
				}
			},
			function() {
				if (!$(this).hasClass('noaction')) {
					$('.chocolate-copy').css('text-indent','-9999px');
					$('.bean-hdr').parent().css('display','block');
					$(this).removeClass('chocolate-text-active');
					$('.home-bean-photo').stop().animate({ width: '480px' }, 700, 'easeOutBack');
				}
			}
		);
		
	/* ------------------------------------------------------------------------------------------------------------------------- SHOW BEAN HOME PAGE */
		$('.show-bean-home').click(function(event) {
			// POSITION HOME PAGE CONTAINER ON TOP
			$('.home-pages-container').css('z-index','90');

			var winwidth = $(window).width();
			$('.bean-home').css('margin-left',-960);
			$('.bean-text').addClass('noaction');
			$('.home-bean-photo').stop().animate({ width: '960px' }, 400, 'easeInCirc', function() {
				$('.home-photos-inner-container').addClass('bgrepeat');
				$('.home-photos-outer-container').addClass('nobg');
				$('.home-chocolate-photo').css('display','none');
			});
			
			$('.home-callouts').stop().animate({ 'margin-top': '138px' }, 400, 'easeInCirc', function() {
				$('.home-callouts-container').stop().animate({ 'margin-top': '627px', height: '30px' }, 300, 'easeInCirc', function() {
					$(this).css('display','none');
				});
				$('.bean-home').css('display','block');
				$('.bean-home').stop().animate({ 'margin-left': ((winwidth-960)/2) }, 1000, 'easeInCirc', function() {
					$(this).css('margin','0px auto');

					// PREP AREA BEHIND HOME PAGE WHEN RETURNED TO
					$('.home-bean-photo').css('width', '');
					$('.home-chocolate-photo').css('display','');
					$('.bean-text').removeClass('bean-text-active');
					$('.bean-copy').css('text-indent','');
					$('.chocolate-hdr').parent().css('display','');
				});
			});
			event.preventDefault();
		});

		/* RETURN TO INTRO PAGE FROM BEAN HOME PAGE */
		$('.bean-intro-return a').click(function(event) {
			// RESTORE AREA BEHIND HOME PAGE WHEN RETURNED TO
			$('.home-photos-inner-container').removeClass('bgrepeat');
			$('.home-photos-outer-container').removeClass('nobg');

			$('.bean-home h1').css('display', 'none');
			$('.bean-home p').css('display', 'none');
			$('.bean-navigation').css('display', 'none');

			$('.bean-home').stop().animate({ 'width': '5px' }, 800, 'easeOutCirc', function() {
				$('.bean-home').css('display','none');
				$('.bean-home').css('width','');

				// SHOW INTRO CALLOUTS
				$('.home-callouts-container').css('display','');
				$('.home-callouts').stop().animate({ 'margin-top': '0px' }, 400, 'easeOutCirc', function() {
					$('.home-callouts-container').stop().animate({ 'margin-top': '489px', height: '148px' }, 300, 'easeOutCirc', function() {
						$(this).css('height', '138px');
						$('.bean-home h1').css('display', '');
						$('.bean-home p').css('display', '');
						$('.bean-navigation').css('display', '');
						$('.bean-text').removeClass('noaction');

						// POSITION HOME PAGE CONTAINER ON TOP
						$('.home-pages-container').css('z-index','');
					});
				});
			});
			event.preventDefault();
		});

	/* ------------------------------------------------------------------------------------------------------------------------- SHOW CHOCOLATE HOME PAGE */
		$('.show-chocolate-home').click(function(event) {
			// POSITION HOME PAGE CONTAINER ON TOP
			$('.home-pages-container').css('z-index','90');

			var winwidth = $(window).width();
			$('.chocolate-home').css('margin-left',winwidth);
			$('.chocolate-text').addClass('noaction');
			$('.home-bean-photo').stop().animate({ width: '5px' }, 400, 'easeInCirc', function() {
				$('.home-photos-inner-container').addClass('nobg');
				$('.home-bean-photo').css('display','none');
			});
			
			$('.home-callouts').stop().animate({ 'margin-top': '138px' }, 300, 'easeInCirc', function() {
				$('.home-callouts-container').stop().animate({ 'margin-top': '627px', height: '30px' }, 300, 'easeInCirc', function() {
					$(this).css('display','none');
				});
				$('.chocolate-home').css('display','block');
				$('.chocolate-home').stop().animate({ 'margin-left': ((winwidth-960)/2) }, 1000, 'easeInCirc', function() {
					$(this).css('margin','0px auto');

					// PREP AREA BEHIND HOME PAGE WHEN RETURNED TO
					$('.home-bean-photo').css('display','');
					$('.home-bean-photo').css('width', '');
					$('.home-chocolate-photo').css('display','');
					$('.chocolate-text').removeClass('chocolate-text-active');
					$('.chocolate-copy').css('text-indent','');
					$('.bean-hdr').parent().css('display','');
				});
			});
			event.preventDefault();
		});

		/* RETURN TO INTRO PAGE FROM CHOCOLATE HOME PAGE */
		$('.chocolate-intro-return a').click(function(event) {
			// RESTORE AREA BEHIND HOME PAGE WHEN RETURNED TO
			$('.home-photos-inner-container').removeClass('nobg');

			$('.chocolate-home h1').css('display', 'none');
			$('.chocolate-home p').css('display', 'none');
			$('.chocolate-navigation').css('display', 'none');

			$('.chocolate-home').stop().animate({ 'width': '5px' }, 800, 'easeOutCirc', function() {
				$('.chocolate-home').css('display','none');
				$('.chocolate-home').css('width','');

				// SHOW INTRO CALLOUTS
				$('.home-callouts-container').css('display','');
				$('.home-callouts').stop().animate({ 'margin-top': '0px' }, 400, 'easeOutCirc', function() {
					$('.home-callouts-container').stop().animate({ 'margin-top': '489px', height: '148px' }, 300, 'easeOutCirc', function() {
						$(this).css('height', '138px');
						$('.chocolate-home h1').css('display', '');
						$('.chocolate-home p').css('display', '');
						$('.chocolate-navigation').css('display', '');
						$('.chocolate-text').removeClass('noaction');

						// POSITION HOME PAGE CONTAINER ON TOP
						$('.home-pages-container').css('z-index','');
					});
				});
			});
			event.preventDefault();
		});
	}

	/* ------------------------------------------------------------------------------------------------------------------------- LOCATION MAP POINTS/DETAILS */
	var activeLocation = '';
	if ($('.locations').length) {
		// ---------------------------------------------------------------------------- LOCATION ICONS EVENTS
		$('.locations .map-point').children('a').each(function() {
			// SHOW LARGER ICON ON HOVER
			$(this).hover(
				function() { $(this).css('background-position','0px -36px'); },
				function() { $(this).css('background-position','0px 0px'); }
			);
			// SHOW DETAILS ON CLICK
			$(this).click(function(event) {
				var div = '#' + $(this).attr('href').split('?location=')[1];
				if ($(div).css('display') == 'none') {
					if (activeLocation != '') {
						var prevpoint = '.point-' + activeLocation;
						$('#' + activeLocation).stop().animate({ 'height': '1px' }, 300, 'easeOutCirc', function() {
							$(this).css('display','');
							$(prevpoint).removeClass('map-point-active');
						});
						activeLocation = '';
					}
	
					var p = '.point-' + $(this).parent().parent().attr('id');
					activeLocation = $(this).attr('href').split('?location=')[1];
	
					$(this).parent().addClass('map-point-active');
					$(div).css('display','block');
					$(div).stop().animate({ 'height': '153px' }, 800, 'easeOutCirc');
				}
				event.preventDefault();
			});
		});

		// ---------------------------------------------------------------------------- LOCATION TEXT EVENTS
		$('.locations-list li').children('a').each(function() {
			$(this).hover(
				function() { $('.locations .point-' + $(this).attr('href').split('?location=')[1] + ' a').css('background-position','0px -36px'); },
				function() { $('.locations .point-' + $(this).attr('href').split('?location=')[1] + ' a').css('background-position','0px 0px'); }
			);
			$(this).click(function(event) {
				$('.locations .point-' + $(this).attr('href').split('?location=')[1] + ' a').trigger('click');
				event.preventDefault();
			});
		});

		// TRIGGER LOCATION FOR QUERYSTRING FALLBACK
		if (url.indexOf('location=') > -1) {
			$('.locations .point-' + getQueryValue('location') + ' a').trigger('click');
		}

		// ---------------------------------------------------------------------------- HIDE DETAILS
		$('.hide-details').children('a').each(function() {
			$(this).click(function(event) {
				var p = '.point-' + $(this).parent().parent().attr('id');
				$(this).parent().parent().stop().animate({ 'height': '1px' }, 300, 'easeOutCirc', function() {
					$(this).css('display','');
					$(p).removeClass('map-point-active');
					activeLocation = '';
				});
				event.preventDefault();
			});
		});		
	}
		
	/* ------------------------------------------------------------------------------------------------------------------------- ARTISAN PROCESS */
	var activeStep = 1;
	if ($('.process-steps').length) {
		// ---------------------------------------------------------------------------- LOCATION ICONS EVENTS
		$('.process-steps li').children('a').each(function() {
			$(this).click(function(event) {
				if (activeStep != '') {
					$('.process-steps li:nth-child(' + activeStep + ') a').removeClass('active');
					$('.step' + activeStep).slideUp(800, 'easeOutCirc', function() {
						$(this).removeClass('active-step');
					});
				}
				$(this).addClass('active');
				
				var x = parseInt($(this).attr('href').split('?step=')[1]);
				if (x < 0) {
					x = 0;
				} else if (x > 5) {
					x = 5;
				}
				activeStep = x;
				var col1x = col2x = 0;
								
				switch(x) {
					case 2:
						col1x = -804;
						col2x = -630;
						break;
					case 3:
						col1x = -536;
						col2x = -1260;
						break;
					case 4:
						col1x = -268;
						col2x = -1890;
						break;
					case 5:
						col1x = 0;
						col2x = -2520;
						break;
					default:
						col1x = -1072;
						col2x = 0;
				}
				
				$('.step' + activeStep).stop().slideDown(800, 'easeOutCirc', function() {
					$('.step' + activeStep).addClass('active-step');
				});

				$('.artisan-col1 p').stop().animate({ 'margin-left': col1x }, 1400, 'easeOutCirc');
				$('.artisan-col2 p').stop().animate({ 'margin-left': col2x }, 1400, 'easeOutCirc');

				event.preventDefault();
			});
		});

		// TRIGGER STEP FOR NEXT STEP LINKS
		$('.next-step').each(function() {
			$(this).click(function(event) {
				$('.process-steps li:nth-child(' + $(this).attr('href').split('?step=')[1] + ') a').trigger('click');
				event.preventDefault();
			});
		});

		// TRIGGER STEP FOR QUERYSTRING FALLBACK
		if (url.indexOf('step=') > -1) {
			$('.process-steps li:nth-child(' + getQueryValue('step') + ') a').trigger('click');
		}
	}		

	/* ------------------------------------------------------------------------------------------------------------------------- OUR CHOCOLATE (PRODUCTS) */
	var activeProduct = 'product-overview';

	if ($('.our-products').length) {
		var plistwidth = Number($('.our-products li').size() * 220);
		var curmargin = 0;
		
		// SET UL WIDTH 
		$('.our-products').css('width',plistwidth);		

		// PRODUCT PREVIOUS BUTTON
		$('.product-prev a').click(function(event) {
			if (!$(this).hasClass('animating')) {
				$(this).addClass('animating');
				$('.our-products').stop().animate({ 'margin-left': (curmargin + 220) }, 400, 'easeOutCirc', function() {
					curmargin = curmargin + 220;
					if (curmargin == 0) {
						$('.product-prev').addClass('hid');
					}
					$('.product-prev a').removeClass('animating');
				});
				if (Math.abs($('.our-products').css('margin-left').replace('px','')) + 880 <= plistwidth) {
					$('.product-next').removeClass('hid');
				}
			}
			event.preventDefault();
		});

		// PRODUCT NEXT BUTTON
		$('.product-next a').click(function(event) {
			if (!$(this).hasClass('animating')) {
				$(this).addClass('animating');
				$('.our-products').stop().animate({ 'margin-left': (curmargin - 220) }, 400, 'easeOutCirc', function() {
					curmargin = curmargin - 220;
					if (curmargin < 0) {
						$('.product-prev a').parent().removeClass('hid');
					}
					$('.product-next a').removeClass('animating');
				});
				if (Math.abs($('.our-products').css('margin-left').replace('px','')) + 1100 == plistwidth) {
					$(this).parent().addClass('hid');
				}
			}
			event.preventDefault();
		});

		// PRODUCT IMAGE LINKS
		$('.our-products li').children('a').each(function() {
			$(this).click(function(event) {
				if (!$(this).hasClass('active')) {
					$('.' + activeProduct).slideUp(400);
					$('.' + $(this).attr('href').split('?product=')[1]).slideDown(400);
	
					// REMOVE/SET ACTIVE PRODUCT CLASS
					$('.our-products li a').removeClass('active');
					$(this).addClass('active');
	
					activeProduct = $(this).attr('href').split('?product=')[1];
				}
				event.preventDefault();
			});
		});

		// HIDE OVERVIEW AFTER 5 SECONDS, SHOW FIRST TIME ONLY
		var firstproduct = $('.our-products li:first-child a').attr('href').split('?product=')[1];
		if (getCookie('product_directions') == 'hidden') {
			$('.our-products li').children('a[href*="' + firstproduct + '"]').trigger('click')
		} else {
			function hideoverview() {
				$('.our-products li').children('a[href*="' + firstproduct + '"]').trigger('click')
			}
			setCookie('product_directions','hidden',30)
			setTimeout(hideoverview, 5000);
		}
		
		// TRIGGER PRODUCT IMAGE LINK
		if (url.indexOf('product=') > -1) {
			$('.our-products li').children('a[href*="' + getQueryValue('product') + '"]').trigger('click');

			// SHOW CORRECT PAGE IF PRODUCT IS NOT ON THE FIRST PAGE
			var i = 1;
			$('.our-products li').children('a').each(function() {
				if ($(this).hasClass('active') && i > 4) {
					var producttotal = $('.our-products li').children('a').size();
					var curpage = Math.ceil(i/4);
					var pagecount = Math.ceil(producttotal / 4);
					curmargin = (220 * 4 * (curpage-1)) * -1;

					if (curpage > 1) {
						if (curpage == pagecount) {
							remainder = (4 - (producttotal - ((pagecount - 1) * 4))) * 220;
							curmargin = curmargin + remainder
							$('.our-products').stop().animate({ 'margin-left': curmargin }, Math.ceil((curpage-1) * .75 * 1000), 'easeOutCirc', function() {
								$('.product-prev a').parent().removeClass('hid');
								$('.product-next a').parent().addClass('hid');
							});
						} else {
							$('.our-products').stop().animate({ 'margin-left': curmargin }, Math.ceil((curpage-1) * .75 * 1000), 'easeOutCirc', function() {
								$('.product-prev a').parent().removeClass('hid');
							});
						}
					}
				}
				i++;
			});
		}		
	}

	// NUTRITION INFO 
	if ($('.nutrition-info').length || $('.nutrition-info-nofloat').length) {
		$('.nutrition-info a, .nutrition-info-nofloat a').each(function() {
			$(this).bind('click',function(event) {
				var href = $(this).attr('href') + ' #nutrition-info-modal-content';

				// IF NUTRITION INFO DIV DOESN'T EXIST, CREATE IT FIRST, OTHERWISE WIPE CONTENTS
				if (!$('#nutrition-info').length) {
					$('body').append('<div id="nutrition-info"></div>');
				} else {
					$('#nutrition-info').html('');
				}

				// LOAD NUTRITION INTO DIV, DISPLAY MODAL UPON SUCCESS
				$('#nutrition-info').load(href, function() {
					$('#nutrition-info').modal( {
						onOpen: function (dialog) {
							dialog.overlay.fadeIn(400, function () {
								dialog.data.show();
								dialog.container.fadeIn(400);
							});
						},
						onClose: function (dialog) {
							dialog.data.fadeOut(200, function () {
								dialog.container.fadeOut(200, function () {
									dialog.overlay.fadeOut(200, function () {
										$.modal.close();
									});
								});
							});
						},
						containerId: 'nutrition-info-container',
						opacity: 80,
						overlayClose: true
					});
				});
				event.preventDefault();
			});
		});
	}

	/* ------------------------------------------------------------------------------------------------------------------------- PAIRING NAVIGATOR */
	var activePairingCategory = 'beverage';
	var activePairingList = '';
	var wheelpos = 0;
	var wheelalreadyanimated = false;
	
	// ANIMATE CACAO INTENSITY BY STEPPING THROUGH BACKGROUND POSITIONS
	function step_wheel() {
		if (wheelpos <= 8) {
			if (wheelpos < 8) {
				wheelpos = wheelpos + 1;
				animate_intensity_wheel();
			} else {
				wheelpos = 0;
				wheelalreadyanimated = true;
				function laststep() {
					$('.intensity-wheel').css('background-position','0px 0px');
				}
				setTimeout(laststep, 150);
			}
		}
	}
	
	function animate_intensity_wheel() {
		$('.intensity-wheel').css('background-position','0px -' + wheelpos * 300 + 'px');
		setTimeout(step_wheel, 200);
	}

	if ($('.pairing-navigation').length) {
		// ----------------------------------------------------------------- PAIRING NAVIGATOR NAVIGATION
		$('.pairing-navigation li').children('a').each(function() {
			$(this).click(function(event) {
				// HIDE CURRENTLY DISPLAYED CATEGORY
				if (activePairingCategory != '') {
					$('.pairing-navigation li').children('a[href*="' + activePairingCategory + '"]').removeClass('active');
					$('.pairing-' + activePairingCategory).css('display','none');

					// REMOVE ACTIVE CATEGORY FROM EXISTING CATEGORY BEFORE SWITCHING TO NEW CATEGORY
					$('.pairing-' + activePairingCategory + ' ul').children('li').each(function() {
						$(this).children('div').css('display','none');
						$(this).children('p').children('a').removeClass('active');
					});
					activePairingList = '';
				}
				
				activePairingCategory = $(this).attr('href').split('pairing=')[1];
				$(this).addClass('active');
				$('.pairing-' + activePairingCategory).css('display','block');
				
				// SHOW CACAO INTENSITY ANIMATION IF WE CLICK ON THAT TAB
				if (activePairingCategory == 'cacao-intensity' && wheelalreadyanimated == false) {
					$('.intensity-overview').html("Select your Cacao Intensity on the wheel to the left.");

					// ANIMATE CACAO INTENSITY WHEEL THE FIRST TIME ONLY
					if (getCookie('intensitywheel') != 'hidden') {
						animate_intensity_wheel();
						setCookie('intensitywheel','hidden',30)
					}
				}
				event.preventDefault();
			});			
		});

		// ----------------------------------------------------------------- PAIRING NAVIGATOR CATEGORIES
		$('.pairing-options li p').children('a').each(function() {
			$(this).click(function(event) {
				if (!$(this).hasClass('active')) {
					// HIDE CURRENTLY DISPLAYED OPTIONS LIST
					if (activePairingList != '') {
						$('.pairing-options li p').children('a[href*="' + activePairingList + '"]').removeClass('active');
						$('.pairing-' + activePairingList).slideUp(400, 'easeOutCirc');
					}
					
					// SHOW NAVIGATOR OPTIONS LIST
					var a = $(this);
					$(this).parent().prev('div').slideDown(500, 'easeInCirc',function() {
						$(a).addClass('active');
					});
					activePairingList = $(this).attr('href').split('category=')[1];
				}
				event.preventDefault();
			});
		});

		// TRIGGER PAIRING NAVIGATOR TAB
		if (url.indexOf('pairing=') > -1) {

			$('.pairing-navigation li').children('a[href*="' + getQueryValue('pairing') + '"]').trigger('click');
			// IF A CATEGORY HAS BEEN PASSED THEN TRIGGER THAT ACTION AS WELL
			if (url.indexOf('category=') > -1) {
				$('.pairing-options li p').children('a[href*="' + getQueryValue('category') + '"]').trigger('click');
			}
		}

		// ----------------------------------------------------------------- PAIRING NAVIGATOR NAVIGATION
		$('#cacaowheel').children('area').each(function() {
			$(this).mouseover(function() {
				switch($(this).attr('href').split('pairing-navigator/')[1]) {
					case 'milk-chocolate-nibby/':
					 $('.intensity-wheel').css('background-position','0px -300px');
					 break;
					case 'milk-chocolate/':
					 $('.intensity-wheel').css('background-position','0px -600px');
					 break;
					case 'extra-dark/':
					 $('.intensity-wheel').css('background-position','0px -900px');
					 break;
					case 'bittersweet/':
					 $('.intensity-wheel').css('background-position','0px -1200px');
					 break;
					case 'semisweet/':
					 $('.intensity-wheel').css('background-position','0px -1500px');
					 break;
					case 'dark-chocolate-nibby/':
					 $('.intensity-wheel').css('background-position','0px -1800px');
					 break;
					case 'mocha/':
					 $('.intensity-wheel').css('background-position','0px -2100px');
					 break;
					case 'sea-salted-almonds/':
					 $('.intensity-wheel').css('background-position','0px -2400px');
					 break;
				}
				$('.intensity-overview').html($(this).attr('alt'));
			});
		});
	}
	
	/* ------------------------------------------------------------------------------------------------------------------------- QUESTION/TIPS */
	if ($('.question-answer-container').length) {
		$('.question a').click(function(event) {
			if ($(this).hasClass('active')) {
				$(this).removeClass('active');
				$(this).parent().next('.answer').slideUp(300);
			} else {
				$(this).addClass('active');
				$(this).parent().next('.answer').slideDown(600);
			}
			event.preventDefault();
		});

		$('.show-all-answers').click(function(event) {
			if ($(this).hasClass('active')) {
				$(this).removeClass('active');
				$(this).html('Show All Answers');

				$('.question a').removeClass('active');
				$('.question a').parent().next('.answer').slideUp(600);
			} else {
				$(this).addClass('active');
				$(this).html('Hide All Answers');

				$('.question a').addClass('active');
				$('.question a').parent().next('.answer').slideDown(600);
			}
			event.preventDefault();
		});

		// TRIGGER QUESTION LINK
		if (url.indexOf('question=') > -1) {
			$('.question a[href*="' + getQueryValue('question') + '"]').trigger('click');
		}

		// TRIGGER SHOW/HID ALL LINK
		if (url.indexOf('show=') > -1) {
			$('.show-all-answers').trigger('click');
		}

		// VIDEO PLAYER PLAYLIST
		$('.video-playlist li a').click(function(event) {
			$('.video-playlist li a').each(function() {
				$(this).removeClass('active');
			});
			$(this).addClass('active');
			
			ytplayer.loadVideoById($(this).attr('href').split('?video=')[1]);
			event.preventDefault();
		});

		// TRIGGER VIDEO LOAD BASED ON URL (SEE FLASH LOADING ABOVE)
	}
	
	/* ------------------------------------------------------------------------------------------------------------------------- RECIPE CATEGORIES */
	// USES hoverIntent PLUGIN
	
	if ($('.recipe').length) {
		$('.recipe-title a').each(function() {
			$(this).hoverIntent(
				function() {
					$('.recipe-overview').stop().animate({ 'margin-top': '77px' }, 300, 'easeInCirc');
					$(this).parent().next('.recipe-overview').stop().animate({ 'margin-top': '0px' }, 400, 'easeOutCirc');
				},
				function() {}
			);
		});
		$('.recipe-overview a').each(function() {
			$(this).mouseout(function() {
				$(this).parent().stop().animate({ 'margin-top': '77px' }, 300, 'easeInCirc');
			});
		});
	}

	// ADJUST INGREDIENT LIST COLUMN SO THAT IT FILLS SPACE (IF THERE IS NO 2ND COLUMN)
	if ($('.ingredient-list-col1').length) {
		if (!$('.ingredient-list-col2').length) {
			$('.ingredient-list-col1').css('width','auto');
		}
	}

	/* ------------------------------------------------------------------------------------------------------------------------- RECIPE SHARE */
	// USES hoverIntent PLUGIN

	function shareover() {}
	function shareout() {
		$(this).slideUp(300, 'easeOutCirc', function() {
			$('.sharecw').parent().removeClass('active');
		});
	}

	if ($('.sharecw').length) {
		$('.sharecw').click(function(event) {
			if ($(this).parent().hasClass('active')) {
				$('.share-details').slideUp(300, 'easeOutCirc', function() {
					$('.sharecw').parent().removeClass('active');
				});
			} else {
				$(this).parent().addClass('active');
				$('.share-details').slideDown(600, 'easeOutCirc')
			}
			event.preventDefault();
		});
		$('.share-details').hoverIntent({
			over: shareover, 
			timeout: 300, 
			out: shareout
		});
	}
	
	// Footer
	function shareover() {}
	function shareout() {
		$(this).slideUp(300, 'easeOutCirc', function() {
			$('.sharecwftr').parent().removeClass('active');
		});
	}

	if ($('.sharecwftr').length) {
		$('.sharecwftr').click(function(event) {
			if ($(this).parent().hasClass('active')) {
				$('.share-detailsftr').slideUp(300, 'easeOutCirc', function() {
					$('.sharecwftr').parent().removeClass('active');
				});
			} else {
				$(this).parent().addClass('active');
				$('.share-detailsftr').slideDown(600, 'easeOutCirc')
			}
			event.preventDefault();
		});
		$('.share-detailsftr').hoverIntent({
			over: shareover, 
			timeout: 300, 
			out: shareout
		});
	}

	/* ------------------------------------------------------------------------------------------------------------------------- EXPAND/COLLAPSE INGREDIENT DETAILS */

	if ($('.show-hide-ingredients').length) {
		$('.show-hide-ingredients a').click(function(event) {
			if ($(this).hasClass('expanded')) {
				$(this).removeClass('expanded');
				$('.ingredient-list').slideUp(600, 'easeOutCirc')
			} else {
				$(this).addClass('expanded');
				$('.ingredient-list').slideDown(600, 'easeOutCirc')
			}
			event.preventDefault();
		});
	}

	/* ------------------------------------------------------------------------------------------------------------------------- PROMO (ELEVATE A CLASSIC DESSERT) */
	if ($('.show-more').length) {
		$('.show-more').click(function(event) {
			$(this).css('display','none');
			$(this).parent().next('.hid').slideDown(600, 'easeOutCirc');
			event.preventDefault();
		});
		$('.show-less').click(function(event) {
			$(this).parent().parent().slideUp(300, 'easeOutCirc');
			$(this).parent().parent().prev().children('.show-more').css('display','');
			event.preventDefault();
		});
	}

	/* ------------------------------------------------------------------------------------------------------------------------- SOCIAL MEDIA */

	/* SHARE PRINT BUTTON */
	if ($('.print').length) {
		$('.print').click(function(event) {
			window.print();
			event.preventDefault();
		});
	}
	
	/* FACEBOOK STREAM PUBLISH FUNCTION */
	function fb_publish_stream(msg,name,capt,desc,thumb,linkurl) {
		if (document.getElementById('fb-root') == null) {
			return; //NO 'FB-ROOT' DIV FOUND
		}
		FB.ui({
			method: 'stream.publish', message: msg, name: name, caption: capt, description: desc, picture: thumb, link: linkurl
		});
	}

	// POPULATE PAGE VARIABLES USED TO PASS ALONG VIA THE SOCIAL MEDIA LINKS
	if ($('.share-details-list').length) {
		var pgTitle = document.title ? document.title : 'HERSHEYS CHOCOLATE WORLD Attraction';
		var pgThumb = 'http://' + window.location.hostname + 'mobile/lib-m/img/global/site-logo.png';
		var pgCapt = '';

		// UPDATE PAGE TITLE
		if ($('.page-title').length) {
			pgTitle = $('.page-title').html();
			pgTitle = pgTitle.replace('<BR','<br');
			if (pgTitle.indexOf('<br />') > -1) pgTitle = pgTitle.split('<br />')[1];
			if (pgTitle.indexOf('<br>') > -1) pgTitle = pgTitle.split('<br>')[1];
		}
		
		// UPDATE PAGE CAPTION
		if ($('.col2-2').length) {
			pgCapt = $('.col2-2').children('.lgmargin').html();
			if (pgCapt == null) {
				// PARIING PAGE
				pgCapt = $('.pairing-text').children('p').html();
				if (pgCapt != null) {
					if (pgCapt.length > 497) {
						pgCapt = pgCapt.substring(0,496) + '...';	
					}
				}
			} else {
				// RECIPE PAGE
				if (pgCapt.length > 497) {
					pgCapt = pgCapt.substring(0,496) + '...';	
				}
			}
		}
		
		// UPDATE PAGE IMAGE
		if ($('.recipe-detail-image img').length) {
			pgThumb = 'http://' + window.location.hostname + $('.recipe-detail-image img').attr('src');
		}

		// FACEBOOK LINK
		$('.share-details-list .facebook').attr('href','#');
		$('.share-details-list .facebook').click(function(event) {
			fb_publish_stream('',pgTitle,pgCapt,'',pgThumb,url);
			return false;
		});

		//TWITTER/DEL.ICI.OUS/REDDIT/DIGG/STUMBLE UPON LINKS
		$('.share-details-list .twitter').attr('href','http://twitter.com/intent/tweet?text=@hersheys%20' + escape(pgTitle) + '&url=' + escape(url));
		$('.share-details-list .delicious').attr('href','http://del.icio.us/post?title=' + escape(pgTitle) + '&url=' + escape(url));
		$('.share-details-list .reddit').attr('href','http://reddit.com/submit?title=' + escape(pgTitle) + '&url=' + escape(url));
		$('.share-details-list .digg').attr('href','http://digg.com/submit?phase=2&amp;title=' + escape(pgTitle) + '&url=' + escape(url));
		$('.share-details-list .stumbleupon').attr('href','http://www.stumbleupon.com/submit?title=' + escape(pgTitle) + '&url=' + escape(url));

		// EMAIL OPTION IN SHARE DROPDOWN MENU
		$('.emailsharecw').click(function(event) {

			// EMAIL FORM HTML
			var modalHTML = '';
				modalHTML = '<div>' +
				'<h2 class="tk-bold">Share</h2>' +
				'<ol class="share-form">' +
					'<li>' +
						'<label for="name">Your Name:</label>' +
						'<input type="text" name="name" id="name" class="verysmall" />' +
					'</li>' +
					'<li class="col2">' +
						'<label for="email">Your Email:</label>' +
						'<input type="text" name="email" id="email" class="verysmall" />' +
					'</li>' +
					'<li>' +
						'<label for="friend_name">Your Friend\'s Name:</label>' +
						'<input type="text" id="friend_name" name="friend_name" class="verysmall" />' +
					'</li>' +
					'<li class="col2">' +
						'<label for="friend_email">Your Friend\'s Email:</label>' +
						'<input type="text" id="friend_email" name="friend_email" class="verysmall" />' +
					'</li>' +
				'</ol>' +
				'<p class="share-btn"><a href="" class="tk-bold">Share</a></p>';				
				
			// EMAIL MODAL OPTIONS
			$.modal(modalHTML, {
				onOpen: function (dialog) {
					dialog.overlay.fadeIn(400, function () {
						dialog.data.show();
						dialog.container.fadeIn(400);
					});
				},
				onClose: function (dialog) {
					dialog.data.fadeOut(200, function () {
						dialog.container.fadeOut(200, function () {
							dialog.overlay.fadeOut(200, function () {
								$.modal.close();
							});
						});
					});
				},
				containerId: 'simplemodal-share-container',
				opacity: 80,
				overlayClose: true
			});
			event.preventDefault();
		});
		
		// EMAIL FORM SUBMIT BUTON
		$('.share-btn a').live('click',function(event) {
			$('.notice_message').remove();
			$('.notice_errors').remove();
			
			// ALL FIELDS MUST BE FILLED OUT
			if ($('#name').val() == '' || $('#email').val() == '' || $('#friend_name').val() == '' || $('#friend_email').val() == '') {
				$('.share-form').before('<div class="notice_errors"></div>');
				$('.notice_message').remove();
				$('.notice_errors').html('<p>All fields are required.</p>');
			// VALID EMAIL ADDRESSES
			} else if (!validate_email($('#email').val()) || !validate_email($('#friend_email').val())) {
				$('.share-form').before('<div class="notice_errors"></div>');
				$('.notice_message').remove();
				$('.notice_errors').html('<p>Pleae enter valid email addresses.</p>');
			// ALL GOOD, SUBMIT DATA
			} else {
				var serviceURL = '' +
					'/lib/ashx/AjaxHandler.ashx' + 
					'?name=' + escape($('#name').val()) + 
					'&email=' + escape($('#email').val()) + 
					'&friend_name=' + escape($('#friend_name').val()) + 
					'&friend_email=' + escape($('#friend_email').val()) + 
					'&url=' + escape(url);
				
				$('.share-form').before('<div id="msg" class="notice_message hid"></div>');
				$('.share-form, .share-btn').addClass('hid');
				$('.share-form').before(
					'<p class="loading-screen">Processing, please wait... </p>' + 
					'<p class="loading-screen"><img src="/lib/img/loading.gif" alt="Loading" /></p>'
				);

				// AJAX SERVICE CALL TO SUBMIT FORM DATA (VIA GET)
				$('#msg').load(serviceURL, function(msg) {
					var resp = msg.split('|')[0];
					var err = msg.split('|')[1]
					
					if (resp == 'success') {
						// EMAIL WAS SENT
						$(this).css('display','block');
						$('.share-form, .share-btn').removeClass('hid');
						$('.loading-screen').remove();
						$(this).html('<p>An email has been sent to your friend.</p>');
						$('.share-form input').val('');
					} else {
						// ERROR SENDING EMAIL
						$(this).removeClass('notice_message');
						$(this).addClass('notice_errors');
						$(this).css('display','block');
						$('.share-form, .share-btn').removeClass('hid');
						$('.loading-screen').remove();
						if (err == '') {
							$(this).html('<p>An error has occurred.</p>');
						} else {
							$(this).html('<p>' + err + '</p>');
						}
					}
				});
			}
			event.preventDefault();
		});
	}
	
	/* ------------------------------------------------------------------------------------------------------------------------- OPEN MODALS */
	// USES simplemodal.js

	if ($('.content').length) {
		// SITE BUMPER MODAL
		$('.content a').each(function() {
			if ($(this).attr('rel') == 'modal') {
				$(this).bind('click',function(event) {
					// PASS ALONG TARGET
					var target = '';
					if ($(this).attr('target') == '_blank') {
						target = 'target="_blank"';
					}

					// BUMPER HTML
					var modalHTML = '';
					if (url.indexOf('contests-and-promotions') > -1) {
						modalHTML = '<div>' +
						'<h2 class="tk-bold">Elevate a Classic Dessert</h2>' +
						'<p>The contest entry process must be completed on a<br />secure 3rd party site. Are you sure you want to<br />leave?</p>' +
						'<p class="bumperyes"><a href="' + $(this).attr('href') + '" class="tk-bold push-past-bumper"' + target + '>Yes, Enter Contest</a></p>' +
						'<p class="bumperno"><a href="#stay-here" class="close-modal">No, stay on this site</a></p>' +
						'</div>';
					} else {
						modalHTML = '<div>' +
						'<h2 class="tk-bold">You Are Leaving</h2>' +
						'<p>You are about to visit a 3rd party site. Are you sure you want to leave?</p>' +
						'<p class="bumperyes"><a href="' + $(this).attr('href') + '" class="tk-bold push-past-bumper"' + target + '>Yes, Continue</a></p>' +
						'<p class="bumperno"><a href="#stay-here" class="close-modal">No, stay on this site</a></p>' +
						'</div>';
					}

					// BUMPER OPTIONS
					$.modal(modalHTML, {
						onOpen: function (dialog) {
							dialog.overlay.fadeIn(400, function () {
								dialog.data.show();
								dialog.container.fadeIn(400);
							});
						},
						onClose: function (dialog) {
							dialog.data.fadeOut(200, function () {
								dialog.container.fadeOut(200, function () {
									dialog.overlay.fadeOut(200, function () {
										$.modal.close();
									});
								});
							});
						},
						closeClass: 'close-modal', // USED FOR 'STAY ON SITE' LINK ABOVE
						opacity: 80,
						overlayClose: true
					});
					
					// CLOSE MODAL WHEN A USER LEAVES THE SITE (FOR LINKS THAT OPEN IN A NEW WINDOW)
					$('.simplemodal-container .push-past-bumper').unbind().bind('click',function(event) {
						$.modal.close();
					});
					event.preventDefault();
				});
			}
		});
	}

	/* ------------------------------------------------------------------------------------------------------------------------- CONTACT FORM */

	if ($('.country-select').length) {
		$('.country-select select').change(function() {
			var val = $(this).val();
			if (val == "") return;

			// SHOW STATES OR PROVINCES BASED ON COUNTRY SELETION
			switch(val) {
				case "USA":
					$('.state-li').css('display',''); 
					$('.state-li label').html('State');
					$('.state-select').css('display',''); 
					$('.province-select').css('display','none'); 
					$('.state-select select').prop('selectedIndex',0); 
					$('.province-select select').prop('selectedIndex',1); 
					break;
				case "Canada":
					$('.state-li').css('display',''); 
					$('.state-li label').html('Province');
					$('.state-select').css('display','none'); 
					$('.province-select').css('display',''); 
					$('.state-select select').prop('selectedIndex',1); 
					$('.province-select select').prop('selectedIndex',0); 
					break;
				default: 
					$('.state-li').css('display','none'); 
					$('.state-li label').html('State/Province');
					$('.state-select select').prop('selectedIndex',1); 
					$('.province-select select').prop('selectedIndex',1); 
					break;
			}
		});
	}

	/* ------------------------------------------------------------------------------------------------------------------------- EXERNAL LINK ICONS */
	// ADD EXTERNAL LINK ICON TO ALL LINKS WITHIN THE "content" DIV THAT HAVE 
	//	A TARGET OF "_blank", NO CLASS OF "noexternal" AND NO REL ATTRIBUTE OF "modal"

	if ($('.content').length) {
		$('.col2-2 a, .fullcol a, .ecd-col2 a').each(function() {
			if ($(this).attr('target') == '_blank' && !$(this).hasClass('noexternal') && $(this).attr('rel') != 'modal') {
				$(this).addClass('external');
			}
		});
	}

	/* ------------------------------------------------------------------------------------------------------------------------- CHECK FOR IE6 UPGRADE PAGE */

	if ($('#ignore-continue').length) {		
		$('#ignore-continue').click(function(event) {
			setCookie('ie6ignore','yes',90);
			window.location = '/';
			return false;
		});
	}
});
