function getHashValue(key) {
	var value = location.hash.match(new RegExp(key+'=([^&]*)'))
	if (value) {
		return value[1];
	} else {
		return false;
	}
}

function enableControls() {
	$("#nodes").attr('disabled', false);
	$("#reports").attr('disabled', false);
	$("#retrieve").attr('disabled', false);
	$("#refresh").attr('disabled', false);
	$("#search").attr('disabled', false);
}

function disableControls() {
	$("#nodes").attr('disabled', true);
	$("#reports").attr('disabled', true);
	$("#retrieve").attr('disabled', true);
	$("#refresh").attr('disabled', true);
	$("#search").attr('disabled', true);
	$("#search").val('');
}

function getLastUpdated(node) {
	var node = $("#nodes").val();
	//console.log(node);
        $.post("query.php", {node : node, json : "lastupdated"} ,function(result){
                $('#updated').empty();
		var unixtime = result;
		var newDate = new Date();
		newDate.setTime(unixtime * 1000);
		dateString = newDate.toUTCString();

		$('#updated').text("Node Last Updated: " + dateString);
        }).fail(function () {
                $('#updated').empty();
                $("#updated").text("Node Last Updated: Unknown");
        });
}

function getNodes() {
	disableControls();
	$('#nodes').empty();
	$("#nodes").append("<option>Loading...</option>");

	$.post("query.php", {node : null, json : "nodes" }, function(result){
		//console.log(result);
		$('#nodes').empty();
		$.each(result, function(i, node){
			if (i == 0) {
				var selected = "selected";
			} else {
				var selected = "";
			}
			$("#nodes").append("<option value='" + i + "'" + selected + ">" + node.name + "</option>");
		});
	}).done(function () {
		enableControls();
		var node = getHashValue('node');
		console.log(node);
		if (node) {
			$("select#nodes option[value='" + node + "']").attr("selected", true);
			getReports();
		} else {
			getReports();
		}

	}).fail(function () {
		$('#nodes').empty();
		$("#nodes").append("<option>No Nodes</option>");
	});
}

function getReports() {
	$("#retrieve").attr('disabled', true);
	$("#reports").attr('disabled', true);

	$('#reports').empty();
	$("#reports ").append("<option>Loading....</option>");

	var node = $("#nodes").val();
	getLastUpdated(node);

	//console.log(node);
	$.post("query.php", {json : "reports", node : node},  function(result){
		$('#reports').empty();
		$.each(result, function(i, field){
			//We only want filename. No Extension or path.
			var parts = field.split("/");
			var value = parts[parts.length - 1].split(".")[0];
			$("#reports").append("<option value='" + field + "'>" + value + "</option>");
		});
	}).fail(function () {
		$("#reports").empty();
		$("#reports").append("<option>No Reports</option>");
	}).success(function () {
		$("#retrieve").attr('disabled', false);
		$("#reports").attr('disabled', false);

                var report = getHashValue('report');
                if (report) {
                        $("select#reports option[value='" + report + "']").attr("selected", true);
			if ( $("select#reports option[value='" + report  + "']").val() !== undefined) {
	                        retrieve();
			}
                }
	});
}

$("#refresh").click(function(){
	getNodes();
});

$("#nodes").change(function() {
	//console.log($("#nodes").val());
	$('#report-title').empty();
	$('#report').empty();
	getReports();
});

function retrieve() {
	var node = $("#nodes").val();
	var report = $( "#reports option:selected" ).val();

	if (report !== undefined) {
		disableControls();
		//console.log(report);
		$("#report").empty();
		$.post("query.php", {file : report, node : node}, function(data){
			$('#report-title').text(
				$("#reports option:selected").text() +
				" for node " +
				$("#nodes option:selected").text() 
			);
			var thead = "";
			$.each(data[0], function(i, header) {
				thead += "<th>" + i + "</th>";
			});
			$("#report").append("<thead><tr>" + thead + "</tr></thead>");
	
	
			$.each(data, function(i, row){
				var trow = "";
	
				$.each(row, function(i, item) {
					trow += "<td>" + jQuery('<div />').text(item).html() + "</td>";
				}); 
	
				$("#report").append("<tr>" + trow + "</tr >");
		
			});
		
			var newTableObject = document.getElementById("report");
			//console.log(newTableObject);
	
			sorttable.makeSortable(newTableObject);
	
		}).done(function() {
			enableControls();
			$('td').filter(function(){
				return $.trim($(this).text()) === "null";
			}).css('color', 'white')
			window.location.hash = '#node=' + node + '&report=' + report;
		});
	} else {
		$('#retrieve').attr('disabled', true);
	}

}

$("#retrieve").click(function(){
	retrieve();
});


$('#search').keyup(function () {
	var text = $('#search').val();
	var count = 0;
	$('tr').show();
	$('td').removeAttr('style');
	if (text.length > 0) {
		count = $("td:visible:contains('" + text  + "')").css('background-color', 'yellow').length;
	}
	$('tbody > tr:not(:contains("' + text + '"))').hide();
	$('#occurrences').text(count + " occurrences");
});

$('#search').dblclick(function() {
	$('tr').show();
	$('td').removeAttr('style');
	$('#search').val('');
	$('#occurrences').text("0 occurrences");

});

$("#enablejavascript").hide();
$("#report").empty();
enableControls();
getNodes();




//var report = getHashValue('report');
//if (report != null) {
//	$("select#reports").find("option#" + report).attr("selected", "selected");
//}

