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

var objIdArray = ["mainCard", "mainPort", "mainDescType", "mainDescription", "mainMinRate", "mainMaxRate", "mainCurRate", "mainSwitchDelay", "backupCard", "backupPort", "backupDescType", "backupDescription", "backupMinRate", "backupMaxRate", "backupCurRate", "backupSwitchDelay", "backupMode", "workState"];
var editIdArray = ["editMainCard", "editMainPort", "editMainMinRate", "editMainMaxRate", "M2BSwitchTime", "editBackupCard", "editBackupPort", "editBackupMinRate", "editBackupMaxRate", "B2MSwitchTime", "editBackupMode"];
var COL_NUM = 18;
var EDIT_NUM = 11;
var mainPortDataArray = [];
var backupPortDataArray = [];

var MAIN_PORT = 1;
var MAIN_DESC_TYPE = 2;
var MAIN_DESC = 3;

var BACKUP_PORT = 9;
var BACKUP_DESC_TYPE = 10;
var BACKUP_DESC = 11;
var BACKUP_MODE = 16;
var WORK_STATE = 17;
var SUPPORT_PORT_DESC = 0;

var MAIN_MIN_RATE = 2; //set param

var INVALID = 0;
var MAIN = 1;
var BACKUP = 2;
var workStateEn = ["Invalid", "Main", "Backup"];
var workStateCn = ["无效", "主路", "备路"];
var workState = [workStateEn, workStateCn];

var backupModeEn = ["", "Assign Main", "Assign Backup", "Main Priority", "One Way Switch", "Floating"];
var backupModeCn = ["", "指定主路", "指定备路", "主路优先", "单向切换", "浮动"];
var backupMode = [backupModeEn, backupModeCn];

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

$(document).ready(function()
{	
	GetMainContentHeight(BUTTON_TOP_NO_MENU, NO_BUTTON_CHANGE);
	funcUpdateDisplay();
	
	if(parent.groupAccess != USER)
	{
		$("input[type=checkbox]").live("click", function()
		{
			EnableButton("deleteBtn");		
		});
	}
});

function funcUpdateDisplay() 
{		
	DisableButton("addBtn");
	DisableButton("deleteBtn");
	DisableButton("refreshBtn");
	PageLoadStatus(true);
	
	generateOption();
	
	ResetColor();
	PageLoadStatus(false);
	
	$("input[type=checkbox]").attr("checked", false);
}

function checkAll()
{
	for(var i = 0; i < rowNum; i++)
	{
		$("#check" + (i + 1)).prop("checked", $("#checkAll").prop("checked"));
	}
}

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

	xmlHttp.open("GET", "/goform/formEMR30?type=" + PORT_BACKUP_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);
			optionArray = response.split(FIRST_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=" + PORT_BACKUP + "&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 != "")
			{
				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(".mainCaseRow").length;
				if((curRowNum < rowNum) && (curRowNum < rowIndex))
				{
					DrawTableTwoRow("dataTable", "mainDataRow", "mainCaseRow", "backupDataRow", "backupCaseRow", rowIndex);
				}
				else if(curRowNum > rowNum)
				{
					DrawTableTwoRow("dataTable", "mainDataRow", "mainCaseRow", "backupDataRow", "backupCaseRow", 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 populateCard()
{
	var editMainCard;
	var editBackupCard;
	var mainCardInfo;
	var backupCardInfo;
	var option;
	var cardNum = optionArray.length;
	
	editMainCard = $("#editMainCard");
	editMainCard.empty();
	editBackupCard = $("#editBackupCard");
	editBackupCard.empty();
	
	if(optionArray[0] == "")
	{
		option = $("<option>").text(noCardList[language]).val(NO_CARD);
		editMainCard.append(option);
		option = $("<option>").text(noCardList[language]).val(NO_CARD);
		editBackupCard.append(option);
		
	}
	else
	{
		for(var i = 0; i < cardNum; i++) 
		{
			mainCardInfo = optionArray[i].split(SECOND_DELIMITER);
			option = $("<option>").text(mainCardInfo[0]).val(mainCardInfo[1]);
			editMainCard.append(option);
		}
		
		for(var i = 0; i < cardNum; i++) 
		{
			backupCardInfo = optionArray[i].split(SECOND_DELIMITER);
			option = $("<option>").text(backupCardInfo[0]).val(backupCardInfo[1]);
			editBackupCard.append(option);
		}
	}
}

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

function populateBackupPort(obj)
{
	var editBackupPort = $("#editBackupPort");
	editBackupPort.empty();
	var option;
	var cardNo = parseInt(obj.val(), 10);
	if(cardNo == NO_CARD)
	{

		option = $("<option>").text(noPortList[language]).val(NO_PORT);
		editBackupPort.append(option);
		$("#editBackupPortName").html("");
	}
	else
	{
		var selectIndex = obj.get(0).selectedIndex;
		var backupPortInfo = optionArray[selectIndex].split(SECOND_DELIMITER);
		var portNum = backupPortInfo.length - 2;
		var displayStr;
		
		for(var i = 0; i < portNum; i++)
		{
			var singlePortInfo = backupPortInfo[2 + i].split(THIRD_DELIMITER);
			displayStr = getPortDisplayStr(cardNo, parseInt(singlePortInfo[0], 10), language);
			option = $("<option>").text(displayStr).val(parseInt(singlePortInfo[0], 10) - 1);
			editBackupPort.append(option);
			if(i == 0)
			{
				$("#editBackupPortName").html(singlePortInfo[1]);
			}
		}
	}
}

function getPortName(index)
{
	if(index == MAIN)
	{
		cardValue = parseInt($("#editMainCard").val(), 10);
		portValue = parseInt($("#editMainPort").val(), 10);
		$nameObj = $("#editMainPortName");
	}
	else
	{
		cardValue = parseInt($("#editBackupCard").val(), 10);
		portValue = parseInt($("#editBackupPort").val(), 10);
		$nameObj = $("#editBackupPortName");
	}
	var cardNum = optionArray.length;
	for(var i = 0; i < cardNum; i++)
	{
		var singleCardInfo = optionArray[i].split(SECOND_DELIMITER);
		if(cardValue == singleCardInfo[1])
		{
			var portNum = singleCardInfo.length - 2;
			for(var j = 0; j < portNum; j++)
			{
				var singlePortInfo = singleCardInfo[2 + j].split(THIRD_DELIMITER);
				if(portValue == parseInt(singlePortInfo[0], 10) - 1)
				{
					$nameObj.html(singlePortInfo[1]);
				}
			}
		}
	}
}

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 == MAIN_DESC_TYPE)||(j == BACKUP_DESC_TYPE))
			{
				continue;
			}
			else if((j == MAIN_PORT)||(j == BACKUP_PORT))
			{
				$("#" + objIdArray[j] + index).html(getPortDisplayStr((parseInt(rowData[j - 1], 10) - 1), parseInt(rowData[j], 10), language));
				if(j == MAIN_PORT)
				{
					mainPortDataArray[index] = parseInt(rowData[j], 10);
				}
				else if(j == BACKUP_PORT)
				{
					backupPortDataArray[index] = parseInt(rowData[j], 10);
				}
			}
			else if((j == MAIN_DESC)||(j == BACKUP_DESC))
			{
				if(parseInt(rowData[j - 1], 10) == SUPPORT_PORT_DESC)
				{
					$("#" + objIdArray[j] + index).html(rowData[j]);
				}
				else
				{
					$("#" + objIdArray[j] + index).html($("#" + objIdArray[j - 2] + index).html());
				}
			}
			else if(j == BACKUP_MODE)
			{
				$("#" + objIdArray[j] + index).html(backupMode[language][parseInt(rowData[j], 10)]);
			}
			else if(j == WORK_STATE)
			{
				if(parseInt(rowData[j], 10) == INVALID)
				{
					$("#modify" + index).css("display", "none");
					$("#mainDataRow" + index + " td").css("color", "#777e88");
					$("#backupDataRow" + index + " td").css("color", "#777e88");
				}
				else
				{
					$("#modify" + index).css("display", "");
					$("#mainDataRow" + index + " td").css("color", "#000");
					$("#backupDataRow" + index + " td").css("color", "#000");
				}
				$("#" + objIdArray[j] + index).html(workState[language][parseInt(rowData[j], 10)]);
			}
			else
			{
				$("#" + objIdArray[j] + index).html(rowData[j]);
			}
			if(parent.groupAccess == USER)
			{				
				$("#modify" + index).css("cursor", "default");
				$("#modify" + index).attr("onclick", "");
			}
		}
	}
}

function openApplyWindow()
{
	var addCard = $("#editMainCard").get(0);
	var addPort = $("#editMainPort").get(0);
	var addCardValue = addCard.options[0].value;
	var addPortValue;
	var editBackupMode = $("#editBackupMode").get(0);
	
	if(actionType == ADD)
	{
		$("#editMainCard").val(addCardValue);
		populateMainPort($("#editMainCard"));
		addPortValue = addPort.options[0].value;
		$("#editMainPort").val(addPortValue);
		$("#editMainMinRate").val("1000");
		$("#editMainMaxRate").val("100000");
		$("#M2BSwitchTime").val("1");
		$("#editBackupCard").val(addCardValue);
		populateBackupPort($("#editBackupCard"));
		$("#editBackupPort").val(addPortValue);
		$("#editBackupMinRate").val("1000");
		$("#editBackupMaxRate").val("100000");
		$("#B2MSwitchTime").val("1");
		$("#editBackupMode").val("3");
		
		$("#editMainCard").attr("disabled", false);
		$("#editMainPort").attr("disabled", false);
	}
	
	else
	{
		$("#editMainCard").val(parseInt($("#mainCard" + modifyRowIndex).html(), 10) - 1);
		populateMainPort($("#editMainCard"));
		$("#editMainPort").val(mainPortDataArray[modifyRowIndex] - 1);
		$("#editMainPortName").html($("#mainDescription" + modifyRowIndex).html());
		$("#editMainMinRate").val($("#mainMinRate" + modifyRowIndex).html());
		$("#editMainMaxRate").val($("#mainMaxRate" + modifyRowIndex).html());
		$("#M2BSwitchTime").val($("#mainSwitchDelay" + modifyRowIndex).html());
		$("#editBackupCard").val(parseInt($("#backupCard" + modifyRowIndex).html(), 10) - 1);
		populateBackupPort($("#editBackupCard"));
		$("#editBackupPort").val(backupPortDataArray[modifyRowIndex] - 1);
		$("#editBackupPortName").html($("#backupDescription" + modifyRowIndex).html());
		$("#editBackupMinRate").val($("#backupMinRate" + modifyRowIndex).html());
		$("#editBackupMaxRate").val($("#backupMaxRate" + modifyRowIndex).html());
		$("#B2MSwitchTime").val($("#backupSwitchDelay" + modifyRowIndex).html());
		
		for(i = 0; i < editBackupMode.options.length; i++)
		{
			if(editBackupMode.options[i].text == $("#backupMode" + modifyRowIndex).html())
			{
				editBackupMode.selectedIndex = i;
				break;
			}
		}
		
		$("#editMainCard").attr("disabled", true);
		$("#editMainPort").attr("disabled", true);
	}
	
	$("#editBackup").modal();	
}

function addBackup()
{
	actionType = ADD;
	openApplyWindow();
}

function modifyBackup(obj)
{
	actionType = SET;
	modifyRowIndex = parseInt(GetIndexFromId(obj, 11), 10);
	openApplyWindow();
}

function editBackupApply()
{
	var data;
	var response;
	var xmlHttp = GetHTTPObject();
	
	if(paramCheck() == false)
	{
		return;
	}
	
	data = "type=" + PORT_BACKUP + "&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("Port backup add successfully!");
					}
					else if(language == CHINESE)
					{
						alert("端口备份添加成功！");
					}
				}
				else
				{
					if(language == ENGLISH)
					{
						alert("Port backup modify successfully!");
					}
					else if(language == CHINESE)
					{
						alert("端口备份修改成功！");
					}
				}
			}
			else
			{
				alert(returnError[language][response]);
			}
			funcUpdateDisplay();
		}
	}
	xmlHttp.send(data);
}

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

function paramCheck()
{
	if(parseInt($("#editMainCard").val(),10) == NO_CARD)
	{
		$.modal.close();
		if(language == ENGLISH)
		{
			alert("Card List is empty, so can't add backup!");
		}
		else
		{
			alert("卡列表为空，不能添加备份！");
		}		
		return false;
	}
	if(ValidateParam($("#editMainMinRate"), "INT_DEC", 0, 200000, "<Main Bitrate Lower Limit>", "<主路码率下限>", language) == false)
	{
		return false;
	}
	if(ValidateParam($("#editMainMaxRate"), "INT_DEC", 0, 200000, "<Main Bitrate Upper Limit>", "<主路码率上限>", language) == false)
	{
		return false;
	}
	if(parseInt($("#editMainMinRate").val(), 10) >= parseInt($("#editMainMaxRate").val(), 10))
	{
		if(language == ENGLISH)
		{
			alert("The main bitrate lower limit should be smaller than the main bitrate upper limit!");
		}
		else
		{
			alert("主路码率下限必须小于主路码率上限！");
		}
		return false
	}
	
	if(ValidateParam($("#M2BSwitchTime"), "INT_DEC", 0, 255, "<M-B Switching Delay>", "<主备切换延时>", language) == false)
	{
		return false;
	}
	
	if(ValidateParam($("#editBackupMinRate"), "INT_DEC", 0, 200000, "<Backup Bitrate Lower Limit>", "<备路码率下限>", language) == false)
	{
		return false;
	}
	if(ValidateParam($("#editBackupMaxRate"), "INT_DEC", 0, 200000, "<Backup Bitrate Upper Limit>", "<备路码率上限>", language) == false)
	{
		return false;
	}
	if(parseInt($("#editBackupMinRate").val(), 10) >= parseInt($("#editBackupMaxRate").val(), 10))
	{
		if(language == ENGLISH)
		{
			alert("The backup bitrate lower limit should be smaller than the backup bitrate upper limit!");
		}
		else
		{
			alert("备路码率下限必须小于备路码率上限！");
		}
		return false
	}
	
	if(ValidateParam($("#B2MSwitchTime"), "INT_DEC", 0, 255, "<B-M Switching Delay>", "<备主切换延时>", language) == false)
	{
		return false;
	}
	
	if((parseInt($("#editMainCard").val(), 10) == parseInt($("#editBackupCard").val(), 10)) && (parseInt($("#editMainPort").val(), 10) == parseInt($("#editBackupPort").val(), 10)))
	{
		if(language == ENGLISH)
		{
			alert("The main and backup have the same card and port!");
		}
		else
		{
			alert("主路和备路的卡和端口不能同时相等！");
		}
		return false;
	}
	
	return true;
}

function generateData()
{
	var data;
	
	if(actionType == ADD)
	{
		for(var i = 0; i < EDIT_NUM; i++)
		{
			if(i == 0)
			{
				data = $("#" + editIdArray[i]).val();
			}
			else
			{
				data += FIRST_DELIMITER + $("#" + editIdArray[i]).val();
			}
		}
	}
	else
	{
		data = modifyRowIndex;
		for(var i = MAIN_MIN_RATE; i < EDIT_NUM; i++)
		{
			data += FIRST_DELIMITER + $("#" + editIdArray[i]).val();
		}
	}
	
	return data;
}

function deleteBackup()
{
	var data;
	var rowData;
	var index;
	var confirmPrompt;
	var xmlHttp = GetHTTPObject();
	var response;
	var deleteBackup = "";
	var deleteNum = 0;
	
	if(language == ENGLISH)
	{
		confirmPrompt = "Are you sure to delete the checked backup?";
	}
	else if(language == CHINESE)
	{
		confirmPrompt = "确定要删除选中的备份吗?";
	}
	if(window.confirm(confirmPrompt))
	{
		data = "type=" + PORT_BACKUP + "&cmd=" + DELETE + "&language=" + language + "&slotNo=" + slotNo + "&setString=";
				
		for(var i = 0; i < rowNum; i++)
		{
			index = i + 1;
			if($("#check" + index).prop("checked") == true)
			{
				rowData = $("#mainCard" + index).html() + SECOND_DELIMITER + mainPortDataArray[index];
				if(deleteNum == 0)
				{
					deleteBackup = rowData;
				}
				else
				{
					deleteBackup += FIRST_DELIMITER + rowData;
				}
				deleteNum++;
			}
		}
		if(deleteNum == 0)
		{
			if(language == ENGLISH)
			{
				alert("Please select one backup at least!");
			}
			else
			{
				alert("请至少选中一个备份！");
			}
			return;
		}
		data += deleteBackup;
		
		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("Port backup delete successfully!");
					}
					else if(language == CHINESE)
					{
						alert("端口备份删除成功！");
					}
				}
				else
				{
					alert(returnError[language][response]);
				}
				funcUpdateDisplay();
			}
		}
		xmlHttp.send(data);
	}
}

