<!-- Copyright (c) 2004, 2006-2008, 2012-2013 by Cisco Systems, Inc. -->
// Parsing code for 3750, 2970, 3560

/* 
 * Used to determine the software upgrade stages. Stages will be 
 * displayed below the 'instructions' table. Appropriate error message   
 * will be displayed if there is any error message. 
 */
var contents = "";
var agt=navigator.userAgent.toLowerCase();
var isff1_5 = (agt.indexOf("firefox/1.5")!=-1) ? true : false;
var startingtime;

function getStreamedOutput(archiveStatus)
{
	//var str 	= "";
	str 		= parent.result.document.body.innerHTML;			// Get the result frame content.
	contents	= parent.result.document.body.innerHTML;
	
	//var date = new Date();
	//startingtime  = date.getTime();
	
	var sizeStr;
	//extract the text without <pre> </pre> tags in IE alone
	if ( isff1_5 )
		currContent = str;				
	else
		currContent = str.substring(5,str.length-6);
	if(currContent.indexOf("BODY") != -1)
		currContent = "";
	diff = getDifference(prevContent, currContent);  		// Get the difference (or) Get the new output. 
	
	
	currStage = getStage(diff, archiveStatus); 		
	if(currStage != prevStage)									// If there is any change of stage, activate the stage.
	{
		displayStage(currStage);			
	}
	
	if(currStage == 2)
	{
		setProgress("percentageDiv",percentage,"content1","content2");
	}
	else if (currStage == 3 )    					 			
	{
		isReloadMsgArrived = true;
	}
		
	/*if(!isStackable && currStage == 3)							// For extracting stage, show the progress bar.
		{	
			size  = getTotalFileSize(diff);							// Get the total file size extracted.
			var date = new Date();
			var currTime = date.getTime();
			currPercentage = (totalExtractedBytes/totalSize) * 100;
			currPercentage = Math.round(currPercentage);
			var elapsedTime = currTime - startTime;
			if(currPercentage > 0) {
				timerInterval = (elapsedTime / currPercentage);
				timerInterval = Math.round(timerInterval);
			}

			totalExtractedBytes  += size;
			currPercentage = (totalExtractedBytes/totalSize) * 100;
			currPercentage = Math.round(currPercentage);
			if(currPercentage >= 100)		
					currPercentage = 100;
			if(currPercentage > prevPercentage)	
			{			
			//window.status = "Devices : " + totalDevices + " , Pre % : " + prevPercentage + " , curr % : " + currPercentage + " , Timer : " + timerInterval;
				startProgress(prevPercentage, currPercentage, timerInterval);	// Show the progress bar.
			}	
			prevPercentage = currPercentage; 
		}
		
		//  If it is reloading state, stop polling and activate the checkReload function after 1 min.
		else if (currStage == 4 )    					 			
		{
			isReloadMsgArrived = true;
			startProgress(currPercentage,100, timerInterval);									// Complete the progress
	}*/
		
	if(anyErrorHappened(archiveStatus) || anyErrorHappened(diff))									// Check for Any errors.
	{
	
			stopPolling();
			isUpgrading = false;
			enableMenu();
			errMsg = getErrorMessage(archiveStatus, diff);							// Get the corresponding error message.
			if(currStage == -1 || currStage == 1)  //  (currStage == -1) is handle the error state, In case of loadding very small file
		 	{	
				unHighlight("load", re_swUpg_Txt_Stage1, false);
				unHighlight("verify", re_swUpg_Txt_Stage2, true);
				
			}
			else if(currStage == 2)
			{
				set_layercontent("extractDivSymbol","&nbsp;");
				set_layercontent("extractDivStage", "<span class=content>" + re_swUpg_Txt_Stage3 + "</span>");					
				stopProgress();
//				document.getElementById("progressBarDiv").style.border = "0px";
				document.getElementById("progressBarDiv").style.display = 'none';
				document.getElementById("progressBarDiv_ok").style.display = 'none';
				document.getElementById("progressBarDiv_err").style.display = 'block';
			}
			if(isMixedStack && numberOfUpgrades == 1) {
				errMsg = errMsg + "<br>" + re_swUpg_Txt_PartialUpgrade;
			}
			showMsgBottomTable(errMsg,"contentred");								// Show the error message.			
			return;
	}
	
	prevStage = currStage;
	prevContent	 = currContent;
	if(currStage == 3 && !isUpgradeOver && numberOfUpgrades > 0)
	{
		notifyFrameLoadStatus("secondUpgrade", "true");
		numberOfUpgrades--;
	}
	else if(currStage != 3 && isUpgrading == true)
	{
		//skip the page reload, when this update triggered from checkTimeElapsedStatus() 
		if(archiveStatus != ""  && archiveStatus.indexOf("IDLE:") == -1)
			id = setTimeout("checkArchiveStatus()",15000);		
		
		setTimeout("checkTimeElapsedStatus()",5000);
	}
}



/**
 *  checkArchiveStatus 
 *  This method will load the "softwareupgradestatus.shtml" file in result1 frame, 
 *	After load completed it will pass the show archive status  output to getStreamedOutput method  
 */
function checkArchiveStatus()
{
	parent.result1.location.href  = "softwareupgradestatus.shtml";
}


/**
 *  checkTimeElapsedStatus 
 *  Every 5 sec only  DM will check the sh archive status,
 *	So there is the change device will goto reload mode,  
 *  So this methode will help to update the webpage stage, even the devices goto reload mode.
 */
function checkTimeElapsedStatus()
{
	if(currStage != 3 && isUpgrading == true)
	{
		getStreamedOutput('');
	}
}



/* 
 * Used to get the current stage. Stages are represented using
 * numbers. Reloading=3;Extracting=2;verifying&loading=1;
 */
function getStage(diff, archiveStatus)
{
	var state = -1;
	
	if(diff != "" && diff.indexOf("ERROR") == -1)
	{
		if(diff.indexOf("reload in progress") != -1 || diff.indexOf("Extracting images from archive into flash completed") != -1)								// Search for Reload stage string.		
		{	
			state = 3;
			numberOfUpgrades--;
			if(numberOfUpgrades < 1)
				isUpgradeOver = true;
		}	
		else if(diff.indexOf("All software images installed") != -1)
		{
			state = 3;
			numberOfUpgrades--;
			if(numberOfUpgrades < 1)
				isUpgradeOver = true;
		}
	}
	else if(archiveStatus != "" && archiveStatus.indexOf("IDLE") == -1)
	{
		var totalFileSize = 31457280; // default size
		var downloadSize  = 0; 
		var sizeStr = "";
		if(archiveStatus.indexOf("Image Size Downloaded:") != -1)
		{
			sizeStr = grep_string("Image Size Downloaded:", archiveStatus);	
			sizeStr =  sizeStr.replace("Image Size Downloaded:", "");
			downloadSize = parseInt(trim_string(sizeStr)) ;
		}
		if(downloadSize == 0)
		{
			state = 1;
		}
		else if(downloadSize > 0)
		{
		  state = 2;
		  if(downloadSize >= totalFileSize)
		  {
			totalFileSize = downloadSize + 5242880; //( increasing totalsize ino 5 mb )
		  }
		  percentage = Math.ceil((downloadSize/totalFileSize) * 100);
		  percentage = parseInt(percentage);
		}
		else if(downloadSize >= totalFileSize)
		{
		  state = 3;		  		
		}
		
		//setProgress("percentageDiv",percentage,"content1","content2");
	}
	
	/* else if(isStackable && (diff.indexOf("will be removed after download") != -1 || diff.indexOf("will be removed before download") != -1 || diff.indexOf("will be deleted after download") != -1 || diff.indexOf("will be deleted before download") != -1)) {
		state = 3;			
		setStartTime();
	}
	else if(diff.indexOf("examining image") != -1 || diff.indexOf("Total Image File Size:") != -1)
	{
		state = 2;
		
		startIndex = diff.indexOf("Total Image File Size:"); 
		if(startIndex != -1)
		{
			//workaround added since \n character is not seen in firefox1.5
			if ( isff1_5)
				stopInd = startIndex+33;
			else
				stopInd = diff.indexOf("\n",startIndex );
			tot_size = diff.substring(startIndex+22,stopInd);
			totalSize = parseInt(tot_size,16);
			totalSize *= totalDevices;
		}
		
		if(diff.indexOf("Extracting images from archive") != -1)				// Check for intersection of two stages.
		{
			state = 3;			
			setStartTime();
		}
	}
	else if(diff.indexOf("Extracting images from archive") != -1)
	{
		state = 3;
		setStartTime();
	}
	if(state == -1)				
		state = currStage;	 */	
	//alert("state = "+state+"\n downloadSize = "+downloadSize+ "\n  diff = "+diff+"\n archiveStatus = "+archiveStatus);
	return state;
}
