$(function() {
	buildRolesTable()
	refreshRoles()
	forceFocusOnInfoMessage()
})

var allRoles = {}
function refreshRoles() {
	var table = $('#roleTable').DataTable()
	table.clear()
	
	var roleId = $("#roleTable").data('selectedRoleId')
	
	$.ajax({
		url : 'ajax/roles',
		dataType : 'json',
		error : commonAjaxErrorHandler,
		success : function(r) {
			var selectedRowIndex = -1
			
			/* Just in case we need details later... CPB */
			allRoles = {}
			for (var i = 0; i < r.roles.length; i++) {
				var role = r.roles[i]
				allRoles['' + role.id] = role
				if (roleId == role.id)
					selectedRowIndex = i
			}
			
			table.rows.add(r.roles)
			table.draw()
			
			if (selectedRowIndex != -1)
				table.row(selectedRowIndex).select()
		}
	})
}

function buildRolesTable() {
	var table = $('#roleTable').DataTable({
		"columnDefs" : [{
			"targets" : 0,
			"data" : function(row, type, set, meta) {
				return row.name
			}
		}, {
			"targets" : 1,
			"data" : function(row, type, set, meta) {
				return row.description
			}
		}],
		pageLength: 5,
		paging : true,
		autowidth : true,
		searching : false,
		select : 'single'
	})

	$('#roleTable tbody').on('click', 'tr', function() {
		var data = table.row(this).data()
		$("#roleTable").data('selectedRoleId', data.id)
		$('#edit').show()
	})	
}

function editSelectedRole() {
	doubleClickSafeguard($("#edit"))
	var roleId = $("#roleTable").data('selectedRoleId')
	if (!roleId) return
	
	document.location.href='roleEdit.html?roleId=' + roleId
}

function forceFocusOnInfoMessage() {

	if($('#informationMessageDiv').is(':visible')){	
		$('#informationMessageDiv p:first').focus()	
	}

}

function forceFocusOnTableHeader() {
	$(this).parent().focus()	
}