
$(document).ready(function() {
	var table = $('#table').DataTable();
	var tbody = table.table().body();
	$(tbody).on('click', ' td a.delete', function() {
	
		var row = $(this).closest('tr');
		var portId = $(row).attr("id");
		row = table.row(row);
		deletePort(row, portId);
	});
	loadPorts(table);
});

function deletePort(row, portId) {
	$.post("removePort", {
		port : portId
	}, function(data) {
		if (data.success) {
			row.remove().draw();
		} else
			information(data.failedMessage);
	});
}

function addPort(params) {
	var table = $("#table").DataTable();

	$.post("addPort", params, function(data) {
		if (data.success) {
			loadPorts(table);
			$("#portParam").modal('hide');
		} else {
			information(data.failedMessage);
		}
	});
}
function loadPorts(table) {
	var deleteButton = "<a class='btn btn-info delete' ><i class='icon-trash icon-white'></i>"+$.i18n.prop('delete')+"</a>";
	table.clear();
	$.post("loadPorts", function(data) {
		if (data.success) {
			if (data.ports != null)
				for ( var i = 0; i < data.ports.length; i++) {
					var tr = table.row.add(
							[i,data.ports[i].port,data.ports[i].inUse,
									deleteButton]).draw().node();
					$(tr).attr("id", data.ports[i].id);
				}

		} else {
			information(data.failedMessage);
		}
		
	});
}
$("#plus").click(function(e) {
	e.preventDefault();
	$("#portParam").modal('show');
});
$('#addPort').click(function(e) {
	e.preventDefault();
	var params = {
		port : $("#port").val()
	};
	addPort(params);

});
$('.list').click(function(e) {
	e.preventDefault();
	var table = $('#table');
	loadPorts(table);
});