$(document).ready(function() {

	var items = jQuery.makeArray($('.gallery').children());
	
	var num_items = items.length;
	
	create_btns(num_items, items);

});

function create_btns(num_items, items) {

	//for each image create a button
	for( i=0; i < num_items; i++ ) {
		
		$('<label>').text(i+1).attr("id", i).addClass("gallery-btn").appendTo(".gallery-nav");
		
		var img_select = $('<input type="radio" name="gallery">').attr("id", i).addClass("img-select");
		
		if(i == 0){
			img_select.attr("checked", "true");
			img_select.checked = true;
		}
		
		//append buttons to labels	
		img_select.appendTo("#"+i);
		
		//add active class to first input
		$("#"+0).addClass("active");

	} 
	
	//bind onclick for button
	$('.gallery-btn').bind('click', function() {
 			 
 		 change_img($(this).children('.img-select').attr("id"), items);
 		 
 		 $(".active").removeClass("active");
 		 
 		 $(this).addClass("active");
 		 
	});
	
	//set container height
	$('img').load(function() {
        	var set_height = $(".current").height();
		$(".gallery-container").animate({height: set_height+"px"}, "slow");
   	 });	

}

function change_img(id, items) {

	if(items[id].className != 'current') {
	
		var next = items[id];
	
		do_swap($(".current"), next);
		
		//change container height
		var new_height = $(next).height();
		$(".gallery-container").animate({height: new_height+"px"}, "slow");

	}
	
}

function do_swap(current, next) {

	current.fadeOut('slow', function() {
    		current.removeClass("current").addClass("hidden");
    		$(next).fadeIn('slow').removeClass("hidden").addClass("current");
  	});

}
