var objIdArray = ["user", "group"];
var editIdArray = ["userName", "userGroup", "curPassword", "newPassword", "confirmPassword"];
var EDIT_GROUP = 1;
var CURRENT_PASSWORD = 2;
var EDIT_ROW_NUM = 4;//添加和修改都不上传确认密码
var ROW_NUM = 5;
var actionType;
var rowNum;
var groupType = ["administrator", "poweruser", "user"];
var groupArrayEn = ["Administrator", "Poweruser", "User"];
var groupArrayCn = ["系统管理员", "超级用户", "普通用户"];
var groupArray = [groupArrayEn, groupArrayCn];
var NAME = 0;
var GROUP = 1;

window.onresize = function()
{
	GetMainContentHeight(BUTTON_TOP_NO_MENU, NO_BUTTON_CHANGE);
}

$(document).ready(function()
{	
	GetMainContentHeight(BUTTON_TOP_NO_MENU, NO_BUTTON_CHANGE);
	funcUpdateDisplay();
	$("#newPsdCheckbox").click(function()
	{
		if($(this).prop("checked") == true)
		{
			$("#newPassword").attr("disabled", false);
			$("#confirmPassword").attr("disabled", false);
		}
		else
		{
			$("#newPassword").attr("disabled", true);
			$("#confirmPassword").attr("disabled", true);
		}
	});
});

function funcUpdateDisplay() 
{		
	DisableButton("addBtn");
	DisableButton("refreshBtn");
	PageLoadStatus(true);
	
	displayParam();
	
	ResetColor();
	EnableButton("addBtn");
	EnableButton("refreshBtn");
	PageLoadStatus(false);
}

function displayParam() 
{
	var data;
	var response;
	var xmlHttp = GetHTTPObject();

	xmlHttp.open("GET", "/goform/formEMR30?type=" + USER_CONFIG + "&cmd=" + GET + 
		"&language=" + language + "&slotNo=" + slotNo + "&ran=" + Math.random(), true);
	xmlHttp.onreadystatechange = function()
	{
		if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
		{
			response = AjaxStrDeal(xmlHttp.responseText);
			if(response == "")
			{
				rowNum = 0;
			}
			else
			{
				data = response.split(FIRST_DELIMITER);
				rowNum = data.length;
			}
			DrawTableRow("userList", "dataRow", "userData", rowNum);
			if(rowNum != 0)
			{
				$("#delete1").css("display", "none");
				$("#boundary1").css("display", "none");
				updateTableData(data);
			}
			refreshFlag = true;
		}
	}
	xmlHttp.send(null);
}

function updateTableData(data)
{
	var rowData;
	var index;
	var length;	
	length = groupType.length;
	for(var i = 0; i < rowNum; i++)
	{
		index = i + 1;
		rowData = data[i].split(SECOND_DELIMITER);
		
		$("#" + objIdArray[NAME] + index).html(rowData[NAME]);
		for(var j = 0; j < length; j++)
		{
			if(rowData[GROUP] == groupType[j])
			{
				$("#" + objIdArray[GROUP] + index).html(groupArray[language][j]);
			}
		}
	}
}

function cancelEdit()
{
	$.modal.close();
}

function clearEdit()
{
	for(var i = 0; i < ROW_NUM; i++)
	{
		if(i == EDIT_GROUP)
		{
			$("#" + editIdArray[i]).val("0");
		}
		else
		{
			$("#" + editIdArray[i]).val("");
		}
	}
}

function addUser()
{
	actionType = ADD;
	clearEdit();
	
	$("#userName").attr("disabled", false);
	$("#userGroup").attr("disabled", false);
	$("#curPasswordStr").css("display", "none");
	$("#newPsdContrlTr").css("display", "none");
	$("#newPassword").attr("disabled", false);
	$("#confirmPassword").attr("disabled", false);
	
	$("#editUser").modal();	
}

function modifyUser(obj)
{
	var i;
	var index = GetIndexFromId(obj, 7);
	var currentGroup = $("#group" + index).html();
	var userGroup = $("#userGroup").get(0);
	
	actionType = SET;
	clearEdit()	;
	
	$("#userName").val($("#user" + index).html());
	$("#userName").attr("disabled", true);
	if(($("#user" + index).html() == "Admin") || ($("#user" + index).html() == parent.curUser))
	{
		$("#userGroup").attr("disabled", true);
	}
	else
	{
		$("#userGroup").attr("disabled", false);
	}
	$("#curPasswordStr").css("display", "");
	$("#newPsdContrlTr").css("display", "");
	$("#newPassword").attr("disabled", true);
	$("#confirmPassword").attr("disabled", true);
	
	for(i = 0; i < userGroup.options.length; i++)
	{
		if(userGroup.options[i].text == currentGroup)
		{
			userGroup.selectedIndex = i;
			break;
		}
	}
		
	$("#editUser").modal();
}
/*************************************************
Function: 		editApply
Description: 	用于用户信息添加或者编辑设置
Input: 			无
Output:			无
Return: 		无
Others: 		无
*************************************************/
function editApply()
{
	var data;
	var xmlHttp = GetHTTPObject();
	var response;
	var curUser = $("#userName").val();
	
	if(paramCheck() == false)
	{
		return;
	}
	
	data = "type=" + USER_CONFIG + "&cmd=" + actionType + "&language=" + language + "&slotNo=" + slotNo + "&setString=";		
	data += generateData();
	
	xmlHttp.open("POST", "/goform/formEMR30", true)
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", data.length);

	xmlHttp.onreadystatechange = function()
	{
		if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
		{
			$.modal.close();
			response = parseInt(AjaxStrDeal(xmlHttp.responseText), 10);
			if(response == RETURN_OK)
			{
				if(actionType == ADD)
				{
					if(language == ENGLISH)
					{
						alert("User(" + curUser + ") add successfully!");
					}
					else if(language == CHINESE)
					{
						alert("用户(" + curUser + ")添加成功！");
					}
				}
				else
				{
					if(language == ENGLISH)
					{
						alert("User(" + curUser + ") modify successfully!");
					}
					else if(language == CHINESE)
					{
						alert("用户(" + curUser + ")修改成功！");
					}
				}
			}
			else
			{
				alert(returnError[language][response]);
			}
			funcUpdateDisplay();
		}
	}
	xmlHttp.send(data);
}

function generateData()
{
	var data;
	
	for(var i = 0; i < EDIT_ROW_NUM; i++)
	{
		if((actionType == ADD) && (i == CURRENT_PASSWORD))
		{
			continue;
		}
		if(i == 0)
		{
			data = $("#" + editIdArray[i]).val();
		}
		else if((actionType == SET) && ($("#newPsdCheckbox").prop("checked") == false) && (i > CURRENT_PASSWORD))
		{
			data += FIRST_DELIMITER + $("#" + editIdArray[CURRENT_PASSWORD]).val();
		}
		else
		{
			data += FIRST_DELIMITER + $("#" + editIdArray[i]).val();
		}
	}
	
	return data;
}
/*************************************************
Function: 		deleteUser
Description: 	用于用户信息删除
Input: 			无
Output:			无
Return: 		无
Others: 		无
*************************************************/
function deleteUser(obj)
{
	var confirmPrompt;
	var index = GetIndexFromId(obj, 7);
	var deleteUser = $("#user" + index).html();
	
	if(language == ENGLISH)
	{
		confirmPrompt = "Are you sure to delete the user(" + deleteUser + ")?";
	}
	else if(language == CHINESE)
	{
		confirmPrompt = "确定要删除用户(" + deleteUser +")吗?";
	}
	if(window.confirm(confirmPrompt))
	{
		var data;
		var xmlHttp = GetHTTPObject();
		var response;
	
		data = "type=" + USER_CONFIG + "&cmd=" + DELETE + "&language=" + language + "&slotNo=" + slotNo + "&setString=";		
		data += $("#user" + index).html();
		
		xmlHttp.open("POST", "/goform/formEMR30", true)
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", data.length);
	
		xmlHttp.onreadystatechange = function()
		{
			if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
			{
				response = parseInt(AjaxStrDeal(xmlHttp.responseText), 10);
				if(response == RETURN_OK)
				{
					if(language == ENGLISH)
					{
						alert("User(" + deleteUser + ") delete successfully!");
					}
					else if(language == CHINESE)
					{
						alert("用户(" + deleteUser + ")删除成功！");
					}
				}
				else
				{
					alert(returnError[language][response]);
				}
				funcUpdateDisplay();
			}
		}
		xmlHttp.send(data);
	}
}

/*************************************************
Function: 		validateName
Description: 	用于检测用户名的合法性
Input: 			obj: jquery对象
Output:			无
Return: 		if validate, return ture; else, return false
Others: 		无
*************************************************/
function validateName(obj)
{
	if(ValidateParam(obj, "LENGTH", 3, 20, "<User Name>", "<用户名>", language) == false)
	{
		return false;
	}
	var name =  obj.val();	
	var str = /[^\w]/;
	if(str.test(name))
	{
		if(language == ENGLISH)
		{
			alert("The user name should consist of only letter,integer or underline!");
		}
		else
		{
			alert("输入名字只能由字母（区分大小写）、数字或下划线组成！");
		}
		setTimeout(function () {obj.focus()}, 0);
		setTimeout(function () {obj.select()}, 0);
		return false;
	}
	
	var str = /^[_]|[_]$/;
	if(str.test(name))
	{
		if(language == ENGLISH)
		{
			alert("Underline can not as a beginning or an ending of the name!");
		}
		else
		{
			alert("输入名字不能以下划线作为开头和结尾！");
		}
		setTimeout(function () {obj.focus()}, 0);
		setTimeout(function () {obj.select()}, 0);
		return false;
	}
	for(i = 0; i < rowNum; i++)
	{
		if(name == $("#user" + (i + 1)).html())
		{
			if(language == ENGLISH)
			{
				alert("The user name already exists!");
			}
			else
			{
				alert("用户名已经存在！");
			}
			setTimeout(function () {obj.focus()}, 0);
			setTimeout(function () {obj.select()}, 0);
			return false;
		}
	}
	return true;	
}

/*************************************************
Function: 		validateName
Description: 	用于检测设置密码的合法性
Input: 			obj: jquery对象
Output:			无
Return: 		if validate, return ture; else, return false
Others: 		无
*************************************************/
function validatePassword(obj)
{
	if(ValidateParam(obj, "LENGTH", 3, 20, "<Password>", "<密码>", language) == false)
	{
		return false;
	}
	var password =  obj.val();	
	var str = /[^\w]/;
	if(str.test(password))
	{
		if(language == ENGLISH)
		{
			 alert("Password can only consist of letter, integer and underline!");
		}
		else
		{
			alert("密码只能由字母（区分大小写）、数字或下划线组成！");
		}
		setTimeout(function () {obj.focus()}, 0);
		setTimeout(function () {obj.select()}, 0);
		return false;
	}	
	var i = 1;
	var s = password.charAt(0);
	while(password.charAt(i) == s)
	{
		i++;
		if(i == password.length)
		{
			if(language == ENGLISH)
			{
				alert("The password cannot be the same letter,integer or underline!");
			}			
			else
			{
				alert("密码不能由同一个字母、数字或者下划线组成！");
			}
			setTimeout(function () {obj.focus()}, 0);
			setTimeout(function () {obj.select()}, 0);
			return false;
		}
	}
	return true;
}
		
function paramCheck()
{	
	if(actionType == ADD)
	{
		if(validateName($("#userName")) == false)
		{
			return false;
		}
	}
	if((actionType == SET) && ($("#newPsdCheckbox").prop("checked") == true) || (actionType == ADD))
	{
		if(validatePassword($("#newPassword")) == false)
		{
			return false;
		}
		if($("#userName").val() == $("#newPassword").val())
		{
			var obj = $("#newPassword");
			if(language == ENGLISH)
			{
				alert("Password and user name cannot be the same!");
			}
			else
			{
				alert("用户名和密码不能相同！");
			}
			setTimeout(function () {obj.focus()}, 0);
			setTimeout(function () {obj.select()}, 0);
			return false; 
		}
		if($("#confirmPassword").val() != $("#newPassword").val())
		{
			var obj = $("#confirmPassword");
			if(language == ENGLISH)
			{
				alert("Confirm password differs with password!");
			}
			else
			{
				alert("确认密码与密码不同！");
			}
			setTimeout(function () {obj.focus()}, 0);
			setTimeout(function () {obj.select()}, 0);
			return false; 
		}
	}	
	return true;
}