var LOGS_PER_PAGE = 20;

var ALARMS = 1;
var USER_OPERATION = 2;
var SYSTEM_EXCEPTION = 3;
var HARDWARE = 4;

var startTime = "";
var endTime = "";
var type = 0;
var timeout;
var noResponse = 0;
var userName = "";
var language;

function mouseOverLog(obj)
{
	if(obj.disabled == false)
	{
		obj.style.background = "url(../images/btn5_hover.png)";
	}
}
function mouseOutLog(obj)
{
	if(obj.disabled == false)
	{
		obj.style.background = "url(../images/btn5_normal.png)";
	}
}


function mouseOverDeleteApply(obj)
{
	if(obj.disabled == false)
	{
		obj.style.background = "url(../images/btn3_hover.png)";
	}
}
function mouseOutDeleteApply(obj)
{
	if(obj.disabled == false)
	{
		obj.style.background = "url(../images/btn3_normal.png)";
	}
}

function updateStatus()
{
	sessPageNum = parseInt(document.getElementById("currPageNum").value);
	sessTotPage = parseInt(document.getElementById("sessTotPages").value);
	if (sessTotPage <= sessPageNum)
	{
		if(language == 0)
		{
			str = "Displaying page " + sessTotPage + " of " + sessTotPage;
		}
		else
		{
			str = "第" + sessTotPage + "页，共" + sessTotPage + "页";
		}
	}
	else
	{
		if(language == 0)
		{
			str = "Displaying page " + sessPageNum + " of " + sessTotPage;
		}
		else
		{
			str = "第" + sessPageNum + "页，共" + sessTotPage + "页";
		}
	}
	
	document.getElementById("statusField").innerHTML = str;
}

function disableControls(flag)
{
	disabledButton(document.getElementById("prev"), flag);
	disabledButton(document.getElementById("next"), flag);
	disabledButton(document.getElementById("last"), flag);
}

/*
	This function dynamically updates the given table with given data. 
	If the data is less than the number of rows, remaining rows will be hidden.
	PARAMS:
	1. tableName -> Name of the table to be updated.
	2. numOfHeaderRows -> Number of the header rows which are not MODIFIED during update operation.
	3. pageData -> Data to be updated to TDs
	4. colSep -> Delemiter which separates the data between each cell within the same row.
	5. rowSep -> Delemiter which is used to separate each row.
*/
function updateRows(tableName, numOfHeaderRows, pageData, colSep, rowSep)
{
	var targetTable = document.getElementById(tableName);
	var rowsCount = parseInt(targetTable.rows.length, 10) - numOfHeaderRows;
	var row;
	var child;
	var j;

	var rowData = pageData.split(rowSep);
	var dataAvailRows = rowData.length;

//	alert("rowsCount="+rowsCount);
	for(var i = 0; i < rowsCount; i++)
	{
		row = targetTable.rows[i + numOfHeaderRows];
		child = row.firstChild;

		j = 0;
		
		if(i < dataAvailRows)
		{
			var colData = rowData[i].split(colSep);

			while(child != null)
			{
			// This if condition is must. This will filter only TD elements from the html text where table is defined.
				if(child.nodeType == 1) 
				{
					if(j == 1)
					{
						switch(parseInt(colData[j]) + 1)
						{
							case ALARMS:
							{
								if(language == 0)
								{
									child.innerHTML = "Alarms";
								}
								else
								{
									child.innerHTML = "告警日志";
								}
								break;
							}
							case USER_OPERATION:
							{
								if(language == 0)
								{
									child.innerHTML = "User Operation";
								}
								else
								{
									child.innerHTML = "用户操作";
								}
								break;
							}
							case SYSTEM_EXCEPTION:
							{
								if(language == 0)
								{
									child.innerHTML = "System Exception";
								}
								else
								{
									child.innerHTML = "系统异常";
								}
								break;
							}
							case HARDWARE:
							{
								if(language == 0)
								{
									child.innerHTML = "Hardware";
								}
								else
								{
									child.innerHTML = "硬件日志";
								}
								break;
							}
							default:
							{
								break;
							}
						}
					}
					else
					{
						child.innerHTML = colData[j];
					}
					child.style.display = "";
					j++;
				}
				child = child.nextSibling;
			}
		}
		else
		{
			while(child!= null)
			{
			// This if condition is must. This will filter only TD elements from the html text where table is defined.
				if(child.nodeType == 1) 
				{
					child.style.display = "none";
					j++;
				}
				child = child.nextSibling;
			}			
		}
		
	}
}

/*
This function hides all the rows in the given table except the table header.
Number of header rows which should not be given through numOfHeaderRows variable.
*/
function hideRows(tableName, numOfHeaderRows)
{
	var targetTable = document.getElementById(tableName);
	var rowsCount = parseInt(targetTable.rows.length, 10) - numOfHeaderRows;
	var row;
	var child;
	var j;

	for (var i = 0; i < rowsCount; i++)
	{
		row = targetTable.rows[i+1];
		child = row.firstChild;

			while (child!= null)
			{
			// This if condition is must. This will filter only TD elements from the html text where table is defined.
				if (child.nodeType == 1) 
				{
					child.style.display = "none";
					j++;
				}
				child = child.nextSibling;
			}			
	}
}

function clearLogs()
{
	hideRows("tableReadLog", 1);
	document.getElementById("currPageNum").value = "1";//当前页数
	document.getElementById("sessTotPages").value = "0";//总页数
	disableControls(true);
	disabledButton(document.getElementById("del"), true);
	updateStatus();
}

function postProcessRequest(responseArr, params)
{
	// if some error when getting pages
	if(responseArr[1] == "0") 
	{
		clearLogs();
		alert(responseArr[0]);
		return;
	}
	
	disabledButton(document.getElementById("del"), false);
	
	if((params=="FIRST") || (params=="LAST"))
	{
		document.getElementById("sessTotPages").value = responseArr[1];
		if(responseArr[1] == "1")
		{
			disableControls(true);
		}
		else
		{
			disableControls(false);
		}
		if(params=="LAST")
		{
			document.getElementById("currPageNum").value = responseArr[1];
			disabledButton(document.getElementById("next"), true);
		}
		else
		{
			disabledButton(document.getElementById("prev"), true);
		}
	}
	else if((params=="PREV") || (params=="NEXT"))
	{
		if(document.getElementById("currPageNum").value == "1")
		{
			disabledButton(document.getElementById("prev"), true);
		}
		else
		{
			disabledButton(document.getElementById("prev"), false);
		}
		
		if(document.getElementById("currPageNum").value == document.getElementById("sessTotPages").value)
		{
			disabledButton(document.getElementById("next"), true);
		}
		else
		{
			disabledButton(document.getElementById("next"), false);
		}
	}
	else if(params == "DEL")
	{
		//If successfully deleted, response will be 1 else 0
		if(responseArr[1] == "1")
		{
			if(responseArr[2] == 0) //If logs is not written for delete operation
			{
				clearLogs();
				alert(responseArr[0]);
			}
			else
			{
				setDefaltValue();
				getFirstSet();
			}
		}
		else //If delete operation is failed, it will get the first page
		{
			setDefaltValue();
			getFirstSet();	
		}
		
		return;
	}

	updateRows("tableReadLog", 1, responseArr[0], ',' , '&');

	updateStatus();
}

function setDefaltValue()
{
	document.getElementById("startTime").value = "";
	startTime = "";
	
	document.getElementById("endTime").value = "";
	endTime = "";
	
	document.getElementById("type").value = 0;
	type = 0;
}

function submitQuery(params)
{
	var response;
	var xmlhttp = getHTTPObject();
	
	queryString = "type=17&cmd=1" +
		"&startTime=" + startTime +
		"&endTime=" + endTime +
		"&logType=" + type + 
		"&currPageNum=" + document.getElementById("currPageNum").value +
		"&mode=" + params +
		"&userName=" + userName + 
		"&language=" + language;


	xmlhttp.open("POST", "/goform/formIPQAM", true);
	if((bd.browser != "IE") && (language == 1))
	{
		xmlhttp.overrideMimeType("text/html;charset=gb2312");
	}
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", queryString.length);

	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4)
		{
			if(noResponse == 1)
			{
				noResponse = 0;
				return;
			}
			
			clearTimeout(timeout);
			$.modal.close();
			document.getElementById("TimeOut").style.display = "none";
			document.getElementById("tableReadLog").style.display = "block";
			
			if((bd.browser == "IE") && (language == 1))
			{
				response = gb2utf8(xmlhttp.responseBody);
				var index = response.indexOf("</html>");
				var bias = response.length - index;
				response = response.slice(7, - bias);
			}
			else
			{
				response = xmlhttp.responseText.slice(7, -8);
			}
			var responseArr = response.split("||");

			postProcessRequest(responseArr, params);			
		}
	}

	xmlhttp.send(queryString);

	return true;
}

function searchLog()
{
	var option = {
		close:false,
		opacity:60
	};
	$("#SerchLock").modal(option);
	
	startTime = document.getElementById("startTime").value;
	endTime = document.getElementById("endTime").value;
	type = document.getElementById("type").value;
	
	getFirstSet();	
	
	disabledButton(document.getElementById("search"), true);
	timeout = setTimeout("changeDisplay()", 10000);
}

function changeDisplay()
{
	$.modal.close();
	document.getElementById("tableReadLog").style.display = "none";
	document.getElementById("TimeOut").style.display = "block";
	noResponse = 1;
}

function enableSearch()
{
	disabledButton(document.getElementById("search"), false);
}

function getFirstSet()
{
	document.getElementById("currPageNum").value = "1";		
	submitQuery("FIRST");
}



/*This function */
function getPrevSet()
{
	var currPageNum = parseInt(document.getElementById("currPageNum").value);
	
	if(currPageNum > 1)
	{
		currPageNum--;
		document.getElementById("currPageNum").value = currPageNum;
		submitQuery("PREV");
	}
}

function getNextSet()
{
	var currPageNum = parseInt(document.getElementById("currPageNum").value);
	var sessTotPages = parseInt(document.getElementById("sessTotPages").value);
	

	if(currPageNum < sessTotPages)
	{
		currPageNum++;
		document.getElementById("currPageNum").value = currPageNum;
		if(currPageNum == sessTotPages)
		{
			// care should be taken in backend if logs are overwritten within the session
		}
		submitQuery("NEXT");
	}
}

function getLastSet()
{
	submitQuery("LAST");
}

function deleteLogs()
{
	if(language == 0)
	{
		if(confirm("This will delete all the logs from QAM. \r\nAre you sure to continue?"))
		{
			submitQuery("DEL");
		}
	}
	else
	{
		if(confirm("将要删除所有的日志。 \r\n需要继续吗？"))
		{
			submitQuery("DEL");
		}
	}
}


window.onload = function()
{
	var del = document.getElementById("del");
	adminDisplay(parent.group, del);
	language = document.getElementById("language").value;
	disabledButton(document.getElementById("search"), true);
	var args = getArgs();
	userName = args["userName"];
	setDefaltValue();
	getFirstSet();	

}
