var MUX_CONFIG = 40;
var PSI_INTERVAL = 43;
var CUSTOM_PROGRAM = 53;
var PROGRAM_DETAIL = 42;
var PSI_EDIT = 44;
var PORT_GENERAL = 41;
var PSI_TIMEOUT = 55;

var portNo;

var FIRST_DELIMITER = "<*1*>";
var SECOND_DELIMITER = "<*2*>";
var THIRD_DELIMITER = "<*3*>";
var FOURTH_DELIMITER = "<*4*>";

//cmd value
var GET = 1;
var SET = 2;
var ADD = 3;
var DELETE = 4;

var OFF = 0;  //Off
var ON = 1;   //On

//language value
var ENGLISH = 0;  //English
var CHINESE = 1;  //Chinese

var pageLanguage = [".asp", "_cn.asp"];


var RETURN_OK = 0;


//按钮类型（按尺寸区分）
var SMALL = 0;

//用户类别权限定义，1是系统管理员，2是超级用户，3是普通用户
var ADMINISTRATOR = 1;
var POWER_USER = 2;
var USER = 3;

var errorEn = ["",
			   "The number of parameters set is wrong!",
			   "The parameter value is illegal!",
			   "Current user password is error!",
			   "Memory acquisition failure!",
			   "Output PID conflict!",
			   "The service number conflict!",
			   "The input port is a backup port, operation is not allowed!",
			   "The input port is used as muxing, which is not allowed to be set to pass-through!",
			   "The output port is used as muxing, which is not allowed to be set to pass-through!",
			   "EMM which is produced by scrambling is not allowed to delete or modify!",
			   "ECM which is produced by scrambling is not allowed to delete or modify!",
			   "Failed to delete PID because there is a backup service in output programs!",
			   "The input port is pass-through which is not allowed to be set to muxing!",
			   "The input program is used as backup which is not allowed to be set to muxing!",
			   "Failed to modify the output programs which include a backup service!",
			   "Time set error!",
			   "No log!",
			   "Get log overflow!",
			   "Service overflow!",
			   "",
			   "The card does not support port backup!",
			   "The port has been used as a backup port!",
			   "The port backup dose not exist!",
			   "The main port dose not exist!",
			   "The backup port has been used as muxing or pass-through!",
			   "The port backup number reaches the limit!",
			   "The backup mode is error!",
			   "The pass-through set of main and backup is inconsistent!",
			   "",
			   "",
			   "The card does not support service backup!",
			   "The port which is set to program backup has been a backup port for other ports!",
			   "The service backup number reaches the limit!",
			   "The backup service of the port has been used as main or backup!",
			   "The service backup dose not exist!",
			   "The main service of service backup dose not exist!",
			   "The PCR structure is not the same!",
			   "The ECM structure is not the same!",
			   "The main service dose not exist!",
			   "The backup service dose not exist!",
			   "The PID set of the main service and the map is inconsistent!",
			   "The backup service has been used as muxing!",
			   "The bitrate is error!",
			   "The service of main and backup is the same!",
			   "The port of backup service has been used as pass-through!",
			   "",
			   "",
			   "",
			   "",
			   "",
			   "EMM overflow!",
			   "The output port does not have service, EMM is not allowed to be set to muxing!",
			   "PID overflow!",
			   "Stream overflow!",
			   "The output port is pass-through which is not allowed to be set to muxing!",
			   "ID conflict!",
			   "Page has expired, please refresh try it again!",
			   "You can not delete your managed accounts!",
			   "Descriptor overflow!",
			   "Failed to get the page parameter!",
			   "CA descriptor add failed,please add PID mapping firstly!",
			   "PMT PID conflict,please check it!",
			   "Network parameters are conflict with private ip(192.165.53.178/24)!",
			   "Don't allow to reduce the authority directly. If necessary, clear authorization and reboot the device!",
			   "License is illegal!",
			   "Input PID conflict!",
			   "Number of pcr structure adjusted overflow!",
			   "The input port is a loop port, so the operation is not allowed!"];
				
var errorCn = ["",
			   "设置的参数个数错误！",
			   "非法参数值！",
			   "当前用户密码输入错误！",
			   "内存获取失败！",
			   "输出端口PID冲突！",
			   "节目号冲突！",
			   "输入端口是备份端口，操作不允许！",
			   "输入端口已被复用，不允许再设置为透传！",
			   "输出端口已被复用，不允许再设置为透传！",
			   "加扰产生的EMM不允许删除或修改！",
			   "加扰产生的ECM不允许删除或修改！",
			   "PID删除失败，输出节目存在备份节目！",
			   "输入端口已被透传，不允许再设置为复用！",
			   "输入节目已作为备份节目，不允许再设置为复用！",
			   "输出节目存在备份节目，不允许修改！",
			   "时间设置错误！",
			   "无日志信息！",
			   "日志超过最大显示条数！",
			   "节目超过板卡或端口下的最大个数！",
			   "",
			   "板卡不支持端口备份功能！",
			   "设置的端口已经用作备份端口！",
			   "备份关系不存在！",
			   "主路端口不存在！",
			   "备份端口已被复用或透传！",
			   "端口备份个数达到极限！",
			   "设置的备份模式错误！",
			   "主备的透传功能不一致！",
			   "",
			   "",
			   "板卡不支持节目备份功能！",
			   "节目备份的端口是其它端口的备份端口！",
			   "节目备份个数达到极限！",
			   "备路的节目在本端口已用成主路或者备路！",
			   "节目备份关系不存在！",
			   "节目备份的主路节目不存在！",
			   "PCR结构不相同！",
			   "ECM结构不相同！",
			   "搜表结果中没找到主路节目！",
			   "搜表结果中没找到备路节目！",
			   "主路节目的PID和映射表中的PID不一致！",
			   "备路节目已用作该端口内的复用！",
			   "设置的码率错误！",
			   "主路和备路节目相同！",
			   "备路节目所在端口已透传！",
			   "",
			   "",
			   "",
			   "",
			   "",
			   "EMM超过端口下最大支持个数！",
			   "输出端口无节目，不允许复用EMM！",
			   "PID超过节目下最大支持个数！",
			   "传送流超过NIT下最大支持个数！",
			   "输出端口已被透传，不允许再设置为复用！",
			   "ID冲突！",
			   "页面已过期，请刷新后重新操作！",
			   "不能删除自己的管理帐户！",
			   "描述符超过最大支持个数！",
			   "获取页面参数失败！",
			   "CA描述符添加失败，请先添加对应的PID映射！",
			   "存在和PMT PID冲突的PID！",
			   "网络参数与内部IP(192.165.53.178/24)冲突！",
			   "不允许降低授权，如有必要，请先清除授权！",
			   "授权码错误！",
			   "输入端口PID冲突！",
			   "PCR结构调整数目超过最大支持个数！",
			   "输入端口是环入端口，不允许循环复用！"];

var returnError = [errorEn, errorCn];
function PageRefresh()
{ 
    funcUpdateDisplay(); 
}

function AjaxStrDeal(str)
{
	var index;
	var end;
	var newStr;
	
	index = str.indexOf("</html>");
	end = str.length - index;
	newStr = str.slice(7, - end);
	
	return newStr;
}
function GetIndexFromId(obj, num)
{
	var tr = obj.parent().parent();
	var trId = tr.attr("id");
	index = parseInt(trId.slice(num));
	
	return index;
}
function PageLoadStatus(flag)
{
	if(flag == true)
	{
		document.body.style.cursor = "wait";
		window.status = "Retrieving data, please wait...";
	}
	else
	{
		document.body.style.cursor = "auto";
		window.status = "Done";
	}
}

function GetArgs() 
{
    var args = new Object();
    var query = location.search.substring(1);  //Get query string
    var pairs = query.split("&");  //Break at & ampersand
    for(var i = 0; i < pairs.length; i++) 
	{
        var pos = pairs[i].indexOf('=');  //Look for "name=value"
        if(pos == -1) 
		{
			continue;  //If not found, skip
		}
        var argname = pairs[i].substring(0, pos);  //Extract the name
        var value = pairs[i].substring(pos + 1);  //Extract the value
        value = decodeURIComponent(value);  //Decode it, if needed
        args[argname] = value;  //Store as a property
    }
    return args;  //Return the object
}

function inButtonClassChange(curClass, id)
{
	switch(curClass)
	{
		case "input_small_normal":
			$("#" + id).attr("class", "input_small_mouseover");
			break;
			
		case "input_normal":
			$("#" + id).attr("class", "input_mouseover");
			break;
			
		case "input_middle1_normal":
			$("#" + id).attr("class", "input_middle1_mouseover");
			break;
			
		case "input_middle2_normal":
			$("#" + id).attr("class", "input_middle2_mouseover");
			break;
			
		case "input_big_normal":
			$("#" + id).attr("class", "input_big_mouseover");
			break;
			
		default:
			break;
	}
}

function outButtonClassChange(curClass, id)
{
	switch(curClass)
	{
		case "input_small_mouseover":
			$("#" + id).attr("class", "input_small_normal");
			break;
			
		case "input_mouseover":
			$("#" + id).attr("class", "input_normal");
			break;
			
		case "input_middle1_mouseover":
			$("#" + id).attr("class", "input_middle1_normal");
			break;
			
		case "input_middle2_mouseover":
			$("#" + id).attr("class", "input_middle2_normal");
			break;
			
		case "input_big_mouseover":
			$("#" + id).attr("class", "input_big_normal");
			break;
			
		default:
			break;
	}
}

function DisableButton(id, size)
{
	var $btn = $("#" + id);
	
	if(size == SMALL)
	{
		$btn.attr("class", "input_small_normal");
	}
	if(id == "applyBtn")
	{
		$btn.attr("class", "input_normal");
	}
	$btn.prop("disabled", true);
	$btn.css("cursor", "auto");	
	$btn.css("color", "#666");	
}

function EnableButton(id)
{
	var $btn = $("#" + id);
	
	$btn.prop("disabled", false);
	$btn.css("cursor", "pointer");
	$btn.css("color", "#1584C4");
}
$(function()
{
	//页面所有的只读input控件边框设为0
	$("input[readonly=readonly]").css("border", "0");
	
	//页面可编辑的输入框（非只读）和textarea绑定keyup事件：背景色变黄，Apply按钮变亮
	//if(top.groupAccess != USER)
	//{
		$("input[type=text][readonly!=readonly], textarea").live("keyup", function()
		{
			//this.style.backgroundColor = "#feffe0";
			EnableButton("applyBtn");
		});
		$("select").live("change", function()
		{
			//this.style.backgroundColor = "#feffe0";
			EnableButton("applyBtn");
		});
	//}	
	//使按钮聚焦时没有虚线框
	$("input[type='button']").bind("focus", function()
	{
		if(this.blur)
		{
			this.blur();
		}
	});
	
	//统一添加鼠标掠过 滑出按钮时的效果
	$("input[type='button']").bind("mouseover", function()
	{
		inButtonClassChange($(this).attr("class"), $(this).attr("id"));
	});
	$("input[type='button']").bind("mouseout", function()
	{
		outButtonClassChange($(this).attr("class"), $(this).attr("id"));
	});
});

function CreateHiddenFormElement(formId, name, value)
{
	var tempform = document.getElementById(formId);
	var newInput = document.createElement("input");
	newInput.type = "hidden";	
	newInput.name = name;		
	newInput.value = value;			
	tempform.appendChild(newInput);	
}

function ValidateAuthCode(obj, language)
{
	var patten = /^([A-F0-9]){32}$/;
	var licence;
	
	licence = obj.val();
	if((licence != DISPLAY_STRING) && (!patten.test(licence)))
	{
		if(language == ENGLISH)
		{
			alert("Please input a valid licence!");
		}
		else if(language == CHINESE)
		{
			alert("请输入合法的授权码！");
		}
		setTimeout(function () {obj.focus()}, 0);
		setTimeout(function () {obj.select()}, 0);
		return false;
	}
	
	return true;
}

function ValidateName(obj, language)
{
	var charName;
	var nameValue = obj.val();
	var length = nameValue.length;
	
	for(var i = 0; i < length; i++)
	{
		charName = nameValue.charAt(i);
		if((charName == '"') || (charName == "%") || (charName == "\\") || (charName == "+") || (charName == "&"))
		{
			if(language == ENGLISH)
			{
				alert("Can't input special symbols!");
			}
			else
			{
				alert("不能输入特殊符号！");
			}
			setTimeout(function () {obj.focus()}, 0);
			setTimeout(function () {obj.select()}, 0);
			return false;
		}
	}
	
	return true;
}
/*************************************************
Function:  		ValidateParam
Description:  	非IP类参数校验，弹出校验结果，输入无效则聚焦
Input:  		obj: current param jquery object; 
				type: param type; 
				minValue: min value; 
				maxValue: max value; 
				str1: English param name; 
				str2: Chinese param name;
				language: current page language, 1-English; 2-Chinese
Output:			无
Return:  		if validate, return ture; else, return false
Others: 		minValue and maxValue both 0, value is no range
				when type is "LENGTH", minValue and maxValue are the length value
*************************************************/
function ValidateParam(obj, type, minValue, maxValue, str1, str2, language)
{
	var patten;
	var strVal = obj.val();
	var numVal;
	var minValDisplay;
	var maxValDisplay;
	switch(type) 
	{
		case "INT_DEC":  //十进制整数
			patten = /^-?\d+$/;
			if(!patten.test(strVal))
			{
				if(language == ENGLISH)
				{
					alert(str1 + " should be a decimal integer!");
				}
				else if(language == CHINESE)
				{
					alert(str2 + "应该是十进制整数！");
				}
				setTimeout(function () {obj.focus()}, 0);
				setTimeout(function () {obj.select()}, 0);
				return false; 
			}
			break;
			
		case "INT_DEC_HEX":  //十进制或十六进制（以0x或0X开头），非负整数
			patten = /(^\d+$)|(^0[xX]([A-Fa-f0-9])+$)/;
			if(!patten.test(strVal))
			{
				if(language == ENGLISH)
				{
					alert(str1 + " should be a non-negative integer(decimal or hexadecimal which starts with 0x or 0X)!");
				}
				else if(language == CHINESE)
				{
					alert(str2 + "应该是非负整数（十进制或者十六进制，其中十六进制数以0x或0X起始）！");
				}
				setTimeout(function () {obj.focus()}, 0);
				setTimeout(function () {obj.select()}, 0);
				return false; 
			}
			break;
			
		case "INT_HEX":  //十六进制非负整数
			patten = /^([A-Fa-f0-9])+$/;
			if(!patten.test(strVal))
			{
				if(language == ENGLISH)
				{
					alert(str1 + " should be a hexadecimal non-negative integer!");
				}
				else if(language == CHINESE)
				{
					alert(str2 + "应该是十六进制非负整数！");
				}
				setTimeout(function () {obj.focus()}, 0);
				setTimeout(function () {obj.select()}, 0);
				return false; 
			}
			break;
			
		case "INT_HEX_NULL":  //十六进制非负整数，可以为空
			patten = /^([A-Fa-f0-9])*$/;
			if(!patten.test(strVal))
			{
				if(language == ENGLISH)
				{
					alert(str1 + " should be a hexadecimal non-negative integer!");
				}
				else if(language == CHINESE)
				{
					alert(str2 + "应该是十六进制非负整数！");
				}
				setTimeout(function () {obj.focus()}, 0);
				setTimeout(function () {obj.select()}, 0);
				return false; 
			}
			break;
			
		case "LENGTH":  //只对长度有要求
			var strLength = strVal.replace(/[^\x00-\xff]/g,'***').length;
			if(minValue == maxValue)  //Length is fixed
			{
				if(strLength != minValue)
				{
					if(language == ENGLISH)
					{
						alert("The length of " + str1 + " should be " + minValue + "!");
					}
					else if(language == CHINESE)
					{
						alert(str2 + "长度应该为 " + minValue + "！");
					}
					setTimeout(function () {obj.focus()}, 0);
					setTimeout(function () {obj.select()}, 0);
					return false;
				}
			}
			else
			{
				if((strLength < minValue) || (strLength > maxValue))  //长度范围
				{
					if(language == ENGLISH)
					{
						alert("The length of " + str1 + " should be between " + minValue + " and " + maxValue + "!");
					}
					else if(language == CHINESE)
					{
						alert(str2 + "长度应该在 " + minValue + "和" + maxValue + "之间！");
					}			
					setTimeout(function () {obj.focus()}, 0);
					setTimeout(function () {obj.select()}, 0);
					return false;
				}
			} 
			break;
			
		case "FLOATING":  //非负浮点数
			var patten  = /^\d+(\.\d+)?$/;
			if(!patten.test(strVal))
			{
				if(language == ENGLISH)
				{
					alert(str1 + " Please input a valid number!");
				}
				else if(language == CHINESE)
				{
					alert(str2 + "请输入合法的数字！");
				}
				setTimeout(function () {obj.focus()}, 0);
				setTimeout(function () {obj.select()}, 0);
				return false;
			}
			break;
		default:
			break;
	}
	if(type != "LENGTH")  //数值范围，非长度范围
	{
		if((type == "INT_DEC") || (type == "INT_DEC_HEX"))  //可输入十进制的整数
		{
			var ch = strVal.slice(0, 2);
			if((ch == "0x") || (ch == "0X"))  //十六进制
			{
				numVal = parseInt(strVal, 16);
			}
			else  //十进制
			{
				numVal = parseInt(strVal, 10);
			}
		}
		else if((type == "INT_HEX") || (type == "INT_HEX_NULL"))  //纯十六进制整数
		{
			if(strVal == "")
			{
				return true;
			}
			numVal = parseInt(strVal, 16);
		}
		else if(type == "FLOATING") //浮点数
		{
			numVal = parseFloat(strVal);
		}
		if((minValue < maxValue) || ((minValue > 0) && (minValue = maxValue))) //有数值范围,主千兆卡端口添加告警可能范围是[1,1]，输入0,0表示参数没有取值范围
		{
			if((numVal < minValue) || (numVal > maxValue))
			{
				if(type == "INT_DEC_HEX")
				{
					minValDisplay = minValue + "(0x" + minValue.toString(16) + ")";
					maxValDisplay = maxValue + "(0x" + maxValue.toString(16) + ")";
				}
				else if((type == "INT_HEX") || (type == "INT_HEX_NULL"))
				{
					minValDisplay = "0x" + minValue;
					maxValDisplay = "0x" + maxValue;
				}
				else
				{
					minValDisplay = minValue;
					maxValDisplay = maxValue;
				}
				if(language == ENGLISH)
				{
					alert(str1 + " should be between " + minValDisplay + " and " + maxValDisplay + "!");
				}
				else if(language == CHINESE)
				{
					alert(str2 + "应该在" + minValDisplay + "和" + maxValDisplay + "之间！");
				}
				setTimeout(function () {obj.focus()}, 0);
				setTimeout(function () {obj.select()}, 0);
				return false;
			}
		}
	}
	return true; 
}
/*************************************************
Function: 		AddRow
Description: 	用于动态添加一行
Input: 			tableId: Table ID;
				trId: Tr ID;
				trClass: Tr Class;
Output: 		无
Return: 		无
Others: 		无
*************************************************/
function AddRow(tableId, trId, trClass)
{ 
	var objArray;
	var obj;
	var objLength;
	var idLength;
	var id;
	var newId;
	var vTb = $("#" + tableId); 
	var vNum = $("#" + tableId + " tr").filter("." + trClass).length + 1;
	var vTr = $("#" + trId + "0");
	var vTrClone = vTr.clone(true);
	vTrClone.attr("id", trId + vNum);
	vTrClone.appendTo(vTb);
	$("#" + tableId + " #" + trId + vNum + " td").each(function(){
		objArray = $(this).children();
		objLength = objArray.length;
		if(objLength != 0)
		{
			for(var i = 0; i < objLength; i++)
			{
				obj = $(objArray[i]);
				id = obj.attr("id");
				idLength = id.length;
				newId = id.slice(0, (idLength - 1)) + vNum;
				obj.attr("id", newId);
			}
		}
	}); 
} 

/*************************************************
Function: 		DelRow
Description: 	用于动态删除一行
Input: 			tableId: Table ID;
				trId: Tr ID;
				trClass: Tr Class;
Output: 		无
Return: 		无
Others: 		无
*************************************************/
function DelRow(tableId, trId, trClass)
{
	var vNum = $("#" + tableId + " tr").filter("." + trClass).length;
	var vTr = $("#" + tableId + " #" + trId + vNum);
	vTr.remove();
}

/*************************************************
Function: 		DrawTableRow
Description: 	用于动态画表格
Input: 			tableId: Table ID;
				trId: Tr ID;
				trClass: Tr Class;
				rowNum: 要画的表格总行数
Output: 		无
Return: 		无
Others: 		无
*************************************************/
function DrawTableRow(tableId, trId, trClass, rowNum)
{
	var curRowNum;
	
	curRowNum = $("#" + tableId + " tr").filter("." + trClass).length;
	if(rowNum == curRowNum)
	{
		return;
	}
	else if(rowNum > curRowNum)
	{
		for(var i = 0; i < (rowNum - curRowNum); i++)
		{
			AddRow(tableId, trId, trClass);
		}
	}
	else
	{
		for(var i = 0; i < (curRowNum - rowNum); i++)
		{
			DelRow(tableId, trId, trClass);
		}
	}
}
function unifyDataFormat(obj)
{
	var paramValue;
	var paramString = obj.val();
	var ch;
	ch = paramString.slice(0, 2);
	if((ch == "0x") || (ch == "0X"))  //十六进制
	{
		paramValue = parseInt(paramString, 16);
	}
	else  //十进制
	{
		paramValue = parseInt(paramString, 10);
	}
	return paramValue;
}
function GetHTTPObject()
{
	var xmlHttp = false;
	try
	{
		xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e2)
		{
			xmlHttp = false;
		}
	}
	if((!xmlHttp) && (typeof xmlHttp != "undefined"))
	{
		try
		{
			xmlHttp = new XMLHttpRequest();
		}
		catch(e)
		{
			xmlHttp = false;
		}
	}

	return xmlHttp;
}