    var currentIndex = 0,
        list = [],
        currentTimeout = false,
        locked = false;
    var Switch = function() {
    	if(arguments.length > 0 && currentIndex == parseInt(arguments[0]))
    	{
    		locked = false;
    		return;
    	}
        $(list[currentIndex]).parent().parent().fadeOut(1000);
        if (arguments.length == 1) {
            currentIndex = parseInt(arguments[0]);
        } else {
            currentIndex = (currentIndex >= list.length - 1) ? 0 : currentIndex + 1;
        }
    	//console.log("argument: " + arguments[0]);
    	//console.log("index: " + currentIndex);
        setTimeout(function() {
            $('.welcomPageImageGallery .buttons div').removeClass('active');
            $('.welcomPageImageGallery .buttons div:nth-child(' + (currentIndex + 1) + ')').toggleClass('active');
            
            $(list[currentIndex]).parent().parent().fadeIn(1000, function() {
            	if(locked == false)
                	Delay();
                	
            	locked = false;
            });
        }, 200);
    };
    
    var Delay = function() {
        currentTimeout = setTimeout(function() {
            Switch();
        }, 5000);
    };
    
    var Start = function(images) {
        list = images;
        Delay();
    };

(function($) {
    function setupGallery() {
    	if ($('.welcomPageImageGallery').find('img').length < 2)
    		return;
	    var images = $('.welcomPageImageGallery').find('img');		
	    $(images).each(function(index){
	    	if(index == 0)
	    		$('.welcomPageImageGallery').find('.buttons').append('<div class="button active" id="'+ index +'">' + (index + 1) + '</div>');
	        else
	        	$('.welcomPageImageGallery').find('.buttons').append('<div class="button" id="'+ index +'">' + (index + 1) + '</div>');
	    });
    
    Start(images);    		
    }
    
    $(document).ready(function() {
        setupGallery(); 
        
        $('.welcomPageImageGallery .controls div').click(function() {
			if (locked) return false;
			locked = true;
		    if (currentTimeout) clearTimeout(currentTimeout);
		    var newCurrentIndex = currentIndex + 1;
		    if($(this).hasClass('prevButton'))
		    	var newCurrentIndex = currentIndex - 1;
		    	
		   	if(newCurrentIndex < 0)
	    		newCurrentIndex = list.length - 1;
		    if(newCurrentIndex > list.length - 1)
		    	newCurrentIndex = 0;
		    Switch(newCurrentIndex);
			return false;        
        });
        
        $('.welcomPageImageGallery .buttons div').click(function() {
			if (locked) return false;
			locked = true;
		    if (currentTimeout) clearTimeout(currentTimeout);
		    Switch($(this).attr('id'));
			return false;
	    }); 
    });
})(jQuery);

