;(function($){
	
	var table;
	var breadcrumbs = [];
	var currentDepth = 0;
	
	$.fn.tableDriller = function( url, options ){
	
		table = $(this);
		
		settings = $.extend({
			titleLocation:	$("#" + table.attr("id") + "_breadcrumb" ),
			tableBody: 		table.find("tbody"),
			rootToken: 		"root_token"
		}, options );
		
		breadcrumbs[0] = settings.titleLocation.html();
		$("#" + settings.rootToken).click( breadcrumbClick );
		
		initializeEvents();
	};
	
	function initializeEvents(){
		table.find("tr").click( function(){
			currentDepth++;
			setBreadcrumbs( $(this).find("td:first").text(), $(this).attr("id") );
			drillFromRow( $(this) );
		});
	};
	
	function breadcrumbClick(){
		var elementId = $(this).attr("id");
		if ( elementId == settings.rootToken ){
			currentDepth = 0;
		} else {
			var tokens = $(this).attr("id").split("_");
			if ( tokens[0] - 1 > currentDepth )
				currentDepth = tokens[0] - 1;
		}
		removeTrailingBreadcrumbs();
		drillToTable( elementId );
	};
	
	function setBreadcrumbs( text, url ){
		var anchor = $("<a id=\"" + currentDepth + "_" + text + "_" + url + "\">" + text + "</a>");
		anchor.click( breadcrumbClick );
		settings.titleLocation.append(" : ").append( anchor );
	};
	
	function removeTrailingBreadcrumbs(){
		$.each( settings.titleLocation.children(), function(){
			var elementId = $(this).attr("id");
			var tokens = elementId.split("_");
			if ( tokens[0] > currentDepth ){
				$(this).remove();
			}
		});
	};
	
	function drillFromRow( row ){
		getTableData( row.attr("id") );
	};
	
	function drillToTable( id ){
		var tokens = id.split("_");
		url = tokens[ tokens.length - 1 ];
		getTableData( url );
	};
	
	function getTableData( dataURL ){
		$.ajax({
				type:	"GET",
				url:	dataURL,
				success:function(data){
					update( settings.tableBody, data );
				}
		});
	};
	
	function update( tableBody, data ){
		tableBody.find("tr").remove();
		tableBody.append( data );
	};
	
})(jQuery);