(function($) {

	$.fn.kGallery = function(options){

		var defaults = {
			current:	'current',
			prev: 		'prev',
			next: 		'next',
			loader:		'loader'
		}; 

		var options = $.extend(defaults, options);  

		this.each(function() {  
			var obj = $(this);

			var current = $("img."+options.current, obj);
			var loader = $("."+options.loader, obj);
			
			var prev = $("."+options.prev, obj);
			var next = $("."+options.next, obj);

			prev.click(function(){
				return adjust($(".items a.active").prev());
			});
			next.click(function(){
				return adjust($(".items a.active").next());
			});

			$(".items a", obj).each(function(){
				$(this).click(function(){
					return adjust($(this));
				});
			});

			function adjust(o) {
				loader.show();
				$(".items a", obj).removeClass("active");
				o.addClass("active");

				if(o.is(".items a:first-child", obj)) prev.hide();
				else prev.show();
				if(o.is(".items a:last-child", obj)) next.hide();
				else next.show();

				var img = new Image();
	
				$(img)
					.addClass('current')
					.load(function() {
						$(this).hide();
						loader.hide();
					    current.parent().append(this);
					    current.remove();
					    $(this).show();
					})
					.error(function(){})
					.attr('src', o.attr("href"));
				
				var current = $("img."+options.current, obj);

				return false;
			}

			if($(".items a.active").is(".items a:first-child", obj)) prev.hide();
			else prev.show();
			if($(".items a.active").is(".items a:last-child", obj)) next.hide();
			else next.show();

		});
	};

})(jQuery);




