var Gravity = {

	last_id: 0,
	num_blocks: 0,
	top_zindex: 0,
		
	init: function() {
/*		
		$("#air .block_container").css({
			height: $("#air").outerHeight() + "px"
		});
*/		
		$(".xtrig").click(function(i) {
	  	var block = Gravity.getblock(this.href);
	  	Gravity.fall(block);
		});

		var block = Gravity.getblock( document.location.hash );
		Gravity.fall( block );
		
		Gravity.num_blocks = $('.block').length;
		Gravity.top_zindex = 1;										
	},

	getblock: function( href ) {									
		// determine which block to move down, based on the href location of this link being clicked
		var block_id = 1;
		var parts = href.split( '#',2 );
		if( parts.length==2 ) {
			parts = parts[1].split('/', 2);
			block_id = parts[0];
		}
		
		if( block_id != Gravity.last_id ) {
			Gravity.last_id = block_id;
			return $('#cards .block')[block_id - 1]
		} else return false;
	}, 
	
	fall: function( block ) {
		if( !block ) return false;

		if( Gravity.top_zindex==(Gravity.num_blocks) ) {
			$('.block').css('z-index',1);
			Gravity.top_zindex = Gravity.top_zindex+2;					
		}   				
		Gravity.top_zindex = (Gravity.top_zindex+1) % (Gravity.num_blocks+1);
		if( !Gravity.top_zindex ) Gravity.top_zindex = 1; 
		$(block).css('z-index',Gravity.top_zindex);
		$(block).css('top','0px');

		//var yposBlock = $(block).position()['top'] - $("#air").position()['top'];
		var fallDist = 327; //($("#air").outerHeight() - yposBlock) - $(block).outerHeight();
		
		//let the block fall
		$(block).stop().animate({
			top: fallDist+"px"
		}, {
			duration: 1000,
			easing: "easeOutBounce",
			complete: function(){
				Gravity.finish(this);
			}
		});		
	},
	
	finish: function( target ) {
		$('#cards .block').each( function(i) {
			if(this != target)
		  	$(this).css('top','0px');				
		});			
	}
		

}

$(document).ready(function(){
	setTimeout( "Gravity.init()", 500 );
});
