$(document).ready(function() {

	var imgcount = 0;

	function preload () {
        
        var imgbox = [];
        var totalimg = 0;
        

		$("#test").css("display","none");
        totalimg = $("#test").children("img").size();
         
        $("#test"+" img").each(function(){
            imgbox.push(this);
            checkloaded(this);
        });

        function checkloaded (obj){
            var img = new Image();
   	
            img.onload = function() {
        		imgcount++;
				if (totalimg == (Math.floor(imgcount/3))	){
					$("#load").css("display","none");
					$("#test").css("display","block");
					start_swap();
				} 

				$("#load").css("display","none");
				$("#test").css("display","block");
				start_swap();
        	}
    	    img.src = obj.src;
        }
    }
    
	// Hide all images but not first one
	$("#test").children("img:first").css("display","block");

	var t;
	var i 			= 1;
	var timer_is_on = 0;
	var img_counter = $("#test").children("img").size();
	

	function swap_state() {
  
		var curr_img = $("#test > img:visible");
		
		if(i == img_counter){
			i = 1;
			curr_img = $("#test > img:first");
			// Hide all images but not first one
			$("#test").children("img").css("display","none");
			$("#test").children("img:first").css("display","block");
		}

		var next_img = $(curr_img).next('img').eq(0);

		curr_img.css("display","none");
		next_img.css("display","block");
  
		t = setTimeout(swap_state,100);

		i++;
	}

	function start_swap() {
		if (!timer_is_on) {
			timer_is_on = 1;
  			swap_state();
  		}
	}

	function stop_swap() {
		clearTimeout(t);
		timer_is_on = 0;
	}

	$("#test > img").hover(
		function() {
			stop_swap(); // Stop
		},
		function() {
			start_swap(); // Go on
		}
	);

	preload();

});