var card_index;//a
var port_index;//b
var channel_index;//c
var global_channel_index;//a/b.c
var ControlName = new Array("Server1", "Server2", "Server3", "Server4", "Server5", "Server6");
var SERVER_NUM = 6;
var casNameGroup = [];
var emmNameGroup = [];
var EMM_NUM = 16;
var language;
var SC_AUTH_NUM = 0;

function mouseOverShow(obj)
{
	if(obj.disabled == false)
	{
		obj.style.background = "url(../images/btn4_hover.png)";
	}
}
function mouseOutShow(obj)
{
	if(obj.disabled == false)
	{
		obj.style.background = "url(../images/btn4_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)";
	}
}

function displayCasName()
{
	var index;
	for(var i = 0; i < SERVER_NUM; i++)
	{
		index = i + 1;
		document.getElementById("Server" + index).innerHTML  = casNameGroup[i];
	}
}

function changeCasGroup()
{
	var xmlhttp = getHTTPObject();
	var selectedGroup = document.getElementById("CasGroup").value;
	var getParams = "type=35&cmd=1&getCasName=1&casGroup=" + selectedGroup;
	
	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);
			casNameGroup = response.split(",");
			displayCasName();
		}
	}
	xmlhttp.send(getParams);
	return true;
}

function EnableKey()
{
	if(document.getElementById("KeyMode").value == 1)
	{
		document.getElementById("FixedKey").disabled = false;
	}
	else
	{
		document.getElementById("FixedKey").disabled = true;
	}
}

function deleteEmmGroupSelect()
{
	for(var i = 0; i < SERVER_NUM; i++)
	{
		var index = i + 1;
		var obj = document.getElementById("Server" + index + "EmmGroup");
		var len = obj.length;
		for(var j = 0; j < len; j++)
		{
			obj.remove(0);
		}
	}
}

function generateEmmGroupSelect()
{
	var index;
	var el;
	for(var i = 0; i < SERVER_NUM; i++)
	{
		index = i + 1;
		var obj = document.getElementById("Server" + index + "EmmGroup");
		for(var j = 0; j < EMM_NUM; j++)
		{
			el = document.createElement("option");
			el.text = emmNameGroup[j];
			el.value = j;
			try
			{
				obj.add(el, null);
			}
			catch(ex)
			{
				obj.add(el);
			}
		}
		el = document.createElement("option");
		el.text = "None";
		el.value = 255;
		try
		{
			obj.add(el, null);
		}
		catch(ex)
		{
			obj.add(el);
		}
	}
}

function displayCasName()
{
	var index;
	for(var i = 0; i < SERVER_NUM; i++)
	{
		index = i + 1;
		document.getElementById("Server" + index).innerHTML  = casNameGroup[i];
	}
}

function ServerParamDisplay(ifIndex)
{
	var xmlhttp = getHTTPObject();
	var getParams = "type=31&cmd=1&getServerParam=1&channel=" + global_channel_index + "&serverNo=" + ifIndex;
	
	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 ifData = response.split("&");
			var ctrlName = ControlName[ifIndex];
			var emmGroup = ctrlName + "EmmGroup";
			var emmPid = ctrlName + "EmmPid";
			var cellCount = 0;
			
			document.getElementById(emmGroup).value = parseInt(ifData[cellCount++]);
			document.getElementById(emmPid).value = ifData[cellCount];

			ifIndex++;
			if(ifIndex >= SERVER_NUM)
			{
				document.body.style.cursor = "auto";
				window.status = "Done";
			}
			else
			{
				ServerParamDisplay(ifIndex);
			}
		}/* End of readyState */
	}/* End of onreadystatechange */
	xmlhttp.send(getParams);
	return true;
}

function NormalParamDisplay()
{
	var xmlhttp = getHTTPObject();
	var getParams = "type=31&cmd=1&getNormalParam=1&channel=" + global_channel_index;
	
	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 ifData = response.split("&");
			var count = 0;
			
			document.getElementById("CasGroup").value = parseInt(ifData[count++]);
			document.getElementById("KeyMode").value = parseInt(ifData[count++]);
			EnableKey();
			document.getElementById("FixedKey").value = ifData[count++];
			document.getElementById("CatFilt").value = parseInt(ifData[count++]);
			document.getElementById("ScgId").value = parseInt(ifData[count++]);
			
			casNameGroup = ifData[count++].split(",");
			displayCasName();
						
			deleteEmmGroupSelect();
			emmNameGroup = ifData[count++].split(",");
			generateEmmGroupSelect();
			
			if(ifData[count] == 1)//MPTS
			{
				document.getElementById("AdvSetDisplay").style.display = "";
			}
			else
			{
				document.getElementById("AdvSetDisplay").style.display = "none";
			}
			count++;
			
			if(ifData[count] == 0)//start scramble
			{
				if(language == 0)
				{
					document.getElementById("Start").value = "Start Scramble";
				}
				else
				{
					document.getElementById("Start").value = "开始加扰";
				}
			}
			else if(ifData[count] == 1)//stop scramble
			{
				if(language == 0)
				{
					document.getElementById("Start").value = "Stop Scramble";
				}
				else
				{
					document.getElementById("Start").value = "停止加扰";
				}
			}
			
			ServerParamDisplay(0);			
		}/* End of readyState */
	}/* End of onreadystatechange */
	xmlhttp.send(getParams);
	return true;
}

function adjustChConfigTable()
{
	var i,j,k;
	var comp = document.getElementById("ScrambleConfig").children[3];

	if(!+"\v1")
	{
		for(i=SERVER_NUM, j=SC_AUTH_NUM; i>j; i--)
		{
			for(k=0; k<2; k++)
			comp.children[k].children[i].disabled = true;
		}
	}
	else
	{
		for(i=SERVER_NUM, j=SC_AUTH_NUM; i>j; i--)
		{
			for(k=0; k<2; k++)
			comp.children[k].children[i].firstElementChild.disabled = true;
		}
	}
}

function getScAuthNum()
{
	var xmlhttp = getHTTPObject();
	var getParams = "type=31&cmd=1&getScAuthNum=1";
	
	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)
		{
			SC_AUTH_NUM = parseInt(xmlhttp.responseText.slice(7, -8));
			adjustChConfigTable();
		}
	}
	
	xmlhttp.send(getParams);
	return true;
}

function PageLoadHandler()
{
	document.body.style.cursor = "wait";
	window.status = "Retrieving data, please wait...";
	DisableApply();
	
	getScAuthNum();
	NormalParamDisplay();
}

function pageRefresh()
{
	PageLoadHandler();
}

var mainIPAddr;
var group;
var nodeId;
window.onload = function()
{
	var args = getArgs();
	
	mainIPAddr = args["mainIPAddr"];
	group = args["group"];
	var apply = document.getElementById("Apply");
	applyDispay(group, apply);
	
	language = document.getElementById("language").value;
	nodeId = args["nodeId"];
	if(nodeId == null)
	{
		nodeId = parent.curTree.getSelectedNodes()[0].id;
	}
	var str = nodeId.toString();
	var len = str.length;
	var cardVal = Math.pow(10, (len - 1));
	var portVal = Math.pow(10, (len - 2));
	card_index = parseInt(nodeId /cardVal) - 3;
	port_index = parseInt((nodeId %cardVal)/portVal);
	channel_index = (nodeId%portVal);

	global_channel_index = card_index + "/" + port_index + "." + channel_index;

	PageLoadHandler();
	$("#mainContent").height(document.body.clientHeight - 28);
	//document.getElementById("AdvSectionDiv").style.display = "none";
}
window.onresize = function()
{
	$("#mainContent").height(document.body.clientHeight - 28);
}

function DisableApply()
{
	disabledButton(document.getElementById("Apply"), true);
}

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

function GenerateServerParam(ifIndex)
{
	var typeStr;
	var params = "";
		
	typeStr = "EmmGroup";
	var EmmGroup = document.getElementById(ControlName[ifIndex] + typeStr).value;
	params = params + typeStr + ifIndex + "=" + EmmGroup + "&";
	
	typeStr = "EmmPid";
	var EmmPid = document.getElementById(ControlName[ifIndex] + typeStr).value;
	params = params + typeStr + ifIndex + "=" + EmmPid + "&";
	
	return params;
}

function ServerParamConfig()
{
	var xmlhttp = getHTTPObject();
	var params = "type=31&cmd=2&setServerParam=1&channel=" + global_channel_index + "&";
		
	for(var i = 0; i < SC_AUTH_NUM; i++)
	{
		params = params + GenerateServerParam(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)
		{
			if(language == 0)
			{
				alert("Channel scramble configuration updated successfully.");
			}
			else
			{
				alert("频点加扰参数设置成功。");
			}
			PageLoadHandler();
		}
	}
	xmlhttp.send(params);
	return true;
}

function GenerateNormalParam()
{
	var data ;
	var typeStr;
	var params = "";
	
	typeStr = "CasGroup";
	data = document.getElementById(typeStr).value;
	params = typeStr + "=" + data;
		
	typeStr = "KeyMode";
	data = document.getElementById(typeStr).value;
	params = params + "&" + typeStr + "=" + data;

	if(document.getElementById("KeyMode").value == 1)
	{
		typeStr = "FixedKey";
		data = document.getElementById(typeStr).value;
		params = params + "&" + typeStr + "=" + data;
	}
		
	typeStr = "CatFilt";
	data = document.getElementById(typeStr).value;
	params = params + "&" + typeStr + "=" + data;
	
	typeStr = "ScgId";
	data = document.getElementById(typeStr).value;
	params = params + "&" + typeStr + "=" + data;

	return params;
}

function NormalParamConfig()
{
	var params = "type=31&cmd=2&setNormalParam=1&channel=" + global_channel_index + "&" + GenerateNormalParam();
	var 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)
		{
			ServerParamConfig();
		}
	}
	xmlhttp.send(params);
	return true;
}

function setScramConfig()
{
	if(ValidateAllInput() == false)
	{
		return false;
	}
	
	DisableApply();
	document.body.style.cursor = "wait";
	window.status = "Applying settings, please wait...";
	NormalParamConfig();		
}

function ValidateID(obj)
{
	
}

function ValidatePID(obj)
{
	
}

function ValidateKey(obj)
{
	
}

function ValidateAllInput()
{
	var obj;
	obj = document.getElementById("FixedKey");
	if(ValidateKey(obj) == false)
	{
		return false;
	}
	
	obj = document.getElementById("ScgId");
	if(ValidateID(obj) == false)
	{
		return false;
	}
	
	for(var i = 0; i < SC_AUTH_NUM; i++)
	{
		obj = document.getElementById(ControlName[i] + "EmmPid");
		if(ValidatePID(obj) == false)
		{
			return false;
		}
	}
	return true;
}

function MM_showHideLayers() 
{ 
	var obj = document.getElementById("AdvSetDisplay");

	if(language == 0)
	{
		if(obj.value == "Hide Advanced Settings")
		{
			obj.value = "Show Advanced Settings";
			document.getElementById("AdvSectionDiv").style.display = "none";
		}
		else
		{
			obj.value = "Hide Advanced Settings"; 
			document.getElementById("AdvSectionDiv").style.display = "";
		}
	}
	else
	{
		if(obj.value == "隐藏高级选项")
		{
			obj.value = "显示高级选项";
			document.getElementById("AdvSectionDiv").style.display = "none";
		}
		else
		{
			obj.value = "隐藏高级选项"; 
			document.getElementById("AdvSectionDiv").style.display = "";
		}
	}
}

function setScramble()
{
	var params;
	var xmlhttp = getHTTPObject();
	var setScramble;
	var respTxt;
	
	if((document.getElementById("Start").value == "Start Scramble") 
		|| (document.getElementById("Start").value == "开始加扰"))
	{
		setScramble = 1;
	}
	else if((document.getElementById("Start").value == "Stop Scramble")
			||(document.getElementById("Start").value == "停止加扰"))
	{
		setScramble = 0;
	}
	params="type=31&cmd=2&setScramble=" + setScramble + "&channel=" + global_channel_index;
	
	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)
		{
			respTxt = xmlhttp.responseText;
			respTxt = respTxt.slice(7, -8);
			if(respTxt.match("OK"))
			{
				if(language == 0)
				{
					if(document.getElementById("Start").value == "Start Scramble")
					{
						alert("Channel scramble successfully.");
					}
					else
					{
						alert("Channel scrambling is stopped successfully.");
					}
				}
				else
				{
					if(document.getElementById("Start").value == "开始加扰")
					{
						alert("开始加扰成功。");
					}
					else
					{
						alert("停止加扰成功。");
					}
				}
			}
			else if(respTxt.match("authorize_err"))
			{
				if(language == 0)
				{
					alert("Channel more than the number of authorized.");
				}
				else
				{
					alert("超过授权数量");
				}
			}
			else
			{
				if(language == 0)
				{
					if(document.getElementById("Start").value == "Start Scramble")
					{
						alert("Channel scrambling is paused because of error.");
					}
					else
					{
						alert("Channel scrambling is stopped incorrectly.");
					}
				}
				else
				{
					if(document.getElementById("Start").value == "开始加扰")
					{
						alert("开始加扰失败。");
					}
					else
					{
						alert("停止加扰失败。");
					}
				}
			}
			PageLoadHandler();
		}
	}
	xmlhttp.send(params);
	return true;
}

function progRefresh()
{
	var xmlhttp = getHTTPObject();
	var params = "type=31&cmd=1&progRefresh=1&channel=" + global_channel_index;
		
	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);
			progInfo = response.split("&");
			deleteAllRows();
			UpdateTable();
		}
	}
	xmlhttp.send(params);
	return true;
}

function setPidSelect()
{
	var xmlhttp = getHTTPObject();
	var params = "type=31&cmd=2&setPid=1&channel=" + global_channel_index + "&setPidString=" + setPidString;
		
	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("The scramble PIDs are set successfully.");
			}
			else
			{
				alert("加扰PID设置成功。");
			}
			progRefresh();
		}
	}
	xmlhttp.send(params);
	return true;
}

function selectAll()
{
	setPidString = "";
	var rowNum = progInfo.length;
	var check;
	var pidSelect;
	if(document.getElementById("selectAll").checked == true)
	{
		check = true;
		pidSelect = "1";
	}
	else
	{
		check = false;
		pidSelect = "0";
	}
	for(var i = 0; i < rowNum; i++)
	{
		var progData = progInfo[i].split(",");
		var pidNum = progData[2];
		setPidString = setPidString + pidNum;
		for(var j = 0; j < pidNum; j++)
		{
			var pidInfo = progData[3 + j].split("|");
			document.getElementById("pidSelect" + (i + 1) + (j + 1)).checked = check;
			var pidNewValue = pidSelect + "|" + pidInfo[2];
			setPidString = setPidString + "," + pidNewValue;
		}
		if(i < (rowNum - 1))
		{
			setPidString = setPidString + "#";
		}
	}
}

function pidCkeckChange()
{
	setPidString = "";
	var rowNum = progInfo.length;
	for(var i = 0; i < rowNum; i++)
	{
		var progData = progInfo[i].split(",");
		var pidNum = progData[2];
		setPidString = setPidString + pidNum;
		for(var j = 0; j < pidNum; j++)
		{
			var pidInfo = progData[3 + j].split("|");
			if(document.getElementById("pidSelect" + (i + 1) + (j + 1)).checked == true)
			{
				pidInfo[1] = "1";
			}
			else
			{
				pidInfo[1] = "0";
			}
			var pidNewValue = pidInfo[1] + "|" + pidInfo[2];
			setPidString = setPidString + "," + pidNewValue;
		}
		if(i < (rowNum - 1))
		{
			setPidString = setPidString + "#";
		}
	}
}

function AddRows(table)
{
	var rowNum = progInfo.length;
	for(var i = 0; i < rowNum; 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;
	var rowNum = progInfo.length;
	for(var i = 0; i < rowNum; i++)
	{
		index = i + 1;
		var progData = progInfo[i].split(",");
		for(var j = 0; j < NUM_COLUMNS; j++)
		{
			var cell = table.rows[index].cells[j];
			if(j == 0)
			{
				cell.innerHTML = index;
			}
			else if(j == 3)
			{
				var pidNum = progData[j - 1];
				var pidTable = document.createElement("table");
				pidTable.className = "pidTable";
				
				for(var k = 0; k < pidNum; k++)
				{
					var pidInfo = progData[j + k].split("|");
					var pidType = parseInt(pidInfo[0]);//Video/Audio
					var pidChecked = parseInt(pidInfo[1]);//1-checked/0-no checked
					var pidValue = pidInfo[2];//PID
					
					var pidRow = pidTable.insertRow(k);
					
					var pidCell = pidRow.insertCell(0);
					var el1 = document.createElement("input");
					el1.type = "checkbox"
					el1.id = "pidSelect" + index + (k + 1);
					if(pidChecked == 1)
					{
						el1.checked = true;
					}
					else
					{
						el1.checked = false;
					}
					el1.onclick = pidCkeckChange;
					pidCell.appendChild(el1);
					
					var pidTypeString;
					if(pidType == 1)//video
					{
						if(language == 0)
						{
							pidTypeString = "Video ";
						}
						else
						{
							pidTypeString = "视频 ";
						}
					}
					else//audio
					{
						if(language == 0)
						{
							pidTypeString = "Audeo ";
						}
						else
						{
							pidTypeString = "音频 ";
						}
					}
					var el2 = document.createElement("label");
					el2.innerHTML = pidTypeString + "PID: " + pidValue;
					pidCell.appendChild(el2);
				}
				cell.appendChild(pidTable);
			}
			else if((j == 1) || (j == 2))
			{
				cell.innerHTML = progData[j - 1];
			}
		}
	}
}

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

function deleteAllRows()
{
	var table = document.getElementById("ProgSetting");
	var length = table.rows.length;
	for(var i = 1; i < length; i++)
	{
		table.deleteRow(g_RowCount);
		g_RowCount--; 
	}
}
var CHANNEL_SCRAMBLE = 0;
var PROGRAM_SCRAMBLE = 1;
var ENGLISH = 0;
var CHINESE = 1;
function pageJump(index)
{
	var language = parseInt($("#language").val(), 10);
	if(index == CHANNEL_SCRAMBLE)
	{
		if(language == ENGLISH)
		{
			self.location.replace("scramble_ch_config.asp?nodeId=" + nodeId + "&group=" + group + "&mainIPAddr=" + mainIPAddr);
		}
		else if(language == CHINESE)
		{
			self.location.replace("scramble_ch_config_cn.asp?nodeId=" + nodeId + "&group=" + group + "&mainIPAddr=" + mainIPAddr);
		}
	}
	else if(index == PROGRAM_SCRAMBLE)
	{
		if(language == ENGLISH)
		{
			self.location.replace("scramble_program.asp?nodeId=" + nodeId + "&group=" + group + "&mainIPAddr=" + mainIPAddr);
		}
		else if(language == CHINESE)
		{
			self.location.replace("scramble_program_cn.asp?nodeId=" + nodeId + "&group=" + group + "&mainIPAddr=" + mainIPAddr);
		}
	}
}