/*
 * This file should only be sourced if a server-side flag is set
 *
 */
function Debug()
{
	this.debugConsole = null;
}

Debug.prototype.startDiv = function()
{
	var me = this;
	var divObj = document.createElement( 'DIV' );
	divObj.style.position = 'absolute';
	divObj.style.zIndex = '1000';
	divObj.style.top = '5px';
	divObj.style.right = '5px';
	divObj.style.width = '500px';
	divObj.style.height = '400px';
	divObj.style.overflow = 'auto';
	divObj.style.border = '2px solid #FF0033';
	divObj.style.backgroundColor = '#DEDEDE';
	divObj.style.fontFamily = 'Verdana';
	divObj.style.fontSize = '10px';
	divObj.style.padding = '2px';
	
	divObj.onclick = function()
	{ 
		this.parentNode.removeChild( this ) 
		me.debugConsole = null;
	}
	
	preObj = document.createElement( 'PRE' );
	divObj.appendChild( preObj );
	
	body = document.getElementsByTagName( 'body' )[0];
	body.appendChild( divObj );
	
	this.debugConsole = preObj;
}

/**
 * Method to build a backtrace of all called function until its calling point in the code.
 * Just call <DebugInstance>.backtrace() anywhere in your code.
 *
 * @return Array
 */
Debug.prototype.backtrace = function()
{
	func = this.backtrace.caller;
	var call_stack = new Array();
	while( func )
	{
		var args = new Array(); // func.arguments is not a normal Array, we need to convert
		for( var x=0; x < func.arguments.length; x++)
		{
			args.push( func.arguments[x] );
		}
		call_stack.unshift( ( func.name? func.name: func.toString().replace( /\(\)(.|\n)*/m, '' ).replace( /^function /, '' ) ) + '('+args+')' );
		func = func.caller;
	}
	return call_stack;
}

/**
 * Override to make array toString() easier to understand
 *
 * @return String
 */
Array.prototype.toString = function()
{
	var args = this;
	var parsedArgs = new Array();
	for( var x=0; x < args.length; x++ )
	{
		switch( typeof args[x] )
		{
			case 'string':
				parsedArgs.push( "'"+args[x]+"'" );
				break;
			default:
				if( args[x].constructor == Array )
				{
					parsedArgs.push( 'Array('+args[x].toString()+')' );
				}
				else
				{
					parsedArgs.push( args[x] );
				}
		}
	}
	return parsedArgs.join( ', ' );
}

Debug.prototype.debugMessage = function( message )
{
	if( !this.debugConsole )
	{
		this.startDiv();
	}
	this.debugWrite( message );
}

Debug.prototype.debugObjectById = function( objId )
{
	obj = document.getElementById( objId );
	this.debugObject( obj );
}

Debug.prototype.debugObject = function( obj )
{
	if( !this.divObj )
	{
		this.startDiv();
	}
	str = '';
	
	for ( i in obj )
	{
		try
		{
			str += '<b>'+obj+'['+i+']</b> = '+obj[i]+'<br />';
		}
		catch(e)
		{
		}
	}
	
	this.debugWrite( str );
}

Debug.prototype.debugWrite = function( txt )
{
	this.debugConsole.innerHTML = txt;
}

var oDebug = new Debug();
