$(document).ready(function() {
	// Headers after paragraphs
	$('p + :header, ul + :header').addClass('next')
	
	// Text inputs
	$(':text').addClass('text');
	
	// Inline labels
	$(':input.inlinelabel').inlineLabel();
	
	// Disable logo link on home page
	$('body.home h1 a').css('cursor', 'default').click(function() {return false;});
	
	// Textarea expand
	$('textarea').prettyComments({maxHeight: 350});
	
	// Find By Fruit fly-outs
	findByFruit();
	
	// Find By Feeling modal
	findByFeeling();
	
	// // Make big clickable areas
	bigClicks();
	
	// Juice Details expand/collapse
	juiceDetails();
	
	// Scrollables
	scrollables();
	
	// Nav drop-downs
	navDrop();
	
	// Breadcrumb product drop-down
	breadcrumbProductDrop();
	
	// Make rows
	makeRows();
	
	// Overlays
	overlays();
	
	// Tooltip
	initTooltip();
	
	// Position footer (plugin)
	$('#footer').positionFooter();
}); // End DOM ready execution


// FUNCTIONS
// ------------------------------------------------------------------------------

// Inline form field label
(function($){
	$.fn.inlineLabel = function() {
		return this.each(function() {
			var id = $(this).attr('id'),
				htmllabel = $('label[for="'+id+'"]').text(),
				// Get label from label tag if there is one, otherwise get it from title attribute
				label =  (htmllabel) ? htmllabel : $(this).attr('title');
			if ($(this).val() === '') {
				$(this).val(label)
					.addClass('inlinelabel');
			}
			$(this).focus(function() {
					if ($(this).val() === label) {
						$(this).val('').removeClass('inlinelabel');
					}
				})
				.blur(function() {
					if ($(this).val() === '') {
						$(this).val(label).addClass('inlinelabel');
					}
				});
		 });	
	}
})(jQuery);

// Nav dropdowns
function navDrop() {
	$("li.nav").hoverIntent({
		interval: 0,
		sensitivity: 30,
		over: function() {$(this).addClass("hover");},
		timeout: 100,
		out: function() {$(this).removeClass("hover");}
	});
}

// Breadcrumb product drop-down
function breadcrumbProductDrop() {
	$('#trail-menu')
		.hoverIntent({
			interval: 0,
			sensitivity: 30,
			over: function() {$(this).addClass("hover");},
			timeout: 100,
			out: function() {
				$(this)
					.find('ul').slideUp('fast', function() {
						// After menu slides up remove hover/click styling
						$(this).parent()
							.removeClass('hover')
							.removeClass('click')						
					});
				$(this).find('span').unbind('click');
			}
		})
		.click(function(event) {
			event.stopPropagation();
			
			$(this).find('span').click(function(event){
				event.stopPropagation();
				$('#trail-menu').find('ul').slideUp('fast', function() {
					// After menu slides up remove hover/click styling
					$(this).parent()
						.removeClass('hover')
						.removeClass('click')						
				});
				$(this).unbind('click');
			});
			
			
			$(this)
				.addClass('click')
				.find('ul').slideDown('fast');
		});
}

// Height equalizer
(function($){
	$.fn.equalizeHeight = function() {
		var max = 0;
		this.each(function(){
			if ($(this).height() > max)
				max = $(this).height();    
		});
		return this.height(max);	
	}
})(jQuery);

// Find By Fruit menu
function findByFruit() {
	$('#findbyfruit li.item').hoverIntent({
		interval: 0,
		sensitivity: 10,
		over: function() {$(this).addClass('hover');},
		timeout: 50,
		out: function() {$(this).removeClass('hover');}
	});
}

// Find By Feeling menu
function findByFeeling() {
	// Does element exist? If not, exit.
	if (!$('#findbyfeeling').length) { return; }

	var $modal = $('#findbyfeeling'),
		$content = $('#fbf-content > div'),
		$menu = $('#fbf-menu');

	// Initially hide content
	$menu.show();
	$content.hide();

	// Menu clicks
	$menu.find('a').click(function() {
		$menu.hide();
		$content.filter($(this).attr('href')).show();
		return false;
	});

	// 'Choose new feeling' click
	$content.find('.fbf-feeling a').click(function() {
		$menu.show();
		$content.hide();
		return false;
	});

}

// Make big clickable areas
function bigClicks() {
	$('body.products.category .column .head').hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	)
	.click(function() {
        goTo = $(this).find('a:first').attr('href');
        if (goTo != undefined) window.location = goTo;        
    });	
}

// Juice Details expand/collapse
function juiceDetails() {
	// Does element exist? If not, exit.
	if (!$('body.products.category div.details').length) { return; }

	var $details = $('div.details');
	
	// Add controller
	$('<div class="details-controller"><a href="#">Collapse This</a></div>')
		.insertBefore($details)
		// Set controller toggle
		.find('a')
			.toggle(
				// Collapse details
				function() {
					$(this)
						.text('Expand This')
						.addClass('collapsed')
						.closest('.section').find('.details')
							.slideUp('fast', function() {
								$(window).unbind("resize");
								$('#footer').css({'position':'relative','top':'auto'}).positionFooter();
							});
					return false;
				},
				// Expand details
				function() {
					$(this)
						.text('Collapse This')
						.removeClass('collapsed')
						.closest('.section').find('.details')
							.slideDown('normal', function() {
								$(window).unbind("resize");
								$('#footer').css({'position':'relative','top':'auto'}).positionFooter();
							});
					return false;
				}
			)
			// Initially collapsed
			.click()
		.end()
		// Only show one controller per row (3 products)
		.filter(function(index) {
			return index % 3 == 0;
		})
			.css('visibility', 'visible');
}

// Scrollables
function scrollables() {
	// Other Products
	// Add prev and next buttons only if there are lots of items
	if ( $('#otherproducts div.scrollable ul.items li').length > 3 ) {
		$('#otherproducts div.scrollable').before('<span class="prevPage browse"></span>').after('<span class="nextPage browse"></span>');
	}
	$('#otherproducts div.scrollable')
		// Initialize
		.scrollable({
			size: 3,
			vertical: true,
			clickable: false,
			keyboard: false
		});
	//$('#otherproducts div.scrollable ul.items li:last').css('border','0');
	
	
	// Tip of the Day
	$('#tip div.scrollable')
		// Add prev and next buttons
		.after('<span class="prevPage browse"></span><span class="nextPage browse"></span>')
		// Initialize
		.scrollable({
			size: 1,
			clickable: false,
			keyboard: false
		})
		.circular();

	// Browse Videos
	// Add prev and next buttons only if there are lots of items
	if ( $('#browse-videos div.scrollable ul.items li').length > 2 ) {
		$('#browse-videos div.scrollable').after('<span class="prevPage browse"></span><span class="nextPage browse"></span>');
	}
	$('#browse-videos div.scrollable')
		// Initialize
		.scrollable({
			size: 2,
			clickable: false,
			keyboard: false
		});

	// Social Media Buzz
	// Add prev and next buttons only if there are lots of items
	if ( $('#socialmedia div.scrollable ul.items li').length > 3 ) {
		$('#socialmedia div.scrollable').before('<span class="prevPage browse"></span>').after('<span class="nextPage browse"></span>');
	}
	$('#socialmedia div.scrollable')
		// Initialize
		.scrollable({
			size: 3,
			vertical: true,
			clickable: false,
			keyboard: false,
			loop: true
		});
}

// Overlays
function overlays() {
	var ie6 = ($.browser.msie && parseInt($.browser.version, 10) <= 6);
	var ie7 = ($.browser.msie && parseInt($.browser.version, 10) <= 7);
	
	if (ie6 || ie7) {
		var inlineExposeSettings = false;
	} else {
		// Global settings ('expose' is the graying out effect)
		$.tools.overlay.conf.expose = { 
				color: '#000', 
				loadSpeed: 200, 
				opacity: 0.3
			};
		var inlineExposeSettings = {opacity:0};
	}

	// Coupons page
	if ($('#coupons').length) {
		$('a[rel="#coupons"]').overlay({onLoad: function(event){loadTrackingForCoupon()}});
	}
		
	// Antioxidant chart	
	$('a[rel="#chart"]').overlay();

	// Video player	
	$('a[rel="#videoplayer"]').overlay({onBeforeClose:function(event){stopAllAudio()}});
	
	// Find By Feelings	
	$('a[rel="#findbyfeeling"],div[rel="#findbyfeeling"]').overlay({expose:inlineExposeSettings, onStart: function(event) { findByFeeling(); }});

	// Nutrition label
	$('a[rel="#nutrition"]').overlay({expose:inlineExposeSettings,onLoad: function(event){addNutritionScrollbars()}});

	// Newsletter sign-up
	$('a[rel="#newsletter-signup"]').overlay({expose:inlineExposeSettings, onBeforeClose: function(event){$.validationEngine.closePrompt(".formError",true)}});
	
	// Recipes
	$('a.recipeoverlay').overlay();
}

function loadTrackingForCoupon() {
	$("#trackingcode").append('<img width="1" height="1" style="border:0" src="HTTP://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?cn=as&amp;ActivityID=62888&amp;ns=1"/>');
	$("#trackingcode").append("<img src='http://smp.specificmedia.com/smp/v=5;m=1;t=2675;ts=' width='1' height='1' border='0' />");
}

// Tooltip
function initTooltip() {
	// Global settings
	$.extend($.tools.tooltip.conf, { 
		effect: 'fade'
	});	

	// Initialize
	$('#size-7').tooltip({position: 'top left', offset: [-10, 54]});
	$('#size-10').tooltip({position: 'top left', offset: [-10, 54]});
	$('#size-11').tooltip({position: 'top left', offset: [-10, 62]});
	$('#size-64').tooltip({position: 'top left', offset: [-10, 62]});
	$('#size-32').tooltip({position: 'top left', offset: [-10, 62]});
	$('#size-4').tooltip({position: 'top left', offset: [-10, 62]});
	$('#size-1').tooltip({position: 'top left', offset: [-10, 62]});
	
	$('.tooltip')
		// Add pointed part of the bottom edge
		.append('<div class="tooltip-btm">')
		// Move tooltips outside of page structure to avoid positioning issues
		.appendTo('body');
}

// Make rows
function makeRows() {
	// Find the first .column element and count the rows.
	// Then go through each column naming the rows so that we can equalize them based on their name.
	// E.g. the first rows in each column will be named row0 and then we'll equalize the row0 to each other.

	// Only perform on these pages: Products, Products Category, Buzz
	if (!$('body.products.main, body.products.category, body.buzz').length) { return; }

	for (var i=0; i < $('#content .column:first .row').length; i++) {
		for (var j=0; j < $('#content .column').length; j++) {
		$('#content .column:eq('+j+')').find('.row:eq('+i+')').addClass('row'+i);
		}
		$('.row'+i).equalizeHeight();
	}
}


function stopAllAudio() {
	$("embed, object").each(function(index){
		try{this.killPlayer()}catch(err){};
	});
}

