var NUM_COLUMNS = 4;
var card_index;
var port_index;
var PageLoadFlag = 0;
var level_set;
var freq_range_set;
var control_set;
var g_RowCount = 0; // row number after which the new is to be inserted. should be incremented
var devPortNum = 0;
var columnName = new Array("", "OutputLevel", "FreqRange", "PortCtrl");
var colWidth = new Array("70px", "150px", "150px", "130px");
var LevelMin;
var LevelMax;
var rfOpenChNum;
var enable;
var nodeId;
var mainIPAddr;
var language;
var userName;

var freqRangeLen;
var freqRangeVal;
var freqRange;

function changeEnabled()
{
	if(document.getElementById("backupEnabled").value == 1)
	{
		enable = 1;
	}
	else
	{
		enable = 0;
	}
	EnableApply();
}

function getElement(Event)
{
    var element;
    if(window.event)
    {
		element = window.event.srcElement;
    }
    else
    {
        element = Event.target;
    }
    return element;
}

function SetColor(obj, color)
{
	obj.style.backgroundColor = color;
}

function ValidateOutputLevel(obj ,index)
{
	var level = parseFloat(obj.value);

	if(validateFloat(level) == false)
	{
		if(language == 0)
		{
			alert("Invalid number. Please enter a valid numeric value for Output Level.");
		}
		else
		{
			alert("无效的数字，请输入一个有效的输出电平。");
		}
		return false;
	}
	if(validateAccuracy(level, 1) == false)
	{
		if(language == 0)
		{
			alert("Accuracy for Output Level is 1 digit.");
		}
		else
		{
			alert("输出电平有效性最多到小数点后一位。");
		}
		return false;
	}
	if((level < LevelMin[index - 1]) || (level > LevelMax[index - 1]))
	{
		if(language == 0)
		{
			alert("Valid range for Output level is " + LevelMin[index - 1] + " - " + LevelMax[index - 1] + " dBuV.");
		}
		else
		{
			alert("输出电平的有效范围是" + LevelMin[index - 1] + " - " + LevelMax[index - 1] + " dBuV。");
		}
		return false;
	}
	return true;
}

function OutputLevelChange(Event)
{
	var obj = getElement(Event);
	var len = obj.id.length;
	var index = obj.id.substring(11,len);
	var level = parseFloat(obj.value);
	
	if(ValidateOutputLevel(obj, index) == false)
	{
		level_set[index - 1] = 2;
		SetColor(obj,"Red");
		return false;
	}
	else
	{
		obj.value = level.toFixed(1);
		level_set[index - 1] = 1;
		SetColor(obj,"Yellow");
		EnableApply();
		return true;
	}
}

function PortCtrlChange(Event)
{
	var obj = getElement(Event);
	var len = obj.id.length;
	var index = obj.id.substring(8,len);
	
	EnableApply();
	control_set[index -1] = 1;
	SetColor(obj,"Yellow");
}

function FreqRangeChane(Event)
{
	var obj = getElement(Event);
	var len = obj.id.length;
	var index = obj.id.substring(9,len);
	
	EnableApply();
	freq_range_set[index -1] = 1;
	SetColor(obj,"Yellow");
}

function mainRfChange()
{
	EnableApply();
}

function ResetSetArrays()
{
	for(var i = 0; i < devPortNum; i ++)
	{
		level_set[i] = 0;
		freq_range_set[i] = 0;
		control_set[i] = 0;
	}
}

function ResetColors()
{
	var index;
	for(var i = 0; i < devPortNum; i++)
	{
		index = i + 1;
		document.getElementById("OutputLevel" + index).style.backgroundColor = "white";
		document.getElementById("FreqRange" + index).style.backgroundColor = "white";
		document.getElementById("PortCtrl" + index).style.backgroundColor = "white";
	}
}

function AddRows(table)
{
	for(var i = 0; i < devPortNum; i++)
	{
		var row = table.insertRow(g_RowCount + 1);

		for(var j = 0; j < NUM_COLUMNS; j++)
		{
			var cell = row.insertCell(j);
		}
		
		g_RowCount++;
	}
}

function UpdateRows(table)
{
	var index;
	for(var i = 0; i < devPortNum; i++)
	{
		index = i + 1;
		for(var j = 0; j < NUM_COLUMNS; j++)
		{
			var cell = table.rows[index].cells[j];
			cell.style.width = colWidth[j];
			if(j == 0)
			{
				port_index = index;
				cell.innerHTML = card_index + "/" + port_index;
			}
			else if(j == 1)
			{
				cell.innerHTML = "";
				var el = document.createElement("input");
				el.type = "text";
				el.id = (columnName[j] + index);
				el.size = "8";
				el.maxlength = "8"
				el.onchange = OutputLevelChange;
				el.onkeyup = EnableApply;
				cell.appendChild(el);
			}
			else if(j == 2)
			{
				cell.innerHTML = "";
				var el = document.createElement("select");
				
				for(var k = 0; k < freqRangeLen; k++)
				{
					el.options[k] = new Option(freqRange[k], freqRangeVal[k]);
				}
				/*
				if(cardType == QT083)
				{
					el.options[0] = new Option("45~269", "0");
					el.options[1] = new Option("75~300", "1");
					el.options[2] = new Option("176~400", "2");
					el.options[3] = new Option("275~499", "3");
					el.options[4] = new Option("375~600", "4");
					el.options[5] = new Option("476~700", "5");
					el.options[6] = new Option("575~799", "6");
					el.options[7] = new Option("675~900", "7");
					el.options[8] = new Option("776~1000", "8");
				}
				else if(cardType == C518)
				{
					el.options[0] = new Option("45~719", "0");
					el.options[1] = new Option("188~862", "1");
					el.options[2] = new Option("362~1000", "2");
				}
				else
				{
					el.options[0] = new Option("45~795", "0");
					el.options[1] = new Option("253~1003", "1");
				}
				*/
				el.id = (columnName[j] + index);
				el.onchange = FreqRangeChane;
				el.onkeyup = EnableApply;
				cell.appendChild(el);
			}
			else if(j == 3)
			{
				cell.innerHTML = "";
				var el = document.createElement("select");
				if(language == 0)
				{
					el.options[0] = new Option("On", "1");
					el.options[1] = new Option("Off", "0");
				}
				else
				{
					el.options[0] = new Option("打开", "1");
					el.options[1] = new Option("关闭", "0");
				}
				el.id = (columnName[j] + index);
				el.onchange = PortCtrlChange;
				el.onkeyup = EnableApply;
				cell.appendChild(el);
			}
		}
	}
}

function UpdateTable()
{
	var table = document.getElementById("OutpConfig");
	AddRows(table);
	UpdateRows(table);
}

function deleteMainPort()
{
	var Row = document.getElementById("mianPort");
	var cellNum = (devPortNum - 1) * 2;
	for(var i=0; i<cellNum; i++)
	{
		Row.deleteCell(1);
	}
}

function updateMainPort()
{
	var Row = document.getElementById("mianPort");
	var cell;
	var cellNum = (devPortNum - 1) * 2;
	for(var i=0; i<cellNum; i++)
	{
		var index = i + 1;
		var id = parseInt(i / 2) + 1;
		Row.insertCell(index);
		
		if((i % 2) == 0)
		{
			cell = Row.cells[index];
			cell.innerHTML = "";
			var el = document.createElement("input");
			el.type = "checkbox";
			el.id = "mainRf" + id;
			el.onclick = mainRfChange;
			cell.appendChild(el);
		}
		else
		{
			cell = Row.cells[index];
			if(language == 0)
			{
				cell.innerHTML = "RF Port " + id;
			}
			else
			{
				cell.innerHTML = "RF 端口 " + id;
			}
		}
	}
	
	document.getElementById("row1").colSpan = cellNum;
	document.getElementById("backupPort").colSpan = cellNum;
	document.getElementById("row2").colSpan = cellNum;
	document.getElementById("bacStatus").colSpan = cellNum;
}

var DISP_ATTR_FLAG = 1;
var RAD_WRT_FLAG = 2;
var PORT_CTRL = 2;

function DealWithData(data)
{
	var len;
	var rad_wrt;
	var id;
	
	for(var i = 0, len = data.length; i < len; i++)
	{
		if(i >= columnName.length)
		{
			break;
		}
		if(data[i] == "")
		{
			continue;
		}
		if(i != PORT_CTRL)
		{
			if((parseInt(data[i]) & RAD_WRT_FLAG) == RAD_WRT_FLAG)	//可读写
			{
				for(var j = 1; j <= devPortNum; j++)
				{
					id = columnName[i + 1] + j;
					document.getElementById(id).disabled = false;
				}
			}
			else													//只读
			{
				for(var j = 1; j <= devPortNum; j++)
				{
					id = columnName[i + 1] + j;
					document.getElementById(id).disabled = true;
				}
			}
		}
	}
}

function GetDispAttr()
{
	var xmlhttp = false;
	var getParams = "type=6&cmd=1&card=" + card_index + "&getDispAttr=1";

	xmlhttp = getHTTPObject();
	xmlhttp.open("POST", "/goform/formIPQAM", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", getParams.length);
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4)
		{
			var response = xmlhttp.responseText.slice(7, -8);
			var data = response.split("&");
			DealWithData(data);
		}
	}
	xmlhttp.send(getParams);
}

function GetPortNum()
{
	var response;
	var data;
	var cnt = 0;
	var xmlhttp = false;
	var params = "type=6&cmd=1&card=" + card_index + "&getPortNum=1";
	xmlhttp = getHTTPObject();
	xmlhttp.open("POST", "/goform/formIPQAM", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4)
		{
			response = xmlhttp.responseText.slice(7, -8).split("&");
			devPortNum = parseInt(response[0]);
			data = response[1].split(",");
			freqRangeLen = parseInt(data[cnt++]);
			freqRangeVal = new Array(freqRangeLen);
			freqRange = new Array(freqRangeLen);
			for(var i = 0; i < freqRangeLen; i++)
			{
				freqRangeVal[i] = data[cnt++];
				freqRange[i] = data[cnt++];
			}
			
			UpdateTable();
			if(devPortNum == 1)
			{
				document.getElementById("RfBackup").style.display = "none";
				document.getElementById("RfBackupTable").style.display = "none";
			}
			else
			{
				updateMainPort();
			}
			GetAllPortsParameters();
			GetDispAttr();
		}
	}
	xmlhttp.send(params);
}

function AllPortsDataDisplay(PortResponse)
{
	var PortData;
	var index;
	rfOpenChNum = new Array(devPortNum);
	LevelMin = new Array(devPortNum);
	LevelMax = new Array(devPortNum);

	for(var i = 0; i < devPortNum; i++)
	{
		index = i + 1;
		PortData = PortResponse[i].split(",");
		document.getElementById("OutputLevel" + index).value = (parseFloat(PortData[0])).toFixed(1);
		document.getElementById("OutputLevel" + index).defaultValue = (parseFloat(PortData[0])).toFixed(1);
		document.getElementById("FreqRange" + index).value = (parseInt(PortData[1]));
		document.getElementById("PortCtrl" + index).value = (parseInt(PortData[2]));
		rfOpenChNum[i] = PortData[3];
		LevelMin[i] = 95;		
		if(PortData.length > 4)
		{
			LevelMin[i] = (Number(PortData[4])/10).toFixed(1);
			LevelMax[i] = (Number(PortData[5])/10).toFixed(1);
		}
		else
		{
			if(rfOpenChNum[i] == 0)
			{			
				LevelMax[i] = 122;
			}
			else
			{
				LevelMax[i] = (122 - 3 * (Math.log(rfOpenChNum[i]) / Math.LN2)).toFixed(1);
			}
		}
		if(language == 0)
		{
			document.getElementById("OutputLevel" + index).title = "RF port output level range: " + LevelMin[index - 1] +
									 " - " + LevelMax[index - 1] + " dBuV";
		}
		else
		{
			document.getElementById("OutputLevel" + index).title = "RF端口输出电平范围：" + LevelMin[index - 1] +
									 " - " + LevelMax[index - 1] + " dBuV";
		}
	}
}

function GetAllPortsParameters()
{
	var xmlhttp = false;
	var response;
	var count;
	var portInfo;
	var mainPortInfo;
	var portStatus;
	var i;
	var id;
	
	var params = "type=6&cmd=1&card=" + card_index + "&getPortParam=1&language=" + language;
	xmlhttp = getHTTPObject();
	xmlhttp.open("POST", "/goform/formIPQAM", true);
	if((bd.browser != "IE") && (language == 1))
	{
		xmlhttp.overrideMimeType("text/html;charset=gb2312");
	}
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4)
		{
			if((bd.browser == "IE") && (language == 1))
			{
				response = gb2utf8(xmlhttp.responseBody);
				var index = response.indexOf("</html>");
				var bias = response.length - index;
				response = response.slice(7, - bias);
			}
			else
			{
				response = xmlhttp.responseText.slice(7, -8);
			}
			portInfo = response.split("&");
			AllPortsDataDisplay(portInfo);
			
			count = devPortNum;
			document.getElementById("backupEnabled").value = portInfo[count++];
			
			if(devPortNum != 1)
			{
				mainPortInfo = portInfo[count++].split(",");
				for(i=0; i<mainPortInfo.length; i++)
				{
					id = i + 1;
					if(mainPortInfo[i] == 1)
					{
						document.getElementById("mainRf" + id).checked = true;
					}
					else
					{
						document.getElementById("mainRf" + id).checked = false;
					}
				}
			}
			
			document.getElementById("backupPort").innerHTML = portInfo[count++];
			document.getElementById("bacStatus").innerHTML = portInfo[count++];
			
			portStatus = portInfo[count++].split(",");
			for(i=0; i<portStatus.length; i++)
			{
				id = i + 1;
				if(portStatus[i] == 1)
				{
					document.getElementById("PortCtrl" + id).disabled = true;
				}
				else
				{
					document.getElementById("PortCtrl" + id).disabled = false;
				}
			}
		}
	}
	xmlhttp.send(params);
}

/***** Page Refresh functionalities *****/
function PageLoadHandler()
{
	PageLoadFlag = 1;
	
	// disable the reset & apply buttons since this is fresh data
	disabledButton(document.getElementById("Reset"), true);
	disabledButton(document.getElementById("Apply"), true);
	
	window.status = "Retrieving data, please wait....";
	document.body.style.cursor = "wait";
	//GetCardType();
 
	GetPortNum();
	level_set = new Array(devPortNum);
	freq_range_set = new Array(devPortNum);
	control_set = new Array(devPortNum);
	ResetSetArrays();
	PageLoadFlag = 0;
	window.status = "Done";
	document.body.style.cursor = "auto";
	EnableReset();
}

/***** functions called on load of page *****/
window.onload = function()
{
	document.body.style.cursor = "wait";
	var args = getArgs();
	var group = args["group"];
	userName = args["userName"];
	nodeId = args["nodeId"];
	mainIPAddr = args["mainIPAddr"];
	if(nodeId == null)
	{
		nodeId = parent.curTree.getSelectedNodes()[0].id;
	}
	card_index = parseInt(nodeId/10);
	language = document.getElementById("language").value;
	var apply = document.getElementById("Apply");
	applyDispay(group, apply);
	PageLoadHandler();
}

/***** functions called onclick of validate button *****/
function ValidatePortParam()
{
	var index;
	var obj;
	for(var i = 0; i < devPortNum; i ++)
	{
		index = i + 1;
		obj = document.getElementById("OutputLevel" + index);
		if(ValidateOutputLevel(obj, index) == false)
		{
			obj.value = (obj.defaultValue < LevelMax[i]) ? obj.defaultValue : LevelMax[i];
			level_set[i] = 1;
			SetColor(obj, "Yellow");
			return false;
		}
	}
}

function PostAllPortsConfig()
{
	var xmlhttp = false;
	xmlhttp = getHTTPObject();
	/* Generate params to POST from the from controls */
	var params = "type=6&cmd=2&userName=" + userName + "&card=" + card_index + "&";
	var i;
	var index;

	for(i = 0; i < devPortNum; i++)
	{
		index = i + 1;
		var outputLevel = parseFloat(document.getElementById("OutputLevel" + index).value);
		var freqRange = document.getElementById("FreqRange" + index).value;
		var portCtrl = document.getElementById("PortCtrl" + index).value;
		// we always add the first spacing value since it doesnot have the leading "&"
		//  subsequent spacing values are only added if they have changed
		if(level_set[i] == 1)
		{
			params = params + "OutputLevel" + index + "=" + outputLevel + "&";
		}
		if(freq_range_set[i] == 1)
		{
			params = params + "FreqRange" + index + "=" + freqRange + "&";
		}			
		if(control_set[i] == 1)
		{
			params = params + "PortCtrl" + index + "=" + portCtrl + "&";
		}			
	}
	
	var bacEnabled = document.getElementById("backupEnabled").value;
    params = params + "backupEnabled=" + bacEnabled;
	
	if(bacEnabled == 1)
	{
		for(i=0; i<(devPortNum - 1); i++)
		{
			index = i + 1;
			if(document.getElementById("mainRf" + index).checked == true)
			{
				params = params + "&mainRf" + index + "=1";
			}
			else
			{
				params = params + "&mainRf" + index + "=0";
			}
		}
	}
	
	xmlhttp.open("POST", "/goform/formIPQAM", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);

	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4)
		{
			if(language == 0)
			{
				alert("Global Port Configuration Updated Successfully.");
			}
			else
			{
				alert("输出参数设置成功。");
			}
			//取消页面刷新
			/*
			if(enable == 1)
			{
				enable = 0;
				var url;
				if(language == 1)
				{
					url = "http://" + mainIPAddr + "/asp/main_cn.asp?nodeId=" + nodeId;
				}
				else
				{
					url = "http://" + mainIPAddr + "/asp/main.asp?nodeId=" + nodeId;
				}
				window.parent.location.replace(url);
			}
			else
			{*/
				PortReset();
			//}
		}
	}
	xmlhttp.send(params);
}

function SwitchRfBackup()
{
	var getParams = "type=6&cmd=2&userName=" + userName + "&rfSwitch=1&card=" + card_index;
	var xmlhttp = getHTTPObject();
	xmlhttp.open("POST", "/goform/formIPQAM", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", getParams.length);
	
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4)
		{
			if(xmlhttp.responseText.match("successful"))
			{
				if(language == 0)
				{
					alert("RF switch successfully.");
				}
				else
				{
					alert("RF切换成功。");
				}
			}
			else
			{
				if(language == 0)
				{
					alert("RF switch failed!");
				}
				else
				{
					alert("RF切换失败！");
				}
			}
			PortReset();
		}
	}
	xmlhttp.send(getParams);
	return true;
}

function RevertRfBackup()
{
	var getParams = "type=6&cmd=2&userName=" + userName + "&rfRevrt=1&card=" + card_index;
	var xmlhttp = getHTTPObject();
	xmlhttp.open("POST", "/goform/formIPQAM", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", getParams.length);
	
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4)
		{
			if(xmlhttp.responseText.match("successful"))
			{
				if(language == 0)
				{
					alert("RF revert successfully.");
				}
				else
				{
					alert("RF回切成功。");
				}
			}
			else
			{
				if(language == 0)
				{
					alert("RF revert failed!");
				}
				else
				{
					alert("RF回切失败！");
				}
			}
			PortReset();
		}
	}
	xmlhttp.send(getParams);
	return true;
}

function PortApply()
{
	if(ValidatePortParam() == false)
	{
		return false;
	}

	// disable the reset & apply buttons since this is fresh data
	disabledButton(document.getElementById("Reset"), true);
	disabledButton(document.getElementById("Apply"), true);
	
	window.status = "Applying configuration changes, please wait....";
	document.body.style.cursor = "wait";
	PostAllPortsConfig();
}

function deleteAllRows()
{
	var table = document.getElementById("OutpConfig");
	var length = table.rows.length;
	for(var i = 1; i < length; i++)
	{
		table.deleteRow(g_RowCount);
		g_RowCount--; 
	}
}

function PortReset()
{
	deleteAllRows();
	deleteMainPort();
	PageLoadHandler();
}

function EnableApply()
{
	if(!PageLoadFlag)
	{
		disabledButton(document.getElementById("Apply"), false);
	}
}

function EnableReset()
{
	disabledButton(document.getElementById("Reset"), false);
}
