/*
 * Functions for gracefull AJAX error recovery. Uses jQuery.
 */

//create namespace objects
if( typeof(mtpsip) == "undefined") 
	mtpsip = new Object();
	
if( typeof(mtpsip.er) == "undefined" )
{
	mtpsip.er = new Object();
	mtpsip.er.init = function()
	{
		//create constants
		this.TIMEOUT = 5;
		this.PANEL_ID = "RecoveryPanel";
		this.SW_ID = "RecoveryPanelStopWatch";
		this.SW_INTERVAL = 1000;
		
		//create fields
		this.timeLeft = this.TIMEOUT;
		this.swTimer = null;
	};
	mtpsip.er.init();
}

/**
 * Begins recovery process.
 */
mtpsip.er.beginRecovery = function()
{
	//remove previous stopwatch if any
	this.stopSw();
	
	//display recovery panel
	$("#"+this.SW_ID).html(this.TIMEOUT);
	$("#"+this.PANEL_ID).css("display", "block");
	
	//begin counting to recovery
	this.startSw();
}

/**
 * Forces recovery without waiting for stopwatch to expire.
 */
mtpsip.er.forceRecovery = function()
{
	//stop countdown
	this.stopSw();
	
	//hide recovery panel
	$("#"+this.PANEL_ID).css("display", "none");
	
	//ask server to rerender last valid state
	this.postRecoveryReq();
}

/**
 * Starts stopwatch.
 */
mtpsip.er.startSw = function()
{
	//remove previous timer
	if( this.swTimer != null )
	{
		window.clearTimeout(this.swTimer);
		this.swTimer = null;
	}
	
	//prepare for new countdown
	this.timeLeft = this.TIMEOUT;
	$("#"+this.SW_ID).html(this.timeLeft);
	
	//start timer
	var cb = "mtpsip.er.swProc();";
	this.swTimer = window.setTimeout(cb, this.SW_INTERVAL);
}

/**
 * Stops stopwatch.
 */
mtpsip.er.stopSw = function()
{ 
	//remove timer
	if( this.swTimer != null )
	{
		window.clearTimeout(this.swTimer);
		this.swTimer = null;
	}
}	

/**
 * Stopwatch event handler.
 */
mtpsip.er.swProc = function()
{ 
	//continue countdown if time has not expired
	if( this.timeLeft > 0 )
	{
		this.timeLeft --;
		
		//update countdown visual
		$("#"+this.SW_ID).html(""+this.timeLeft);
	
		//wait until next second expired
		var cb = "mtpsip.er.swProc();";
		this.swTimer = window.setTimeout(cb, this.SW_INTERVAL);
		return;
	}
	
	//countdown expired remove timer
	this.stopSw();
	
	//hide recovery panel
	$("#"+this.PANEL_ID).css("display", "none");
	
	//ask server to rerender last valid state
	this.postRecoveryReq();
}

/**
 * Posts recovery request to server.
 */
mtpsip.er.postRecoveryReq = function()
{
	//NOTE: wait icon ID is taken from qcodo internal variable, assuming it was set by previous (failed) AJAX request
	qcodo.pA('MasterControl', '', 'ErrorRecovery', '', qcodo.objAjaxWaitIcon.control.id);
}

/**
 * Hides recovery related visuals. Also stops recovery to avoid suprising the user.
 */
mtpsip.er.hideVisuals = function()
{
	//stop countdown
	this.stopSw();
	
	//hide recovery panel
	$("#"+this.PANEL_ID).css("display", "none");
}
