var actionType;
var rowNum = 0;
var initRow = true;
var curRespRowNum;
var rowIndex;

var inputArray;
var outputArray;
var modifyRowIndex;

var inPortDataArray = [];
var outPortDataArray = [];
var pidPriority = [];
var pidPriorityText = [["Normal", "Low"],["普通", "低"]];

var objIdArray = ["index", "inCard", "inPort", "inPid", "outCard", "outPort", "outPid", "priority"];
var editIdArray = ["", "editInCard", "editInPort", "editInPid", "editOutCard", "editOutPort", "editOutPid", "lowerPriority"];
var COL_NUM = 8;
var INDEX = 0;
var INPUT_CARD = 1;
var INPUT_PORT = 2;
var OUTPUT_CARD = 4;
var OUTPUT_PORT = 5;
var PRIORITY = 7;
var CHECKED = 1;

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

$(document).ready(function()
{	
	GetMainContentHeight(BUTTON_TOP_NO_MENU, NO_BUTTON_CHANGE);
	funcUpdateDisplay();
	$("#editMap").css("display", "none");	
});

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

function pageRefresh()
{
	PageRefresh(TOP);
	$("#editMap").css("display", "none");	
}

function generateOption()
{
	var data;
	var response;
	var cardArray;
	var xmlHttp = GetHTTPObject();

	xmlHttp.open("GET", "/goform/formEMR30?type=" + PID_MAP_LIST + "&cmd=" + GET + 
		"&language=" + language + "&slotNo=" + slotNo + "&ran=" + Math.random(), true);
	xmlHttp.onreadystatechange = function()
	{
		if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
		{
			response = AjaxStrDeal(xmlHttp.responseText);
			cardArray = response.split(FIRST_DELIMITER);
			inputArray = cardArray[0].split(SECOND_DELIMITER);
			outputArray = cardArray[1].split(SECOND_DELIMITER);
			//populateCard();
			displayParam();
		}
	}
	xmlHttp.send(null);
}

function displayParam() 
{
	var data;
	var response;
	var indexInfo;
	var curRowNum;
	var xmlHttp = GetHTTPObject();
	if(initRow)
	{
		rowIndex = 0;		
	}
	xmlHttp.open("GET", "/goform/formEMR30?type=" + PID_MAP + "&cmd=" + GET + "&rowIndex=" + rowIndex + 
		"&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
			{
				initRow = false;
				data = response.split(FIRST_DELIMITER);
				curRespRowNum = data.length - 1;
				indexInfo = data[curRespRowNum].split(SECOND_DELIMITER);
				rowIndex = parseInt(indexInfo[0], 10);
				rowNum = parseInt(indexInfo[1], 10);
				curRowNum = $("#dataTable tr").filter(".CaseRow").length;
				if((curRowNum < rowNum) && (curRowNum < rowIndex))
				{
					DrawTableRow("dataTable", "dataRow", "CaseRow", rowIndex);
				}
				else if(curRowNum > rowNum)
				{
					DrawTableRow("dataTable", "dataRow", "CaseRow", rowNum);
				}
			}
			if(curRespRowNum != 0)
			{
				updateTableData(data);
			}
			if(rowIndex < rowNum)
			{
				setTimeout("displayParam()", 5);
			}
			else if(rowIndex == rowNum)
			{
				if(parent.groupAccess != USER)
				{
					EnableButton("addBtn");
				}
				EnableButton("refreshBtn");
				initRow = true;
				refreshFlag = true;
			}
		}
	}
	xmlHttp.send(null);
}

function getCardDisplayStr(cardNo, language)
{
	var displayStr;
	var index = language - 1;

	displayStr = cardArray[index] + cardNo;
	
	return displayStr;
}

function updateTableData(data)
{
	var rowData;
	var index;
	
	for(var i = (rowIndex - curRespRowNum); i < rowIndex; i++)
	{
		index = i + 1;
		rowData = data[i - (rowIndex - curRespRowNum)].split(SECOND_DELIMITER);
		
		for(var j = 0; j < COL_NUM; j++)
		{
			if(j == INDEX)
			{
				$("#" + objIdArray[j] + index).html(index);
			}
			else if((j == INPUT_PORT) || (j == OUTPUT_PORT))
			{
				$("#" + objIdArray[j] + index).html(getPortDisplayStr(rowData[j - 2] - 1, parseInt(rowData[j - 1]), language));
				if(j == INPUT_PORT)
				{
					inPortDataArray[index] = parseInt(rowData[j - 1]);
				}
				else if(j == OUTPUT_PORT)
				{
					outPortDataArray[index] = parseInt(rowData[j - 1]);
				}
			}
			else if(j == PRIORITY)
			{
				pidPriority[index] = parseInt(rowData[j - 1]);
				$("#" + objIdArray[j] + index).html(pidPriorityText[language][parseInt(rowData[j - 1])]);
			}
			else
			{
				$("#" + objIdArray[j] + index).html(rowData[j - 1]);
			}
			if(parent.groupAccess == USER)
			{				
				$("#modify" + index).css("cursor", "default");
				$("#modify" + index).attr("onclick", "");
				$("#delete" + index).css("cursor", "default");
				$("#delete" + index).attr("onclick", "");				
			}
		}
	}		
}

function populateCard()
{
	var editInCard;
	var inCardInfo;
	var editOutCard;
	var outCardInfo;
	var option;
	var inCardNum = inputArray.length; 
	var outCardNum = outputArray.length;

	editInCard = $("#editInCard");
	editInCard.empty();
	if(inputArray[0] == "")
	{
		option = $("<option>").text(noCardList[language]).val(NO_CARD);
		editInCard.append(option);
	}
	else
	{
		for(var i = 0; i < inCardNum; i++) 
		{
			inCardInfo = inputArray[i].split(THIRD_DELIMITER);
			option = $("<option>").text(inCardInfo[0]).val(inCardInfo[1]);
			editInCard.append(option);	
		}
	}
	
	editOutCard = $("#editOutCard");
	editOutCard.empty();
	if(outputArray[0] == "")
	{
		option = $("<option>").text(noCardList[language]).val(NO_CARD);
		editOutCard.append(option);
	}
	else
	{
		for(var i = 0; i < outCardNum; i++) 
		{		
			outCardInfo = outputArray[i].split(THIRD_DELIMITER);
			option = $("<option>").text(outCardInfo[0]).val(outCardInfo[1]);
			editOutCard.append(option);	
		}
	}	
}

function populateInputPort(obj)
{
	var editInPort = $("#editInPort");
	var option;
	var cardNo = parseInt(obj.val(), 10);
	
	editInPort.empty();
	if(cardNo == NO_CARD)
	{
		option = $("<option>").text(noPortList[language]).val(NO_PORT);
		editInPort.append(option);
	}
	else
	{		
		var selectIndex = obj.get(0).selectedIndex;
		var inPortInfo = inputArray[selectIndex].split(THIRD_DELIMITER);
		var portNum = inPortInfo.length - 2;
		var displayStr;
		
		for(var i = 0; i < portNum; i++)
		{
			displayStr = getPortDisplayStr(cardNo, parseInt(inPortInfo[2 + i]), language);
			option = $("<option>").text(displayStr).val(parseInt(inPortInfo[2 + i]) - 1);
			editInPort.append(option);
		}
	}
}

function populateOutputPort(obj)
{
	var editOutPort = $("#editOutPort");
	var option;
	var cardNo = parseInt(obj.val(), 10);
	
	editOutPort.empty();
	if(cardNo == NO_CARD)
	{
		option = $("<option>").text(noPortList[language]).val(NO_PORT);
		editOutPort.append(option);
	}
	else
	{			
		var selectIndex = obj.get(0).selectedIndex;
		var outPortInfo = outputArray[selectIndex].split(THIRD_DELIMITER);
		var portNum = outPortInfo.length - 2;	
		var displayStr;
				
		for(var i = 0; i < portNum; i++)
		{		
			displayStr = getPortDisplayStr(cardNo, parseInt(outPortInfo[2 + i]), language);
			option = $("<option>").text(displayStr).val(parseInt(outPortInfo[2 + i]) - 1);
			editOutPort.append(option);
		}
	}
}

function cancelEdit()
{
	$("#editMap").css("display", "none");
}

function openApplyWindow()
{
	populateCard();
	var editInCard = $("#editInCard").get(0);
	var editInPort = $("#editInPort").get(0);
	var editInCardValue = editInCard.options[0].value;
	var editInPortValue;
	
	var editOutCard = $("#editOutCard").get(0);
	var editOutPort = $("#editOutPort").get(0);
	var editOutCardValue = editOutCard.options[0].value;
	var editOutPortValue;
	
	if(actionType == ADD)
	{
		for(var i = INPUT_CARD; i <= OUTPUT_PORT; i++)
		{
			$("#" + editIdArray[i]).attr("disabled", false);
		}
		$("#editInCard").val(editInCardValue);
		populateInputPort($("#editInCard"));
		editInPortValue = editInPort.options[0].value;
		$("#editInPort").val(editInPortValue);
		$("#editInPid").val("");
		$("#editOutCard").val(editOutCardValue);
		populateOutputPort($("#editOutCard"));
		editOutPortValue = editOutPort.options[0].value
		$("#editOutPort").val(editOutPortValue);
		$("#editOutPid").val("");
		$("#lowerPriority").prop("checked", false);
	}
	else
	{
		for(var i = INPUT_CARD; i <= OUTPUT_PORT; i++)
		{
			$("#" + editIdArray[i]).attr("disabled", true);
		}
		
		$("#editInCard").val($("#inCard" + modifyRowIndex).html() - 1);
		populateInputPort($("#editInCard"));
		$("#editInPort").val(inPortDataArray[modifyRowIndex] - 1);	
		$("#editInPid").val($("#inPid" + modifyRowIndex).html());
		$("#editOutCard").val($("#outCard" + modifyRowIndex).html() - 1);
		populateOutputPort($("#editOutCard"));
		$("#editOutPort").val(outPortDataArray[modifyRowIndex] - 1);	
		$("#editOutPid").val($("#outPid" + modifyRowIndex).html());
		if(pidPriority[modifyRowIndex] == CHECKED)
		{
			$("#lowerPriority").prop("checked", true);
		}
		else
		{
			$("#lowerPriority").prop("checked", false);
		}
	}
	ResetColor();
	$("#editMap").css("display", "");	
}


function addMapInfo()
{	
	actionType = ADD;
	if(language == ENGLISH)
	{
		$("#cancelBtn").val("Finish");
		$("#tableHeader").html("Add PID");
	}
	else
	{
		$("#cancelBtn").val("完 成");
		$("#tableHeader").html("添加PID映射");
	}
	openApplyWindow();	
}

function modifyMapInfo(obj)
{
	actionType = SET;
	modifyRowIndex = parseInt(GetIndexFromId($(obj), 7), 10);	
	if(language == ENGLISH)
	{
		$("#cancelBtn").val("Cancel");
		$("#tableHeader").html("Modify PID");
	}
	else
	{
		$("#cancelBtn").val("取 消");
		$("#tableHeader").html("修改PID映射");
	}	
	openApplyWindow();	
}

/*************************************************
Function: 		editMapInfoApply
Description: 	用于PID映射添加或者修改设置
*************************************************/
function editMapInfoApply()
{
	var data;
	var xmlHttp = GetHTTPObject();
	var response;
	
	if(paramCheck() == false)
	{
		return;
	}
	
	data = "type=" + PID_MAP + "&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))
		{
			response = parseInt(AjaxStrDeal(xmlHttp.responseText), 10);
			if(response == RETURN_OK)
			{
				if(actionType == ADD)
				{
					if(language == ENGLISH)
					{
						alert("PID Map add successfully!");
					}
					else if(language == CHINESE)
					{
						alert("PID映射添加成功！");
					}
				}
				else
				{
					$("#editMap").css("display", "none");	
					if(language == ENGLISH)
					{
						alert("PID Map modify successfully!");
					}
					else if(language == CHINESE)
					{
						alert("PID映射修改成功！");
					}
				}
			}
			else
			{
				alert(returnError[language][response]);
			}
			funcUpdateDisplay();
		}
	}
	xmlHttp.send(data);
}

function generateData()
{
	var data;
	
	if(actionType == ADD)
	{	
		for(var i = INPUT_CARD; i < COL_NUM; i++)
		{
			if(i == INPUT_CARD)
			{
				data = $("#" + editIdArray[i]).val();
			}
			else if(i == PRIORITY)
			{
				if($("#" + editIdArray[i]).prop("checked") == true)
				{
					data += FIRST_DELIMITER + 1;
				}
				else
				{
					data += FIRST_DELIMITER + 0;
				}
			}
			else
			{
				data += FIRST_DELIMITER + $("#" + editIdArray[i]).val();
			}
		}
	}
	else
	{
		for(var i = OUTPUT_CARD; i < COL_NUM - 1; i++)
		{
			if(i == OUTPUT_CARD)
			{
				data = $("#" + editIdArray[i]).val();
			}
			else
			{
				data += FIRST_DELIMITER + $("#" + editIdArray[i]).val();
			}
		}
		data += FIRST_DELIMITER + $("#outPid" + modifyRowIndex).html();
		if($("#" + editIdArray[i]).prop("checked") == true)
		{
			data += FIRST_DELIMITER + 1;
		}
		else
		{
			data += FIRST_DELIMITER + 0;
		}
	}
	return data;
}

function deleteMapInfo(obj)
{
	var confirmPrompt;
	if(language == ENGLISH)
	{
		confirmPrompt = "Are you sure to delete the PID Map?";
	}
	else if(language == CHINESE)
	{
		confirmPrompt = "确定要删除当前PID映射吗?";
	}
	if(window.confirm(confirmPrompt))
	{
		index = GetIndexFromId($(obj), 7);
		var data;
		var xmlHttp = GetHTTPObject();
		var response;
	
		data = "type=" + PID_MAP + "&cmd=" + DELETE + "&language=" + language + "&slotNo=" + slotNo + "&setString=";		
		data += $("#outCard" + index).html() + FIRST_DELIMITER + outPortDataArray[index] + FIRST_DELIMITER + $("#outPid" + 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("PID Map delete successfully!");
					}
					else if(language == CHINESE)
					{
						alert("PID映射删除成功！");
					}
				}
				else
				{
					alert(returnError[language][response]);
				}
				funcUpdateDisplay();
				$("#editMap").css("display", "none");
			}
		}
		xmlHttp.send(data);
	}
}
		
function paramCheck()
{	
	if(actionType == ADD)
	{
		if((parseInt($("#editInCard").val(), 10) == NO_CARD) || (parseInt($("#editOutCard").val(), 10) == NO_CARD))
		{
			$.modal.close();
			if(language == ENGLISH)
			{
				alert("Card List is empty, so can't add PID map!");
			}
			else
			{
				alert("卡列表为空，不能添加PID映射！");
			}		
			return false;
		}
		if(ValidateParam($("#editInPid"), "INT_DEC_HEX", 0, 8191, "<Input PID>", "<输入PID>", language) == false)
		{
			return false;
		}
			
		if(ValidateParam($("#editOutPid"), "INT_DEC_HEX", 0, 8191, "<Output PID>", "<输出PID>", language) == false)
		{
			return false;
		}
	}
	else
	{
		if(ValidateParam($("#editOutPid"), "INT_DEC_HEX", 0, 8191, "<Output PID>", "<输出PID>", language) == false)
		{
			return false;
		}		
	}
	return true;
}