// IE doesn't have indexOf - amazing.  This ALSO Adds "1" to the index value when you do array length.  So SUCKY!
var array_offset = 0;
if (!Array.prototype.indexOf)
{
	var array_offset = 1;


  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}



// Preload images
var preloaded_images = new Array();
var m_length = mosiac_images.length;
for (var i=0; i < m_length; i++) {
	preloaded_images[i] = new Image();
	preloaded_images[i].src = base + mosiac_images[i];
};

//path = "lib/images/mosiac/";
var this_box_image;
var last_flip = 0;
var current_images = new Array();
var boxes_flipped =new Array();
function fadeSequence( image_list ){
	i=0;
	for( k in image_list){
		
		num = image_list[k];
		this_box = $('#mosiac_' + k);
		this_box_image = $('#mosiac_' + k + " img");
		
		boxes_flipped.push(k);
		
		// create image
		var image = $("<img>").css("display", "none");
		
		// get source - make sure not in current images list
		source = '';
		while( source == '' || current_images.indexOf( source ) != -1 ){
			if(image_list[k])
				source = image_list[k];
			else{
				seed = Math.floor( Math.random() * (mosiac_images.length - array_offset) )
				source = mosiac_images[ seed ];
			}
			source = base + source
			
		}
		//console.info("New source: " + source)
		current_images.push( source )
		//console.info(current_images)
    
		// Fade out old image if exists
		if(this_box_image.length > 0 ){
			
			this_box_image.fadeOut(  750, function(a){ 
				src = this_box_image.attr("src");
				index = current_images.indexOf( src )
				
				// remove the old element
  			current_images.splice( index, 1);
								
				this_box_image.attr("src",  source)
				this_box_image.fadeIn( 1500 )
			
			});
		}else{
			image.attr( "src", source );
			this_box.html( image );
			$(image).delay( i*250 ).fadeIn( 1500 ); 
		}
		
		i++;
	};
} 


function randomFlips( count ){
	num = Math.floor( Math.random()*9+1);
		
	eval(' seq = {'+num+':""}')
	fadeSequence( seq );
	
	//if(count == 6 )
	//	setTimeout( "fadeSequence({5:'upload/thumbnails/wmlogo_small.jpg'})", 4500);
	//else
	setTimeout( "randomFlips("+(count+1)+")", 4500);
}


function loadMosiac(){
	// Inital load sequence 1,2,3,6,9,8,7,4,5
	fadeSequence({1:"",2:"",3:"",6:"",9:"",8:"",7:"", 4:"", 5:""});
	setTimeout( "randomFlips(1)", 4000);
}


$(document).ready(function(){
	loadMosiac();
});
