var agentColumnIndex = {
	"hostName" : 0,
	"id" : 1,
	"port" : 2,
	"currentStatus" : 3,
	"maxLoad" : 4,
	"remainLoad:" : 5,
	"action" : 6
};
var agentTableModel = new Array("hostName", "port", "currentStatus", "maxLoad",
		"remainLoad");

$(document).ready(function() {
	var table = $('#agents').DataTable();
	var tbody = table.table().body();
	$(tbody).on('click', 'td a.delete', function(e) {
		e.preventDefault();
		var row = $(this).closest("tr");
		var id = $(row).attr("id");
		row = table.row(row);
		var hostName = row.data()[0]
		deleteAgent(id, hostName, row);
	});

	loadAgents(table);

});
function loadAgents(table) {
	var deleteButton = "<a class='btn btn-info delete' ><i class='icon-trash icon-white'></i>"
			+ $.i18n.prop('delete') + "</a>";
	table.clear();
	$.post("loadAgents", {}, function(data) {
		if (data.success) {
			if (data.agents != null) {
				for ( var i = 0; i < data.agents.length; i++) {
					var agent = data.agents[i];
					var tr = table.row.add(
							[ agent.hostName, agent.port,
									formatAgentStatus(agent.currentEnumStatus),
									agent.maxLoad, agent.remainLoad,
									deleteButton ]).draw().node();
					$(tr).attr("id", agent.id);
				}

			}

		} else {
			information($.i18n.prop('fail'));

		}

	})
	function formatAgentStatus(status) {
		if (status == "InIdle") {
			return $.i18n.prop('agent-InIdle');
		}
		if (status == "InRunning") {
			return $.i18n.prop('agent-InRunning')
		}
		if (status == "BackUp") {
			return $.i18n.prop('agent-BackUp');
		}
		if (status == "BreakDown") {
			return $.i18n.prop('agent-BreakDown');
		}

	}

}

function deleteAgent(id, hostName, row) {
	$.post("deleteAgent", {
		agentId : id,
		hostName : hostName
	}, function(data) {
		if (data.success)
			row.remove().draw();
		else {
			information(data.failedMessage);
		}

	}, "json");

}
function addAgentToDB() {
	var table = $('#agents');
	$.post("addAgent", {
		hostName : $("#hostName").val(),
		port : $("#port").val(),
		maxLoad : $("#maxLoad").val(),
		remainLoad : $("#remainLoad").val()
	}, function(data) {
		if (data.success) {
			loadAgents(table.DataTable());
		} else {
			information(data.failedMessage);
		}
	}, "json");
}
$('#agentList').click(function(e) {
	e.preventDefault();
	var table = $('#agents');
	loadAgents(table);
});
$('.btn-setting').click(function(e) {
	e.preventDefault();
	$("#agentParam").modal('show');
});