var PARAM_APPLY = 1;
var currentId;
var rowNum;
var objIdArray = ["", "psiType", "psiPid", "id_ext",""];
var COL_NUM = 5;
var HIDDEN_TYPE = 0;
var ID_EXT = 3;
var SECTION_NO = 4;
var psiTypeArray = [];
var IdArray = [];
var sectionNoArray = [];

var pageNameEn =["pat_edit.asp", "pmt_edit.asp", "sdta_edit.asp", "sdto_edit.asp", "nita_edit.asp", "nito_edit.asp", "bat_edit.asp", "cat_edit.asp"];
var pageNameCn =["pat_edit_cn.asp",  "pmt_edit_cn.asp", "sdta_edit_cn.asp", "sdto_edit_cn.asp", "nita_edit_cn.asp", "nito_edit_cn.asp", "bat_edit_cn.asp", "cat_edit_cn.asp"];
var pageName = [pageNameEn, pageNameCn];

//宏定义的值是为了和添加表时的type对应
var PAT = 0;
var CAT = 7;
var BAT = 6;
var SDTo = 3;
var NITo = 5;
var NITa = 4;
var PMT = 1;
var SDTa = 2;

var checkboxArray = ["sdtoCheckbox", "nitaCheckbox", "nitoCheckbox", "batCheckbox"];
var hiddenCheck = ["sdtoCheck", "nitaCheck", "nitoCheck", "batCheck"];
var checkValue = [];
var CHECKBOX_NUM = 4;

var UNCHECKED = 0;
var CHECKED = 1;
var DVB = 0;
var identifyData;
var group;
var userName;
var mainIpAddr;

var option=
{
	minHeight: 110
};

$(document).ready(function()
{
	var args = GetArgs();
	currentId = args["ID"];
	group = args["group"];
	userName = args["userName"];
	mainIpAddr = args["mainIpAddr"];
	if(language == CHINESE)
	{
		var breadCrumbText = encodeURIComponent("PSI/SI编辑", "utf-8");
	}
	else
	{
		var breadCrumbText = encodeURIComponent("PSI/SI Edit", "utf-8");
	}	
	$("#transferFrame").attr("src", "http://" + mainIpAddr + "/asp/transfer.asp?group=" + group + "&userName=" + userName +"&information=" + breadCrumbText + "&url=" + encodeURIComponent(self.location.href));
	funcUpdateDisplay();
});

function funcUpdateDisplay() 
{	
	DisableButton("addBtn");
	DisableButton("deleteBtn");
	DisableButton("refreshBtn");
	PageLoadStatus(true);
	
	displayParam();
		
	EnableButton("refreshBtn");
	PageLoadStatus(false);
	$("input[type=checkbox]").prop("checked", false);
}

function uploadTable()
{
	var fileName = document.getElementById("uploadFileName");
	var path = fileName.value.split("\\");
	var strVal = new String(path[path.length - 1]);
	var dat = strVal.split(".");
	var checkedCnt = 0;

	if(dat[dat.length - 1] != "ts")
	{
		if(language == ENGLISH)
		{
			alert("Please make sure to upload the configuration file!");
		}
		else
		{
			alert("请确保正确的配置文件！");
		}
		return;
	}
	if(fileName.files[0].size > 2097152)
	{
		if(language == ENGLISH)
		{
			alert("The size of configuration file can not be larger than 2M!");
		}
		else
		{
			alert("配置文件的大小不得超过2M！");
		}
		return;
	}
	for(var i = 0; i < CHECKBOX_NUM; i++)
	{
		if($("#" + checkboxArray[i]).prop("checked") == true)
		{
			checkValue.push(CHECKED);
			checkedCnt++;
		}
		else
		{
			checkValue.push(UNCHECKED);
		}
	}
	if(checkedCnt == 0)
	{
		if(language == ENGLISH)
		{
			alert("Please select the PSI table type!");
		}
		else
		{
			alert("请选择PSI表类型！");
		}
		return;
	}
	if(language == ENGLISH)
	{
		var confirmPrompt = "Are you sure you want to import your TS configuration?";	
	}
	else
	{
		var confirmPrompt = "确定要导入TS包?";	
	}
	if(window.confirm(confirmPrompt))
	{
		var url="/goform/siTableImport?language=" + language + "&outputid=" + currentId + "&sdtoCheck=" + checkValue[0] + "&nitaCheck=" + checkValue[1] + "&nitoCheck=" + checkValue[2] + "&batCheck=" + checkValue[3];        
     	document.uploadForm.action = url;
		$("#uploadForm").submit();
	}
}

function downloadTable()
{
	var checkedCnt = 0;
	$("#language").val(language);
	$("#outputid").val(currentId);
	for(var i = 0; i < CHECKBOX_NUM; i++)
	{
		if($("#" + checkboxArray[i]).prop("checked") == true)
		{
			$("#" + hiddenCheck[i]).val(CHECKED);
			checkedCnt++;
		}
		else
		{
			$("#" + hiddenCheck[i]).val(UNCHECKED);
		}
	}
	if(checkedCnt == 0)
	{
		if(language == ENGLISH)
		{
			alert("Please select the PSI table type!");
		}
		else
		{
			alert("请选择PSI表类型！");
		}
		return;
	}
	$("#downloadForm").submit();
}

function modeControl()
{
	if(identifyData == DVB)
	{
		/*if(parent.groupAccess == USER)
		{
			$("#configuration").css("display", "none");
			DisableButton("addBtn");
		}
		else
		{*/
			$("#configuration").css("display", "");
			EnableButton("addBtn");			
		//}
	}
	else
	{
		$("#configuration").css("display", "none");
		DisableButton("addBtn");
	}
}

function displayParam() 
{
	var data;
	var rowData;
	var response;
	var xmlHttp = GetHTTPObject();

	xmlHttp.open("GET", "/goform/formIPQAM?type=" + PSI_EDIT + "&cmd=" + GET + "&id=" + currentId + "&language=" + language + "&ran=" + Math.random(), true);
	xmlHttp.onreadystatechange = function()
	{
		if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
		{
			response = AjaxStrDeal(xmlHttp.responseText);
			data = response.split(FIRST_DELIMITER);
			rowNum = data.length - 1;
			identifyData = data[rowNum];
			DrawTableRow("dataTable", "dataRow", "CaseRow", rowNum);
			if(rowNum != 0)
			{							
				updateTableData(data);		
			}
			modeControl();
			refreshFlag = true;
		}
	}
	xmlHttp.send(null);
}

function pageApply()
{
	var data;
	var xmlHttp = GetHTTPObject();
	var response;
	
	data = "type=" + PSI_EDIT + "&cmd=" + SET + "&id=" + currentId + "&language=" + language + "&setString=";		
	data += PARAM_APPLY;
	
	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))
		{
			$.modal.close();
			response = parseInt(AjaxStrDeal(xmlHttp.responseText), 10);
			if(response == RETURN_OK)
			{
				if(language == ENGLISH)
				{
					alert("Parameters take effect!");
				}
				else if(language == CHINESE)
				{
					alert("参数生效！");
				}
			}
			else
			{
				alert(returnError[language][response]);
			}
			funcUpdateDisplay();
		}
	}
	xmlHttp.send(data);
}

function updateTableData(data)
{
	var rowData;
	var index;
	var patExistFlag = false;
	
	for(var i = 0; i < rowNum; i++)
	{
		index = i + 1;
		rowData = data[i].split(SECOND_DELIMITER);
		for(var j = 0; j < COL_NUM; j++)
		{
			if((j != HIDDEN_TYPE) && (j != SECTION_NO))
			{
				$("#" + objIdArray[j] + index).html(rowData[j]);
			}		
		}
		if((rowData[HIDDEN_TYPE] == "PAT") || (rowData[HIDDEN_TYPE] == "PMT"))
		{
			$("#check" + index).css("display", "none");
			if(rowData[HIDDEN_TYPE] == "PAT")
			{
				patExistFlag = true;
			}
			
		}
		else if((rowData[HIDDEN_TYPE] == "SDTa") && (patExistFlag == true))
		{
			$("#check" + index).css("display", "none");
		}
		else
		{
			$("#check" + index).css("display", "");
		}
		psiTypeArray[index] = rowData[HIDDEN_TYPE];
		IdArray[index] = rowData[ID_EXT];
		sectionNoArray[index] = rowData[SECTION_NO];
	}
}

function psiJump(obj)
{
	var index = GetIndexFromId(obj, 7);
	var editPsiType = psiTypeArray[index];
	var deleteId = IdArray[index];
	switch(eval(editPsiType))
	{
		case PAT:
		case CAT:
		case SDTa:	
			self.location.replace(pageName[language][eval(editPsiType)] + "?psiId=" + currentId + "&mainIpAddr=" + mainIpAddr + "&group=" + group + "&userName=" + userName);
			break;
		case PMT:
			self.location.replace(pageName[language][eval(editPsiType)] + "?psiId=" + currentId + "_" + deleteId + "&mainIpAddr=" + mainIpAddr + "&group=" + group + "&userName=" + userName);
			break;
		case SDTo:
		case BAT:
		case NITa:
		case NITo:
			self.location.replace(pageName[language][eval(editPsiType)] + "?psiId=" + currentId + "_" + deleteId + "_" + sectionNoArray[index] + "&mainIpAddr=" + mainIpAddr + "&group=" + group + "&userName=" + userName);
			break;
	}	
}

function changeType()
{
	switch(parseInt($("#addPsiType").val(),10))
	{
		case CAT:
			$("#bat").css("display","none");
			$("#sdt").css("display","none");
			$("#nit").css("display","none");
			break;
		case BAT:
			$("#bat").css("display","");
			$("#sdt").css("display","none");
			$("#nit").css("display","none");
			break;
		case SDTa:
		case SDTo:
			$("#bat").css("display","none");
			$("#sdt").css("display","");
			$("#nit").css("display","none");
			break;
		case NITa:
		case NITo:
			$("#bat").css("display","none");
			$("#sdt").css("display","none");
			$("#nit").css("display","");
			break;
		default:
			break;
	}
}

function cancelAdd()
{
	$.modal.close();
}

function addPsi()
{
	$("#addPsi").modal(option);	
}

function addApply()
{
	var data;
	var xmlHttp = GetHTTPObject();
	var response;
	
	if(paramCheck() == false)
	{
		return;
	}
	
	data = "type=" + PSI_EDIT + "&cmd=" + ADD + "&id=" + currentId + "&language=" + language + "&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))
		{
			$.modal.close();
			response = parseInt(AjaxStrDeal(xmlHttp.responseText), 10);
			if(response == RETURN_OK)
			{
				if(language == ENGLISH)
				{
					alert("PSI add successfully!");
				}
				else if(language == CHINESE)
				{
					alert("PSI表添加成功！");
				}
			}
			else
			{
				alert(returnError[language][response]);
			}
			funcUpdateDisplay();
		}
	}
	xmlHttp.send(data);
}

function checkAll()
{
	var flag = $("#checkAll").prop("checked");
	for(var i = 0; i < rowNum; i++)
	{
		$("#check" + (i + 1)).prop("checked", flag);
	}
	//if(parent.groupAccess != USER)
	//{
		EnableButton("deleteBtn");
	//}
}

function changeRowChecked()
{	
	//if(parent.groupAccess != USER)
	//{
		EnableButton("deleteBtn");
	//}
}

function deletePsi(obj)
{
	var confirmPrompt;
	var deleteNum = 0;
	var deletePsi;
	
	if(language == ENGLISH)
	{
		confirmPrompt = "Are you sure to delete the selected PSI table?";
	}
	else if(language == CHINESE)
	{
		confirmPrompt = "确定要删除选中的PSI表吗?";
	}
	if(window.confirm(confirmPrompt))
	{
		var data;
		var xmlHttp = GetHTTPObject();
		var response;
		
		data = "type=" + PSI_EDIT + "&cmd=" + DELETE + "&id=" + currentId + "&language=" + language + "&setString=";
		for(var i = 0; i < rowNum; i++)
		{
			var index = i + 1;
			if(($("#check" + index).prop("checked") == true) && ($("#check" + index).css("display") != "none"))
			{
				if(deleteNum == 0)
				{
					deletePsi = eval(psiTypeArray[index]) + SECOND_DELIMITER + IdArray[index];
				}
				else
				{
					deletePsi += FIRST_DELIMITER + eval(psiTypeArray[index]) + SECOND_DELIMITER + IdArray[index];
				}
				deleteNum++;
			}
		}
		data += deletePsi;
		if(deleteNum == 0)
		{
			if(language == ENGLISH)
			{
				alert("Please select one PSI table at least!");
			}
			else
			{
				alert("请至少选中一个PSI表！");
			}
			return;
		}
		if(deleteNum > 256)
		{
			if(language == ENGLISH)
			{
				alert("One operation can only delete 256 PSI table!");
			}
			else
			{
				alert("一次最多删除256个PSI表！");
			}
			return;
		}
		
		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)
				{
					if(language == ENGLISH)
					{
						alert("PSI delete successfully!");
					}
					else if(language == CHINESE)
					{
						alert("PSI表删除成功！");
					}
				}
				else
				{
					alert(returnError[language][response]);
				}
				funcUpdateDisplay();
			}
		}
		xmlHttp.send(data);
	}
}
function generateData()
{
	var data;
	
	var addPsiType = parseInt($("#addPsiType").val() , 10);
	data = addPsiType;
	if(addPsiType == CAT)
	{
		data += FIRST_DELIMITER + 0;
	}
	else if(addPsiType == BAT)
	{
		data += FIRST_DELIMITER + $("#bouquetId").val();
	}
	else if((addPsiType == SDTo) || (addPsiType == SDTa))
	{
		data += FIRST_DELIMITER + $("#streamId").val();
	}
	else
	{
		data += FIRST_DELIMITER + $("#networkId").val();
	}
	return data;
}

function paramCheck()
{
	var returnFlag;
	var tableId;
	var length;
	var addPsiType;
	length = psiTypeArray.length;
	addPsiType = parseInt($("#addPsiType").val(), 10);
	if(addPsiType == CAT)
	{
		for(var i = 0; i < length; i++)
		{
			if(eval(psiTypeArray[i]) == CAT)
			{
				if(language == ENGLISH)
				{
					alert("CAT already exists!");
				}
				else
				{
					alert("CAT表已经存在！");
				}
				return false;
			}
		}
	}
	else if(addPsiType == BAT)
	{
		returnFlag = ValidateParam($("#bouquetId"), "INT_DEC", 0, 65535 , "<Bouquet ID>", "<业务群ID>", language);
		if(returnFlag == false)
		{
			return false;
		}
		tableId = parseInt($("#bouquetId").val(), 10);
		for(var i = 0; i < length; i++)
		{
			if(eval(psiTypeArray[i]) == BAT)
			{
				if(IdArray[i] == tableId)
				{
					if(language == ENGLISH)
					{
						alert("BAT with the same bouquet ID already exists!");
					}
					else
					{
						alert("具有相同业务群ID的BAT已经存在！");
					}
					return false;
				}			
			}
		}
	}
	else if(addPsiType == SDTo)
	{
		returnFlag = ValidateParam($("#streamId"), "INT_DEC", 0, 65535 , "<Stream ID>", "<流ID>", language);
		if(returnFlag == false)
		{
			return false;
		}
		tableId = parseInt($("#streamId").val(), 10);
		for(var i = 0; i < length; i++)
		{
			if((eval(psiTypeArray[i]) == SDTo) || (eval(psiTypeArray[i]) == SDTa))
			{
				if(IdArray[i] == tableId)
				{
					if(language == ENGLISH)
					{
						alert(psiTypeArray[i] + " with the same stream ID already exists!");
					}
					else
					{
						alert("具有相同流ID的" + psiTypeArray[i] + "已经存在！");
					}
					return false;
				}			
			}
		}
	}
	else if((addPsiType == NITo) || (addPsiType == NITa))
	{
		returnFlag = ValidateParam($("#networkId"), "INT_DEC", 0, 65535 , "<Network ID>", "<网络标识符>", language);
		if(returnFlag == false)
		{
			return false;
		}
		tableId = parseInt($("#networkId").val(), 10);
		for(var i = 0; i < length; i++)
		{
			if((eval(psiTypeArray[i]) == NITo) || (eval(psiTypeArray[i]) == NITa))
			{
				if(IdArray[i] == tableId)
				{
					if(language == ENGLISH)
					{
						alert(psiTypeArray[i] + " with the same network ID already exists!");
					}
					else
					{
						alert("具有相同网络ID的" + psiTypeArray[i] + "已经存在！");
					}
					return false;
				}			
			}
		}
	}
	return true;
}