$(window).load(function(){

	var gallery = $('.gallery .images > div');
	if(gallery.length > 1){
		buttons = [];
		var galleryIndex = 0;
		var nextIndex = 0;
		var delay = 5000;
		locked = false;
				
		var Switch = function(){
			
			if(arguments.length > 0){
				nextIndex = parseInt(arguments[0]);
				$(gallery[galleryIndex]).clearQueue('fx').animate({'opacity': 0}, 600);
				$(gallery[nextIndex]).clearQueue('fx').animate({'opacity': 1},600, function(){
					updateButtons();
					locked = false;
				});
				galleryIndex = nextIndex;
			}
			else{
				nextIndex = (nextIndex + 1) >= gallery.length ? 0 : nextIndex + 1;
				$(gallery[galleryIndex]).delay(delay).animate({'opacity': 0}, 600);
				$(gallery[nextIndex]).delay(delay).animate({'opacity': 1}, 600, function(){
					updateButtons();
					galleryIndex = nextIndex;
					Switch()
				});
			}
			
			
		}
		
		var updateButtons = function(){		
				$('.gallery .controllers .button.active').removeClass('active');
				$(buttons[nextIndex]).addClass('active');
			}
		
		Switch();			
	
		var controllers = $('<div class="controllers"/>');
		controllers.append('<div class="active button"/>');
		
		var i = 0;
		while(i < gallery.length - 1)
		{
			controllers.append('<div class="button"/>');
			i++;
		}
		$('.gallery').append(controllers);
		$('.controllers .button').click(function(){			
			Switch($(this).index());
		});
		
		buttons = $('.gallery .controllers .button');
	}
});
