$(document).ready(function() {
	// build nav
	var nav_markup = '';
	var i = 1;
	$('.carousel .item').each(function(){
		var item_id = 'carousel-item-'+i;
		$(this).attr('id', item_id);
		nav_markup = nav_markup + '<li><a href="#'+item_id+'">'+i+'</a></li>';
		i++;
	});
	// add and format the nav
	$('.carousel').append('<ul class="carousel-nav">'+nav_markup+'</ul>');
	$('.carousel-nav').addClass('first-run');
	$('.carousel-nav li:first a').addClass('active');
	// activate cycle
	$('.carousel .items').cycle({
		timeout: 7000,
		speed: 500,
		pause: 1,
		cleartype: 0,
		before: updateNav,
		after: removeFirstFlag
	});
	// activate nav
	$('.carousel-nav a').click(function(){
//		var new_item = $(this).attr('href');
		// IE 7 converts the href to be absolute, so reformat it to be safe
		var new_item_parts = $(this).attr('href').split('#');
		var new_item = '#'+new_item_parts[new_item_parts.length - 1];
		var new_item_index = $(new_item).index();
		$('.carousel .items').cycle(new_item_index);
		$('.carousel-nav a').removeClass('active');
		$(this).addClass('active');
		return false; 
	});
	// update nav on automatic change
	function updateNav(curr, next, opts) {
		if (!$('.carousel-nav').hasClass('first-run')) {
			var item_index = opts.nextSlide;
			var item_id = $('.carousel .item').eq(item_index).attr('id');
			$('.carousel-nav a').removeClass('active');
			$('.carousel-nav a').each(function(){
				// IE 7 converts the href to be absolute, so a straight comparison doesn't work
				if ($(this).attr('href').indexOf('#'+item_id) > -1) $(this).addClass('active');
			});
		}
	}
	// prevent updateNav from running before the first transition
	function removeFirstFlag() {
		$('.carousel-nav').removeClass('first-run');
	}
});

