var PROGRAM_SCRAMBLE_TYPE = 56;
var progNum;
var pidNum = [];
var casNum = [];
var COL_NUM = 3;
var PID_LIST = 0;
var CAS_LIST = 2;

var pidIdArray = ["check", "pidString"];
var PID_COL_NUM = 2;
var CHECK_BOX = 0;
var PROGRAM = 0;

var CHECKED = 1;
var UN_CHECKED = 0;

var casIdArray = ["casId", "ecmPid", "ecmPrivateData"];
var CAS_COL_NUM = 3;
var CAS_ID = 0;

window.onresize = function()
{
	$("#mainContent").height(document.body.clientHeight - 28);
}

var mainIPAddr;
var group;
var nodeId;
var card_index;
var port_index;
var channel_index;
$(document).ready(function()
{
	var args = GetArgs();
	mainIPAddr = args["mainIPAddr"];
	group = args["group"];
	nodeId = args["nodeId"];
	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;
	$("#mainContent").height(document.body.clientHeight - 28);
	funcUpdateDisplay();	
});

function funcUpdateDisplay()
{
	DisableButton("applyBtn");
	DisableButton("refreshBtn");
	PageLoadStatus(true);
	
	displayParam();
	
	EnableButton("refreshBtn");
	PageLoadStatus(false);
}

function checkAll()
{
	var flag = $("#checkAll").prop("checked");
	$("input[type=checkbox]").prop("checked", flag);
	var rowIndex;
	for(var i = 0; i < progNum; i++)
	{
		rowIndex = i + 1;
		changeParamStatus(rowIndex, flag);
	}
	EnableButton("applyBtn");
}

function changeCheckAllStatus()
{
	var flag = true;
	$("[name=pidItem]:checkbox").each(function()
	{
		if(!this.checked)
		{
			flag = false;
		}
	});
	$("#checkAll").prop("checked", flag);
}

function checkSingleProgAll(obj)
{
	var flag = obj.prop("checked");
	var $curPidTable = obj.closest("table");
	var rowIndex = GetIndexFromId($curPidTable, 11);
	$curPidTable.find("input[type=checkbox]").prop("checked", flag);
	changeCheckAllStatus();
	changeParamStatus(rowIndex, flag);
	EnableButton("applyBtn");
}

function checkSinglePid(obj)
{
	var flag = true;
	var checkedFlag = false;
	var $curPidTable = obj.closest("table");
	var rowIndex = GetIndexFromId($curPidTable, 11);
	$curPidTable.find("[name=pidItem]:checkbox").each(function()
	{
		if(!this.checked)
		{
			flag = false;
		}
		else
		{
			checkedFlag = true;
		}
	});
	$curPidTable.find("#check1").prop("checked", flag);
	changeCheckAllStatus();
	changeParamStatus(rowIndex, checkedFlag);
	EnableButton("applyBtn");
}

/*************************************************
Function: 		changeParamStatus
Description: 	节目或者PID未加扰时，ECM PID,AC Data,ECM私有描述三个参数不可写
Input: 			rowIndex：当前行数（大表格）；
				checkedFlag: 当前行是否有节目或者PID进行加扰，true-是，flase-否；
Output: 		无
Return: 		无
Others: 		无
*************************************************/
function changeParamStatus(rowIndex, checkedFlag)
{
	var casIndex;
	for(var i = 0; i < casNum[rowIndex - 1]; i++)
	{
		casIndex = i + 1;
		if(checkedFlag == false)
		{
			$("#casTable" + rowIndex + " #ecmPid" + casIndex).attr("disabled", true);
			$("#casTable" + rowIndex + " #acData" + casIndex).attr("disabled", true);
			$("#casTable" + rowIndex + " #ecmPrivateData" + casIndex).attr("disabled", true);
		}
		else
		{
			$("#casTable" + rowIndex + " #ecmPid" + casIndex).attr("disabled", false);
			$("#casTable" + rowIndex + " #acData" + casIndex).attr("disabled", false);
			$("#casTable" + rowIndex + " #ecmPrivateData" + casIndex).attr("disabled", false);
		}
	}
}

function displayParam()
{
	var data;
	var length;
	var response;
	var singleProgInfo;
	var progIndex;
	var pidList;
	var casList;
	var xmlHttp = GetHTTPObject();
	
	xmlHttp.open("GET", "/goform/formIPQAM?type=" + PROGRAM_SCRAMBLE_TYPE + "&cmd=" + GET + "&language=" + language + "&channel=" + global_channel_index + "&ran=" + Math.random(), true);
	xmlHttp.onreadystatechange = function()
	{
		if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
		{
			response = AjaxStrDeal(xmlHttp.responseText);
			//response = "1<*4*>Program1 cctv<*3*>1<*4*>Mpeg2 Audio PID 0X201<*3*>1<*4*>Mpeg2 Audio PID 0X205<*3*>1<*4*>Mpeg2 Audio PID 0X201<*2*>3333333<*2*>0xD402<*4*>0x102<*4*>FEFEEFE<*3*>0xD402<*4*>0x102<*4*>FEFEEFE<*1*>0<*4*>Program1 cctv<*3*>0<*4*>Mpeg2 Audio PID 0X201<*2*>3333333<*2*>0xD402<*4*>0x102<*4*>FEFEEFE<*3*>0xD402<*4*>0x102<*4*>FEFEEFE";
			if(response == "")
			{
				progNum = 0;
			}
			else
			{
				data = response.split(FIRST_DELIMITER);
				progNum = data.length;
			}
			DrawTableRow("dataTable", "progDataRow", "progCaseRow", progNum);
			for(var i = 0; i < progNum; i++)
			{
				progIndex = i + 1;
				singleProgInfo = data[i].split(SECOND_DELIMITER);
				pidList = singleProgInfo[PID_LIST].split(THIRD_DELIMITER);
				length = pidList.length;
				pidNum.push(length);
				DrawTableRow("pidTable" + progIndex, "pidListRow", "pidCaseRow", pidNum[i]);
				if(singleProgInfo[CAS_LIST] == "")
				{
					casNum.push(0);
				}
				else
				{
					casList = singleProgInfo[CAS_LIST].split(THIRD_DELIMITER);
					length = casList.length;
					casNum.push(length);
				}
				DrawTableRow("casTable" + progIndex, "casListRow", "casCaseRow", casNum[i]);
			}
			if(progNum != 0)
			{
				updateTableData(data);
			}
			refreshFlag = true;
		}
	}
	xmlHttp.send(null);
}

function updateTableData(data)
{
	var length;
	var checkedFlag;
	var progIndex;
	var pidList;
	var casList;
	var pidData;
	var casData;
	for(var i = 0; i < progNum; i++)
	{
		checkedFlag = false;
		progIndex = i + 1;
		singleProgInfo = data[i].split(SECOND_DELIMITER);
		for(var j = 0 ; j < COL_NUM; j ++)
		{
			if( j == PID_LIST)
			{
				pidList = singleProgInfo[j].split(THIRD_DELIMITER);
				length = pidList.length;
				for(var k = 0; k < length; k++)
				{
					pidData = pidList[k].split(FOURTH_DELIMITER);
					for(var s = 0; s < PID_COL_NUM; s++)
					{
						if(s == CHECK_BOX)
						{
							if(parseInt(pidData[s], 10) == CHECKED)
							{
								$("#pidTable" + progIndex + " #" +  pidIdArray[s] + (k + 1)).prop("checked", true);
								checkedFlag = true;
							}
							else
							{
								$("#pidTable" + progIndex + " #" +  pidIdArray[s] + (k + 1)).prop("checked", false);
							}
							if(k == PROGRAM)
							{
								$("#pidTable" + progIndex + " #" +  pidIdArray[s] + (k + 1)).attr("onclick", "checkSingleProgAll($(this))");
								$("#pidTable" + progIndex + " #" +  pidIdArray[s] + (k + 1)).parent().addClass("program_td");
							}
							else
							{
								$("#pidTable" + progIndex + " #" +  pidIdArray[s] + (k + 1)).attr("onclick", "checkSinglePid($(this))");
								$("#pidTable" + progIndex + " #" +  pidIdArray[s] + (k + 1)).attr("name", "pidItem");
							}
						}
						else
						{
							$("#pidTable" + progIndex + " #" +  pidIdArray[s] + (k + 1)).html(pidData[s]);
						}						
					}

				}
				changeCheckAllStatus();
				changeParamStatus(progIndex, checkedFlag);
			}
			else if(j == CAS_LIST)
			{
				casList = singleProgInfo[j].split(THIRD_DELIMITER);
				length = casList.length;
				for(var k = 0; k < length; k++)
				{
					casData = casList[k].split(FOURTH_DELIMITER);
					for(var s = 0; s < CAS_COL_NUM; s++)
					{
						if(s == CAS_ID)
						{
							$("#casTable" + progIndex + " #" +  casIdArray[s] + (k + 1)).html(casData[s]);
						}
						else
						{
							$("#casTable" + progIndex + " #" +  casIdArray[s] + (k + 1)).val(casData[s]);
						}						
					}
				}
			}
			else
			{
				$("#acData" + (i + 1)).val(singleProgInfo[j]);
			}
		}
	}
}

function pageApply()
{
	var data;
	var response;
	var xmlHttp = GetHTTPObject();
	
	if(paramCheck() == false)
	{
		return;
	}
	
	data = "type=" + PROGRAM_SCRAMBLE_TYPE + "&cmd=" + SET + "&language=" + language + "&channel=" + global_channel_index + "&setString=";
	data += generateData();
	
	xmlHttp.open("POST", "/goform/formIPQAM", true)
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", data.length);

	xmlHttp.onreadystatechange = function()
	{
		if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
		{
			response = parseInt(AjaxStrDeal(xmlHttp.responseText), 10);
			if(response == RETURN_OK)
			{
				applyFlag = true;
			}
			else
			{
				alert(returnError[language][response]);
			}
			applyFlag = false;  //设置标识符恢复为false
			funcUpdateDisplay();
		}
	}
	xmlHttp.send(data);
}

function paramCheck()
{
	var returnFlag;
	var checkedFlag;
	var progIndex;
	var $curPidTable;
	var casIndex;
	var $curEcmPid;
	var $curAcData;
	var $curEcmPrivateData;
	for(var i = 0; i < progNum; i++)
	{
		checkedFlag = false;
		progIndex = i + 1;
		for(var j = 0 ; j < pidNum[i]; j++)
		{
			$curPidTable = $("#pidTable" + progIndex);
			$curPidTable.find("[name=pidItem]:checkbox").each(function()
			{
				if(this.checked)
				{
					checkedFlag = true;
				}
			});
		}
		if(checkedFlag == true)
		{
			returnFlag = ValidateParam($("#acData" + progIndex), "INT_DEC", 0, 1024, "<Access Criteria Data>", "<Access Criteria Data>", language);
			if(returnFlag == false)
			{
				return false;
			}
			for(var j = 0; j < casNum[i]; j++)
			{
				casIndex = j + 1;
				$curEcmPid = $("#casTable" + progIndex + " #ecmPid" + casIndex);
				$curEcmPrivateData = $("#casTable" + progIndex + " #ecmPrivateData" + casIndex);
				
				returnFlag = ValidateParam($curEcmPid, "INT_DEC_HEX", 1, 8191, "<ECM PID>", "<ECM PID>", language);
				if(returnFlag == false)
				{
					return false;
				}
				
				returnFlag = ValidateParam($curEcmPrivateData, "INT_HEX_NULL", 0, 0, "<ECM Private Data>", "<ECM私用描述>", language);
				if(returnFlag == false)
				{
					return false;
				}
				returnFlag = ValidateParam($curEcmPrivateData, "LENGTH", 0, 128, "<ECM Private Data>", "<ECM私用描述>", language);
				if(returnFlag == false)
				{
					return false;
				}
				if($curEcmPrivateData.val().length % 2 != 0)
				{
					if(language == ENGLISH)
					{
						alert("The length of <ECM Private Data> should be a even number!");						 
					}
					else
					{
						alert("<ECM私用描述>只能输入偶数个字符!");						
					}
					return false;
				}
			}
		}
	}
	return true;
}

function generateData()
{
	var data;
	var progIndex;
	var pidIndex;
	var casIndex;
	for(var i = 0; i < progNum; i++)
	{
		progIndex = i + 1;
		for(var j = 0; j < pidNum[i]; j++)
		{
			pidIndex = j + 1;
			if((i == 0) && (j == 0))
			{
				if($("#pidTable" + progIndex + " #check" + pidIndex).prop("checked") == true)
				{
					data = CHECKED;
				}
				else
				{
					data = UN_CHECKED;
				}
			}
			else if((i != 0) && (j == 0))
			{
				if($("#pidTable" + progIndex + " #check" + pidIndex).prop("checked") == true)
				{
					data += FIRST_DELIMITER + CHECKED;
				}
				else
				{
					data += FIRST_DELIMITER + UN_CHECKED;
				}
			}
			else
			{
				if($("#pidTable" + progIndex + " #check" + pidIndex).prop("checked") == true)
				{
					data += THIRD_DELIMITER + CHECKED;
				}
				else
				{
					data += THIRD_DELIMITER + UN_CHECKED;
				}
			}
		}
		data += SECOND_DELIMITER + $("#acData" + progIndex).val();
		for(var j = 0; j < casNum[i]; j++)
		{
			casIndex = j + 1;
			for(var k = 0; k < CAS_COL_NUM; k++)
			{
				if((j == 0) && (k == 1))
				{
					data +=  SECOND_DELIMITER + $("#casTable" + progIndex + " #" + casIdArray[k] + casIndex).val();
				}
				else if((j != 0) && (k == 1))
				{
					data +=  THIRD_DELIMITER + $("#casTable"  + progIndex + " #" + casIdArray[k] + casIndex).val();
				}
				else if(k != CAS_ID)
				{
					data +=  FOURTH_DELIMITER + $("#casTable" + progIndex + " #" + casIdArray[k] + casIndex).val();
				}
			}
		}
	}
	return data;
}
var CHANNEL_SCRAMBLE = 0;
var PROGRAM_SCRAMBLE = 1;
function pageJump(index)
{
	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);
		}
	}
}