$(document).ready(function() {
	// ******** HOMEPAGE SLIDESHOW ********
	// initialize the jQuery Tools Scrollable and get a reference to its api
	var api = $('div.scrollable').scrollable({
							api: true,
							loop: true,
							size: 4,
							circular: true,
							next: '#homepage-callout-slideshow-next',
							prev: '#homepage-callout-slideshow-prev'
						});

	// this helper function will be called when either the auto-clicker or the user initiates a click
	function slideClicked(index, manual) {
		// if the auto-clicker is on and if the click was manually initiated, turn it off
		//if(manual) clearInterval(autoclicker);
		
		// simulate the click for the jQuery Tools API so that it correctly records the last index clicked
		// (note that this doesn't seem to call the item's jQuery .click() event)
		//api.click(index);
		
		// retrieve the slide based on index
		var slide = api.getItems().eq(index);
		
		// set up the slide
		var backgroundImage = $('#site-background-image');
		var imageUrl = slide.attr('imageUrl');
		backgroundImage.fadeOut('fast', function() {
			$('#homepage-callout-wrap a').attr('href', slide.attr('linkUrl'));
			$('#homepage-callout-main-caption').html(slide.attr('imageTitle'));
			$(this).css('background-image', 'url(' + imageUrl + ')');
			backgroundImage.fadeIn('fast');
		});
	}
	
	// event handler for the user's click on the actual image
	$('.homepage-callout-thumb-wrap').click(function() {
		// this is a little janky, but it allows a cleaner implementation of slideClicked above
		//slideClicked($('.homepage-callout-thumb-wrap').index($(this)), true);
		
		// Force slide clicks to go to destination URL rather than load background image
		$(this).unbind();
		var linkUrl = $(this).attr('linkUrl');
		window.location.replace(linkUrl);
		return false;
	});
	
	// event handler for the user's click on the prev button 
	/*$('#homepage-callout-slideshow-prev').click(function() {
		// JANK ALERT
		var targetIndex = api.getClickIndex() - 1;
		if(targetIndex < 0) targetIndex = api.getSize() + targetIndex;
		slideClicked(targetIndex, true)
	})*/
	
	// event handler for the user's click on the next button 
	/*$('#homepage-callout-slideshow-next').click(function() {
		slideClicked((api.getClickIndex() + 1) % api.getSize(), true)
	})*/
	
	// kick off the auto-clicker and programmatically click the first slide
	/*var autoclicker = setInterval(function() {
		slideClicked((api.getClickIndex() + 1) % api.getSize(), false);
	}, 5000);
	slideClicked(0, false);*/
	
	if ( $('div.homepage-callout-thumb-wrap:first').length ) {
	  slideClicked(0, true);
	  $('div.homepage-callout-thumb-wrap:first').remove();
	}
	
});
