function getData()
{
	var xmlhttp = false;
	xmlhttp = getHTTPObject();
	var params = "type=7&cmd=1&getDataPort=" + devPort;
	
	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)
		{
			var response = xmlhttp.responseText.slice(7, -8);
			dealData(response);
		}
	}
	xmlhttp.send(params);
	return false;
}
var titleDisplayEn = ["Channel Level Diagram", "Normal", "Carrier Wave", "Mute", "Frequency(MHz)", "Output Level(dBuV)"];
var titleDisplayCn = ["频点电平图", "正常", "载波", "关闭", "频率值(MHz)", "输出电平值(dBuV)"];
var titleDisplay = [titleDisplayEn, titleDisplayCn];
function dealData(rData)
{
	eval(rData);
	$(document).ready(function () {
		plot1 = $.jqplot("chart1", data, {
			title: titleDisplay[language][0],
			seriesDefaults:{
				markerRenderer: $.jqplot.MarkerRenderer,   
				markerOptions: {    
					show: true,
					style: 'filledCircle',
					size: 9,
					color: '#666'
				}   
			},
			series:[
				{
					label:titleDisplay[language][1],
					renderer: $.jqplot.BarRenderer,
					rendererOptions: {
						barWidth: barWidth,
						barPadding: 0 - barWidth
					}
				},
				{
					label:titleDisplay[language][2],
					renderer: $.jqplot.BarRenderer,
					rendererOptions: {
						barWidth: 2,
						barPadding: -2
					}
				},
				{
					label:titleDisplay[language][3],
					color:"#666",
					lineWidth:-1,
					shadow: false
				}
			],
			legend: {
				show: true,
				location: 'ne'
			},
			axes: {
				xaxis: {
					min:minX,
					max:maxX,
					numberTicks:numberTicks,
					label: titleDisplay[language][4],
					labelOptions:{
						fontFamily:'Arial',
						fontSize: '12pt'
					},
					labelRenderer: $.jqplot.CanvasAxisLabelRenderer
				},
				yaxis: {
					min:minY,
					max:maxY,
					numberTicks:8,
					tickOptions:{
						formatString:'%.1f'
					},
					label: titleDisplay[language][5],
					labelOptions:{
						fontFamily:'Arial',
						fontSize: '12pt'
					},
					labelRenderer: $.jqplot.CanvasAxisLabelRenderer
				}
			},
			highlighter: {
				show: true, 
				showLabel: true,
				sizeAdjust: 5,
				tooltipAxes: 'xy',
				useAxesFormatters: false,
				tooltipFormatString: '%.3f',
				tooltipOffset: 6,
				tooltipLocation : 'n'
			}
		});
	  
	});
}

// global variables
var bLoadingData = false;	//global var to determine if a change is being made to a row while loading
							//or due to changes made by the user. Should be set appropriately before and after
var bChangeDataduringLoad = false;							

var BASE_ROW_HEIGHT;
var BASE_ROW_HEIGHT_INT;

var PortAuthMaxChNum = 0;
var PortMaxChNum = 0;

//line 13~45 added by chenjin at 20140209
var freqDefault = true;
var moduDefault = true;
var symbDefault = true;
var bwDefault = true;

var FreqAttr = 0;	//0为不临频； 1为临频；
					//默认为不临频。
var chnExistFlag = new Array();

var freqValArray = new Array();
var moduValArray = new Array();
var symbValArray = new Array();
var bwValArray = new Array();					

var GROUP_NUM;
var MODU_GROUP_NUM;
var SYMB_GROUP_NUM;
var BW_GROUP_NUM;

var groupRange = new Array();
var moduGroupRange = new Array();
var symbGroupRange = new Array();
var bwGroupRange = new Array();

var groupIncrem = new Array();
var moduGroupIncrem = new Array();
var symbGroupIncrem = new Array();
var bwGroupIncrem = new Array();

var firstFreqIdx = new Array();
var firstModuIdx = new Array();
var firstSymbIdx = new Array();
var firstBwIdx = new Array();

var card_index = 0;
var port_index = 0;
var devPort;
var FrequencyMin = 48;
var FrequencyMax = 996;
var FreqDefaultVal = 500; 
var SymbolRateMin = 3.5;
var SymbolRateMax = 7.0;
var AttenMin = 0;
var AttenMax = 100;
var channelChange = 0;
var nodeId;
var mainIPAddr;
var h;
var ROW_NUM = 11;
var newRowFlag = [];
var maxFlag = false;
var language;
var userName;

var channelNumChange = 0;  //add this value to point out the used channel number of this rf port has changed 

function mouseOverRuleApply(obj)
{
	if(obj.disabled == false)
	{
		obj.style.background = "url(../images/btn3_hover.png)";
	}
}
function mouseOutRuleApply(obj)
{
	if(obj.disabled == false)
	{
		obj.style.background = "url(../images/btn3_normal.png)";
	}
}
function mouseOverBig(obj)
{
	if(obj.disabled == false)
	{
		obj.style.background = "url(../images/btn3_hover.png)";
	}
}
function mouseOutBig(obj)
{
	if(obj.disabled == false)
	{
		obj.style.background = "url(../images/btn3_normal.png)";
	}
}

//added by chenjin at 20140209
function getGroupIdx(index, gNum, gRange)//gNum:联动参数的分组个数；gRange:每组的频点个数
{
	var groupIdx;
	var chnCnt = parseInt(gRange[0]);
	
	for(var i = 0; i < gNum; i++)
	{
		if(index < chnCnt)
		{
			groupIdx = i;
			break;
		}
		else
		{
			chnCnt += parseInt(gRange[i]);
		}
	}
	
	return groupIdx;
}

function getGroupExistFlag(startCh, endCh)
{
	var bFlag = false;
	
	for(var i = startCh; i < endCh; i++)
	{
		if(chnExistFlag[i] == 1)
		{
			bFlag = true;
			break;
		}
	}
	
	return bFlag;
}

function getChannelNo(index)
{
	var channel = parseInt(g_RfConfigRows[index].split(",")[1]);
	return channel;
}

function chnNumToDisplay(card, port, channel)
{
	return card + "/" + port + "." + channel;
}

function ToggleLoading()	// test function to toggle the global var for loading
{
	bLoadingData = !bLoadingData;
}

function DisableApply(bDisable)
{
	var baseApply = document.getElementById("BaseApply");
	disabledButton(baseApply, bDisable);
	/* If the Apply is being enabled during Load, set it to Disable again */
	if((bLoadingData == true) && (bDisable == false))
	{
		disabledButton(baseApply, true);
		bChangeDataduringLoad = true;
    }
}

function DisableReset(bEnable)
{
	document.getElementById("BaseReset").disabled = bEnable;
	document.getElementById("BaseAddRow").disabled = bEnable;
}

window.onload = function()
{
	if(bd.browser == "IE")
	{
		BASE_ROW_HEIGHT = "24px";
		BASE_ROW_HEIGHT_INT = 24;
	}
	else
	{
		BASE_ROW_HEIGHT = "22px";
		BASE_ROW_HEIGHT_INT = 22;
	}
	language = document.getElementById("language").value;
	document.body.style.cursor = "wait";
	window.status = "Retrieving data, please wait...";
	disabledButton(document.getElementById("BaseRuleApply"), true);

	if(bLoadingData == false)
	{
		ToggleLoading();
	}

	DisableApply(true);
	DisableReset(true);
	
	var args = getArgs();
	nodeId = args["nodeId"];
	mainIPAddr = args["mainIPAddr"];
	var group = args["group"];
	userName = args["userName"];
	h = (document.body.scrollHeight);  
	$("body").append('<iframe style="display:none;" id="agent" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://' + mainIPAddr + '/../asp/agent.asp?t='+ new Date().getTime()+'#height=' + h + '" ></iframe>');     
	var apply = document.getElementById("BaseApply");
	applyDispay(group, apply);
	if(nodeId == null)
	{
		nodeId = parent.curTree.getSelectedNodes()[0].id;
	}

	card_index = parseInt(nodeId/100);
	port_index = (nodeId%10);
	devPort = card_index + "/" + port_index;
	
	getData();
	GetDeviceInfo();
}

function PopulateImpRulesCombos(card, port)
{
	var startLen = document.getElementById("QamBaseStart").length;
	var endLen = document.getElementById("QamBaseEnd").length;
	var channel;
	var elOptNew;
	for(var i = 0; i < startLen; i++)
	{
		document.getElementById("QamBaseStart").remove(0);
	}
	for(var i = 0; i < endLen; i++)
	{
		document.getElementById("QamBaseEnd").remove(0);
	}
	for(var i = 0; i < ROW_NUM; i++)
	{
		var obj = document.getElementById("a" + i + "_set");
		var len = obj.length;
		for(var j = 0; j < len; j++)
		{
			obj.remove(0);
		}
		for(var j = 0; j < PortMaxChNum; j++)
		{
			channel = j + 1;
			try
			{
				elOptNew = document.createElement("option");
				elOptNew.text = chnNumToDisplay(card, port, channel);
				elOptNew.value = j;
				obj.add(elOptNew, null); // Non IE
				
			}
			catch(ex)
			{
				elOptNew = document.createElement("option");
				elOptNew.text = chnNumToDisplay(card, port, channel);
				elOptNew.value = j;
				obj.add(elOptNew);
			}
		}
	}
	
	for(var i = 0; i < PortMaxChNum; i++)
	{
		channel = i + 1;
		try
		{
			var elOptNew1 = document.createElement("option");
			elOptNew1.text = chnNumToDisplay(card, port, channel);
			elOptNew1.value = i;
			var elSel1 = document.getElementById("QamBaseStart");
			elSel1.add(elOptNew1, null); // Non IE
			
			var elOptNew2 = document.createElement("option");
			elOptNew2.text  = chnNumToDisplay(card, port, channel);
			elOptNew2.value = i;
			var elSel2 = document.getElementById("QamBaseEnd");
			elSel2.add(elOptNew2, null); // Non IE

		}
		catch(ex)
		{
			var elOptNew1 = document.createElement("option");
			elOptNew1.text = chnNumToDisplay(card, port, channel);
			elOptNew1.value = i;
			var elSel1 = document.getElementById("QamBaseStart");
			elSel1.add(elOptNew1);
			
			var elOptNew2 = document.createElement("option");
			elOptNew2.text  = chnNumToDisplay(card, port, channel);
			elOptNew2.value = i;
			var elSel2 = document.getElementById("QamBaseEnd");
			elSel2.add(elOptNew2);
		}
	}
	
	/*不临频子卡，不存在带宽设置*/
	if(FreqAttr == 0)
	{
		for(var i = 0; i < ROW_NUM; i++)
		{
			$("#e" + i).attr("disabled", true);
		}
		$("#BandwidthRule").attr("disabled", true);
	}
}

/***************
function: fill array of the special value 
chenjin,20140209
****************/
function fillChnArray(gNum, gRange, gIncrem, firstIdx, valArray)
{
	for(var i = 0; i < gNum; i++)
	{
		for(var j = 0; j < gRange[i]; j++)
		{
			var idx = parseInt(firstIdx[i]) + j;
			if(chnExistFlag[idx] == 1)		//the group has no less than one existent channel 
			{
				//voluation the special value of channels in the group
				for(var k = firstIdx[i]; k < (parseInt(firstIdx[i]) + parseInt(gRange[i])); k++)
				{
					valArray[k] = parseFloat(valArray[idx]) + (k - idx)* parseInt(gIncrem[i]);
				}
				break;
			}
		}
	}
}

function fillGroupChArray(index, startCh, endCh, increment, valArray)
{
	for(var i = startCh; i < endCh; i++)
	{
		valArray[i] = parseFloat(valArray[index]) + (i - index) * parseInt(increment);
	}
}

function GetRfConfigAttr()//为了知道页面上的哪些参数修改的时候会级联改动
{
	var xmlhttp = getHTTPObject();
	var params = "type=7&cmd=1&getRfAttrVal=" + devPort;
	var aName;
	var gNum;
	var gRange;
	var gIncrem;
	var i;
	
	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)
		{
			var response = xmlhttp.responseText;
			if(response.slice(7, -8) != "NULL")
			{
				var data = response.slice(7, -8).split("|");
				var len = data.length;
				var attrVal;
				
				for(i=0; i<len; i++)
				{
					attrVal = data[i].split("&");
					
					aName = attrVal[0];
					gNum = attrVal[1];
					gRange = attrVal[2].split(",");
					gIncrem = attrVal[3].split(",");
					
					switch(aName)
					{
						case "frequency":
							GROUP_NUM = gNum;
							groupRange = gRange;
							groupIncrem = gIncrem;
							freqDefault = false;
							break;
						
						case "modulation":
							MODU_GROUP_NUM = gNum;
							moduGroupRange = gRange;
							moduGroupIncrem = gIncrem;
							moduDefault = false;
							break;
							
						case "symbolRate":
							SYMB_GROUP_NUM = gNum;
							symbGroupRange = gRange;
							symbGroupIncrem = gIncrem;
							symbDefault = false;
							break;
	
						case "bandwidth":
							BW_GROUP_NUM = gNum;
							bwGroupRange = gRange;
							bwGroupIncrem = gIncrem;
							bwDefault = false;
							break;
	
						default:
							
							break;
					}
				}
			}
			
			GetRfConfigRows();
		}
	}
	
	xmlhttp.send(params);
	return false;
}

function GetDeviceInfo()
{
	var xmlhttp = false;
	var cnt = 0;
	xmlhttp = getHTTPObject();
	var params = "type=7&cmd=1&RFPort=" + devPort;
	
	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)
		{
			var response = xmlhttp.responseText;
			var DeviceInfo = response.slice(7, -8).split("&");
			PortAuthMaxChNum = parseInt(DeviceInfo[cnt++]);
			PortMaxChNum = parseInt(DeviceInfo[cnt++]);
			//CardType = parseInt(DeviceInfo[cnt++]);
			FreqAttr = parseInt(DeviceInfo[cnt++]);
			
			var freqRange = DeviceInfo[cnt++].split(",");
			FrequencyMin = parseInt(freqRange[0]);
			FrequencyMax = parseInt(freqRange[1]);
			
			FreqDefaultVal = (FrequencyMin + FrequencyMax) / 2;
			FreqDefaultVal = parseInt(FreqDefaultVal / 100) * 100;
			$("#FrequencyBase").val(FreqDefaultVal);
			
			PopulateImpRulesCombos(card_index, port_index);
			//get setting attribute of frequency, modulation, symbol rate and bandwidth
			GetRfConfigAttr();
		}
	}
	xmlhttp.send(params);
	return false;
}

function cntRelatedValue()
{
	var len = g_RfConfigRows.length;
	for(var i = 0; i < len; i++)
	{
		//added by chenjin at 20140209, get special value of the existent channel
		var data = g_RfConfigRows[i].split(",");
		var chnIdx = data[1];
		chnExistFlag[chnIdx] = 1;
		freqValArray[chnIdx] = parseFloat(data[2]).toFixed(3);
		moduValArray[chnIdx] = parseInt(data[3]);
		symbValArray[chnIdx] = parseFloat(data[4]).toFixed(3);
		bwValArray[chnIdx] = parseInt(data[5]);
	}
	
	if(!freqDefault)
	{
		firstFreqIdx[0] = 0;
		for(i = 0; i < (GROUP_NUM - 1); i++)
		{
			firstFreqIdx[i + 1] = parseInt(firstFreqIdx[i]) + parseInt(groupRange[i]);
		}
		fillChnArray(GROUP_NUM, groupRange, groupIncrem, firstFreqIdx, freqValArray);
	}
	
	if(!moduDefault)
	{
		firstModuIdx[0] = 0;
		for(i = 0; i < (MODU_GROUP_NUM - 1); i++)
		{
			firstModuIdx[i + 1] = parseInt(firstModuIdx[i]) + parseInt(moduGroupRange[i]);
		}
		fillChnArray(MODU_GROUP_NUM, moduGroupRange, moduGroupIncrem, firstModuIdx, moduValArray);
	}

	if(!symbDefault)
	{
		firstSymbIdx[0] = 0;
		for(i = 0; i < (SYMB_GROUP_NUM - 1); i++)
		{
			firstSymbIdx[i + 1] = parseInt(firstSymbIdx[i]) + parseInt(symbGroupRange[i]);
		}
		fillChnArray(SYMB_GROUP_NUM, symbGroupRange, symbGroupIncrem, firstSymbIdx, symbValArray);
	}
	
	if(!bwDefault)
	{
		firstBwIdx[0] = 0;
		for(i = 0; i < (BW_GROUP_NUM - 1); i++)
		{
			firstBwIdx[i + 1] = parseInt(firstBwIdx[i]) + parseInt(bwGroupRange[i]);
		}
		fillChnArray(BW_GROUP_NUM, bwGroupRange, bwGroupIncrem, firstBwIdx, bwValArray);
	}
}

var init_row = true;
var start_chn;
function GetRfConfigRows()
{
	var xmlhttp = false;
	xmlhttp = getHTTPObject();
	
	if(init_row)
	{
		start_chn = card_index + "/" + port_index + "." + "1";
	}
	var getParams = "type=7&cmd=1&start_chn=" + start_chn;

	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;
			var s_map_response = response.slice(7, -8).split("&");
			var s_map_len = s_map_response.length;

			FillInternalTable(s_map_response);
			if(init_row == true)
			{
				RenderBaseTable();
			}

			init_row = false;
			
			if(s_map_response[s_map_len - 1].indexOf("start_chn") != -1)
			{
				var cur_row_string = s_map_response[s_map_len - 1].split(",");
				start_chn = cur_row_string[1]; //The element before-last in response array stores the value of "cur-row"
			}

			if(s_map_response[s_map_len - 1] == "end")
			{
				init_row = true;
				if(bLoadingData == true)
				{
					ToggleLoading();
				}
				if(bChangeDataduringLoad)
				{
					DisableApply(false);
					bChangeDataduringLoad = false;
				}	
				DisableReset(false);
				resizeWidth();
				cntRelatedValue();
				document.body.style.cursor = "auto";
				window.status = "Done";
				return true;
			}
			setTimeout("GetRfConfigRows()", 5);
			//DisableDataRate();
		}
	}
	xmlhttp.send(getParams);
	return true;
}

var g_RfConfigRows = [];	// Contains array of strings - each element containing , separated values
var curFocus;				// UI Element that has got current keyboard focus (that was last clicked)
var lastRowRendered;		// Used to handle insertion

var scrollLock = false;
function FillInternalTable(s_map)
{
	var len = s_map.length;
	var getDefVal = true;
	
	for(var i = 0; i < len; i++)
	{
		if(s_map[i] == "end")
		{
			continue;	// The last value is "end"
		}
		if(s_map[i].indexOf("start_chn") != -1)
		{
		// The current row is "cur_row". Hence skip.
			continue;	
		}
		// & separated rows with , separated fields
		s_map[i] = "C," + s_map[i]; // When loading the rows are Clean
		g_RfConfigRows.push(s_map[i]);
		newRowFlag.push(false);
		// Create a row in the invisible table - this is used in adjusting the scrollbar
		var row = document.getElementById("InvisibleTable").insertRow(-1);
		row.style.height = BASE_ROW_HEIGHT; // This value has to match the stream map row"s height. Only then the scrollbar"s thumb will be of proper size.
		var cell = row.insertCell(0);
		cell.innerHTML = g_RfConfigRows.length;
	}
}

function OnRuleScroll()
{
	document.getElementById("baseTable").scrollLeft = document.getElementById("baseRule").scrollLeft;
}

function RenderBaseTable()
{
	var RowNo = parseInt(document.getElementById("BaseTableDiv").scrollTop, 10);
	RowNo = parseInt((RowNo) / BASE_ROW_HEIGHT_INT, 10); // 30 is the height of a single row
	
	var RowsToDisplay = parseInt(document.getElementById("BaseSettings").rows.length, 10);
	RowsToDisplay = RowsToDisplay - 1; // 1 rows in the heading table
	
	for(var i = RowNo; i < (RowNo + RowsToDisplay); i++)
	{
		if(i >= g_RfConfigRows.length)
		{
			RenderBlankRow(i - RowNo);
			continue;
		}
		RenderBaseRow(i, (i - RowNo), g_RfConfigRows[i]);
	}

	if(i > g_RfConfigRows.length)
	{
		lastRowRendered = g_RfConfigRows.length - 1;
	}
	else
	{
		lastRowRendered = i - 1;
	}
}

function RenderBaseRow(index, rowNo, rowData)
{
	if(rowNo <= ROW_NUM)
	{
		var fields = rowData.split(",");
		var smapRow = document.getElementById("BaseSettings").rows[1 + rowNo];
		var smapRowCells = smapRow.cells;
		
		smapRowCells[0].innerHTML = index;
		//display the group No.
		if(!freqDefault)
		{
			smapRowCells[1].innerHTML = getGroupIdx(parseInt(fields[1]), GROUP_NUM, groupRange);
		}
		else
		{
			smapRowCells[1].innerHTML = parseInt(fields[1]);
		}
		smapRowCells[2].firstChild.innerHTML = chnNumToDisplay(card_index, port_index, (parseInt(fields[1]) + 1));
		smapRowCells[3].firstChild.value = parseFloat(fields[2]).toFixed(3);
		smapRowCells[4].firstChild.value = fields[3];
		smapRowCells[5].firstChild.value = parseFloat(fields[4]).toFixed(3);
	
		for(var i = 6; i <= 10; i++)
		{
			smapRowCells[i].firstChild.value = fields[i - 1];
		}
		
		smapRowCells[11].firstChild.value = parseFloat(fields[10]).toFixed(3);
		for(var j = 12; j <= 14; j++)
		{
			smapRowCells[j].firstChild.value = fields[j - 1];
		}
	
		if(fields[0] == "M")
		{
			// Highlight modified row
			smapRow.style.backgroundColor = "yellow";
		}
		else if(fields[0] == "D")
		{
			// Highlight deleted row
			smapRow.style.backgroundColor = "red";
		}
		else if(fields[0] == "N")
		{
			// Highlight newly created row
			smapRow.style.backgroundColor = "green";
		}
		else
		{
			// Normal row
			smapRow.style.backgroundColor = "white";
		}
		
		if((fields[0] == "N") && (newRowFlag[index] == true))
		{
			document.getElementById("a" + rowNo + "_set").style.display = "";
			document.getElementById("a" + rowNo).style.display = "none";
		}
		else
		{
			document.getElementById("a" + rowNo + "_set").style.display = "none";
			document.getElementById("a" + rowNo).style.display = "";
		}
		
		smapRow.style.display = "";
	}
}

function RenderBlankRow(rowNo)
{
	var smapRow = document.getElementById("BaseSettings").rows[1 + rowNo];
	smapRow.style.display = "none";
}

function recombineData(data, field, value)
{	
	data[field] = value;
	
	if(data[0] != "N") // Update the status according to modification only for existing and not for new rows
	{
		if(data[9] == 50) // The Active column is set to DELETE
		{
			data[0] = "D";
		}
		else
		{
			data[0] = "M";
		}
	}
		
	newRowString = data[0];
	for(var i=1; i < data.length; i++)
	{
		newRowString = newRowString + "," + data[i];
	}
	
	return newRowString;
}

function OnRfConfigCellChange(obj)
{
	var i;
	var j;
	var row = obj.parentNode.parentNode; // This will give us the row objects reference
	var index = parseInt(row.cells[0].innerHTML);
	var GuiRowNo = 0;
	if(obj.id.length > 3)
	{
		GuiRowNo = parseInt(obj.id.split("_")[0].substr(1), 10); // if id is "a2" GuiRowNo will be 2
	}
	else
	{
		GuiRowNo = parseInt(obj.id.substr(1), 10); // if id is "a2" GuiRowNo will be 2
	}

	// Find out which field has changed
	var fieldIndex = obj.id.charCodeAt(0) - 97 + 1; // 97 is the char code for "a"
	var rowValue = g_RfConfigRows[index]; // This will be , separated
	var rowFields = rowValue.split(",");
	var Idx = parseInt(rowFields[1]);
	var newRowString;
	
	//added by chenjin at 20140209
	var freFlag = 0;
	var moduFlag = 0;
	var symbFlag = 0;
	var bwFlag = 0;
	
	var gIndex;
	var startCh;
	var endCh;
	if(fieldIndex == 1)			//change output channel No. when add a new row
	{
		var idx = obj.value;
		if(!freqDefault)		
		{
			gIndex = getGroupIdx(idx, GROUP_NUM, groupRange);
			startCh = firstFreqIdx[gIndex];
			endCh = parseInt(firstFreqIdx[gIndex]) + parseInt(groupRange[gIndex]); 
			if(getGroupExistFlag(startCh, endCh))		//group has no less than one existent channel
			{
				$("#b" + GuiRowNo).val(freqValArray[idx]);
				g_RfConfigRows[index] = recombineData(rowFields, 2, freqValArray[idx]);
			}
			else
			{
				freqValArray[idx] = parseFloat(rowFields[2]);
				fillGroupChArray(idx, startCh, endCh, groupIncrem[gIndex], freqValArray);
			}
		}
		/*
		if(!moduDefault)
		{
			gIndex = getGroupIdx(idx, MODU_GROUP_NUM, moduGroupRange);
			startCh = firstModuIdx[gIndex];
			endCh = parseInt(firstModuIdx[gIndex]) + parseInt(moduGroupRange[gIndex]); 
			if(getGroupExistFlag(startCh, endCh))
			{
				$("#c" + GuiRowNo).val(moduValArray[idx]);
				g_RfConfigRows[index] = recombineData(rowFields, 3, moduValArray[idx]);
			}
			else
			{
				freqValArray[idx] = parseInt(rowFields[3]);
				fillGroupChArray(idx, startCh, endCh, moduGroupIncrem[gIndex], moduValArray);
			}
		}
		
		if(!symbDefault)
		{
			gIndex = getGroupIdx(idx, SYMB_GROUP_NUM, symbGroupRange);
			startCh = firstSymbIdx[gIndex];
			endCh = parseInt(firstSymbIdx[gIndex]) + parseInt(symbGroupRange[gIndex]); 
			if(getGroupExistFlag(startCh, endCh))
			{
				$("#d" + GuiRowNo).val(symbValArray[idx]);
				g_RfConfigRows[index] = recombineData(rowFields, 4, symbValArray[idx]);
			}
			else
			{
				freqValArray[idx] = parseFloat(rowFields[4]);
				fillGroupChArray(idx, startCh, endCh, symbGroupIncrem[gIndex], symbValArray);
			}
		}

		if(!bwDefault)
		{
			gIndex = getGroupIdx(idx, BW_GROUP_NUM, bwGroupRange);
			startCh = firstBwIdx[gIndex];
			endCh = parseInt(firstBwIdx[gIndex]) + parseInt(bwGroupRange[gIndex]); 
			if(getGroupExistFlag(startCh, endCh))
			{
				$("#e" + GuiRowNo).val(bwValArray[idx]);
				g_RfConfigRows[index] = recombineData(rowFields, 5, bwValArray[idx]);
			}
			else
			{
				freqValArray[idx] = parseInt(rowFields[5]);
				fillGroupChArray(idx, startCh, endCh, bwGroupIncrem[gIndex], bwValArray);
			}
		}
		*/
	}
	else if(fieldIndex == 2)
	{
		if(!checkFrequency(obj.value))
		{
			setTimeout(function () {obj.focus()}, 50);
			obj.select();
			return false;
		}
		freqValArray[Idx] = obj.value;
		freFlag = 1;
	}
	
	else if(fieldIndex == 3)
	{
		moduFlag = 1;
		moduValArray[Idx] = obj.value;
	}
	
	else if(fieldIndex == 4)
	{
		if(!checkSymbolRate(obj.value))
		{
			setTimeout(function () {obj.focus()}, 50);
			obj.select();
			return false;
		}
		symbFlag = 1;
		symbValArray[Idx] = obj.value;
	}
	
	else if(fieldIndex == 5)
	{
		bwFlag = 1;
		bwValArray[Idx] = obj.value;
	}
	
	else if(fieldIndex == 6)
	{
		if(!checkTranStrId(obj.value))
		{
			setTimeout(function () {obj.focus()}, 50);
			obj.select();
			return false;
		}
	}
	
	else if(fieldIndex == 8)
	{
		if(validateName(obj.value, 1, language) == false)
		{
			setTimeout(function () {obj.focus()}, 50);
			obj.select();
			return false;
		}
	}
	
	else if(fieldIndex == 9)
	{
		if(channelNumChange == 0)
		{
			channelNumChange = 1;
		}
	}
	
	else if(fieldIndex == 10)
	{
		if(!checkAtten(obj.value))
		{
			setTimeout(function () {obj.focus()}, 50);
			obj.select();
			return false;
		}
	}
	
	else if(fieldIndex == 13)
	{
		if(!checkSdvUDP(obj.value))
		{
			setTimeout(function () {obj.focus()}, 50);
			obj.select();
			return false;
		}
	}
	
	g_RfConfigRows[index] = recombineData(rowFields, fieldIndex, obj.value);
	RenderBaseRow(index, GuiRowNo, g_RfConfigRows[index]);
	
	var gIdx;
	var startIdx;
	var id;
	var rowData;
	var len = g_RfConfigRows.length;
	
	//特殊值实现按组联动
	if((freFlag == 1) && (freqDefault == false))
	{
		gIdx = getGroupIdx(Idx, GROUP_NUM, groupRange);
		startIdx = parseInt(firstFreqIdx[gIdx]);
		
		for(i = startIdx; i < (startIdx + parseInt(groupRange[gIdx])); i++)
		{
			freqValArray[i] = parseFloat(obj.value) + ((i - Idx) * parseInt(groupIncrem[gIdx]));
			
			for(j = 0; j < len; j++)
			{
				rowData = g_RfConfigRows[j].split(",");
				if(rowData[1] == i)
				{
					g_RfConfigRows[j] = recombineData(rowData, 2, freqValArray[i]);
				}
			}
		}
		RenderBaseTable();
	}
	
	if((moduFlag == 1) && (moduDefault == false))
	{
		gIdx = getGroupIdx(Idx, MODU_GROUP_NUM, moduGroupRange);
		startIdx = parseInt(firstModuIdx[gIdx]);
		
		for(i = startIdx; i < (startIdx + parseInt(moduGroupRange[gIdx])); i++)
		{
			moduValArray[i] = parseInt(obj.value) + ((i - Idx) * parseInt(moduGroupIncrem[gIdx]));
			
			for(j = 0; j < len; j++)
			{
				rowData = g_RfConfigRows[j].split(",");
				if(rowData[1] == i)
				{
					g_RfConfigRows[j] = recombineData(rowData, 3, moduValArray[i]);
				}
			}
		}

		RenderBaseTable();
	}
	
	if((symbFlag == 1) && (symbDefault == false))
	{
		gIdx = getGroupIdx(Idx, SYMB_GROUP_NUM, symbGroupRange);
		startIdx = parseInt(firstSymbIdx[gIdx]);
		
		for(i = startIdx; i < (startIdx + parseInt(symbGroupRange[gIdx])); i++)
		{
			symbValArray[i] = parseFloat(obj.value) + ((i - Idx) * parseInt(symbGroupIncrem[gIdx]));
			
			for(j = 0; j < len; j++)
			{
				rowData = g_RfConfigRows[j].split(",");
				if(rowData[1] == i)
				{
					g_RfConfigRows[j] = recombineData(rowData, 4, symbValArray[i]);
				}
			}
		}

		RenderBaseTable();
	}
	
	if((bwFlag == 1) && (bwDefault == false))
	{
		gIdx = getGroupIdx(Idx, BW_GROUP_NUM, bwGroupRange);
		startIdx = firstBwIdx[gIdx];
		
		for(i = startIdx; i < (startIdx + parseInt(bwGroupRange[gIdx])); i++)
		{
			bwValArray[i] = parseInt(obj.value) + ((i - Idx) * parseInt(bwGroupIncrem[gIdx]));
			
			for(j = 0; j < len; j++)
			{
				rowData = g_RfConfigRows[j].split(",");
				if(rowData[1] == i)
				{
					g_RfConfigRows[j] = recombineData(rowData, 5, bwValArray[i]);
				}
			}
		}
		
		RenderBaseTable();
	}

	DisableApply(false);
	DisableReset(false);
}

function ResetPostData()
{
	deleteCount = 0;
	insertCount = 0;

	deleteRows = [];
	insertRows = [];

	deleteCnt = 0;
	deleteNumCnt = 0;
	insertCnt = 0;
	insertNumCnt = 0;
	
	postString = "";
	postDeleteString = "";
	postAddString = "";
	
	loopDelCnt = 1;
	loopAddCnt = 1;
}

function PerformReload()
{
	DisableApply(true);
	DisableReset(true);

	bLoadingData = true;
	// Clear displays
	var RowsToDisplay = parseInt(document.getElementById("BaseSettings").rows.length, 10) - 1;
	var BaseTable = document.getElementById("BaseTableBody");

	for(var i = 0; i < RowsToDisplay; i++)
	{
		var Row = BaseTable.rows[i];
		var Child = Row.firstChild;

		{
			while(Child != null)
			{
				if((Child.firstChild) && (Child.firstChild.nodeName == "INPUT"))
				{
					Child.firstChild.value = "";
				}
				else if((Child.firstChild) && (Child.firstChild.nodeName == "SELECT"))
				{
					Child.firstChild.value = -1;
				}
				Child = Child.nextSibling;
			}
		}
	}

	g_RfConfigRows.length = 0;
	newRowFlag.length = 0;

	var len = document.getElementById("InvisibleTable").rows.length - 1;
	var table = document.getElementById("InvisibleTable");
	for(var i = 0; i < len; i++)
	{
		table.deleteRow(-1);
	}

	if(bd.browser == "IE")
	{
		document.getElementById("BaseTableDiv").scrollTop = 0;
	}
	
	ResetPostData();
	ResetBaseRules();
	
	$("#chart1").empty();
	getData();
	GetDeviceInfo();
}

function ValidateBeforeApply(data)
{
	if(!checkFrequency(data[2]))
	{
		return false;
	}
	
	if(!checkSymbolRate(data[4]))
	{
		return false;
	}
	
	if(!checkTranStrId(data[6]))
	{
		return false;
	}
	
	if(validateName(data[8], 1, language) == false)
	{
		return false;
	}
	
	if(!checkAtten(data[10]))
	{
		return false;
	}
	
	if(!checkSdvUDP(data[13]))
	{
		return false;
	}
	return true;
}

var deleteCount = 0;
var insertCount = 0;

var deleteRows = [];
var insertRows = [];
function PerformApply()
{
	var len = g_RfConfigRows.length;
	var data;
	for(var i = 0; i < len; i++)
	{
		data = g_RfConfigRows[i].split(",");
		if((data[0] == "N") || (data[0] == "M"))
		{
			// Added row
			var insertRow;
			if(ValidateBeforeApply(data) == false)
			{
				DisableApply(false);
				DisableReset(false);
				document.body.style.cursor="auto";
				window.status = "Done";
				return false;
			}
			else
			{
				DisableApply(true);
				DisableReset(true);

				window.status = "Applying settings, please wait...";
				document.body.style.cursor = "wait";
			}
			
			if((data[0] == "N") && (data[9] != "50"))	// Dont add the row in the backend if the status of the new row is set to DELETE
			{
				insertCount++;
				if(channelChange == 0)
				{
					channelChange = 1;
				}
				if(channelNumChange == 0)
				{
					channelNumChange = 1;
				}
				insertRow = data[1]; // channel index
				for(var j = 2; j < data.length; j++)
				{
					insertRow = insertRow + "," + data[j];
				}
				insertRows.push(insertRow);
			}
			else					// Modified row
			{
				insertCount++;
				insertRow = data[1]; // channel index
				for(var j = 2; j < data.length; j++)
				{
					insertRow = insertRow + "," + data[j];
				}
				insertRows.push(insertRow);
			}
		}//if
				
		// Delete row
		else if(data[0] == "D")
		{
			DisableApply(true);
			DisableReset(true);
			// Deleted row
			if(channelChange == 0)
			{
				channelChange = 1;
			}
			if(channelNumChange == 0)
			{
				channelNumChange = 1;
			}
			deleteCount++;
			var delRow = data[1];
			deleteRows.push(delRow);
		}//else if
	}
	
	if(channelNumChange == 1)
	{
		channelNumChange = 0;
		if(language == 0)
		{
			alert("Change the used channel number of this RF port, will affect the level of this.");
		}
		else
		{
			alert("改变RF端口下使用频点数量，会影响该RF端口电平。");
		}
	}
	
	// Show a confirmation box when the time taken for apply is expected to be high
	if(insertCount + deleteCount > 10)
	{
		if(language == 0)
		{
			alert("This operation may take a long time. Please do not navigate away from this page or close the browser till the confirmation box is shown.");
		}
		else
		{
			alert("该操作将会需要很长时间，请不要跳转其它页面或者关闭浏览器直到成功设置确认框弹出为止。");
		}
	}
	
	first = 1;
	setPostData();
	setStreamData();
}

var deleteCnt;//post delete row count
var deleteNumCnt;//post delete loop count
var insertCnt;//post add row count
var insertNumCnt;//post add loop count
function setPostData()
{
	deleteCnt = deleteCount;
	deleteNumCnt = parseInt(deleteCnt / deletePerPost);
	if((deleteCnt % deletePerPost) > 0)
	{
		deleteNumCnt = deleteNumCnt + 1;
	}
	
	insertCnt = insertCount;
	insertNumCnt = parseInt(insertCnt / addPerPost);
	if((insertCnt % addPerPost) > 0)
	{
		insertNumCnt = insertNumCnt + 1;
	}
}

var postString = "";
var postDeleteString = "";
var postAddString = "";

var loopDelCnt = 1;
var deletePerPost = 32;

var loopAddCnt = 1;
var addPerPost = 10;

var first = 1;//add flag
function setStreamData()
{
	if(loopDelCnt == deleteNumCnt)
	{
		var j = (loopDelCnt - 1) * deletePerPost;
		var postDelCnt = deleteCnt - j;
		for(var i = j; i < (j + postDelCnt); i++)
		{
			if(i == j)	
			{
				postDeleteString = deleteRows[i];
			}
			else
			{
				postDeleteString = postDeleteString + "|" + deleteRows[i];
			}
		}	
		postString = "DELETE#" + postDelCnt + "#" + devPort + "#" + postDeleteString;		
		loopDelCnt++;
		PostStreamMapRows(postString);
	}
	else if(loopDelCnt < deleteNumCnt)
	{
		var j = (loopDelCnt - 1) * deletePerPost;
		for(var i = j; i < (j + deletePerPost); i++)
		{
			if(i == j)	
			{
				postDeleteString = deleteRows[i];
			}
			else
			{
				postDeleteString = postDeleteString + "|" + deleteRows[i];
			}
		}			
		postString = "DELETE#" + deletePerPost + "#" + devPort + "#" + postDeleteString;		
		loopDelCnt++;
		PostStreamMapRows(postString);
	}
	else if((loopDelCnt > deleteNumCnt) && (first == 1))
	{
		first = 0;
	}
//Last iteration
	if(first == 0)
	{
		if(loopAddCnt == insertNumCnt)
		{
			var j = (loopAddCnt - 1) * addPerPost;
			var postAddCnt = insertCnt - j;
			for(var i = j; i < (j + postAddCnt); i++)
			{
				if(i == j)
				{
					postAddString = insertRows[i];
				}
				else
				{
					postAddString = postAddString + "|" + insertRows[i];
				}
			}
			postString = "INSERT#" + postAddCnt + "#" + devPort + "#" + postAddString;
			loopAddCnt++;
			PostStreamMapRows(postString);
			return;
		}
		else if(loopAddCnt < insertNumCnt)
		{
			var j = (loopAddCnt - 1) * addPerPost;
			for(var i = j; i < (j + addPerPost); i++)
			{
				if(i == j)
				{
					postAddString = insertRows[i];
				}
				else
				{
					postAddString = postAddString + "|" + insertRows[i];
				}
			}
			postString = "INSERT#" + addPerPost + "#" + devPort + "#" + postAddString;
			loopAddCnt++;
			PostStreamMapRows(postString);
			return;
		}
		else if(loopAddCnt > insertNumCnt)
		{
			if(language == 0)
			{
				alert("RF configuration modified successfully.");
			}
			else
			{
				alert("RF参数设置成功。");
			}
			if(channelChange == 1)
			{
				channelChange = 0;
				var url;
				if(language == 0)
				{
					url = "http://" + mainIPAddr + "/asp/main.asp?nodeId=" + nodeId;
				}
				else
				{
					url = "http://" + mainIPAddr + "/asp/main_cn.asp?nodeId=" + nodeId;
				}
				window.parent.location.replace(url);
			}
			else
			{
				PerformReload();
			}
			return;
		}
	}
}

function PostStreamMapRows(sValueString)
{
	var params = "type=7&cmd=2&userName=" + userName + "&rfConfigSetString=" + sValueString;

	var xmlhttp = false;
	
	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)
    	{
       		setTimeout("setStreamData()", 50);
		}
	}

	xmlhttp.send(params);
	return false;
}

function checkFrequency(data)
{
	var patten  = /^\d+(\.\d+)?$/;
	if(!patten.test(data))
	{
		if(language == 0)
		{
			alert("Frequency should be a decimal number!");
		}
		else
		{
			alert("频率值应该为十进制数!");
		}
		return false;
	}
	if(validateFloat(data) == false)
	{
		if(language == 0)
		{
			alert("Invalid number. Please enter a valid numeric value for Frequency.");
		}
		else
		{
			alert("无效的数字，请输入一个有效的频率值。");
		}
		return false;
	}
	if(validateAccuracy(data, 3) == false)
	{
		if(language == 0)
		{
			alert("Accuracy for Frequency is 3 digits.");
		}
		else
		{
			alert("频率值的有效性最多到小数点后三位。");
		}
		return false;
	}
	if((data < FrequencyMin)|| (data > FrequencyMax))
	{
		if(language == 0)
		{
			alert("Valid range for Frequency is " + FrequencyMin + " - " + FrequencyMax + " MHz.");
		}
		else
		{
			alert("频率值的有效范围是" + FrequencyMin + " - " + FrequencyMax + " MHz。");
		}
		return false;
	}
	return true;
}

function checkSymbolRate(data)
{
	if(validateFloat(data) == false)
	{
		if(language == 0)
		{
			alert("Invalid number. Please enter a valid numeric value for Symbol Rate.");
		}
		else
		{
			alert("无效的数字，请输入一个有效的符号率。");
		}
		return false;
	}
	if(validateAccuracy(data, 3) == false)
	{
		if(language == 0)
		{
			alert("Accuracy for Symbol Rate is 3 digits.");
		}
		else
		{
			alert("符号率的有效性最多到小数点后三位。");
		}
		return false;
	}
	if((data < SymbolRateMin)|| (data > SymbolRateMax))
	{
		if(language == 0)
		{
			alert("Valid range for Symbol Rate is " + SymbolRateMin + " - " + SymbolRateMax + " Mbaud.");
		}
		else
		{
			alert("符号率的有效范围是" + SymbolRateMin + " - " + SymbolRateMax + " Mbaud。");
		}
		return false;
	}
	return true;
}

function checkTranStrId(data)
{
	if(validateNumber(data) == false)
	{
		if(language == 0)
		{
			alert("Invalid number. Please enter a valid numeric value for Transport Stream ID.");
		}
		else
		{
			alert("无效的数字，请输入一个有效的传输流ID。");
		}
		return false;
	}
	if((data < 0) || (data > 65535))
	{
		if(language == 0)
		{
			alert("Valid range for Transport Stream ID is 0 - 65535.");
		}
		else
		{
			alert("传输流ID的范围是0 - 65535。");
		}
		return false;
	}
	return true;
}

function checkAtten(data)
{
	if(validateFloat(data) == false)
	{
		if(language == 0)
		{
			alert("Invalid number. Please enter a valid numeric value for Atten.");
		}
		else
		{
			alert("无效的数字，请输入一个有效的衰减值。");
		}
		return false;
	}
	if(validateAccuracy(data, 3) == false)
	{
		if(language == 0)
		{
			alert("Accuracy for Atten is 3 digits.");
		}
		else
		{
			alert("衰减的有效性最多到小数点后三位。");
		}
		return false;
	}
	if((data < AttenMin)|| (data > AttenMax))
	{
		if(language == 0)
		{
			alert("Valid range for Atten is " + AttenMin + " - " + AttenMax + ".");
		}
		else
		{
			alert("衰减的有效范围是" + AttenMin + " - " + AttenMax + "。");
		}
		return false;
	}
	return true;
}

function checkSdvUDP(data)
{
	if(validateNumber(data) == false)
	{
		if(language == 0)
		{
			alert("Invalid number. Please enter a valid numeric value for Starting UDP Port."); 
		}
		else
		{
			alert("无效的数字，请输入有效的动态UDP起始值。"); 
		}
		return false;
	}
	if((data < 0) || (data  > 65535))
	{
		if(language == 0)
		{
			alert("Valid range for Starting UDP Port is 0 - 65535.");
		}
		else
		{
			alert("动态UDP起始值的有效范围是0 - 65535。");
		}
		return false;
	}
	return true;
}

function ValidateFrenquency()
{
	var obj = document.getElementById("FrequencyBase");
	var frenquency = obj.value;
	
	if(!checkFrequency(frenquency))
	{
		setTimeout(function () {obj.focus()}, 50);
		obj.select();
		return false;
	}
	document.getElementById("BaseRuleApply").disabled = false;
	return true;
}

function ValidateSymbolRate()
{
	var obj = document.getElementById("SymbolRateRule");
	var symbolRate = obj.value;
	
	if(!checkSymbolRate(symbolRate))
	{
		setTimeout(function () {obj.focus()}, 50);
		obj.select();
		return false;
	}
	document.getElementById("BaseRuleApply").disabled = false;
	return true;
}

function ValidateTranStrId()
{
	var obj = document.getElementById("TranStrIdBase");
	var tranStrId = obj.value;
	
	if(!checkTranStrId(tranStrId))
	{
		setTimeout(function () {obj.focus()}, 50);
		obj.select();
		return false;
	}
	document.getElementById("BaseRuleApply").disabled = false;
	return true;
}

function ValidateGroupName()
{
	var obj = document.getElementById("GroupNameRule");
	var groupName = obj.value;
	
	if(validateName(groupName, 1, language) == false)
	{
		setTimeout(function () {obj.focus()}, 50);
		obj.select();
		return false;
	}
	document.getElementById("BaseRuleApply").disabled = false;
	return true;
}

function ValidateAtten()
{
	var obj = document.getElementById("AttenRule");
	var atten = obj.value;
	
	if(!checkAtten(obj.value))
	{
		setTimeout(function () {obj.focus()}, 50);
		obj.select();
		return false;
	}
	document.getElementById("BaseRuleApply").disabled = false;
	return true;
}

function ValidateSdvUDPBase()
{
	var obj = document.getElementById("SdvUdpBase");
	var UDPPort = obj.value;
	
	if(!checkSdvUDP(UDPPort))
	{
		setTimeout(function () {obj.focus()}, 50);
		obj.select();
		return false;
	}
	document.getElementById("BaseRuleApply").disabled = false;
	return true;
}

function ValidateChanneloffset_Frequency()
{
	var obj = document.getElementById("FrequencyChOffset");
	var chOffsetFrequency = obj.value;
	
	if(validateFloat(chOffsetFrequency) == false)
	{
		if(language == 0)
		{
			alert("Invalid number. Please enter a valid numeric value for Frequency Offset.");
		}
		else
		{
			alert("无效的数字，请输入一个有效的频率值组间增量。");
		}
		setTimeout(function () {obj.focus()}, 50);
		obj.select();
		return false;
	}
	if(validateAccuracy(chOffsetFrequency, 3) == false)
	{
		if(language == 0)
		{
			alert("Accuracy for Frequency Offset is 3 digits.");
		}
		else
		{
			alert("频率值组间增量的有效性最多到小数点后三位。");
		}
		setTimeout(function () {obj.focus()}, 50);
		obj.select();
		return false;
	}
	if((chOffsetFrequency < 4)|| (chOffsetFrequency > FrequencyMax))
	{
		if(language == 0)
		{
			alert("Valid range for Frequency Offset is " + 4 + " - " + FrequencyMax + " MHz.");
		}
		else
		{
			alert("频率值组间增量的有效范围是" + 4 + " - " + FrequencyMax + " MHz。");
		}
		setTimeout(function () {obj.focus()}, 50);
		obj.select();
		return false;
	}
	
	document.getElementById("BaseRuleApply").disabled = false;
	return true;
}

function ValidateChanneloffset_TranStrId()
{
	var obj = document.getElementById("TranStrIdChOffset");
	var chOffsetTranStrId = obj.value;
	
	if(validateNumber(chOffsetTranStrId) == false)
	{
		if(language == 0)
		{
			alert("Invalid number. Please enter a valid numeric value for Transport Stream ID Channel Offset.");
		}
		else
		{
			alert("无效的数字，请输入一个有效的传输流ID频点增量。");
		}
		setTimeout(function () {obj.focus()}, 50);
		obj.select();
		return false;
	}
	document.getElementById("BaseRuleApply").disabled = false;
	return true;
}

function ValidateChanneloffset_UDP()
{
	var obj = document.getElementById("SdvUdpPortChOffset");
	var chOffsetUDP = obj.value;
	
	if(validateNumber(chOffsetUDP) == false)
	{
		if(language == 0)
		{
			alert("Invalid number. Please enter a valid numeric value for Starting UDP Port Channel Offset.");
		}
		else
		{
			alert("无效的数字，请输入一个有效的频点间动态UDP起始值增量。");
		}
		setTimeout(function () {obj.focus()}, 50);
		obj.select();
		return false;
	}
	if((chOffsetUDP < 0) || (chOffsetUDP  > 65535))
	{
		if(language == 0)
		{
			alert("Valid range for Starting UDP Port Channel Offset is 0 - 65535.");
		}
		else
		{
			alert("效的频点间动态UDP起始值增量的有效范围是0 - 65535。");
		}
		setTimeout(function () {obj.focus()}, 50);
		obj.select();
		return false;
	}
	document.getElementById("BaseRuleApply").disabled = false;
	return true;
}

function ValidateBaseImplementRules()
{
	if(set_base_flag[0] == 1)
	{
		if((!ValidateFrenquency()) && (!ValidateChanneloffset_Frequency()))
		{
			return false;
		}
	}
	
	if(set_base_flag[2] == 1)
	{
		if(!ValidateSymbolRate())
		{
			return false;
		}
	}
	
	if(set_base_flag[4] == 1)
	{
		if((!ValidateTranStrId()) && (!ValidateChanneloffset_TranStrId()))
		{
			return false;
		}
	}
	
	if(set_base_flag[6] == 1)
	{
		if(!ValidateGroupName())
		{
			return false;
		}
	}
	
	if(set_base_flag[8] == 1)
	{
		if(!ValidateAtten())
		{
			return false;
		}
	}
	
	if(set_base_flag[11] == 1)
	{
		if((!ValidateSdvUDPBase()) && (!ValidateChanneloffset_UDP()))
		{
			return false;
		}
	}
	
	return true;
}

// This variable holds the default values that need to appear when a new row is created. Channel number has to be adjusted before use.
var g_defaultNewRowString; 
var moduDefVal = 0;
var symbDefVal = "6.875";
var bwDefVal = 8;

var baseId = new Array("baseAll", "baseFreq", "baseModu", "baseSymb", "baseBw", "baseTsId", "baseQamManager", 
						"baseQamGroupName", "baseChnMode", "baseAtten", "baseDtsAdjust", "baseSdv", "baseSdvUdp");
var set_base_flag = new Array(0,0,0,0,0,0,0,0,0,0,0,0);

function setBaseAll(obj)
{
	var len = baseId.length;
	
	if(obj.id == baseId[0])
	{
		if(obj.checked == true)
		{
			for(var i = 1; i < len; i++)
			{
				document.getElementById(baseId[i]).checked = true;
				set_base_flag[i - 1] = 1;
			}
		}
		else
		{
			for(var i = 1; i < len; i++)
			{
				document.getElementById(baseId[i]).checked = false;
				set_base_flag[i - 1] = 0;
			}
		}
	}
	
	for(var i = 1; i < len; i++)
	{
		if(obj.id == baseId[i])
		{
			if(obj.checked == true)
			{
				set_base_flag[i - 1] = 1;
			}
			else
			{
				set_base_flag[i - 1] = 0;
			}
			break;
		}
	}
	disabledButton(document.getElementById("BaseRuleApply"), false);
}

function AddRowToTable()
{
	var freqVal = FreqDefaultVal;

	//added by chenjin,20140209
	if((!freqDefault) && getGroupExistFlag(0, groupRange[0]))
	{
		freqVal = freqValArray[0];
	}
	
	if((!moduDefault) && getGroupExistFlag(0, moduGroupRange[0]))
	{
		moduDefVal = moduValArray[0];
	}
	
	if((!symbDefault) && getGroupExistFlag(0, symbGroupRange[0]))
	{
		symbDefVal = symbValArray[0];
	}

	if((!bwDefault) && getGroupExistFlag(0, bwGroupRange[0]))
	{
		bwDefVal = bwValArray[0];
	}

	g_defaultNewRowString = "N,0," + freqVal + "," + moduDefVal + "," + symbDefVal + "," + bwDefVal + ",1,0,QG1,0,0,0,0,0";
	var index = 0;
	if(g_RfConfigRows.length >= PortAuthMaxChNum)
	{
		if(language == 0)
		{
			alert("Can't add the Channel, the number of Authorized Channel is " + PortAuthMaxChNum + ".");
		}
		else
		{
			alert("不能添加频点，授权的频点个数是" + PortAuthMaxChNum + "。");
		}
		return;
	}

	if(curFocus != null)
	{
		// If there is a keyboard focus, take that position
		var row = curFocus.parentNode.parentNode;
		index = parseInt(row.cells[0].innerHTML);
	}
	else if(lastRowRendered != -1)
	{
		// There is no keyboard focus, but there are some rows rendered
		index = lastRowRendered;
	}
	else
	{
		// No rows rendered (table is empty) and obviously, no keyboard focus either.
		index = 0; // Starting channel for the current selection is used when there is no rows for a series of channels.
	}
	
	var data = g_defaultNewRowString.split(","); // Channel number of default new row should be modified

	var newRow = data[0]; 
	for(var i = 1; i < data.length; i++)
	{
		newRow = newRow + "," + data[i];
	}
	g_RfConfigRows.splice(index, 0, newRow);//below index
	newRowFlag.splice(index, 0, true);
	
	// Create a row in the invisible table - this is used in adjusting the scrollbar
	var row = document.getElementById("InvisibleTable").insertRow(-1);
	row.style.height = BASE_ROW_HEIGHT; // This value has to match the stream map row's height. Only then the scrollbar's thumb will be of proper size.
	var cell = row.insertCell(0);
	cell.innerHTML = g_RfConfigRows.length;

	RenderBaseTable();
}

function UpdateBaseTableRow(row_index, Frequency, Modulation, SymbolRate, Bandwidth, TsId, QamManager, GroupName, ChannelMode, Atten, DtsAdjust, SdvSupport, SdvUdpPortStart)
{
	var modifiedRow = g_RfConfigRows[row_index];
	var data = modifiedRow.split(",");
	
	if(data[0] != "N") // If the row is already NEW we should not set it to modified. NEW rows remain NEW till Applied.
	{
		if(ChannelMode == 50)
		{
			data[0] = "D";
		}
		else
		{
			data[0] = "M";
		}
	}
	
	if(set_base_flag[0] == 1)
	{
		data[2] = Frequency;
	}
	if(set_base_flag[1] == 1)
	{
		data[3] = Modulation;
	}
	if(set_base_flag[2] == 1)
	{
		data[4] = SymbolRate;
	}
	if(set_base_flag[3] == 1)
	{
		data[5] = Bandwidth;
	}
	if(set_base_flag[4] == 1)
	{
		data[6] = TsId;
	}
	if(set_base_flag[5] == 1)
	{
		data[7] = QamManager;
	}
	if(set_base_flag[6] == 1)
	{
		data[8] = GroupName + (parseInt(data[1]) + 1);
	}
	if(set_base_flag[7] == 1)
	{
		data[9] = ChannelMode;
	}
	if(set_base_flag[8] == 1)
	{
		data[10] = Atten;
	}
	if(set_base_flag[9] == 1)
	{
		data[11] = DtsAdjust;
	}
	if(set_base_flag[10] == 1)
	{
		data[12] = SdvSupport;
	}
	if(set_base_flag[11] == 1)
	{
		data[13] = SdvUdpPortStart;
	}

	modifiedRow = data[0];
	for(var i = 1; i < data.length; i++)
	{
		modifiedRow = modifiedRow + "," + data[i];
	}

	g_RfConfigRows.splice(row_index, 1, modifiedRow); // Replace the row at row_index with modifiedRow
}

function AddRowToMasterTable(row_index, channel, Frequency, Modulation, SymbolRate, Bandwidth, TsId, QamManager, GroupName, ChannelMode, Atten, DtsAdjust, SdvSupport, SdvUdpPortStart)
{
	if(ChannelMode == 50)
	{
		return false;
	}
	var newRow = "N" + "," + channel + "," + Frequency + "," + Modulation + "," + SymbolRate + "," + Bandwidth + "," + 
						 TsId + "," + QamManager + "," + GroupName + (channel + 1) + "," + ChannelMode + "," + Atten + "," + 
						 DtsAdjust + "," + SdvSupport + "," + SdvUdpPortStart;

	if(g_RfConfigRows.length >= PortAuthMaxChNum)
	{
		maxFlag = true;
		return false;
	}
	g_RfConfigRows.splice(row_index, 0, newRow);
	newRowFlag.splice(row_index, 0, false);
	// Create a row in the invisible table - this is used in adjusting the scrollbar
	var row = document.getElementById("InvisibleTable").insertRow(-1);
	row.style.height = BASE_ROW_HEIGHT; // This value has to match the stream map row's height. Only then the scrollbar's thumb will be of proper size.
	var cell = row.insertCell(0);
	cell.innerHTML = g_RfConfigRows.length;
	return true;
}

function checkBaseSet()
{
	var len = set_base_flag.length;
	
	for(var i = 0; i < len; i++)
	{
		if(set_base_flag[i] == 0)
		{
			if(language == 0)
			{
				alert("add channels must select all base rules!");
			}
			else
			{
				alert("添加频点必须选中所有应用规则项！");
			}
			return false;
		}
	}
	
	return true;
}

function noteMissChannel()
{
	var text;
	if(language == 0)
	{
		text = "There are missing channels between start channel and end channel,are you sure add those channels?";
	}
	else
	{
		text = "起始到结束频点间有缺失频点，确定添加该频点吗？";
	}
	
	if(confirm(text))
	{
		if(!checkBaseSet())
		{
			return false;
		}
	}
	else
	{
		return false;
	}
	return true;
}

function ImplementBaseRules()
{
	var checkCount = 0;
	var StartChan = parseInt($("#QamBaseStart").val());
	var EndChan = parseInt($("#QamBaseEnd").val());
	
	if((StartChan > EndChan))
	{
		if(language == 0)
		{
			alert("Start QAM Channel is greater than End QAM Channel.");
		}
		else
		{
			alert("起始频点大于结束频点。");
		}
		return;
	}
	
	var baseRuleNum = set_base_flag.length;
	var cnt = 0;
	
	for(var i = 0; i < baseRuleNum; i++)
	{
		if(set_base_flag[i] == 0)
		{
			cnt++;
		}
		if(set_base_flag[i] == 1)
		{
			checkCount++;
		}
	}
	
	if(cnt == baseRuleNum)
	{
		if(language == 0)
		{
			alert("Please select no less than one base rule!");
		}
		else
		{
			alert("请至少选择一项应用规则！");
		}
		return;
	}
	
	if(!ValidateBaseImplementRules())
	{
		$("#BaseRuleApply").attr("disabled", true);
		return;
	}

	var BaseFreq, Modulation, SymbolRate, Bandwidth, BaseTsId, QamManager, GroupName, ChannelMode, Atten, DtsAdjust, SdvSupport, BaseSdvUdpStart;
	var ChanIncrFreq, ChanIncrTsId, ChanIncrSdvUdpStart;
	
	BaseFreq = $("#FrequencyBase").val();
	Modulation = $("#ModulationRule").val();
	SymbolRate = $("#SymbolRateRule").val();
	Bandwidth = $("#BandwidthRule").val();
	BaseTsId = $("#TranStrIdBase").val();
	QamManager = $("#QamManagerRule").val();
	GroupName = $("#GroupNameRule").val();
	ChannelMode = $("#ChannelModeRule").val();
	Atten = $("#AttenRule").val();
	DtsAdjust = $("#DtsAdjustRule").val();
	SdvSupport = $("#SdvSupportRule").val();
	BaseSdvUdpStart = $("#SdvUdpBase").val();
	
	ChanIncrFreq = parseFloat($("#FrequencyChOffset").val()).toFixed(3);
	ChanIncrTsId = parseInt($("#TranStrIdChOffset").val(), 10);
	ChanIncrSdvUdpStart = parseInt($("#SdvUdpPortChOffset").val(), 10);
	
	var len = g_RfConfigRows.length;
	
	var curFreq = BaseFreq;
	var curTsId = BaseTsId;
	var curSdvUdpStart = BaseSdvUdpStart;
	
	var startGroup;
	var endGroup;
	
	if((!freqDefault) && (set_base_flag[0] == 1))//各个频点参数联动，并且批量规则中选中
	{
		freqValArray[StartChan] = BaseFreq;
		startGroup = getGroupIdx(StartChan, GROUP_NUM, groupRange);
		endGroup = getGroupIdx(EndChan, GROUP_NUM, groupRange);
		
		fillGroupChArray(StartChan, firstFreqIdx[startGroup], (firstFreqIdx[startGroup] + groupRange[startGroup]), groupIncrem[startGroup], freqValArray);
		if(startGroup != endGroup)		//the start channel and the end channel is not in the same group
		{
			var cnt = 1;
			if((startGroup + cnt) <= endGroup)
			{
				var sChannel = firstFreqIdx[startGroup + cnt];
				var eChannel = sChannel + parseInt(groupRange[startGroup + cnt]);
				//if(!getGroupExistFlag(sChannel, eChannel))
				{
					freqValArray[sChannel] = freqValArray[sChannel - 1] + parseFloat(ChanIncrFreq);
					fillGroupChArray(sChannel, sChannel, (sChannel + groupRange[startGroup + cnt]), groupIncrem[startGroup + cnt], freqValArray);
				}
				cnt++;
			}
		}
	}
	
	if((!moduDefault) && (set_base_flag[1] == 1))
	{
		moduValArray[StartChan] = Modulation;
		startGroup = getGroupIdx(StartChan, MODU_GROUP_NUM, moduGroupRange);
		endGroup = getGroupIdx(EndChan, MODU_GROUP_NUM, moduGroupRange);
		
		fillGroupChArray(StartChan, firstModuIdx[startGroup], (firstModuIdx[startGroup] + moduGroupRange[startGroup]), moduGroupIncrem[startGroup], moduValArray);
		if(startGroup != endGroup)		//the start channel and the end channel is not in the same group
		{
			var cnt = 1;
			if((startGroup + cnt) <= endGroup)
			{
				var sChannel = firstModuIdx[startGroup + cnt];
				moduValArray[sChannel] = Modulation;
				fillGroupChArray(sChannel, sChannel, (sChannel + moduGroupRange[startGroup + cnt]), moduGroupIncrem[startGroup + cnt], moduValArray);
				cnt++;
			}
		}
	}
	
	if((!symbDefault) && (set_base_flag[2] == 1))
	{
		symbValArray[StartChan] = SymbolRate;
		startGroup = getGroupIdx(StartChan, SYMB_GROUP_NUM, symbGroupRange);
		endGroup = getGroupIdx(EndChan, SYMB_GROUP_NUM, symbGroupRange);
		
		fillGroupChArray(StartChan, firstSymbIdx[startGroup], (firstSymbIdx[startGroup] + symbGroupRange[startGroup]), symbGroupIncrem[startGroup], symbValArray);
		if(startGroup != endGroup)		//the start channel and the end channel is not in the same group
		{
			var cnt = 1;
			if((startGroup + cnt) <= endGroup)
			{
				var sChannel = firstSymbIdx[startGroup + cnt];
				symbValArray[sChannel] = SymbolRate;
				fillGroupChArray(sChannel, sChannel, (sChannel + symbGroupRange[startGroup + cnt]), symbGroupIncrem[startGroup + cnt], symbValArray);
				cnt++;
			}
		}
	}

	if((!bwDefault) && (set_base_flag[3] == 1))
	{
		bwValArray[StartChan] = Bandwidth;
		startGroup = getGroupIdx(StartChan, BW_GROUP_NUM, bwGroupRange);
		endGroup = getGroupIdx(EndChan, BW_GROUP_NUM, bwGroupRange);
		
		fillGroupChArray(StartChan, firstBwIdx[startGroup], (firstBwIdx[startGroup] + bwGroupRange[startGroup]), bwGroupIncrem[startGroup], bwValArray);
		if(startGroup != endGroup)		//the start channel and the end channel is not in the same group
		{
			var cnt = 1;
			if((startGroup + cnt) <= endGroup)
			{
				var sChannel = firstBwIdx[startGroup + cnt];
				bwValArray[sChannel] = Bandwidth;
				fillGroupChArray(sChannel, sChannel, (sChannel + bwGroupRange[startGroup + cnt]), bwGroupIncrem[startGroup + cnt], bwValArray);
				cnt++;
			}
		}
	}
	
	var curModulation;
	var curSymbolRate;
	var curBandwidth;
	var noteMissingChn = false;
	for(var i = 0; i < len; i++)
	{
		var curChan = getChannelNo(i);		
		//added by chenjin
		if((curChan < StartChan) || (curChan > EndChan))
		{
			var grpIdx;
			var data;
			if((!freqDefault) && (set_base_flag[0] == 1))
			{
				startGroup = getGroupIdx(StartChan, GROUP_NUM, groupRange);
				endGroup = getGroupIdx(EndChan, GROUP_NUM, groupRange);
				grpIdx = getGroupIdx(curChan, GROUP_NUM, groupRange);
				data = g_RfConfigRows[i].split(",");
				
				if((grpIdx == startGroup) || (grpIdx == endGroup))
				{
					g_RfConfigRows[i] = recombineData(data, 2, freqValArray[curChan]);
				}
			}
			
			if((!moduDefault) && (set_base_flag[1] == 1))
			{
				startGroup = getGroupIdx(StartChan, MODU_GROUP_NUM, moduGroupRange);
				endGroup = getGroupIdx(EndChan, MODU_GROUP_NUM, moduGroupRange);
				grpIdx = getGroupIdx(curChan, MODU_GROUP_NUM, moduGroupRange);
				data = g_RfConfigRows[i].split(",");	
							
				if((grpIdx == startGroup) || (grpIdx == endGroup))
				{
					g_RfConfigRows[i] = recombineData(data, 3, moduValArray[curChan]);
				}
			}
			
			if((!symbDefault) && (set_base_flag[2] == 1))
			{
				startGroup = getGroupIdx(StartChan, SYMB_GROUP_NUM, symbGroupRange);
				endGroup = getGroupIdx(EndChan, SYMB_GROUP_NUM, symbGroupRange);
				grpIdx = getGroupIdx(curChan, SYMB_GROUP_NUM, symbGroupRange);
				data = g_RfConfigRows[i].split(",");	
				
				if((grpIdx == startGroup) || (grpIdx == endGroup))
				{
					g_RfConfigRows[i] = recombineData(data, 4, symbValArray[curChan]);
				}
			}
			
			if((!bwDefault) && (set_base_flag[3] == 1))
			{
				startGroup = getGroupIdx(StartChan, BW_GROUP_NUM, bwGroupRange);
				endGroup = getGroupIdx(EndChan, BW_GROUP_NUM, bwGroupRange);
				grpIdx = getGroupIdx(curChan, BW_GROUP_NUM, bwGroupRange);
				data = g_RfConfigRows[i].split(",");	
				
				if((grpIdx == startGroup) || (grpIdx == endGroup))
				{
					g_RfConfigRows[i] = recombineData(data, 5, bwValArray[curChan]);
				}
			}
		}
						
		// Handle Case when channels missing in top. 
		if((i == 0) && (curChan > StartChan))
		{
			if(checkCount == baseRuleNum)//规则全部选中的时候，按照批量添加来处理
			{	
				if((!noteMissingChn) && (!noteMissChannel()))
				{
					PerformReload();
					return;
				}		
				noteMissingChn = true;
				
				var MissingChannels;
				if(EndChan >= curChan)
				{
					MissingChannels = curChan - StartChan;
				}
				else
				{
					MissingChannels = EndChan - StartChan + 1;
				}
				for(var newChan = StartChan; newChan < (StartChan + MissingChannels); newChan++)
				{
					if(freqDefault)
					{
						curFreq = parseFloat(parseFloat(BaseFreq) + parseFloat(ChanIncrFreq * (newChan - StartChan))).toFixed(3);
					}
					else
					{
						curFreq = freqValArray[newChan];
					}
					
					if(moduDefault)
					{
						curModulation = Modulation;
					}
					else
					{
						curModulation = moduValArray[newChan];
					}
					
					if(symbDefault)
					{
						curSymbolRate = SymbolRate;
					}
					else
					{
						curSymbolRate = symbValArray[newChan];
					}
					
					if(bwDefault)
					{
						curBandwidth = Bandwidth;
					}
					else
					{
						curBandwidth = bwValArray[newChan];
					}
					curTsId = parseInt(BaseTsId, 10) + parseInt(ChanIncrTsId * (newChan - StartChan), 10);
					curSdvUdpStart = parseInt(BaseSdvUdpStart, 10) + parseInt(ChanIncrSdvUdpStart * (newChan - StartChan), 10);
					
					if(AddRowToMasterTable(i, newChan, curFreq, curModulation, curSymbolRate, curBandwidth, curTsId, QamManager, GroupName, ChannelMode, Atten, DtsAdjust, SdvSupport, curSdvUdpStart) == true)
					{
						i++;
						len++;
					}
				}
			}
		}
		
		if((curChan >= StartChan) && (curChan <= EndChan))
		{
			if(freqDefault)
			{
				curFreq = parseFloat(parseFloat(BaseFreq) + parseFloat(ChanIncrFreq * (curChan - StartChan))).toFixed(3);
			}
			else
			{
				curFreq = freqValArray[curChan];
			}
			
			if(moduDefault)
			{
				curModulation = Modulation;
			}
			else
			{
				curModulation = moduValArray[curChan];
			}
			
			if(symbDefault)
			{
				curSymbolRate = SymbolRate;
			}
			else
			{
				curSymbolRate = symbValArray[curChan];
			}
			
			if(bwDefault)
			{
				curBandwidth = Bandwidth;
			}
			else
			{
				curBandwidth = bwValArray[curChan];
			}
			curTsId = parseInt(BaseTsId, 10) + parseInt(ChanIncrTsId * (curChan - StartChan), 10);
			curSdvUdpStart = parseInt(BaseSdvUdpStart, 10) + parseInt(ChanIncrSdvUdpStart * (curChan - StartChan), 10);

			UpdateBaseTableRow(i, curFreq, curModulation, curSymbolRate, curBandwidth, curTsId, QamManager, GroupName, ChannelMode, Atten, DtsAdjust, SdvSupport, curSdvUdpStart);
		}
		
		if(checkCount == baseRuleNum)//规则全部选中的时候，按照批量添加来处理
		{	
		// Case to detect missing channels in the middle
			if(((i + 1) < len) &&		// still there are some rows in the table
				((getChannelNo(i + 1) - curChan) > 1)) // Next channel is not (curChan+1)
			{
				
					// There are some missing channels in the given channel range
					var start = 0;
					var end = 0;
					var MissingChannels = 0;
					if(curChan >= StartChan)
					{
						start = curChan;
					}
					else
					{
						start = StartChan - 1;
					}
					if(getChannelNo(i + 1) <= EndChan)
					{
						end = getChannelNo(i + 1) - 1;
					}
					else
					{
						end = EndChan;
					}
					if(end > start)
					{
						MissingChannels = end - start;
					}
					else
					{
						continue;
					}
					
					if((!noteMissingChn) && (!noteMissChannel()))
					{
						PerformReload();
						return;
					}
					noteMissingChn = true;
		
					for(var newChan = start + 1; newChan <= (start + MissingChannels); newChan++)
					{
						if(freqDefault)
						{
							curFreq = parseFloat(parseFloat(BaseFreq) + parseFloat(ChanIncrFreq * (newChan - StartChan))).toFixed(3);
						}
						else
						{
							curFreq = freqValArray[newChan];
						}
						
						if(moduDefault)
						{
							curModulation = Modulation;
						}
						else
						{
							curModulation = moduValArray[newChan];
						}
						
						if(symbDefault)
						{
							curSymbolRate = SymbolRate;
						}
						else
						{
							curSymbolRate = symbValArray[newChan];
						}
						
						if(bwDefault)
						{
							curBandwidth = Bandwidth;
						}
						else
						{
							curBandwidth = bwValArray[newChan];
						}
						curTsId = parseInt(BaseTsId, 10) + parseInt(ChanIncrTsId * (newChan - StartChan), 10);
						curSdvUdpStart = parseInt(BaseSdvUdpStart, 10) + parseInt(ChanIncrSdvUdpStart * (newChan - StartChan), 10);
						
						if(AddRowToMasterTable((i + 1), newChan, curFreq, curModulation, curSymbolRate, curBandwidth, curTsId, QamManager, GroupName, ChannelMode, Atten, DtsAdjust, SdvSupport, curSdvUdpStart) == true)
						{
							i++;
							len++;
						}
					}
			}

			// Case to detect missing channels in the end of the entire table
			if((i == (len - 1)) &&    // If we are at the last row of the table and
					(curChan < EndChan)) // Still there are channels to add
			{
					if((!noteMissingChn) && (!noteMissChannel()))
				{
					PerformReload();
					return;
				}
				noteMissingChn = true;
				
				var start;
				if(StartChan <= curChan)
				{
					start = curChan;
				}
				else
				{
					start = StartChan - 1;
				}
				while(start < EndChan)
				{
					start++; // curChan is already processed; need to start from curChan + 1 or StartChan
					
					if(freqDefault)
					{
						curFreq = parseFloat(parseFloat(BaseFreq) + parseFloat(ChanIncrFreq * (start - StartChan))).toFixed(3);
					}
					else
					{
						curFreq = freqValArray[start];
					}
					
					if(moduDefault)
					{
						curModulation = Modulation;
					}
					else
					{
						curModulation = moduValArray[start];
					}
					
					if(symbDefault)
					{
						curSymbolRate = SymbolRate;
					}
					else
					{
						curSymbolRate = symbValArray[start];
					}
					
					if(bwDefault)
					{
						curBandwidth = Bandwidth;
					}
					else
					{
						curBandwidth = bwValArray[start];
					}
					curTsId = parseInt(BaseTsId, 10) + parseInt(ChanIncrTsId * (start - StartChan), 10);
					curSdvUdpStart = parseInt(BaseSdvUdpStart, 10) + parseInt(ChanIncrSdvUdpStart * (start - StartChan), 10);
	
					if(AddRowToMasterTable((i + 1), start, curFreq, curModulation, curSymbolRate, curBandwidth, curTsId, QamManager, GroupName, ChannelMode, Atten, DtsAdjust, SdvSupport, curSdvUdpStart) == true)
					{
						i++;
						len++;
					}
				}
			}
		}
	}// for (var i = 0; i < len; i++)
	
	if(checkCount == baseRuleNum)//规则全部选中的时候，按照批量添加来处理
	{	
		// Handling the case - If the entire table is parsed and still the StartChan is not found
		if(len == 0)
		{
			if((!noteMissingChn) && (!noteMissChannel()))
			{
				PerformReload();
				return;
			}
			noteMissingChn = true;
	
			i = 0;
			var curChan = StartChan;
			while(curChan <= EndChan)
			{
				// Since this is the beginning of a new channel, we offset the values by channel offsets
				if(freqDefault)
				{
					curFreq = parseFloat(parseFloat(BaseFreq) + parseFloat(ChanIncrFreq * (curChan - StartChan))).toFixed(3);
				}
				else
				{
					curFreq = freqValArray[curChan];
				}
				
				if(moduDefault)
				{
					curModulation = Modulation;
				}
				else
				{
					curModulation = moduValArray[curChan];
				}
				
				if(symbDefault)
				{
					curSymbolRate = SymbolRate;
				}
				else
				{
					curSymbolRate = symbValArray[curChan];
				}
				
				if(bwDefault)
				{
					curBandwidth = Bandwidth;
				}
				else
				{
					curBandwidth = bwValArray[curChan];
				}
				curTsId = parseInt(BaseTsId, 10) + parseInt(ChanIncrTsId * (curChan - StartChan), 10);
				curSdvUdpStart = parseInt(BaseSdvUdpStart, 10) + parseInt(ChanIncrSdvUdpStart * (curChan - StartChan), 10);
				
				if(AddRowToMasterTable(i, curChan, curFreq, curModulation, curSymbolRate, curBandwidth, curTsId, QamManager, GroupName, ChannelMode, Atten, DtsAdjust, SdvSupport, curSdvUdpStart) == true)
				{
					i++; // Update i so that the next row insertion happens at the right place g_StreamMapRows
					len++;
				}
				curChan++;
			}
		}
	}
	if(maxFlag == true)
	{
		if(language == 0)
		{
			alert("Can't add all the Channels, the number of Authorized Channel is " + PortAuthMaxChNum + ".");
		}
		else
		{
			alert("不能添加批量添加的所有频点，授权的频点个数是" + PortAuthMaxChNum + "。");
		}
		maxFlag = false;
	}
	RenderBaseTable();
	DisableApply(false);
}

function resetAllCheckbox()
{
	var len = baseId.length;
	for(var i = 0; i < len; i++)
	{
		document.getElementById(baseId[i]).checked = false;
		if(i)
		{
			set_base_flag[i - 1] = 0;
		}
	}
}

function ResetBaseRules()
{
	document.getElementById("FrequencyBase").value				= FreqDefaultVal;
	document.getElementById("ModulationRule").value				= 0;
	document.getElementById("SymbolRateRule").value				= "6.875";
	document.getElementById("BandwidthRule").value				= 8;
	document.getElementById("TranStrIdBase").value				= "1";
	document.getElementById("QamManagerRule").value				= 0;
	document.getElementById("GroupNameRule").value				= "QG";
	document.getElementById("ChannelModeRule").value			= 0;
	document.getElementById("AttenRule").value					= "0";
	document.getElementById("DtsAdjustRule").value				= 0;
	document.getElementById("SdvSupportRule").value				= 0;
	document.getElementById("SdvUdpBase").value				    = "0";

	document.getElementById("FrequencyChOffset").value			= "8";
	document.getElementById("TranStrIdChOffset").value			= "1";
	document.getElementById("SdvUdpPortChOffset").value			= "0";
	
	document.getElementById("QamBaseStart").value				= 0;
	document.getElementById("QamBaseEnd").value					= 0;

	resetAllCheckbox();
	disabledButton(document.getElementById("BaseRuleApply"), true);
	return;
}

function EnableBaseRuleApply()
{
	disabledButton(document.getElementById("BaseRuleApply"), false);
}

function resizeWidth()
{
	var width = document.body.offsetWidth;
	document.getElementById("rfDiv").style.width = (width - 16);
	document.getElementById("baseTable").style.width = (width - 34);
	document.getElementById("baseTabDiv").style.width = (width - 36);
	document.getElementById("baseRulesDiv").style.width = (width - 36);
	
	if(width < 850)
	{
		document.getElementById("ruleRow").style.width = 71;
	}
	else
	{
		document.getElementById("ruleRow").style.width = 160;
	}
	/*
	if(g_RfConfigRows.length <= 11)
	{
		document.getElementById("baseTable").style.width = (width - 16);
		document.getElementById("BaseTableDiv").style.width = 0;
	}
	else
	{
		document.getElementById("baseTable").style.width = (width - 34);
		document.getElementById("BaseTableDiv").style.width = 18;
	}
	*/
	setTimeout("resizeWidth()", 500);
}