var table= $('#agents');
$('.datatable').dataTable({
	"sDom": "<'row-fluid'<'span6'l><'span6'f>>t<'row-fluid'<'span12 center'p>>",
	"sPaginationType": "bootstrap",
	"oLanguage": {
	"sLengthMenu": "_MENU_ records per page"
	}
} );


$('.btn-setting').click(function(e){
e.preventDefault();
$("#agentParam").modal('show');
});
$(document).ready(function() {
	loadAgents(table);

});
function cancel(){
	$("#agentParam").modal('hide');
}
function loadAgents() {
	table.dataTable().fnClearTable();
	$.post("loadAgents", {}, function(data) {
		if (data!=null) {
			for (var i = 0; i<data.list.length; i++) 
				addAgentTableRow(table, data.list[i]);
		}
	},"json");

	$('.btn-info').click(function() {
		deleteAgent(this);
	});
}

function addAgentTableRow(table, data) {
	var status = "NA";
	switch (data.currentStatus) {
	case 1:
		status = "Idle";
		break;
	case 2:
		status = "Running";
		break;
	case 3:
		status = "BackUp";
		break;
	case 4:
		status = "BreakDown";
		break;
	default:
		status = "NA";
		break;
	}
	table.dataTable().fnAddData(
			[ data.hostName, data.id, data.port, status, data.maxLoad,
					data.remainLoad, deleteButton ]);

}

function getAgentId(obj) {
	var row = obj.parentNode.parentNode;
	var tbody = row.parentNode;
	var id = $(tbody).children("tr").eq(row.rowIndex - 1).children("td").eq(1)
			.text();
	return id;
}

function deletetablerow(obj) {
	id=getAgentId(obj);
	table=obj.pratent.parent;
	$.post("removeAgentFromPool", {
		id : id,
	}, function(data) {
		if (data)
			$(table).dataTable().fnDeleteRow(row.rowIndex - 1);
		else{}
		
	});
	
}

function addAgentToDB() {
	$.post("addAgentToPool", {
		hostName : $("#hostName").val(),
		port : $("#port").val(),
		maxLoad : $("#maxLoad").val(),
		remainLoad : $("#remainLoad").val()
	}, function(data) {
		if (data) {
			loadAgents();
		}
	});
}
