var ajaxLog = {};

function ajaxEntry( name )
{
	this.name = name;
	this.start = null;
	this.end = null;
}

function ajaxLogCreate( name )
{
	var e = new ajaxEntry(name);
	e.start = new Date();
	ajaxLog[name] = e;
}

function ajaxLogFlex( name, responseText )
{
	now = new Date();
	ajaxMS = now - ajaxLog[name].start;
	pagedebug = $('pagedebug');
	if( pagedebug)
	{
		if($('flexdebug') == null)
		{
			Element.insert(pagedebug, '<div id="flexdebug" />');
		}
		Element.insert('flexdebug', '<div class="cgws_debug">FLEX CALL (' + ajaxMS + ') ms<br>RESPONSE: ' + responseText + '</div>');
	}
	ajaxLog[name].end = now;
	ajaxLog[name].took = ajaxMS;
}

function ajaxLogSuccess( name, responseText )
{
	now = new Date();
	ajaxMs = now - ajaxLog[name].start;
	i = responseText.indexOf("<!-- CGWS DEBUG START -->");
	debugInfo = "";
	if( i != -1 )
	{
		debugInfo = responseText.substring(i);
		responseText = responseText.substring(0,i);
	}
	if( debugInfo.length )
	{
		timing = debugInfo.match(/<!-- Q=(\d+\.\d*) P=(\d+\.\d*) C=(\d+\.\d*) T=(\d+\.\d*) -->/);
		if( timing && timing.length == 5 )
		{
			queriesTook = parseFloat(timing[1]);
			processingTook = parseFloat(timing[2]);
			callsTook = parseFloat(timing[3]);
			totalTook = parseFloat(timing[4]);
			ajaxTook = (ajaxMs / 1000.0) - totalTook;
			totalTook = (ajaxMs / 1000.0);
			q = parseInt(Math.round((queriesTook / totalTook)*100), 10);
			p = parseInt(Math.round((processingTook / totalTook)*100), 10);
			c = parseInt(Math.round((callsTook / totalTook)*100), 10);
			a = 100 - (q+p+c);
			debugInfo = debugInfo.replace(/(cht=p3&chd=t:)[\d,]+(&chs=250x100&chl=).+?(&chf=bg)/,"$1"+q+","+p+","+c+","+a+"$2Query|Proc.|Websvc|Ajax$3");
			debugInfo = debugInfo.replace(/Web Services:/g,"Ajax: "+Math.round(ajaxTook*1000)+" ms&nbsp;&nbsp;&nbsp;&nbsp;Web Services:");
		}
		debugInfo = debugInfo.replace('<div class="cgws_debug">','<div class="cgws_debug" id="' + name + '">').replace('Ajax Statistics',name + " (" + (ajaxMs/1000) + " sec)");
		if($(name))
		{
			$(name).remove();
		}
		pagedebug = $('pagedebug');
		if( pagedebug)
		{
			Element.insert(pagedebug,debugInfo);
		}
	}
	ajaxLog[name].end = now;
	ajaxLog[name].took = ajaxMs;
	return responseText;
}

function logDebug(content)
{
	if( $('pagedebug') != null )
	{
		Element.insert('pagedebug','<div class="cgws_debug">'+content+'</div>');
	}
}
