var objectIdArray = ["inputPid", "outputPid", "serviceName", "inputPattern", "inputBitrate", "outputBitrate", "curCompressionRatio", "averCompressionRatio"];
var COL_NUM = 8;
var IN_BITRATE = 4;
var OUT_BITRATE = 5;
var inBitrateArray = [];
var outBitrateArray = [];
//var colorList = ["red", "green", "blue", "magenta", "yellow", "chocolate", "black", "aquamarine", "brown", "perpule"];
var colorList =  ['#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', 
   '#492970', '#f28f43', '#77a1e5', '#c42525', '#a6c96a','#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', 
   '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1']
var timeId;
var inTimeId;
var outTimeId;
var monitorAction = false;
var tableShowFlag = true;
var showList = ["Show List>>", "显示列表>>"];
var pickUpList = ["Pick Up List<<", "收起列表<<"];
var startString = ["Start Monitor", "开始监控"];
var stopString = ["Stop Monitor", "停止监控"];
var maxValue;
var statMuxBitrate;
var firstUpdateFlag = false;
var noProgFlag = false;
var oldProgNum;
var charText = [["Input Bitrate", "输入码率"], ["Output Bitrate","输出码率"], ["Bitrate (Mbps)", "码率(Mbps)"]];
window.onresize = function()
{
	GetMainContentHeight(BUTTON_TOP_MENU, NO_BUTTON_CHANGE);
}

$(document).ready(function()
{
	var args = GetArgs();
	slotNo = parseInt(args["slotNo"], 10);
	//portNo = parseInt(args["portNo"], 10);
	maxValue = parseInt($("#maxBitrate").val(), 10);
	GetMainContentHeight(BUTTON_TOP_MENU, NO_BUTTON_CHANGE);
	funcUpdateDisplay();
	$("#expandBtn").click(function()
	{
		if(tableShowFlag == true)
		{
			$("#dataTable").css("display", "none");
			tableShowFlag = false;
			$(this).val(showList[language]);
		}
		else
		{
			$("#dataTable").css("display", "");
			tableShowFlag = true;
			$(this).val(pickUpList[language]);
		}
	});	
});

function funcUpdateDisplay()
{
	PageLoadStatus(true);
	
	displayParam();
	
	ResetColor();
	PageLoadStatus(false);
}

function displayParam()
{
	var data;
	var secondData;
	var length;
	var response;
	var xmlHttp = GetHTTPObject();
	
xmlHttp.open("GET", "/goform/formEMR30?type=" + CARD_STATISTIC + "&cmd=" + GET + 
		"&language=" + language + "&slotNo=" + slotNo + "&stamuxGroup=" + $("#statmuxGroup").val() + "&ran=" + Math.random(), true);
	xmlHttp.onreadystatechange = function()
	{
		if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
		{
			response = AjaxStrDeal(xmlHttp.responseText);
			if(response == "")
			{
				progNum = 0;
			}
			else
			{
				data = response.split(FIRST_DELIMITER);
				progNum = data.length - 1;
				statMuxBitrate = parseInt(data[progNum], 10);	
				if(firstUpdateFlag == false)
				{
					oldProgNum = progNum;
					maxValue = (parseInt(statMuxBitrate/8000000) + 3)*8000000;
					$("#maxBitrate").val(maxValue);
				}
			}
			DrawTableRow("dataTable", "progDataRow", "progCaseRow", progNum);
			if(progNum != 0)
			{
				if(noProgFlag == true) //上次刷新的节目数为0,这次不为0
				{
					oldProgNum = progNum;
					window.clearInterval(timeId);
					EnableButton("monitorControlBtn");
					noProgFlag = false;
					monitorControl();
				}
				else if(oldProgNum != progNum) //the prog num changed
				{
					window.clearInterval(timeId);	
					monitorAction = false; //stop monitor(don't change button text)
					monitorControl(); //start monitor
					oldProgNum = progNum;
				}
				updateTableData(data);				
			}
			else
			{
				if(noProgFlag == false)
				{
					oldProgNum = progNum;
					DisableButton("monitorControlBtn");
					noProgFlag = true;
					$("#monitorControlBtn").val(startString[language]);
					monitorAction = false;
				}
			}
			refreshFlag = true;  //刷新标识符设为true表示刷新成功
		}
	}
	xmlHttp.send(null);
}

function updateTableData(data)
{
	var secondData;
	var progData;
	var pidData;
	inBitrateArray = [];
	outBitrateArray = [];
	for(var i = 0; i < progNum; i++)
	{
		secondData = data[i].split(SECOND_DELIMITER);
		for(var j = 0; j < COL_NUM; j++)
		{
			$("#index" + (i + 1)).parent().css("background-color", colorList[i]);
			if(firstUpdateFlag == true)
			{	
				if(j == IN_BITRATE)
				{
					if(i == 0)
					{
						inBitrateArray.push(secondData[j]);
					}
					else
					{
						inBitrateArray.push(Number(secondData[j]) + Number(inBitrateArray[i - 1]));
					}
					$("#" + objectIdArray[j] + (i + 1)).html((secondData[j]/1000000).toFixed(6));
				}
				else if(j == OUT_BITRATE)
				{
					if(i == 0)
					{
						outBitrateArray.push(secondData[j]);
					}
					else
					{
						outBitrateArray.push(Number(secondData[j]) + Number(outBitrateArray[i - 1]));
					}
					$("#" + objectIdArray[j] + (i + 1)).html((secondData[j]/1000000).toFixed(6));
				}
				else
				{
					$("#" + objectIdArray[j] + (i + 1)).html(secondData[j]);
				}
			}
			else
			{
				if(j < IN_BITRATE)
				{
					$("#" + objectIdArray[j] + (i + 1)).html(secondData[j]);
				}
				else
				{
					$("#" + objectIdArray[j] + (i + 1)).html("--");
				}
			}
		}
	}
	if(firstUpdateFlag == true)
	{
		var chart1 = $("#inContainer").highcharts();
		var chart2 = $("#outContainer").highcharts();
		var series;
		var x;
		var y;	
		for(var i = 0; i < progNum; i++)
		{
			series = chart1.series[i];
			x = (new Date()).getTime();
			y = parseInt(inBitrateArray[i], 10);
			series.addPoint([x, y], true, true);
			series = chart2.series[i];
			x = (new Date()).getTime();
			y =  parseInt(outBitrateArray[i], 10);
			series.addPoint([x, y], true, true);
		}
		series = chart2.series[progNum];
		x = (new Date()).getTime();
		y = statMuxBitrate;
		series.addPoint([x, y], true, true);
	}
	if(firstUpdateFlag == false)
	{
		firstUpdateFlag = true;
	}
}
function changeY()
{
	var chart1 = $("#inContainer").highcharts();
	var chart2 = $("#outContainer").highcharts();
	maxValue = parseInt($("#maxBitrate").val(), 10);
	chart1.yAxis[0].update({max: maxValue, tickInterval: maxValue/8});
	chart2.yAxis[0].update({max: maxValue, tickInterval: maxValue/8});
}
function monitorControl()
{
	if(monitorAction == false)
	{
		$("#monitorControlBtn").val(stopString[language]);
		getInStatus();
		getOutStatus();	
		displayParam();
		timeId = setInterval("displayParam();", 2000);
		if($("#graghDiv").css("display") == "none")
		{
			$("#graghDiv").css("display", "");
		}
		monitorAction = true;
		
	}
	else
	{
		$("#monitorControlBtn").val(startString[language]);
		window.clearInterval(timeId);	
		monitorAction = false;
	}
}

function getInStatus()
{
	Highcharts.setOptions({
		global: {
			useUTC: false
		}
	});
	var chart;
	$("#inContainer").highcharts({
		colors: colorList,
		chart: {
			type: "spline",
			animation: Highcharts.svg, // don't animate in old IE
			marginRight: 10,
		},
		title: {
			text: charText[0][language]
		},
		credits:
		{
			enabled: false
		},
		xAxis: {
			type: "datetime",
			tickPixelInterval: 150,
			tickWidth: 0,
			labels:
			{
			 	enabled: false
			}
		},
		yAxis: {
			title: {text: charText[2][language] },
			tickInterval: maxValue/8,
		 	min: 0,
			max: maxValue,
			labels: {
                formatter: function () {
                    return this.value/1000000;
                }
			},
			gridLineDashStyle: 'Dot'
		},
		legend: {
			enabled: false
		},
		exporting: {
            buttons: {
                contextButton: {
                    menuItems: null,
                    onclick: function () {
                        this.print();
                    }
                }
            }
        },
		plotOptions: {
				series: {
					lineWidth: 2,
					marker: {
						enabled: false
					},
					shadow: false,
					enableMouseTracking: false
				}
			},
		series: (function() {
			var series = [];
			for(var i = 0; i < progNum; i++)
			{
				series.push({
					data: (function() {
						
						// generate an array of random data
						var data = [];
						time = (new Date()).getTime();
						for (var j = -19; j <= 0; j++)
						{
							data.push({
								x: time + j * 1000,
								y: 0
							});
						}
						return data;
					})()
				});
			}
			return series;
		})()
	});
}

function getOutStatus()
{
	Highcharts.setOptions({
		global: {
			useUTC: false
		}
	});
	var chart;
	$("#outContainer").highcharts({
		colors: colorList,
		chart: {
			type: "spline",
			animation: Highcharts.svg, // don't animate in old IE
			marginRight: 10,
		},
		title: {
			text: charText[1][language]
		},
		credits:
		{
			enabled: false
		},
		xAxis: {
			type: "datetime",
			tickPixelInterval: 150,
			tickWidth: 0,
			labels:
			{
			 	enabled: false
			}
		},
		yAxis: {
			title: {text: charText[2][language] },
			tickInterval: maxValue/8,
		 	min: 0,
			max: maxValue,
			labels: {
                formatter: function () {
                    return this.value/1000000;
                }
			},
			gridLineDashStyle: 'Dot'
		},
		legend: {
			enabled: false
		},
		exporting: {
            buttons: {
                contextButton: {
                    menuItems: null,
                    onclick: function () {
                        this.print();
                    }
                }
            }
        },
		plotOptions: {
				series: {
					lineWidth: 2,
					marker: {
						enabled: false
					},
					shadow: false,
					enableMouseTracking: false
				}
			},
		series: (function() {
			var series = [];
			for(var i = 0; i < progNum; i++)
			{
				series.push({
					data: (function() {
						
						// generate an array of random data
						var data = [];
						time = (new Date()).getTime();
						for (var j = -19; j <= 0; j++)
						{
							data.push({
								x: time + j * 1000,
								y: 0
							});
						}
						return data;
					})()
				});
			}
			series.push({
					data: (function() {
						
						// generate an array of random data
						var data = [];
						time = (new Date()).getTime();
						for (var j = -19; j <= 0; j++)
						{
							data.push({
								x: time + j * 1000,
								y: statMuxBitrate
							});
						}
						return data;
					})()
				});
			return series;
		})()
	});
}