var g_Tabs = new Array();
var trees = new Array();
var curTree = null;
var imageClickFlag = 0;
var gRebootEnable = true;

var oldTab = null;

function treeClose()
{
	document.getElementById("tree-frame").style.display = "none";
	document.getElementById("main").style.width = "1010px";
	document.getElementById("breadCrumbs").style.width = "1010px";
	document.getElementById("open").style.display = "";
}

function treeOpen()
{
	document.getElementById("tree-frame").style.display = "";
	document.getElementById("main").style.width = "794px";
	document.getElementById("breadCrumbs").style.width = "794px";
	document.getElementById("open").style.display = "none";
}

function addPage(tabId, treeId, href)
{
	g_Tabs.push(new tab(tabId, treeId, href));
}

function tab(tabId, treeId, href)
{
	this.tabId = tabId;
	this.treeId = treeId;
	this.href = href;
}

function AddTree(treeId, tree)
{
	var tr = new Object();
	tr.treeId = treeId;
	tr.tree = tree;
	trees.push(tr);
}

function setTree(treeId, tree)
{
	for(var i = 0; i < g_Tabs.length; i++)
	{
		if(g_Tabs[i].treeId == treeId)
		{
			g_Tabs[i].tree = tree;
		}
	}
}

function displayTreeList()
{
	if(curTree.setting.treeId == "Alarms")
	{
		document.getElementById("tree_menu").innerHTML = "Alarm List";
	}
	else if(curTree.setting.treeId == "Scramb")
	{
		document.getElementById("tree_menu").innerHTML = "Scramb List";
	}
	else if(curTree.setting.treeId == "System")
	{
		document.getElementById("tree_menu").innerHTML = "System List";
	}
	else
	{
		document.getElementById("tree_menu").innerHTML = "Card List";
	}
}

function displayTreeListCn()
{
	if(curTree.setting.treeId == "Alarms")
	{
		document.getElementById("tree_menu").innerHTML = "告警列表";
	}
	else if(curTree.setting.treeId == "Scramb")
	{
		document.getElementById("tree_menu").innerHTML = "加扰列表";
	}
	else if(curTree.setting.treeId == "System")
	{
		document.getElementById("tree_menu").innerHTML = "系统列表";
	}
	else
	{
		document.getElementById("tree_menu").innerHTML = "卡列表";
	}
}

function getBreadCrumbs(treeId, treeNode)
{
	var language = document.getElementById("language").value;
	var treeObj = $.fn.zTree.getZTreeObj(treeId);
	var levelValue = "";
	if(language == 0)
	{
		BreadCrunmsValue = (" > " + treeId);
	}
	else
	{
		BreadCrunmsValue = (" > " + getTreeIdCh(treeId));
	}
	if(treeId == "Scramb")
	{
		var idIndex = parseInt(treeNode.id.toString().charAt(0));
		var pId = treeNode.pId;
		if(((idIndex < 3) && (pId == 0)) || ((idIndex == 3) && (treeNode.id.toString().length < 3)))
		{
			return;
		}
	}
	if(treeNode.id.toString().length <= 3)
	{
		if((treeNode.id.toString().length == 3) && (treeId == "Scramb") && (treeNode.pId == 1))
		{
			levelValue = getNodeLevel(treeObj, treeId, treeNode, 2);
		}
		else
		{
			levelValue = getNodeLevel(treeObj, treeId, treeNode, treeNode.id.toString().length);
		}
	}
	else
	{
		if((treeId == "Monitor") || (treeId == "Cards"))
		{
			levelValue = getNodeLevel(treeObj, treeId, treeNode, 4);
		}
		else
		{
			levelValue = getNodeLevel(treeObj, treeId, treeNode, 3);
		}
	}
	BreadCrunmsValue += (" > " + levelValue);
	document.getElementById("breadCrumbsText").innerHTML = BreadCrunmsValue;
}

var selectNode = null;
function setsrc(tabId)
{
	var language = document.getElementById("language").value;
	var tab = null;
	for(var i = 0; i < g_Tabs.length; i++)
	{
		if(g_Tabs[i].tabId == tabId)
		{
			tab = g_Tabs[i];
			break;
		}
	}
	
	if(tab == null)
	{
		return;
	}
	
	if((curTree != null) && (curTree != tab.tree))
	{
		document.getElementById(curTree.setting.treeId).style.display = "none";
	}
	
	if(tab.tree != null)
	{
		curTree = tab.tree;
		// show tree
		document.getElementById("main").style.width = "794px";
		document.getElementById("breadCrumbs").style.width = "794px";
		document.getElementById("tree-frame").style.display = "";
		document.getElementById("open").style.display = "none";
		
		document.getElementById(curTree.setting.treeId).style.display = ""
		
		if(language == 0)
		{
			displayTreeList();
		}
		else
		{
			displayTreeListCn();
		}
		
		if(imageClickFlag >= 1)
		{
			selectNode = curTree.getNodeByParam("id", imageClickFlag);
			//curTree.expandAll(false);
			//curTree.refresh();
			curTree.selectNode(selectNode, false);
			imageClickFlag = 0;
		}
		
		if(curTree.getSelectedNodes()[0] == null)
		{
			if(curTree.setting.treeId == "Scramb")
			{
				selectNode = curTree.getNodeByParam("id", 117);
			}
			else if(curTree.setting.treeId == "Monitor")
			{
				selectNode = curTree.getNodeByParam("id", 1);
			}
			else
			{
				selectNode = curTree.getNodeByParam("id", 1);
			}
			curTree.selectNode(selectNode, false);
		}
		self.frames[0].location.replace(curTree.getSelectedNodes()[0].url);
		getBreadCrumbs(curTree.setting.treeId, curTree.getSelectedNodes()[0]);
	}
	else
	{
		// hide tree
		document.getElementById("main").style.width = "1010px";
		document.getElementById("breadCrumbs").style.width = "1010px";
		document.getElementById("tree-frame").style.display = "none";
		document.getElementById("open").style.display = "none";
		self.frames[0].location.replace(tab.href);
		//main.window.location.replace(tab.href);
		curTree = null;
		if(language == 0)
		{
			document.getElementById("breadCrumbsText").innerHTML = " > Summary";
		}
		else
		{
			document.getElementById("breadCrumbsText").innerHTML = " > 概要";
		}
	}
}

function onChangeTab(id)
{
	if(oldTab == id)
	{
		return;
	}
	document.getElementById(oldTab).className = "";
	document.getElementById(id).className = "menu_select";
	setsrc(id);
	oldTab = id;
}

window.onload = function()
{
	SysInReboot = 0;
	var reboot = document.getElementById("reboot");
	adminDisplay(group, reboot);
	startConnectionMonitor();
	var language = document.getElementById("language").value;
	
	if(deviceAttr == 1)
	{
		document.getElementById("menu-summary").style.display = "none";
	}
	var args = getArgs();
	var nodeId = args["nodeId"];
	if(nodeId == null)
	{
	//C518
		if(deviceAttr == 1)
		{
			onChangeTab("menu-monitor");
		}
		else
		{
			if(language == 0)
			{
				self.frames["main"].location.replace("../asp/summary.asp");
			}
			else
			{
				self.frames["main"].location.replace("../asp/summary_cn.asp");
			}
		}
	}
}

function mouseOver(id)
{
	if(document.getElementById(id).className != "menu_select")
	{
		document.getElementById(id).className = "menu_mouseover";
	}
}

function mouseOut(id)
{
	if(document.getElementById(id).className == "menu_mouseover")
	{
		document.getElementById(id).className = "";
	}
}

function Reboot(isConfirmRequired)
{
	var language = document.getElementById("language").value;
	var xmlhttp = false;
	var params = "type=0&cmd=2&reboot=1&userName=" + userName;
	
	if(gRebootEnable == false)
	{
		return;
	}

	
	var confirmResult;

	if(1 == isConfirmRequired)
	{
		confirmResult = true;
	}
	else
	{
		if(language == 0)
		{
			confirmResult = confirm("All Services will be interrupted. All unsaved configuration and connection to the QAM will be lost.\r\nProceed?");
		}
		else
		{
			confirmResult = confirm("所有服务将被中断，一切未保存的操作和连接将会丢失，确定重启系统吗？");
		}
	}

	if(true == confirmResult)
	{

		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)
			{
				if(xmlhttp.responseText.match("RebootAllowed"))
				{
					if(1 == isConfirmRequired)// reboot called from restore factory defaults
					{
					}
					else // to change UI locktype to reboot
					{
						SysInReboot = 1;
						lockType = REBOOTLOCK;
						LockUI(lockType);
					}
				}
				else
				{
					if(language == 0)
					{
						alert("Reboot operation is not allowed. Some other critical operation is in progress.");
					}
					else
					{
						alert("系统重启失败，其他重要操作正在进行中。");
					}
				}
			}
		}
		xmlhttp.send(params);
	}
	else 
	{
		return false;
	}
}

function openHelp()
{
	window.open("/fs/about.html","","width=760,height=480,scrollbars=yes,resizable=yes");
}

function setSysName(sysName)
{
	var sn = "";
	if(sysName.length > MAX_SYS_NAME)
	{
		var sn = sysName.slice(0, (MAX_SYS_NAME - 3));
		sn += "...";
	}
	else
	{
		sn = sysName;
	}
	document.getElementById("sysName").innerHTML = sn;
}

function refreshPage()
{
	if(curTree == null)
	{
		top.frames["main"].location.reload(true);
	}
	else
	{
		self.frames[0].location.replace(curTree.getSelectedNodes()[0].url);
	}
}

function RebootEnable()
{
	gRebootEnable = true;
	document.body.style.cursor='auto';
	document.getElementById("rebootfont").style.color='black';
	document.getElementById('rebootfont').style.cursor = '';
}


function RebootDisable()
{
	gRebootEnable = false;
	document.body.style.cursor = 'wait';
	document.getElementById("rebootfont").style.color='gray';
	document.getElementById('rebootfont').style.cursor = 'default';
}


var NOLOCK = 0;
var REBOOTLOCK = 1;
var BACKUPLOCK = 2;
var RESTORELOCK = 3;
var FACTORYLOCK = 4;
var SYNCPARAMLOCK = 5;
var CONNECTIONLOCK = 6;
var disconnected = 0;

function LockUI(lock)
{
	var language = document.getElementById("language").value;
	var option = {
		close:false,
		opacity:60
	};
	
	if(lock == REBOOTLOCK)
	{
		$("#RebootLock").modal(option);
	}	
	else if(lock == BACKUPLOCK)
	{		
		$("#BackupLock").modal(option);
	}
	else if(lock == RESTORELOCK)
	{
		$("#RestoreLock").modal(option);
	}
	else if(lock == FACTORYLOCK)
	{
		$("#FactoryLock").modal(option);
	}
	else if(lock == SYNCPARAMLOCK)
	{
		$("#SyncParamLock").modal(option);
	}
	else if(lock == CONNECTIONLOCK)
	{
		if(curTree == null)
		{
			/*
			var frameUrl = frames["main"].location.href;
			var frameArr = frameUrl.split("/");
			var len = frameArr.length;
			var frameName = frameArr [len - 1];
	
			if(frameName == "summary_ie6.asp")
			{
				if((frames["main"].document.getElementById("MP_1") != null) && 
				(frames["main"].document.getElementById("MP_2") != null) && 
				(frames["main"].document.getElementById("MP_3") != null) &&
				(frames["main"].document.getElementById("MP_4") != null))
				{
					frames["main"].document.getElementById("MP_1").style.display = "none";
					frames["main"].document.getElementById("MP_2").style.display = "none";
					frames["main"].document.getElementById("MP_3").style.display = "";
					frames["main"].document.getElementById("MP_4").style.display = "none";
					frames["main"].document.getElementById("MP_3").title = "Management Port - Down";
				}
			}
			*/
			//else if(frameName == "summary.asp")
			//{
			if (frames["main"].document.getElementById("MP") != null)
			{
				frames["main"].document.getElementById("MP").src = "../images/Inter_Red_Left.png";
				if(language == 0)
				{
					frames["main"].document.getElementById("MP").title = "Management Port - Down";
				}
				else
				{
					frames["main"].document.getElementById("MP").title = "控制口 - 未连接";
				}
			}
			//}
		}
		if(language == 0)
		{
			document.getElementById("qam-status-text").innerHTML = "Unconnect";
		}
		else
		{
			document.getElementById("qam-status-text").innerHTML = "未连接";
		}
		
		$("#UILock").modal(option);
	}
}

function UnlockUI(unlock)
{
	var language = document.getElementById("language").value;
	if(disconnected == 1)
	{
		disconnected = 0;
		refreshPage();
	}
		
	if(unlock == CONNECTIONLOCK)
	{
		if(curTree == null)
		{
			/*
			var frameUrl = frames["main"].location.href;
			var frameArr = frameUrl.split("/");
			var len = frameArr.length;
			var frameName = frameArr [len - 1];
			
			if(frameName == "summary_ie6.asp")
			{
				if((frames["main"].document.getElementById("MP_1") != null) && 
				(frames["main"].document.getElementById("MP_2") != null) && 
				(frames["main"].document.getElementById("MP_3") != null) &&
				(frames["main"].document.getElementById("MP_4") != null))
				{
					frames["main"].document.getElementById("MP_1").style.display = "none";
					frames["main"].document.getElementById("MP_2").style.display = "";
					frames["main"].document.getElementById("MP_3").style.display = "none";
					frames["main"].document.getElementById("MP_4").style.display = "none";
					frames["main"].document.getElementById("MP_2").title = "Management Port - Up";
				}
			}
			*/
			//else if(frameName == "summary.asp")
			//{
			if (frames["main"].document.getElementById("MP") != null)
			{
				frames["main"].document.getElementById("MP").src = "../images/Inter_Green_Left.png";
				if(language == 0)
				{
					frames["main"].document.getElementById("MP").title = "Management Port - Up";
				}
				else
				{
					frames["main"].document.getElementById("MP").title = "控制口 - 已连接";
				}
			}
			//}
		}
	}
	$.modal.close(); 

}

function changeLock(lock)
{
	if(lockType != NOLOCK)
	{
		UnlockUI(lockType);
	}
	lockType = lock;
	LockUI(lockType);
}

function disconnect()
{
	// If none of the objects are free - all the objects are waiting for reply - qam is unreachable
	abortStatusRequests();
	if(SysInReboot) // connection lost due to reboot
	{
		if(lockType != REBOOTLOCK)
		{
			changeLock(REBOOTLOCK);
		}
	}
	else
	{
		if(lockType != CONNECTIONLOCK)
		{
			changeLock(CONNECTIONLOCK);
		}
	}
}


var TIMEOUT = 5;
var xmlhttp_objects = new Array(); // Array of TIMEOUT objects

function queryQAMStatus()
{
	// Link Loss Detection = TIMEOUT seconds; Link Up Detection = 1s + n/w roundtrip delay

	// Send out a status request through one of the available objects
	var i = 0;
	for(i = 0; i < TIMEOUT; i++)
	{
		var xmlhttpobj = xmlhttp_objects[i];
		var params = "type=0&cmd=1&ID=" + i + "&ran=" + Math.random();

		if((xmlhttpobj.readyState == 0) || (xmlhttpobj.readyState == 4))
		{
			// This object is in UNSENT state (or) the response is processed
			xmlhttpobj.open("GET", "/goform/formIPQAM?" + params, true);
			setReadyStateChange(i);
			xmlhttpobj.send(null);
			break;
		}
	}
	if(i == TIMEOUT)
	{
		disconnect();
	}
}

// Utility Function to parse the value of the given name, from a name-value pair (name1=val1&name2=val2...)
function getValue(string, name)
{
	var startPos = string.indexOf(name + "=");
	if(startPos > -1)
	{
		startPos = startPos + name.length + 1;
		var endPos = string.indexOf("&",startPos);
		if(endPos == -1)
		{
			endPos = string.length;
		}
	return unescape(string.substring(startPos,endPos));
	}
	return "";
}


var lockType = NOLOCK;

function processQAMState(i)
{
	var language = document.getElementById("language").value;
	var obj = xmlhttp_objects[i];
	var newLockType;
	if(obj.readyState == 4)
	{
		if(obj.responseText.length != 0)
		{
			// QAM connection alive
			if(lockType == CONNECTIONLOCK)
			{
				UnlockUI(CONNECTIONLOCK);
				lockType = NOLOCK;
			}
			
			var data = obj.responseText.slice(7, -8);
			
			document.getElementById("qam-status-text").innerHTML = getValue(data, "time");

			var timeArray = getValue(data, "time").split(":");	
			document.getElementById("CurrentTimeHour").value = timeArray[0];
			document.getElementById("CurrentTimeMinute").value = timeArray[1];
			document.getElementById("CurrentTimeSecond").value = timeArray[2];	
			
			if(deviceAttr == 0)
			{
				var webSimulId = parseInt(getValue(data, "webSimulId"));
				if(systemId != webSimulId)
				{
					if(language == 0)
					{
						if(confirm("Card stauts is changed, will you reload the tree?\r\nIf you choose 'yes', the page will jump to summary page.") == true)
						{
							self.location.reload(true);
						}
					}
					else
					{
						if(confirm("卡状态发生改变，是否重新加载树？\r\n选择“确定”，页面自动跳转到概要页面。") == true)
						{
							self.location.reload(true);
						}
					}
				}
			}
			var newLock = getValue(data, "LockValue");
			
			if(newLock != "")
			{
				if(newLock == "00000")
				{
					if(lockType != NOLOCK)
					{
						UnlockUI(lockType);
						lockType = NOLOCK;
					}
				}
				else
				{
					var len = newLock.length;
					for(var i = 0; i < len; i++)
					{
						if(newLock.charAt(i) != "0")
						{
							newLockType = len - i;
							break;
						}
					}
					if(newLockType != lockType)
					{
						changeLock(newLockType);
						
					}//if(newLockType != lockType)
				
				}//else
				
			}//if(newLock != "")
			
		}//if(obj.responseText.length != 0)
		else
		{
			// QAM connection failure
			disconnect();
		}
	}//if(obj.readyState == 4)
}

function setReadyStateChange(i)
{
/*
	xmlhttp_objects[i].onreadystatechange = function ()
	{
		processQAMState(i);
	}
	*/
	if(i == 0)
	{
		xmlhttp_objects[i].onreadystatechange = function ()
		{
			processQAMState(0);
		}
	}
	else if(i == 1)
	{
		xmlhttp_objects[i].onreadystatechange = function ()
		{
			processQAMState(1);
		}
	}
	else if(i == 2)
	{
		xmlhttp_objects[i].onreadystatechange = function ()
		{
			processQAMState(2);
		}
	}
	else if(i == 3)
	{
		xmlhttp_objects[i].onreadystatechange = function ()
		{
			processQAMState(3);
		}
	}
	else if(i == 4)
	{
		xmlhttp_objects[i].onreadystatechange = function ()
		{
			processQAMState(4);
		}
	}
}

function startConnectionMonitor()
{
	for(var i = 0; i < TIMEOUT; i++)
	{
		xmlhttp_objects[i] = getHTTPObject();
	}
	queryQAMStatus();
	setInterval(function(){updateClockLocal()}, 1000);
}

function abortStatusRequests()
{
	for(var i = 0; i < TIMEOUT; i++)
	{
		xmlhttp_objects[i].abort();
	}
}

var interval = 0;
function updateClockLocal()
{
	var tmpSec = "";
	var tmpMin = "";
	var tmpHrs = "";
	
	interval++;
	if(interval == 5)
	{
		queryQAMStatus();
		interval = 0;
	}
	var nTimeSec = document.getElementById("CurrentTimeSecond").value;
    var nTimeMin = document.getElementById("CurrentTimeMinute").value;
    var nTimeHrs = document.getElementById("CurrentTimeHour").value;


    if((++nTimeSec) == 60)
    {
        nTimeSec = 0;
        if((++nTimeMin) == 60)
        {
            nTimeMin = 0;
            if((++nTimeHrs) == 24)
            {
                nTimeHrs = 0;
				//Get the new day information from the board on midnight
				queryQAMStatus(); 
			}
        }
    }

    if(parseInt(nTimeSec,10) < 10)
	{
    	tmpSec = "0" + (parseInt(nTimeSec,10)); //*10) / 10;
	}
    else
	{
    	tmpSec = nTimeSec;
	}
    if(parseInt(nTimeMin,10) < 10)
	{
    	tmpMin = "0" + (parseInt(nTimeMin,10)); //*10) / 10;
	}
    else
	{
    	tmpMin = nTimeMin;
	}
    if(parseInt(nTimeHrs,10) < 10)
	{
    	tmpHrs = "0" + (parseInt(nTimeHrs,10)); //*10) / 10;
	}
	else
	{
		tmpHrs = nTimeHrs;
	}
	
	if(lockType != CONNECTIONLOCK)
	{
		document.getElementById("qam-status-text").innerHTML =  tmpHrs + ":" + tmpMin + ":" + tmpSec;
	}
    document.getElementById("CurrentTimeSecond").value = nTimeSec;
    document.getElementById("CurrentTimeMinute").value = nTimeMin;
    document.getElementById("CurrentTimeHour").value = nTimeHrs;
	
}
