// vars
var ymca_slide_delay = 10000;
var ymca_slide_stop = false;
var ymca_slide_timer;

// run when dom is available
$(document).ready(function(){
	if($('.feature a.slide').length > 1){
		ymca_slide_timer = setTimeout("ymca_slide_show(1)", ymca_slide_delay);
		ymca_add_nav();
	}
});

// auto slideshow
function ymca_slide_show(show_slide){
	next_slide_index = (show_slide+1 >= $('.feature a.slide').length) ? 0 : show_slide + 1;
	// load next feature bg image
	var img = new Image();
	$(img)
		// once the image has loaded...
		.load(function () {
			// fade out image and link
			$('.feature-bg').fadeOut();
			$('.feature a.slide:visible').fadeOut(function(){
				// swap bg image
				bgurl = 'url('+$(img).attr('src')+')';
				//alert(bgurl);
				$('.feature-bg').css('background-image', bgurl);
				// fade in image and link
				$('.feature a.slide:eq('+show_slide+')').fadeIn();
				$('.feature-bg').fadeIn();
				// update navigation
				$('ul.slide_nav li a.current').removeClass('current');
				$('ul.slide_nav li:eq('+show_slide+') a').addClass('current');
				// restart timer if necessary
				if(ymca_slide_stop != true){
					ymca_slide_timer = setTimeout("ymca_slide_show("+next_slide_index+")", ymca_slide_delay);
				}
			});
		})
		// errors
		.error(function() { alert('error loading photo') })
		// set the src attribute of the new image
		.attr('src', '/images/home/'+$('.feature a.slide:eq('+show_slide+')').attr('data-bg'));
}

// manual navigation
function ymca_add_nav(){
	slides = $('.feature a.slide').length;
	$('.feature-wrap').append('<ul class="slide_nav"></ul>');
	for(var i=1;i<=slides;i++){
		$('ul.slide_nav').append('<li class="slide"><a href="#slide'+i+'">&nbsp;</a></li>');
	}
	$('ul.slide_nav li.slide:first a').addClass('current');
	// add listeners
	$('ul.slide_nav li a').click(function(){
		// stop timer
		clearTimeout(ymca_slide_timer);
		ymca_slide_stop = true;
		requested_slide = $(this).attr('href').match(/#slide(\d)/)[1]; // have to use regex to get around IE href bug
		ymca_slide_show(requested_slide-1)
		return false;
	});
}
