var PLAYLIST = [];
var SELECTED = -1;
var PAUSE_TIME = 6000;
var ANIMATION_TIME = 2000;
var GRID = {};
GRID.X = 150;
GRID.Y = 190;
var MARGINS = 6;

//shuffle function credit to:Jonas Raoni Soares Silva http://jsfromhell.com/array/shuffle
function shuffle(v){
    for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
}

function buildShuffledPlaylist(){
	var tiles = $(".tile");
	for(var i=0; i<tiles.length; i++){
		PLAYLIST.push(i);
	}
	PLAYLIST = shuffle(PLAYLIST);
}

function animateRandomTile(){
	if(SELECTED == -1){
		if (PLAYLIST.length == 0) buildShuffledPlaylist();
		var this_tile = PLAYLIST.pop();
		animateTile($('.tile')[this_tile]);
	}else{
		animateTile($('.tile')[SELECTED]);
	}
	setTimeout(animateRandomTile,ANIMATION_TIME+PAUSE_TIME);
}

function animateTile(tile_object){
	var img = $(tile_object).children('img');
	var height = $(img).height();
	var top = $(img).position().top;
	var remainder = 190 % top;
	
	if(top <= -height+190){
		// check if we need to go back to the top
		if(Modernizr.cssanimations){
			$(img).css('top','0px');
		}else{	
			$(img).animate({'top': '0px'}, {queue: false, duration: ANIMATION_TIME});
		}
	}else{
		// otherwise go down one
		if(Modernizr.cssanimations){
			$(img).css('top',top - 190);
		}else{
			$(img).animate({'top': '-=190px'}, {queue: false, duration: ANIMATION_TIME});
		}
	}
}

function colorToBinary(r,g,b,k){
	var result = 0;
	if(r) result += 8;
	if(g) result += 4;
	if(b) result += 2;
	if(k) result += 1;
	return (result - 1) * -50;
}

// Turn on event handlers as soon as the DOM loads
$(document).ready(function(){

	$('div.tile').live('mouseenter mouseleave', function(e){
		e.stopPropagation();
		if(e.type == 'mouseenter'){
			$('.tile').children('.details').hide();
			$(this).children('.details').show();
			$(this).css("z-index", 3);
			$('#selector').css({
				left: $(this).position().left-10
				,top: $(this).position().top-10
				,display: "block"
			});
			
			SELECTED = $(this).index();
			PAUSE_TIME = 4000;
			ANIMATION_TIME = 500;
			$('#ribbons').css({
				'backgroundPosition': 0 + 'px ' + colorToBinary($(this).data("red"),$(this).data("green"),$(this).data("blue"),$(this).data("black")) + 'px'
			});
			
		}
		else if(e.type == 'mouseleave'){
			$(this).children('.details').hide();
			$(this).css("z-index", 1);
			$('#selector').css({
				display: "none"
			});
			
			SELECTED = -1;
			PAUSE_TIME = 6000;
			ANIMATION_TIME = 2000;
		}
	});
	
	setTimeout(animateRandomTile,PAUSE_TIME);

});



