jQuery(function($){

	$('.cnav a').click(function(){
		var $this = $(this);
		var link = $this.attr('href');
		var name = $('dfn', $this).text();
		var $cname = $('#cname');

		$('.cnav a').removeClass('active');
		$this.addClass('active');
		
		$('#cpic img').fadeOut(100, function(){
			$(this).remove();
			$cname.text(name);

			var img = new Image();			
			$(img).load(function(){
				$('#cpic div').append($(this).hide().fadeIn(500));
			}).attr('src', link);			
		});

		return false;
	});

	$('.cswitch').eq(0).addClass('active');
	
	$('.cswitch').click(function(){		
		var index = $(this).attr('href');
		animate(index);		
		return false;
	});

	$('.cswitchprev').click(function(){		
		var active = get_active();
		var prev;
		if (active == 0){
			prev = get_last();
		}else{
			prev = active - 1;
		}
		animate(prev);
		return false;
	});

	$('.cswitchnext').click(function(){
		var active = get_active();
		var next;
		if (active == get_last()){
			next = 0;
		}else{
			next = active + 1;
		}
		animate(next);
		return false;
	});

	function get_active(){
		return ($('#cswitches .active').text() -1);
	}

	function get_last(){		
		return $('.cswitch').length - 1;
	}

	function animate(index){
		$('#cswitches .active').removeClass('active');
		$('.cswitch:eq('+index+')').addClass('active');	

		var x = -(index * 290);
		$('#chnavs').animate({'left':x+'px'}, 300);
	}

});
