$(document).ready(function(){
	// set carousel container
	var container = $('#carousel-container');
	var ajax_url = "carousel/";
	var gallery_count = $(container).attr('class').replace(/\D/g,'');
	var container_width = "550px"; // in pixels
	
	if ( gallery_count > 0 ) {
		$(container).after('<a class="carousel-button button inactive-prev prev" id="prev" href="javascript:void(0)"><span>Prev</span></a><a class="carousel-button button next" id="next" href="javascript:void(0)"><span>Next</span></a>');
	}
	$(container).prepend('<div id="loader"></div>');
	

	
	// add loader and fade first image in
	// $("#loader").show();
	// $('#carousel-container img').hide().load(function(){
		$("#loader").hide();
	// 	$(this).fadeIn(200);
	// });
	

	
	$('#next').bind('mouseup',nextImageHandler);
	$('#prev').bind('mouseup',prevImageHandler);

	
	function nextImageHandler(event) {
		$(this).unbind('mouseup',nextImageHandler);
		var current_image = parseInt($('.image-container:last-child').attr('id').replace(/\D/g,''));
		if (current_image < gallery_count) {
			$('#loader').show();
			$.get(ajax_url + (current_image + 1), function(carousel_item) {	
				$('#image-carousel').append(carousel_item);		
				$('#img-'+ (current_image + 1) +' img').hide().load(function(){
					$(this).show().parent().prev().animate({marginLeft : "-=950px"},450,'swing', function(){
						$('#loader').hide();
						$('#img-' + current_image).remove();
						//event.preventDefault();
						$('#next').bind('mouseup',nextImageHandler);
					});

				});
			});
			if (current_image +1 == gallery_count) {
				$('#next').addClass('inactive-next');							
			}
			$('#prev').removeClass('inactive-prev');
		}
		else {
			$(this).bind('mouseup',nextImageHandler);
		}
		//return false;
	};

	function prevImageHandler(event) {
		$(this).unbind('mouseup',prevImageHandler);
		var image_container = $('.image-container:first-child');
		var current_image = parseInt($(image_container).attr('id').replace(/\D/g,''));
		if (current_image > 1) {
			$('#loader').show();
			$.get(ajax_url + (current_image - 1), function(carousel_item) {				
				$('#image-carousel').prepend(carousel_item);
				$('#img-'+ (current_image - 1) +' img').hide().load(function(){
					$(this).parent().css({marginLeft : "-950px"}).end().show().parent().animate({marginLeft : "0px"},450,'swing', function(){
						$('#loader').hide();
						$('#img-' + current_image).remove();
						//event.preventDefault();
						$('#prev').bind('mouseup',prevImageHandler);
					});
				});
			});	
			if (current_image == 2) {
				$('#prev').addClass('inactive-prev');
			}
			$('#next').removeClass('inactive-next');
		}		
		else {
			$(this).bind('mouseup',prevImageHandler);
		}
		//return false;
	}
});
