(function($){
	var gallery_div;
	var items;
	var item_class = 'gallery-item';
	var cycle_timer;
	var current_index = 0;
	var display_time = 5000;
	var fade_time = 1000;
	var image_container;
	var loader_anim;
	var loader_anim_source = "images/glasshaus-loader_anim.gif";	
	
	function beginCycle() {
		clearInterval(cycle_timer);
		cycle_timer = setInterval("$('#" + gallery_div.attr('id') + "').cycleGalleryItems(1)", display_time);
	}
	
	function stepImages(byindeces) {
		gallery_div.css('background-image', 'none');
		gotoImageAt(current_index + byindeces);
	}

	function gotoImageAt(index)
	{
		clearInterval(cycle_timer);
		var nextindex;

		if(index > items.length - 1) nextindex = index - items.length;
		else if (index < 0 ) nextindex = index.length + index;
		else nextindex = index;

		if (items[nextindex].complete) {
			
			loader_anim.stop().animate({ 'opacity' : 0 }, 1000);
			
			$(items[current_index]).stop();
			$(items[current_index]).fadeTo(fade_time, 0);

			$(items[nextindex]).stop();
			$(items[nextindex]).fadeTo(fade_time, 1, function() { beginCycle(); });

			current_index = nextindex;

		} else $(items[nextindex]).load(function() { beginCycle(); });

	}
	
	$.fn.cycleGalleryItems = function(byindeces) {
		stepImages(byindeces);
	}
	
	$.fn.glasshausCycleGallery = function(params) {
		
		clearInterval(cycle_timer);
		
		gallery_div = this;
		
		current_index = 0;
		
		if(params) {
			item_class = params.itemClass ? params.itemClass : item_class;
			fade_time = params.fadeTime ? params.fadeTime : fade_time;
			display_time = params.displayTime ? params.displayTime : display_time;
			loader_anim_source = params.loaderAnim? params.loaderAnim : loader_anim_source;
		}
		
		this.append('<div id="gallery-image-container"></div>');
		this.append('<img id="gallery-loader-anim" src="' + loader_anim_source + '">');
		image_container = $("#gallery-image-container");
		loader_anim = $("#gallery-loader-anim");
		image_container.css({
			'display': 'block',
			'position': 'relative',
			'top': 0,
			'left': 0,
			'float' : 'none',
			'clear' : 'both',
			'width' : '100%',
			'height' : '100%',
			'z-index': 2
		});
		loader_anim.css({
			'display': 'block',
			'position': 'absolute',
			'top': ((gallery_div.height() - loader_anim.height()) / 2),
			'left': ((gallery_div.width() - loader_anim.width()) / 2),
			'z-index': 1
		});
		
		items = this.find('.' + item_class);		

		items.each(function(){
			
			$(this).css({
				'position': 'absolute',
				'left': 0,
				'bottom' : 0,
				'display' : 'block',
				'opacity' : 0
			});
			
			image_container.append($(this));
			
			$(this).fadeOut(0);
			
		});
		
		gotoImageAt(0);
		
	}	
}(jQuery));
