$(document).ready(function() {

	// Slideshow setup for homepage
	$('#home #slides').cycle({
		fx: 'fade',
		timeout: 5000,
		prev: '#home #controls a.prev',
		next: '#home #controls a.next'
	});
	
	
	// Slideshow setup for farmer profiles
	$('#farmer-gallery').cycle({
		fx: 'fade',
		timeout: 5000,
		prev: '#gallery-controls li.prev a',
		next: '#gallery-controls li.next a',
		pause: true
	});
	
	
	// Temporarily stop slideshow when images/controls are hovered
	$('#farmer-gallery, #gallery-controls').hover(function() {
		$('#farmer-gallery').cycle('pause');
	}, function() {
		$('#farmer-gallery').cycle('resume');
	});
	
	
	// Show gallery controls if there's multiple photos
	if ($('#farmer-gallery li').size() > 1) {
		$('#gallery-controls').fadeIn('fast');
	}
		
	
	// Email subscribe popup
	$('a.subscribe').fancybox({
		'type': 'iframe',
		'autoDimensions': false,
		'margin': 0,
		'padding': 8,
		'width' : 350,
		'height' : 495,
		'overlayColor': '#000',
		'overlayOpacity': '0.5',
		'hideOnOverlayClick': false
	});
	

	// Swap form field values when focused
	$('input[type=text]').each(function() {
		 var default_value = $(this).attr("data-default");
	    $(this).focus(function() {
	        if(this.value == default_value) {this.value = '';}
	    });
	    $(this).blur(function() {
	        if(this.value == '') {this.value = default_value;}
	    });
	});
	
	
	// Switch between product details and nutrition facts
	$('#switcher dt a').click(function() {
		var curSect = $(this).parent().attr('data-name');
		
		$(this).parent().addClass('current');
		$('#switcher dt[data-name!='+curSect+']').attr('class','');
		
		$('#switcher dd[data-name='+curSect+']').show();
		$('#switcher dd[data-name!='+curSect+']').hide();
				
		return false;
	});
	
	
	// Toggle testimonials on product details page
	$('#product #actions li.testimonials.local a').click(function() {
		$('#switcher dt').attr('class','');
		$('#switcher dd[data-name="testimonial"]').show();
		$('#switcher dd[data-name!="testimonial"]').hide();
		
		return false;
	});
	
	
	// How It's Made (popups)
	$('#storybook dt a').click(function() {
		var tipNum = $(this).parent().attr('data-caption');
		var tipHtml = $(this).parents('dl').find('dd[data-story='+tipNum+']').html();		
		
		$('#storybook #popup').html(tipHtml).parent().css('opacity','0');
		
		/* Get the element height after appending html */
		var tipPos = $('#popup-wrap').height()/2;
		
		/* Apply negative top margin to vertically center content */
		$('#popup-wrap').css('margin-top','-'+tipPos+'px').fadeTo('normal', 1);
			
		return false;
	});
	
	/* Hide popup if closed or if slide changes */
	$('#storybook #nav-wrap a, #storybook #popup-wrap a.close').live("click", function() {
		$('#storybook #popup-wrap').fadeOut();
		return false;
	});
	
	$('#storybook #page-controls a').click(function() {
		$('#storybook #popup-wrap').fadeOut();
		return false;
	});
	
	
	// How It's Made (slideshow)
	$('#storybook #pages').cycle({
		fx: 'fade',
		timeout: 0,
		pager: '#storybook #page-list',
		prev: '#storybook #page-controls .prev a',
		next: '#storybook #page-controls .next a',
		nowrap: true,
		before: function(curSlide,nextSlide,opts,forwardFlag) {	$("#storybook #toc h2").text($(nextSlide).find("h2").text()); }
	});


	// Calculate the width of the slideshow and apply css
	function slideshowWidth() {
		var numSlides = $('#all-products ul li').size();
		var slideWidth = $('#all-products ul li').outerWidth();
		var totalWidth = numSlides * slideWidth;
		
		$('#all-products ul').css('width', totalWidth);
	}
	slideshowWidth();	

	$('select#availSelect').change(function() {
		var o=$(this).find("option:selected");
		var pname=$('#information h1').html();

		$('#product-photo img').attr("src",$(o).attr("data-image"));
		$('#product-photo img').attr("width",$(o).attr("data-image-w"));
		$('#product-photo img').attr("height",$(o).attr("data-image-h"));
		$('#product-photo img').attr("alt",'Photo of '+pname+' - '+$(o).html());

	});

	$('form#find-product').submit(function() {
		var link=$(this).find('option:selected').attr("value");
		if (link=="") return false;
	});
	
	
	// Scroll the slideshow on prev and next link click
	$('#all-products a.prev').click(function() {
		$("#scroller").stop().scrollTo('-=938', 500, {axis:'x'});
		//var maxScroll=$.scrollTo.max($('#scroller'),'x');
		return false;
	});

	$('#all-products a.next').click(function() {
		$("#scroller").stop().scrollTo('+=938', 500, {axis:'x'});
		return false;
	});


	// Handle Our Farmers jump menu
	$("#farmers_jumpmenu select").change(function() {
		var link=$(this).find("option:selected").attr("value");
		if (link=="") alert("Please select a farmer");
		else document.location=link;
		return false;
	});


	// Decode encrypted blocks of text
	var encDivs=$('.jsNeeded');
	for (var i=0;i<encDivs.length;i++) {
		var encoded=$(encDivs[i]).attr("data-enc");
		eval(rot13(unescape(encoded)));
		$(encDivs[i]).html(decoded);
	}


	// Did You Know block
	$("#communicate .fact_nav a").click(function() {
		id=$("#communicate .fact_nav").attr("data-id");
		dir=$(this).attr("class");
		loadNextFact(id,dir);
		return false;
	});


	// Where We Farm map (info window pop-up on hover over a marker)
	/* First we need to position all the info-windows in "logical" places still within the map. */
	$("#farmMap .dot.big").each(function(idx) {
		var pos=$(this).position();
		var newX='0';
		if (pos.left>892-355) newX='-335px';
		var newY='-160px';
		if (pos.top<170) newY='30px';
		$(this).find(".container").css({top:newY,left:newX});
	});
	
	$("#farmMap .dot.big").hover(function() {
		var img=$(this).find(".container .info .image");
		if ($(img).css("background-image")=='none') {
			var src=$(img).attr("data-bg");
			try {
				$(img).css("background-image",'url("'+src+'")');
			}
			catch(e) { alert(e.message); }
		}
	});
	$("#farmMap .dot.big").click(function() { var url=$(this).attr("data-href"); document.location=url; });

	$("#farmMap #legend input").click(function() {

		var type=$(this).attr("value");
		var selected=$(this).attr("checked");

		if (selected) {
			$("#farmMap .dot").filter(".type_"+type).show();
			$("#farmMap #legend .farmtype_"+type).addClass("on");
		}
		else {
			$("#farmMap .dot").filter(".type_"+type).hide();
			$("#farmMap #legend .farmtype_"+type).removeClass("on");
		}
	});

	$("#farmMapFilters form select").change(function() { $(this).parent("form").submit(); });

	// make all "A.NewWindow" links open in a new window...
	$('a.NewWindow').attr('target','_blank');

	try {
		if ($("body").attr("id")=="store-locator") {
			sl_prepare();
		}
	}
	catch(e) {}

	
});  // End of document ready


function loadNextFact(id,dir) {
	$.getJSON("/ajax/ajax-didyouknow.php?id="+id+"&dir="+dir,function(data) {
		$("#communicate .fact_nav").attr("data-id",data.id);
		$("#communicate .fact").html(data.fact);
	});
}

var rot13map=null;

function rot13init() {
	var map = new Array();
	var s   = "abcdefghijklmnopqrstuvwxyz";
	for (i=0; i<s.length; i++) map[s.charAt(i)]=s.charAt((i+13)%26);
	for (i=0; i<s.length; i++) map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();
	return map;
}

function rot13(a) {
	var s = "";
	if (!rot13map) rot13map=rot13init();
	for (i=0; i<a.length; i++) {
		var b = a.charAt(i);
		s += (b>='A' && b<='Z' || b>='a' && b<='z' ? rot13map[b] : b);
	}
	return s;
}
