<!-- Copyright (c) 2005-2006 by Cisco Systems, Inc. -->

/*
 *------------------------------------------------------------------
 * alerts.js
 *
 * JS file to parse show alert counters CLI output
 *
 * requires sitewide.js
 *------------------------------------------------------------------
*/

var ENTITY = 0;
var SEVERITY = 1;
var TIME_STAMP = 2;
var DESCRIPTION = 3;


var monthsArr = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

function parseAlertsData(cliOutput) {
	var cliArr = split("\n", cliOutput);
	var interfaceName = "";
	var errorsArr = new Array();
	for(var i=0; i<cliArr.length-1;i++) {
		if(cliArr[i].indexOf("Interface: ") == 0) {
			interfaceName = trim_string(cliArr[i]).replace("Interface:", "Port");
			continue;
		}
		else if(cliArr[i] == null || cliArr[i] == "" || split(" ", cliArr[i]).length < 2) { //empty line
			continue;
		}else if(trim_string(cliArr[i]).indexOf("Global Errors :")==0){
		          interfaceName="";continue;
		}
		else {
		    var tempArr=cliArr[i];
         	errorsArr[errorsArr.length] = new Object();
			errorsArr[errorsArr.length-1].entity = (interfaceName == null || interfaceName == "") ? "" : interfaceName;
			errorsArr[errorsArr.length-1].severity = split("-",tempArr)[1];
			var errorCode=split(":",tempArr)[1];
			errorsArr[errorsArr.length-1].errorcode=trim_string(errorCode);
			errorsArr[errorsArr.length-1].description =trim_string(errorCode);
			var temp_dateString = trim_string(split(":",cliArr[i+1])[1]);
			var dateString=split(" ",temp_dateString);
			errorsArr[errorsArr.length-1].timeStamp = monthsArr[parseInt(dateString[1], 10)-1] + " " + dateString[2] + ", " + dateString[0] + " " + dateString[3] + ":" + dateString[4] + ":" + dateString[5];
			errorsArr[errorsArr.length-1].index = errorsArr.length-1;
		    i = i + 3;
		}
	}
	return errorsArr;
}

function getLastAlert(errorsArr) {
	if(errorsArr.length >= 1) {
		errorsArr.sort(	function by_name(a,b) {
								if (Date.parse(a.timeStamp) < Date.parse(b.timeStamp)) { return -1; }
								if (Date.parse(a.timeStamp) > Date.parse(b.timeStamp)) { return 1; }
								if(Date.parse(a.timeStamp) == Date.parse(b.timeStamp) ) {
									if(a.index < b.index) { return -1; }
									if(a.index > b.index) { return 1; }
								}
								return 0;
							}
						);
	 	var temp = errorsArr[errorsArr.length-1];
		var entity = (temp.entity == "") ? " " : temp.entity + ": ";
		return entity + "##" + temp.severity + "##" + temp.timeStamp + "##"+ temp.errorcode;
	}
	else {
		return "No Alerts";
	}
}

