//------------------------------------------------------------------------------------------
// Common RHP JS  (c) netAdapt Ltd.
//------------------------------------------------------------------------------------------

function ValInPx( numericValue )
{
	return numericValue + 'px';
}

function AsInt( strVal )
{
	return parseInt( strVal.replace('px', ''));
}

function GetRandId( )
{
	return Math.floor(Math.random()*99999);
}

function ToggleBlock( elementId)
{
	var element = document.getElementById( elementId );
	if( element.style.display == 'block' )
	{
		element.style.display = 'none';
		element.style.position = 'relative';
	}
	else
	{
		element.style.display = 'block';
		element.style.position = 'relative';
	}
}

function CreateElement( elType, cssClass, id)
{
	var newEl=document.createElement( elType );
	newEl.className = cssClass || null;		
	newEl.id = id || null;		
	return newEl;
}

function SetElStyleFloat( el, floatDir )
{
	el.style.styleFloat = floatDir;
	el.style.cssFloat = floatDir;
}

function GetPagePosArray( ev  )
{
    var ev = GetCrossBrowserEvent( ev );
    var posArray = new Array( );
	if ( ev.pageX && ! window.opera )
	{
		posArray['x'] = ev.pageX;
		posArray['y'] = ev.pageY;
	}
	else
	{
		posArray['x'] = document.documentElement.scrollLeft + ev.clientX;
		posArray['y'] = document.documentElement.scrollTop + ev.clientY;
	}
	return posArray;
}

function GetViewPortHeight( )
{
	return (window.innerHeight)?window.innerHeight:document.documentElement.clientHeight;
}

function XViewPop( ev, divId, isPosAnchoredParam, offSetXP, offSetYP, zIndexP )
{
	var ev = GetCrossBrowserEvent( ev );
    var offSetX = offSetXP || 10;
	var offSetY = offSetYP || -10;
	var zIndex = zIndexP || GetTopZIndex( );

	var isPosAnchored = isPosAnchoredParam || false;

	var popUpEl = document.getElementById( divId );
	var popupStyle = popUpEl.style;

	var posArray = GetPagePosArray( ev );
	var xPos = posArray['x'];
	var yPos = posArray['y'];

	xPos += offSetX;
	yPos += offSetY;

	PositionEl( popUpEl, xPos, yPos, isPosAnchored, zIndex );
	
	popupStyle.visibility = 'visible';	
}

function PositionEl( posEl, xPos, yPos, isPosAnchoredParam, zIndexP )
{
	var zIndex = zIndexP || 0;
	var isPosAnchored = isPosAnchoredParam || false;
	if ( ! isPosAnchored )
	{
		var elWidth =  posEl.scrollWidth;
		var elHeight =  posEl.scrollHeight;
		var clWidth = document.body.clientWidth + document.body.scrollLeft;
		var clHeight = document.body.clientHeight + document.body.scrollTop;

		if ((xPos + elWidth) > clWidth)
		{
			xPos -= ((xPos + elWidth+20)-clWidth); //correction
		}
		
		//alert( 'Create function to force into client hieght : Fix to client hieghtclHeight= ' + clHeight  + '   elHeight= ' + elHeight  + '     yPos= '  + yPos );
		if ((yPos + elHeight) > clHeight)
		{
			yPos -= ((yPos + elHeight+20)-clHeight); //correction
		}
	}
	
	if ( zIndex > 0 )
	{
		posEl.style.zIndex = zIndex;
	}
	SetElPos( posEl, xPos, yPos );
	
}

function SetElPos( el, xPos, yPos )
{
	el.style.top = ValInPx( yPos );
	el.style.left = ValInPx( xPos );
}

function XKillPop( divId )
{
	DestroyElement( divId );
}

function XViewPopTip( ev, toolTopText, offSetXP, offSetYP, zIndexP  )
{
	var ev = GetCrossBrowserEvent( ev );
    var bodyEl = document.getElementById( 'docbody_id' );
	if ( bodyEl )
	{
		var offSetX = offSetXP || 0;
		var offSetY = offSetYP || 0;
		var zIndex = zIndexP || 5000;
		var popTipDiv = CreateElement('div', 'poptip', 'xpopltip_id');		
		popTipDiv.innerHTML = toolTopText;

		bodyEl.appendChild( popTipDiv );

		XViewPop( ev, popTipDiv.id, true, offSetX, offSetY, zIndex );
	}
}

function XKillPopTip( )
{
	XKillPop( 'xpopltip_id' );
}

function PopFullWin( url )
{
	var newWindow = window.open( url );
	newWindow.focus();
}

function PopAppWin( popUrl, popWidth, popHeight )
{
	var winParams='toolbar=no,status=no,width=' + popWidth + 'px,height=' + popHeight + 'px,resizable=yes,scrollbars=yes';
	var newWindow = window.open( popUrl, 2, winParams );
	newWindow.focus( );
}

function SelectAllCheckBoxes( formId, elNamefilter, isToggle )
{
	var checkBoxForm = document.getElementById( formId );
	var numFormEls = checkBoxForm.length;
	//Traverse form and get all selected options.
	for (var i=0; i<numFormEls; i++ )
	{
		//is actual or target
		var formEl = checkBoxForm[i];
		if ( formEl.type == 'checkbox') //a select element
		{
			var elName =  formEl.name;
			if ( elName.indexOf( elNamefilter ) >= 0 ) //is a substr
			{
				if ( isToggle )
				{
					formEl.checked  = !formEl.checked;
				}
				else
				{
					formEl.checked  = true;
				}
			}
		}
	}
}

function SetFormValueAndSubmit( containerFormId, formElId, formValue )
{
	var containerFormEl = document.getElementById( containerFormId );
	var formEl = document.getElementById( formElId );
	formEl.value = formValue;
	containerFormEl.submit( );
}

var g_activeXMenuWinId = 0;
var g_activeTimerId = 0;
var g_activeEvent = 0;

function ViewFlagToolTip( ev, countryCode )
{
	g_activeTimerId	=	setTimeout('PopFlagToolTipFlag(\'' + countryCode + '\');', 1000);
	if ( ev.clientX )
	{
		g_activeEvent = new Object( ); //Cheap clone for IE
		g_activeEvent.clientX = ev.clientX;
		g_activeEvent.clientY = ev.clientY;
	}
	else
	{
		g_activeEvent = ev;
	}
}

function PopFlagToolTipFlag( countryCode )
{
	g_activeXMenuWinId = PopXMenuToolTip( g_activeEvent, '/json/xpopmenu/countrycode_json.php?countrycode=' + countryCode, 200, +20);
}

function KillXMenuToolTip( )
{
	clearTimeout( g_activeTimerId );
	g_popWinManager.RemoveWin( g_activeXMenuWinId );
	g_activeEvent = g_activeTimerId = g_activeXMenuWinId = 0;
}


function GetCrossBrowserEvent( evt )
{
    return evt || window.event;
}

function SetCookie( cookieName, value, expireDays, pathP)
{
	var path = pathP || '/';
	var expDate=new Date( );
	expDate.setDate(expDate.getDate( ) + expireDays);
	document.cookie= cookieName + '=' + escape(value) +	((expireDays==null) ? '' : ';expires=' + expDate.toGMTString( ) + ';path=' + path);	
}

//------------------------------------------------------------------------------------------
// Mini Boards - (c) netAdapt Ltd.
//------------------------------------------------------------------------------------------

var g_pcSize;
var g_pcSet;
var g_board;

function InitMiniBoard( pcSize, pcSet, board  )
{
	g_pcSize = pcSize || 30;
	g_pcSet = pcSet || 'book';
	g_board = board || 'std';
}


function GetVacantMiniBoardCode( gameId )
{

	var boardDim = (8*g_pcSize);
	var surroundDim = boardDim+12;
	var boardCode = '<div style="width:' + surroundDim  + 'px;height:' + surroundDim + 'px;background-color:#FFFFFF;border-width:1px;border-style:solid;border-color:#797979;position:relative;">';
	boardCode += '<div style="width:' + (boardDim+2)  + 'px;height:' + (boardDim+2) + 'px;background-color:#FFFFFF;border-width:1px;border-style:solid;border-color:#797979;position:absolute;top: 4px; left: 4px">';
	boardCode += '<div id="miniboard_' + gameId + '" style="width:' + boardDim  + 'px;height:' + boardDim + 'px;position:absolute;background:url(/img/set/board/' + g_board + '_' + g_pcSize + 'px.gif);top: 0px; left: 0px">';
	//empty div
	boardCode += '</div>';
	boardCode += '</div>';
	boardCode += '</div>';
	return boardCode;
}

function RenderBoard( gameId, fen, pcSize, pcSet, board, isInverted, lastMoveParam)
{
	var lastMove = lastMoveParam || '';
	InitMiniBoard( pcSize, pcSet, board );
	document.write( GetVacantMiniBoardCode( gameId )  );
	PopulateMiniBoard( gameId, fen, isInverted, lastMoveParam);

}

function PopulateMiniBoard( gameId, fen, isInvertedParam, lastMoveParam  )
{
	var boardEl = document.getElementById( 'miniboard_' + gameId );
	lastMove = lastMoveParam || '';
	isInverted = isInvertedParam || false;
	boardEl.innerHTML = '';
	AddBoardToEl( gameId, boardEl, fen, isInverted, lastMove );
}

function AddBoardToEl( gameId, targetEl, fen, isInverted, lastMove )
{
	var fenlen 		= fen.length;
	var tileCounter = 0;

	for (var f = 0; f < fenlen; f++ )
	{
		var xPos = parseInt( tileCounter%8 );
		var yPos = parseInt( tileCounter/8 );

		var fenChar = fen.charAt(f);
		if (fenChar == ' ' )
		{
			f = fenlen;
		}
		else if (fenChar == '/' )
		{
			//
		}
		else if ( ! isNaN( fenChar ) )
		{
			tileCounter += parseInt(fenChar);
		}
		else
		{
			var pc = CreatePcEl( gameId, g_pcSet, g_pcSize, fenChar, xPos, yPos, isInverted);
			targetEl.appendChild( pc );
			tileCounter++;
		}
		if ( tileCounter >= 64 )
		{
			f = fenlen;
		}
	}

	//Render last move
	if ( lastMove && lastMove.length == 4 )
	{
		var lastMoveSrcX = parseInt(lastMove.charAt(0));
		var lastMoveSrcY = parseInt(lastMove.charAt(1));
		var lastMoveTgtX = parseInt(lastMove.charAt(2));
		var lastMoveTgtY = parseInt(lastMove.charAt(3));
		if ( isInverted )
		{
			lastMoveSrcX = 7-lastMoveSrcX;
			lastMoveSrcY = 7-lastMoveSrcY;
			lastMoveTgtX = 7-lastMoveTgtX;
			lastMoveTgtY = 7-lastMoveTgtY;
		}
		AddTileHighlight( targetEl, lastMoveSrcX, lastMoveSrcY);
		AddTileHighlight( targetEl, lastMoveTgtX, lastMoveTgtY);
	}
}

function CorrectBoardPos( val, isInverted)
{
	return ( isInverted )?(7-val):val;
}

function CreatePcEl( gameId, pcSet, pcSize, pcChar, xPos, yPos, isInverted )
{
	var xPos = xPos || 0;
	var yPos = yPos || 0;
	var pc = document.createElement('div');
	pc.id = GetPcId(gameId,xPos,yPos);
	pc.style.height = ValInPx( pcSize );
	pc.style.width = ValInPx( pcSize );
	pc.style.backgroundImage = 'url(/img/set/pc/' + pcSet + '_set_' + pcSize + 'px.gif)';
	pc.style.position = 'absolute';
	pc.style.zIndex = 30;
	pc.style.backgroundPosition = GetImgStyle ( pcChar, pcSize );
	SetElPos( pc,  CorrectBoardPos( xPos, isInverted)*pcSize, CorrectBoardPos( yPos, isInverted)*pcSize);
	pc.m_isLMovement = (pcChar.toLowerCase( ) == 'n');
	return pc;
}

function GetPcEl( gameId, xPos, yPos )
{
	return document.getElementById( GetPcId( gameId, xPos, yPos ));
}

function GetPcId( gameId, xPos, yPos )
{
	return ('pc' + '_' + gameId + '_' + xPos + '_' + yPos);
}

function AddTileHighlight(  targetEl, xPos, yPos)
{
	var tile = document.createElement('div');
	tile.style.height = ValInPx ( g_pcSize );
	tile.style.width = ValInPx( g_pcSize );
	tile.style.left = ValInPx(xPos*g_pcSize);
	tile.style.top 	= ValInPx(yPos*g_pcSize);
	tile.style.position = 'absolute';
	tile.style.zIndex = 25;
	tile.style.background = '#C6F1C6';
	targetEl.appendChild( tile );
}

function GetImgStyle( pcCode, tileSize )
{
	var offSet = 0;
	var scalar = -tileSize;
	var isWhite = true;
	switch ( pcCode )
	{
		case 'q':isWhite=false;
		case 'Q':offSet = 1;break;
		case 'b':isWhite=false;
		case 'B':offSet = 2;break;
		case 'n':isWhite=false;
		case 'N':offSet = 3;break;
		case 'r':isWhite=false;
		case 'R':offSet = 4;break;
		case 'p':isWhite=false;
		case 'P':offSet = 5;break;
		case 'k':isWhite=false;
		case 'K':offSet = 0;break;
	}
	var xOffset = offSet*scalar;
	var yOffset = ((isWhite) ? 0 : -tileSize);
	return (xOffset) + 'px ' +  (yOffset) + 'px ';
}

function DestroyElement( elId )
{
	var el = document.getElementById( elId );
	if ( el && el.parentNode)
	{
		el.parentNode.removeChild( el );
		return true;
	}
	return false;
}

function SetOpaqueVal( el, val )
{
	if ( el )
	{
		el.style.opacity = val;
		//el.style.filter = 'alpha(opacity = ' + (val*100) + ')';
	}
}

//------------------------------------------------------------------------------------------
// Ajax helpers (c) netAdapt Ltd.
//------------------------------------------------------------------------------------------
function GetXMLHttpRequest( )
{	
	return (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');	
}

function GetCacheBusterUrlExt( )
{
	return '&cachebuster=' + (Math.floor(Math.random( )*999999));
}

//------------------------------------------------------------------------------------------
// Game waiting (c) netAdapt Ltd.
//------------------------------------------------------------------------------------------
var g_waitBoxXmlDoc;
var g_waitBoxRequestInProgress = false;
var g_waitBoxIntervalId;
var g_waitBoxRefreshCount = 0;
var g_waitBoxNextRefreshDate;
var g_waitBoxSecondsRegression = 10;

function WaitForGameMove( ev, gameIdP )
{
	var ev = GetCrossBrowserEvent( ev );
	var gameId = gameIdP || 0;
	
	DarkenDesktop( );		
	
	var waitBoxDiv = CreateElement( 'div', 'waitbox', 'gamemovewaitboxid');
	var waitBoxHtml = '';
	waitBoxHtml += '<div style="float:right;width:70px;text-align:center" onmouseover="XViewPopTip( event, \'Time and next check time\');"  onmouseout="XKillPopTip( );">';
	waitBoxHtml += '<img src="/img/uix/dialog/waitbox-clock.png" style="margin:4px;">';
	waitBoxHtml += '<div style="border:1px solid #CCC">';
	waitBoxHtml += '<div style="padding:4px;color:#777"><span id="waitbox_current_hours_id"></span>:<span id="waitbox_current_minutes_id">:</span>:<span id="waitbox_current_seconds_id"></span></div>';
	waitBoxHtml += '<div style="padding:4px;color:#CCC"><span id="waitbox_next_hours_id"></span>:<span id="waitbox_next_minutes_id">:</span>:<span id="waitbox_next_seconds_id"></span></div>';
	waitBoxHtml += '</div>';
	waitBoxHtml += '</div>';
	
	
	waitBoxHtml += '<div style="font-weight:bold;font-size:11px;border-bottom:solid 1px #666;padding-bottom:4px;">Waiting for move ' + (gameId>0?' in game ' + gameId:'in any game')  +  '</div>';
	waitBoxHtml += '<p>Board will show when your move.<div class="waitboxprogressbar"></p>';
	
	waitBoxHtml += '<img src="/img/uix/iobar.gif" width="200px" class="xiobar">';
	waitBoxHtml += '<div style="clear:both"></div>';
	waitBoxHtml += '<p class="waitboxlinks"><a href="#" onclick="CancelWaitForGameMove( );WaitForGameMove( event, ' + gameId + ');return false;">Check now</a> | <a href="#" onclick="CancelWaitForGameMove( );return false;">Cancel</a></p>';
	
	
	waitBoxDiv.innerHTML = waitBoxHtml;
		
	var bodyEl = document.getElementById( 'docbody_id' );
	bodyEl.appendChild( waitBoxDiv );
	ShowElDeadCenter( 'gamemovewaitboxid', 300, 120 );
	
	// Start clock	
	g_waitBoxNextRefreshDate = new Date( );	
	WaitBoxUpdates( gameId );
	g_waitBoxIntervalId = setInterval('WaitBoxUpdates(' + gameId + ')', 1000);			
}

function WaitBoxUpdates( gameIdP )
{	
	var gameId = gameIdP || 0;
	UpdateClock( new Date( ), 'waitbox_current_hours_id', 	'waitbox_current_minutes_id', 	'waitbox_current_seconds_id' );
	UpdateClock( g_waitBoxNextRefreshDate, 'waitbox_next_hours_id', 		'waitbox_next_minutes_id', 		'waitbox_next_seconds_id' );
	
	if ( ! g_waitBoxRequestInProgress )
	{	
		var currentDate = new Date( );		
		if ( currentDate.getTime( ) > g_waitBoxNextRefreshDate.getTime( ) )
		{		
			g_waitBoxRequestInProgress = true;
			var url = '/xml/xstatus/gameswaitingxml.php?gameid=' + gameId + GetCacheBusterUrlExt( );	
			g_waitBoxXmlDoc = GetXMLHttpRequest( );
			g_waitBoxXmlDoc.onreadystatechange = this.WaitBoxProcessReqChange;
			g_waitBoxXmlDoc.open('GET', url, true);
			g_waitBoxXmlDoc.send( null );
							
			g_waitBoxSecondsRegression =  Math.round( g_waitBoxSecondsRegression * 1.2 );
			g_waitBoxSecondsRegression = ( g_waitBoxSecondsRegression>300 )?300:g_waitBoxSecondsRegression; //5mins max between ticks			
			
			g_waitBoxNextRefreshDate = new Date();
			g_waitBoxNextRefreshDate.setSeconds( g_waitBoxNextRefreshDate.getSeconds( ) + g_waitBoxSecondsRegression );
		}
	}		
}

function WaitBoxProcessReqChange()
{	
	if (g_waitBoxXmlDoc.readyState == 4)  //state complete
    {
        if (g_waitBoxXmlDoc.status == 200)  // only if status ok
        {
           
            var xmlDocRes = g_waitBoxXmlDoc.responseXML;
  
            //Get win id from doc
            var xmlRootEl = xmlDocRes.documentElement;
            
            
            var statusItems = xmlRootEl.childNodes;
			var numStatusNodes = statusItems.length;
									
			var gamesWaiting = parseInt( xmlRootEl.getElementsByTagName('gameswaiting').item(0).firstChild.nodeValue );
			if ( gamesWaiting > 0 )
			{
				var gameId = parseInt( xmlRootEl.getElementsByTagName('gameid').item(0).firstChild.nodeValue );
				GotoWaitingGame( gameId );
			}
			else
			{
				//Delay check request.
				g_waitBoxRequestInProgress = false;
			}						
        }
        else
        {
            alert('There was a problem retrieving the XML data:\n' + g_waitBoxXmlDoc.statusText);
            CancelWaitForGameMove( );
            g_waitBoxRequestInProgress = false;
        }
    }
    else
    {
    	//CancelWaitForGameMove( );
    	g_waitBoxRequestInProgress = false;
    }
}

function UpdateClock( dateInstance, hoursElId, minsElId, secElId )
{	
	hours = dateInstance.getHours( );
	mins =  dateInstance.getMinutes( );
	secs =  dateInstance.getSeconds( );
	document.getElementById( hoursElId ).innerHTML = (hours<10)?'0'+hours:hours;
	document.getElementById( minsElId ).innerHTML = (mins<10)?'0'+mins:mins;
	document.getElementById( secElId ).innerHTML = (secs<10)?'0'+secs:secs;	
}

function GotoWaitingGame( gameIdP )
{		
	var gameId = gameIdP || 0;
	location.href = '/core/gameserve.php?gameid=' + gameId;	
}

function CancelWaitForGameMove( )
{
	clearInterval ( g_waitBoxIntervalId );
	g_waitBoxSecondsRegression = 10; //reset regression value 	
	DestroyElement('gamemovewaitboxid');	
	UndarkenDesktop( );	
}

function DarkenDesktop( )
{
	DestroyElement('darkbackgroundid');
	var darkDiv = CreateElement('div', 'darkenbackground', 'darkbackgroundid');	
	darkDiv.style.opacity =  '0.7';
	darkDiv.style.filter = 'alpha(opacity=70)';	
	var bodyEl = document.getElementById( 'docbody_id' );
	bodyEl.appendChild( darkDiv );	
}

function UndarkenDesktop( )
{
	DestroyElement('darkbackgroundid');		
}

function ShowElDeadCenter( elId, widthXPx, heightYPx ) 
{ 	
	var el		= document.getElementById(elId); 
	var elStyle	= el.style; 
		
			
	var scrolledX;
	var scrolledY; 	
	var centerX;
	var centerY; 
	
	if( self.pageYoffset ) 
	{ 
		scrolledX = self.pageXoffset; 
		scrolledY = self.pageYoffset; 
	} 
	else if( document.documentElement && document.documentElement.scrollTop ) 
	{ 
		scrolledX = document.documentElement.scrollLeft; 
		scrolledY = document.documentElement.scrollTop; 
	} 
	else if( document.body ) 
	{ 
		scrolledX = document.body.scrollLeft; 
		scrolledY = document.body.scrollTop; 
	} 
		
	if( self.innerHeight ) 
	{ 
		centerX = self.innerWidth; 
		centerY = self.innerHeight; 
	} 
	else if( document.documentElement && document.documentElement.clientHeight ) 
	{ 
		centerX = document.documentElement.clientWidth; 
		centerY = document.documentElement.clientHeight; 
	} 
	else if( document.body ) 
	{ 
		centerX = document.body.clientWidth; 
		centerY = document.body.clientHeight; 
	} 
	
	var leftoffset = scrolledX + (centerX - widthXPx) / 2; 
	var topoffset = scrolledY + (centerY - heightYPx) / 2; 

	
	elStyle.position='absolute'; 
	elStyle.top 	= ValInPx( topoffset );
	elStyle.left 	= ValInPx( leftoffset );
	elStyle.display = 'block'; 
} 

//------------------------------------------------------------------------------------------
// DAD (c) netAdapt Ltd.
//------------------------------------------------------------------------------------------
var g_currentDragDivEl = null;
var g_dragOffsetX	= 0;
var g_dragOffsetY	= 0;
var g_topZindex		= 100;

function DAD_StartDrag( evt, dragElId )
{
	if ( ! g_currentDragDivEl )
	{
		var evt = GetCrossBrowserEvent( evt  );
		var posArray  = GetPagePosArray( evt );

		g_currentDragDivEl = document.getElementById( dragElId );
		SetOpaqueVal( g_currentDragDivEl, 0.9 );
		
		if ( g_currentDragDivEl.isDragLocked )
		{
			DAD_EndDrag( );			
			return false;
		}
		
		g_dragOffsetX = posArray['x']-parseInt( g_currentDragDivEl.style.left );
		g_dragOffsetY = posArray['y']-parseInt( g_currentDragDivEl.style.top );
		if ( document.addEventListener )
		{
			document.addEventListener('mousemove', DAD_Drag, false);
		}
		else if ( document.attachEvent )
		{
			document.attachEvent('onmousemove', DAD_Drag );
		}
		DAD_SetZIndex( g_currentDragDivEl );
		return false;
	}
}

function DAD_Drag( evt )
{
	if (  g_currentDragDivEl )
	{
		var evt = GetCrossBrowserEvent( evt );
		var posArray  = GetPagePosArray( evt );

		g_currentDragDivEl.style.left = ValInPx( posArray['x']-g_dragOffsetX );
		g_currentDragDivEl.style.top =  ValInPx( posArray['y']-g_dragOffsetY );
	}
	return false;
}

function DAD_EndDrag( )
{
	SetOpaqueVal( g_currentDragDivEl, 1 );
	g_currentDragDivEl = null;
	if ( document.addEventListener )
	{
		document.removeEventListener("mousemove", DAD_Drag, false);
	}
	else if ( document.detachEvent )
	{
		document.detachEvent("onmousemove", DAD_Drag );
	}
}

function DAD_SetZIndex( el )
{
	el.style.zIndex = ++g_topZindex;
}

function GetCssClassFromNode( itemNode )
{
	return itemNode.getAttribute('cssclass');
}

function GetOffSetPopWin( elIdPrefix, offSetX, offSetY )
{
	var popWinId = elIdPrefix +  Math.floor(Math.random()*99999)
	return new CPopWin( popWinId, false, offSetX, offSetY );	
}

function PopXMenuToolTip(  ev, url, widthPx, offSetX, offSetY )
{
	var widthPx = (widthPx || 200);
	var offSetX = (offSetX || 0);
	var offSetY = (offSetY || 0);
	var popWinId = 'xmenutooltip' +  Math.floor(Math.random()*99999)
	var popWin = new CPopWin( popWinId, true, offSetX, offSetY );
	popWin.PositionOffEvent( ev );
	popWin.SetIsTitleBar( false );
	popWin.SetWidth( widthPx );
	popWin.Render( );
	popWin.ReloadContent( url );		
	return popWinId;
}

function PopXConWin( ev, title, winId, contentId, widthPx, offSetX,  offSetY)
{
	var popWinId = winId;
	if ( ! g_popWinManager.IsPopWin( winId ))
	{
		var popWin = new CPopWin(  popWinId, true, offSetX, offSetY );
		popWin.PositionOffEvent( ev );
		popWin.SetWidth( widthPx );
		popWin.LaunchCopyContent(contentId, title );		
	}
}

function CloseWin( popWinId )
{
	g_popWinManager.RemoveWin( popWinId );
}

function ReloadWin( popWinId )
{	
	g_popWinManager.GetPopWin( popWinId ).ReloadContent( );
}

function GetTopZIndex( )
{
	return ++g_topZindex;
}


function LoadComConsole( win )
{
	if ( g_debugComConsoleWinId )
	{
		var comConsoleDiv = CreateElement('div');
		win.AddContentItem( comConsoleDiv );
		g_debugComConsoleEl = comConsoleDiv;
		g_debugComConsoleEl.innerHTML = 'Started' + '\n';
		g_debugComConsoleEl.className = 'comconsole';
		comConsoleDiv.style.width = '100%';
	}
}


function LogComConsoleTrace( value, isResponse, requestUrl )
{
	if ( g_debugComConsoleWinId )
	{
		var currentDate = new Date( );
		var requestTypeStr = ( isResponse )?'<<< Response <<<':'>>> Send >>>';		
		
		value = value.replace(  /{/g, '<li>{<ul style="padding-left:25px"><li><pre>');
		value = value.replace(  /}/g, '</pre></li></ul>}</li>');
		value = value.replace(  /\\"/g, '"');
		
		var requestUrl = requestUrl || '';
		
		g_debugComConsoleEl.innerHTML = '<h3>' + requestTypeStr + ' @[ ' + currentDate.toLocaleString( ) + ' ]</h3><h4>' + requestUrl + '</h4>' +  value + '' + g_debugComConsoleEl.innerHTML;
	}
}

function XPopLoadComConsole( )
{	
	if ( ! g_popWinManager.IsPopWin( g_debugComConsoleWinId ) )
	{
		
		//CPopWin( elId, isPosAnchoredParam, offSetXP, offSetYP )
		var popWin = new CPopWin( 'comconsole', false, 20, 20  );	
		popWin.SetRefreshCallBack( LoadComConsole );		
		g_debugComConsoleWinId = popWin.GetWinId( );		
		popWin.SetTitle( 'COM Console');
		popWin.SetLaunchPos( 1200,120 );
		popWin.SetWidth( 800 );
		popWin.RepaintHeight( 400 );
		popWin.Render( );
		LoadComConsole( popWin );		
	}
}

//--------------------------------------------------------------------------------
// Ajax/Json calls.
//--------------------------------------------------------------------------------

function FireJsonWinRequest( win, url, jsonObjectP)
{	
	var jsonObject = jsonObjectP || {};	 //Create request object if non provided		
	jsonObject.m_winId = win.GetWinId( );		
	win.SetReloadUrl( url );
	FireJsonRequest( url, jsonObject );
}

function FireJsonRequest( url, jsonObject  )
{
	var nameValuePairsStr =   '&json_request=' + escape( JSON.stringify( jsonObject ));
	
	var isQueryString = (url.indexOf('?') > 0);
	
	url += ((isQueryString)?'&':'?') + 'timestamp=' + new Date( ).getTime( ) + nameValuePairsStr; //tack to url for debugging only.

	if ( LogComConsoleTrace )
	{
		LogComConsoleTrace( JSON.stringify( jsonObject ), false, url );
	}

	$ajaxJsonCall = new  CAjaxJsonCall( url, nameValuePairsStr );
	$ajaxJsonCall.SendRequest( );
}


//------------------------------------------------------------------------------------------
// Ajax Connection class (c) netAdapt Ltd.
//------------------------------------------------------------------------------------------
function CAjaxJsonCall( urlP, dataP ) 
{		
	this.m_ajaxHttp = GetXMLHttpRequest( );
	this.m_url = urlP;
	this.m_data = dataP;
	this.SendRequest = SendRequest;	
	
}

function SendRequest(  )
{
	var thisVar = this; //ie6 workaround 	
	this.m_ajaxHttp = GetXMLHttpRequest( );
	this.m_ajaxHttp.open('POST', this.m_url, true);	
	this.m_ajaxHttp.onreadystatechange = function( )
	{					
		if ( thisVar.m_ajaxHttp.readyState == 4)  //state complete
		{		
			if ( thisVar.m_ajaxHttp.status == 200 )  // only if status ok
			{						
				jsonText = thisVar.m_ajaxHttp.responseText;
				//alert( jsonText );
				LogComConsoleTrace( JSON.stringify( jsonText ), true );
				var jsonObj = JSON.parse( jsonText );
				ProcessJsonResponse( jsonObj );
			}
			else
			{
				alert('There was a problem with this request:\\n\\n' + thisVar.statusText);
			}
		}
		else
		{
			//
		}
	}
		
	this.m_ajaxHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded;');	
	this.m_ajaxHttp.send( this.m_data );
}

//--------------------------------------------------------------------------------
// Json response
//--------------------------------------------------------------------------------
function ProcessJsonResponse( jsonObj )
{		
	if ( jsonObj.m_status )
	{
		var responseDiv = CreateElement('div');		
		if ( g_popWinManager.IsPopWin( jsonObj.m_winId ))	
		{
			var popWin = g_popWinManager.GetPopWin( jsonObj.m_winId );
			//Recursivly parse through jsonObj			
			ParseJsonResponse( jsonObj, responseDiv, popWin );
			popWin.AddContentItem( responseDiv );
		}
	}
	if ( jsonObj.m_winId )
	{
		var popWin = g_popWinManager.GetPopWin( jsonObj.m_winId );
		popWin.RenderTabBar( );
		popWin.WinWake( );		
	}
	else
	{
		alert('no win id');	
	}
}

function AddFormLabelElement( parentEl, labelValue, labelName  )
{
	var labelEl = CreateElement('label');
	labelEl.innerHTML = ((labelValue!='')?labelValue:'&nbsp;');
	labelEl.className = 'xmenulabel';
	if ( labelName )
	{		
		labelEl.htmlFor = labelName;
	}
	parentEl.appendChild( labelEl );
}

function ProcessContentReloadRequest( winId, url )
{	
	if ( g_popWinManager.IsPopWin( winId ))
	{
		var popWin = g_popWinManager.GetPopWin( winId );
		
		popWin.ReloadContent( url );
	}	
}

function ParseJsonResponse( jsonObj, parentDomEl, win )
{
	var elementArray = jsonObj.m_elementArray;
	for( key in elementArray)  //loop elements array and add content to window
	{
		var jsonElement	= elementArray[key];
			
		if ( jsonElement.m_formElLabel != null )
		{			
			AddFormLabelElement( parentDomEl, jsonElement.m_formElLabel, jsonElement.m_name );
		}
		
		var isLineBr = false;
		var newEl = null;				
		switch( jsonElement.m_type )
		{
			case 'layout_menu':				
				newEl = CreateElement('div', jsonElement.m_cssClass );																
				ParseJsonResponse( jsonElement, newEl, win  );  //recurse	
				win.RepaintHeight( jsonElement.m_heightPx );
				win.RepaintWidth( jsonElement.m_widthPx );
			break;			
			case 'layout_tab' :															
				var newTab = win.AddTab( jsonElement.m_name );
				if ( jsonElement.m_isFocus )
				{
					newTab.ShowContent( );				
				}
				else
				{
					newTab.HideContent( );				
				}				
				newEl = newTab.GetContentContainerEl( );								
				ParseJsonResponse( jsonElement, newEl, win );  //recurse						
			break;			
			case 'layout_menuitem':				
				newEl = CreateElement('div', jsonElement.m_cssClass );
				ParseJsonResponse( jsonElement, newEl, win  );  //recurse								
				newEl.appendChild( CreateElement( 'div', 'xmenuclearfloat' ));
			break;			
			case 'layout_menucolumn':
				newEl = CreateElement('div', jsonElement.m_cssClass );
				newEl.style.width = ValInPx( jsonElement.m_widthPx );	
				SetElStyleFloat( newEl, 'left');
				ParseJsonResponse( jsonElement, newEl, win  );  //recurse		
			break;					
			case 'layout_title' :
				newEl = CreateElement('h1', jsonElement.m_cssClass );
				newEl.innerHTML = jsonElement.m_value;	
				isLineBr = true;							
			break;			
			case 'layout_subtitle' :
				newEl = CreateElement('h2', jsonElement.m_cssClass );
				newEl.innerHTML = jsonElement.m_value;								
				isLineBr = true;
			break;			
			case 'layout_labelvalue' :
				var newEl = CreateElement('div',  jsonElement.m_cssClass);				
				newEl.innerHTML = '<div style="float:left" class="xmenulabel">' + jsonElement.m_label + '</div>' +  jsonElement.m_value;					
				isLineBr = true;
			break;						
			case 'layout_text' : 
				newEl = CreateElement('div',  jsonElement.m_cssClass);
				newEl.innerHTML = jsonElement.m_value;	
				isLineBr = true;			
			break;						
			case 'layout_linkhref' : 
				var aEl = CreateElement('a');				
				aEl.href = jsonElement.m_value;								
				aEl.innerHTML = GetLinkIcon( jsonElement.m_iconUrl ) + jsonElement.m_text;
				newEl = CreateElement('div', jsonElement.m_cssClass );
				newEl.innerHtml = 
				newEl.appendChild( aEl );
				isLineBr = true;
			break;			
			case 'layout_linkjs' : 
				var destoryElementCode = '';	
				if ( jsonElement.m_isCloseOnSelect )
				{
					destoryElementCode = 'CloseWin(\'' +  win.GetWinId( ) + '\');';
				}				
				newEl = CreateElement('div',  jsonElement.m_cssClass );							
				newEl.innerHTML = GetLinkIcon( jsonElement.m_iconUrl ) + '<a href="#" class="' + jsonElement.m_cssClass + '" onclick="' + unescape(jsonElement.m_value) + ';' + destoryElementCode + 'return false;">' + jsonElement.m_text + '</a>'; 
				isLineBr = true;
			break;			
			case 'layout_image':			
				var imageEl = CreateElement('img', jsonElement.m_cssClass);		
				imageEl.src = jsonElement.m_value;
				imageEl.style.width = ValInPx( jsonElement.m_widthPx );
				imageEl.style.height = ValInPx( jsonElement.m_heightPx );	
				imageEl.alt = jsonElement.m_metaText;		
												
				newEl = CreateElement('div', 'imagecontainer' );	 //'imagecontainer'				
				newEl.appendChild( imageEl );	
				isLineBr = true;						
			break;						
			case 'layout_boardstatic': 				
				var fen = jsonElement.m_value;
				var pcSize = jsonElement.m_pcSize;
				var pcStyle = jsonElement.m_pcStyle;
				var boardStyle = jsonElement.m_boardStyle;
				var lastMove = jsonElement.m_lastMove;
				var isInverted = jsonElement.m_isInverted;
				
				var fenDiv = document.createElement('div');				
										
				InitMiniBoard( pcSize, pcStyle, boardStyle, lastMove );
				var randGameId = Math.floor(Math.random( )*999999);
				fenDiv.innerHTML = GetVacantMiniBoardCode( randGameId )

				miniBoardEl = fenDiv.firstChild.firstChild.firstChild;
				AddBoardToEl( randGameId, miniBoardEl, fen, isInverted, lastMove );								
				newEl = fenDiv;				
			break;			
			case 'layout_bar': 			
				var barValue	= jsonElement.m_value;				
				var maxValue 	= jsonElement.m_maxValue;
				var barWidthPx 	= jsonElement.m_widthPx;				
				var barLenPercent =  (barValue/maxValue)*100;
				var barLenPx = (barLenPercent/100)* barWidthPx;
				var altValue = barValue + ' of ' + maxValue;
				
				var barCode = '<div style="float:right;">';
				barCode += barValue;
				barCode += '<span style="border:solid 1px #AAA;padding:0px;margin-left:8px;">';
				barCode += '<img alt="' + altValue + '" width="' + (barLenPx) + 'px" height="8px" src="/img/uix/graphbg_remaining.gif" border="0px"><img alt="' + altValue + '" width="' + (barWidthPx-barLenPx) + 'px" height="8px" src="/img/uix/graphbg_used.gif" border="0px">';
				barCode += '</span>'; //end bar container.				
				barCode += '</div>';										
												
				var newEl = CreateElement('div',  jsonElement.m_cssClass);				
				newEl.innerHTML = '<div style="padding:4px"><div style="float:left;;" class="xmenulabel">' + jsonElement.m_label + '</div>' +  barCode + '</div>';					
				isLineBr = true;								
			break;			
			case 'layout_linkreloadcontent':
				
				var reloadUrl 	= jsonElement.m_value;				
				var text	 	= jsonElement.m_text;				
				var note 		= jsonElement.m_note;				
				var linkDiv =  CreateElement( 'div',  jsonElement.m_cssClass );				
				var linkContent = '<a href="#" class="' + jsonElement.m_cssClass + '" onclick="ProcessContentReloadRequest(\'' +  win.GetWinId( ) +  '\',\'' +  unescape(reloadUrl) +  '\');">' + text + '</a>' + note;								  				
				linkDiv.innerHTML = linkContent;
				newEl = linkDiv;
				isLineBr = true;
			break;			
			case 'form' :
				var formEl = CreateElement('form', 'xlayoutcontainer', 'formid_' + GetRandId( ));
				formEl.name = jsonElement.m_formName;
				formEl.action = jsonElement.m_action;
				formEl.onsubmit = function( e ) { return SubmitPopWinForm( win.GetWinId( ), formEl ); }
							
				var formStatusEl = CreateElement('div', '', formEl.id + '_statusdiv' );			
				formEl.appendChild( formStatusEl );				
				ParseJsonResponse( jsonElement, formEl, win  );  //recurse	
				newEl = formEl;
			break;			
			case 'form_text' :
				newEl = CreateElement('input', 'formelement');
				newEl.name = jsonElement.m_name;
				newEl.type = 'text';
				newEl.maxLength = jsonElement.m_maxLen;
				newEl.size		= jsonElement.m_size;
				newEl.value 	= jsonElement.m_value;
				isLineBr = true;
			break			
			case 'form_textarea' :
				newEl = CreateElement('textarea', 'formelement');
				newEl.name = jsonElement.m_name;
				newEl.innerHTML = jsonElement.m_value;
				newEl.cols = jsonElement.m_cols;
				newEl.rows = jsonElement.m_rows;				
				isLineBr = true;
			break;			
			case 'form_checkbox' :
				newEl = CreateElement('input', 'formelement');				
				newEl.type = 'checkbox';
				newEl.name = jsonElement.m_name;
				newEl.checked =  jsonElement.m_isChecked;
				isLineBr = true;				
			break;			
			case 'form_hidden' :
				newEl = CreateElement('input', 'formelement');				
				newEl.type = 'hidden';
				newEl.name = jsonElement.m_name;
				newEl.value = jsonElement.m_value;								
			break;			
			case 'form_select' :
				newEl = CreateElement('select', 'formelement');
				newEl.selectedIndex = jsonElement.m_selectedIndex;
				newEl.name = jsonElement.m_name;
				newEl.checked =  jsonElement.m_isChecked;
				if  ( jsonElement.m_optionsArray )
				{
					for(optionKey in jsonElement.m_optionsArray)  //loop element array
					{
						var optionText =  jsonElement.m_optionsArray[optionKey];
						var newOptionEl = CreateElement('option');
						newEl.options[newEl.options.length] = new Option (optionText, optionKey);
					}
				}				
				isLineBr = true;
			break;			
			case 'form_submit' :
				newEl = CreateElement('input', 'formbutton');
				newEl.name = jsonElement.m_name;
				newEl.type = 'submit';
				newEl.value = jsonElement.m_value;				
				isLineBr = true;
			break;
			
			case 'formsubmissionresponse' : 
				SetMessageStack( win, jsonElement );
			break;	
			
			default:
				alert('nA PopWin : Unknown element type.   [' + jsonElement.m_type + ']');
			break;			
		}
				
		if ( newEl )
		{			
			parentDomEl.appendChild( newEl );
			if ( isLineBr )
			{				
				parentDomEl.appendChild(  CreateElement('div', 'xmenuitempad') );
			}			
		}
	}
}

function GetLinkIcon( iconUrl )
{
	if ( iconUrl != undefined && iconUrl != '')
	{		
		return 	'<img src="' + unescape( iconUrl ) + '" align="absmiddle">&nbsp;';
	}
	return '';
}

function SubmitPopWinForm( winId, form )
{
	var elArray = form.elements;
	var n;
	var formResponseObj =  {}; //object

	formResponseObj.action = 'submit';
	formResponseObj.m_formId = form.id;	
	for (n=0;n<elArray.length;n++)
	{
		if ( elArray[n].name )
		{			
			formResponseObj[ 'm_' + elArray[n].name ] = elArray[n].value;
		}
	}	
	var win = g_popWinManager.GetPopWin( winId );			
	SetMessageStackContent( form.id, 'Please wait...' );	
	FireJsonWinRequest( win, form.action, formResponseObj );	
	return false;
}

function SetMessageStack( win, jsonElement ) 
{	
	var stackCode = '';
	var messageStackArray = jsonElement.m_messageStackArray;
	if ( messageStackArray )
	{	
		stackCode += '<div class="formMessageStack">';
		for(key in messageStackArray)
		{
			stackCode += '<div>' + messageStackArray[key] + '</div>';
		}
		stackCode += '</div>';
	}	
	SetMessageStackContent(  jsonElement.m_formId, jsonElement.m_title, stackCode, jsonElement.m_isFormError);	
}

function SetMessageStackContent( formId, title, stackCodeP, isErrorP )
{
	var isErrorState = (isErrorP != undefined);	
	var isError = isErrorP || false;
	var stackCode = stackCodeP || '';	
	stackCode = '<div>' + title + '</div>' + stackCode;			
	var formStatusDiv = document.getElementById( formId + '_statusdiv');		
	if ( isErrorState )
	{
		statusDivClass = (isError)?'formupdateerror':'formupdateok';
	}
	else
	{
		statusDivClass = 'formupdateneutral';
	}
	formStatusDiv.className = statusDivClass;
	formStatusDiv.innerHTML = stackCode;
}

//------------------------------------------------------------------------------------------
// Pop Win class (c) netAdapt Ltd.
//------------------------------------------------------------------------------------------

var g_popWin;
var g_popWinXmlDoc;

function CPopWin( elId, isPosAnchoredParam, offSetXP, offSetYP )
{	
	this.m_winId = elId;
	this.m_elId = elId;
	this.m_isPosAnchoredParam = isPosAnchoredParam;
	this.m_offSetX = offSetXP || 0;
	this.m_offSetY = offSetYP || 0;
	this.m_isTitleBar = true;	
	this.m_isAnchoredToDock = false;
	
    this.m_outerFrameEl = CreateElement('div', 'xpopmenuouterframe', this.m_elId );    
	this.m_outerFrameEl.style.zIndex = GetTopZIndex( );    
    this.m_outerFrameEl.onclick = Focus;
        
	this.m_mainContentEl = CreateElement('div', 'xpopmenumaincontent' );		
	this.m_scrollingContentEl = CreateElement('div', 'xpopmenuscrollingcontent' );		
	this.m_statusBarEl = CreateElement('div', 'xmenustatusbar');		
	this.m_tabBarEl  = CreateElement('ul', 'xmenutabbar', 'xmenutabbar');
	
	this.m_staticContentParent = null;

	
	this.m_refreshCallback = null;	
	this.m_refreshCallbackParam = 0;	
	this.SetRefreshCallBack = SetRefreshCallBack;
	this.InvokeRefreshCallBack = InvokeRefreshCallBack;
		
	this.m_reloadUrl;
	this.SetReloadUrl = function( reloadUrl ){ this.m_reloadUrl = reloadUrl; }
	this.GetReloadUrl = function( ){ return  this.m_reloadUrl};
	
	this.m_isReloadable = false
	this.SetIsReloadable = function( isReloadable ){ this.m_isReloadable = isReloadable; }
	this.IsReloadable = function( ){ return this.m_isReloadable; }
	
	this.GetWinId = GetWinId;
	this.Render = Render;	
	this.RepaintHeight = RepaintHeight;
	this.RepaintWidth = RepaintWidth;
	this.AddContentItem = AddContentItem;
	this.AddTitleBar = AddTitleBar;
	this.SetIsTitleBar = SetIsTitleBar;
		
	this.SetIOMessage = SetIOMessage;	
	this.LaunchCopyContent = LaunchCopyContent;
	this.ReloadContent = ReloadContent;
	this.SetIsAnchoredToDock = SetIsAnchoredToDock;
	this.GetElId = function( ){return this.m_elId };
	g_popWin = this;
	this.m_activeEl = null;
	DAD_SetZIndex( this.m_outerFrameEl );
	this.Close = Close;
	g_popWinManager.AddPopWin( this.m_winId, this )
	
	this.m_launchXPos=0;
	this.m_launchYPos=0;
	this.SetLaunchPos = SetLaunchPos;	
	this.PositionOffEvent = PositionOffEvent;
	
	this.m_width = 300;
	this.m_height = 36;
	this.SetWidth = SetWidth;
	this.SetHeight = SetHeight;
	this.SetTitle = SetTitle;	
	this.WinSleep = WinSleep;
	this.WinWake = WinWake;
	
	this.m_tabsArray = new Array( );
	this.AddTabBar = AddTabBar;
	this.AddTab = AddTab;
	this.RenderTabBar = RenderTabBar;
	this.SelectTab = SelectTab;
}


function RenderTabBar( )
{			
	for( key in this.m_tabsArray)  //loop elements array and add content to window
	{				
		var tab	= this.m_tabsArray[key];		
		var tabEl = tab.GetTabOptionEl( );	
		tabEl.innerHTML = '<a href="#"  onclick="GlobalFunc_SelectTab(\'' + this.GetWinId( ) + '\',\'' +  key + '\');return false;">' + tab.GetTabName( ) + '</a>';
		this.m_tabBarEl.appendChild( tabEl );		
	}		
	if ( this.m_tabsArray.length != 0 )
	{
		this.m_tabBarEl.style.height = ValInPx( 26 );				
	}	
	//this.Repaint( );	
}

function GlobalFunc_SelectTab( winId, tabKey ) //This is not a method of the win object
{
	var win = g_popWinManager.GetPopWin( winId, tabKey );			
	win.SelectTab( tabKey );
}

function SelectTab( selectedTabKey )
{
	for( tabKey in this.m_tabsArray)  //loop elements array and add content to window
	{		
		var tab  =  this.m_tabsArray[ tabKey ];		
		if ( selectedTabKey == tabKey )
		{						
			tab.ShowContent( );
		}
		else
		{				
			tab.HideContent( );				
		}
	}	
}

function GetWinId( )
{
	return this.m_winId;
}

function WinSleep( )
{ 			
	this.SetIOMessage('<img src="/img/uix/iobar.gif" class="xiobar">');	
}

function WinWake( )
{		
	DestroyElement( 'winiomessageid' + this.GetWinId( ) );
}

function SetLaunchPos( launchXPos, launchYPos )
{
	this.m_launchXPos = launchXPos;
	this.m_launchYPos = launchYPos;
}

function SetWidth( width )
{
	this.m_width = width;
}

function SetHeight( height )
{
	this.m_height = height;
}

function PositionOffEvent( ev )
{
	var ev = GetCrossBrowserEvent( ev );    
	var posArray = GetPagePosArray( ev );
	this.SetLaunchPos(  posArray['x'], posArray['y']);	
}

function Focus( )
{
	 DAD_SetZIndex( this );
}

function SetIsAnchoredToDock( isAnchoredToDock )
{
	this.m_isAnchoredToDock = isAnchoredToDock;
}

function SetTitle( title )
{
	this.m_title = title;	
}

function SetRefreshCallBack( refreshCallback, refreshCallbackParam )
{
	this.m_refreshCallback = refreshCallback;
	this.m_refreshCallbackParam = refreshCallbackParam;
}

function InvokeRefreshCallBack( )
{
	if ( this.m_refreshCallback != null )
	{		
		this.ResetContent( );
		this.m_refreshCallback( this, this.m_refreshCallbackParam ); //callback
	}	
}

function LaunchCopyContent( contentId, title )
{
	this.SetTitle( title );
	this.Render( );
	var contentEl = document.getElementById( contentId );
	if ( contentEl )
	{
		this.m_staticContentParent = contentEl.parentNode;
		var menuOptionDiv=document.createElement('div');
		menuOptionDiv.className = 'xmenuitem';

		menuOptionDiv.appendChild( contentEl );
		contentEl.style.display ='block';

		this.m_scrollingContentEl.appendChild( menuOptionDiv );
	}
}

function Close( )
{
	if ( this.m_staticContentParent )
	{
		this.m_scrollingContentEl.firstChild.style.display = 'none';
		this.m_staticContentParent.appendChild( this.m_scrollingContentEl.firstChild );
	}
	DestroyElement( this.m_elId );
}

function ReloadContent( urlP )
{	
	var url = urlP || this.GetReloadUrl( );
	this.m_scrollingContentEl.innerHTML = '';	
	this.SetReloadUrl( url );
	FireJsonWinRequest(  this, url);	
}

function RepaintHeight( height )
{
	this.m_scrollingContentEl.style.height = ValInPx( height );
	if ( this.m_isAnchoredToDock )
	{
		var dockHeightPx = 16;
		//Hack for pop out menu		
		this.m_outerFrameEl.style.position = 'fixed'; 
		this.m_outerFrameEl.style.top = null;						
		this.m_outerFrameEl.style.bottom = ValInPx( dockHeightPx );
		this.m_outerFrameEl.isDragLocked = true;												
		var heightRequested =  parseInt(height) + parseInt(dockHeightPx*4);
		if ( GetViewPortHeight( ) <  heightRequested)
		{								
			this.m_scrollingContentEl.style.height = ValInPx( (GetViewPortHeight( )-80) );			
		}		
	}
}

function RepaintWidth( width )
{
	width+=30; //for win padding;
	//TODO - hack - no checking for render out of viewport.
	this.m_mainContentEl.style.width = ValInPx( width );
}

function SetIsTitleBar( isTitleBar )
{
	this.m_isTitleBar = isTitleBar;
}

function AddTitleBar( title )
{
	var barDiv = document.createElement('div');
	barDiv.style.width = this.m_mainContentEl.style.width; //val has "px" suffix already
	title = (title==''?'&nbsp':title);	
	var innerHtml = '<div class="xmenutitlebar" onmousedown="return DAD_StartDrag( event, \'' + this.m_elId + '\' );"  onmouseup="return DAD_EndDrag( );" >';	
	innerHtml += '<img src="/img/controls/' + ((this.m_isAnchoredToDock)?'popmin.gif':'popclose.gif') + '" class="xmenupopcloseicon" onclick="CloseWin(\'' + this.m_winId + '\');">';
	if(this.IsReloadable( ) )
	{
		innerHtml += '<img src="/img/controls/poprefresh.gif" class="xmenupopcloseicon" onclick="ReloadWin(\'' + this.m_winId + '\');">';
	}
	innerHtml += '<h2 class="xmenutitlebartitle">' + title + '</h2></div>'	  
	barDiv.innerHTML = innerHtml;
	this.m_mainContentEl.appendChild( barDiv );
}

function AddTabBar( )
{	
	this.m_tabBarEl.style.height = ValInPx( 0 );	
	this.m_mainContentEl.appendChild( this.m_tabBarEl );
}

function AddTab( tabName )
{
	var newTab = new CPopTab( this.GetWinId( ), tabName ); 	
	this.m_tabsArray[this.m_tabsArray.length] = newTab; 	
	return newTab;
}

function AddContentItem( itemDiv )
{
	this.m_scrollingContentEl.appendChild( itemDiv );
}


function Render( )
{
	if ( this.m_isTitleBar )
	{
		this.AddTitleBar( this.m_title );
	}	
	
	this.AddTabBar( this.m_isTabBar );	
		
	
		
	this.m_mainContentEl.appendChild( this.m_scrollingContentEl );
    this.m_outerFrameEl.appendChild( this.m_mainContentEl );    	
	this.m_mainContentEl.style.width = ValInPx( this.m_width  );
	this.m_outerFrameEl.visibility = 'visible';	
		
	document.body.appendChild( this.m_outerFrameEl );			
	PositionEl( this.m_outerFrameEl, this.m_launchXPos + this.m_offSetX, this.m_launchYPos + this.m_offSetY, this.m_isPosAnchoredParam );		
}

function SetIOMessage( ioMessage )
{
	if (ioMessage != '')
	{
		ioMessage = '<div id="winiomessageid' + this.GetWinId( ) + '" style="text-align:center;padding:6px;">' + ioMessage + '<div>';
	}
	this.m_scrollingContentEl.innerHTML = ioMessage;
	this.RepaintHeight( 48 );
}

function ProcessContentRefreshRequest( winId, url )
{
	if ( g_popWinManager.IsPopWin( winId ))
	{
		var popWin = g_popWinManager.GetPopWin( winId );
		popWin.ReloadContent( url );
	}
}

//------------------------------------------------------------------------------------------
// Pop Win class (c) netAdapt Ltd.
//------------------------------------------------------------------------------------------
function CPopTab( parentWinId, tabName ) 
{
	this.m_tabName = tabName;
	this.m_parentWinId = parentWinId;				
	
	this.m_contentContainerEl = CreateElement('div');		
	this.m_contentContainerEl.style.overflow = 'auto';	
	this.m_contentContainerEl.style.position = 'relative';
	this.m_contentContainerEl.style.display = 'none';
	this.m_contentContainerEl.ownerTab = this;
	this.m_isSelected = true;
	
	this.GetContentContainerEl = function( ) { return this.m_contentContainerEl; }
	this.HideContent = function( ) { this.m_tabOptionEl.className='xmenutab';this.m_isSelected = false; this.m_contentContainerEl.style.display = 'none'; }
	this.ShowContent = function( ) { this.m_tabOptionEl.className='xmenutabselected';this.m_isSelected = true; this.m_contentContainerEl.style.display = 'block'; }	
	this.IsSelected = function( ) { return this.m_isSelected;}
	
	this.GetTabName  = function( ) { return this.m_tabName };
	
	this.m_tabOptionEl = CreateElement('li', 'xmenutab');	
	this.GetTabOptionEl = function( ) { return this.m_tabOptionEl;}
}

function GetParentWinId( )
{
	return this.m_parentWinId;
}

function AddContentArea( )
{
	this.m_contentContainerEl.style.width = this.m_containerEl.style.width; //val has "px" suffix already		
	this.m_containerEl.appendChild( this.m_contentContainerEl );	
}

//------------------------------------------------------------------------------------------
// Pop Win Manager class (c) netAdapt Ltd.
//------------------------------------------------------------------------------------------
function CPopWinManager(  )
{
	this.m_popWinArray = new Array( );
	this.AddPopWin 	= AddPopWin;
	this.GetPopWin 	= GetPopWin;
	this.RemoveWin = RemoveWin;
	this.IsPopWin = IsPopWin;
}

function AddPopWin( popWinId, popWin )
{
	this.m_popWinArray[ popWinId ] = popWin;
}

function IsPopWin( popWinId )
{
	if (this.m_popWinArray[ popWinId ])
	{
		return true;
	}
	return false;
}

function GetPopWin( popWinId )
{
	return this.m_popWinArray[ popWinId ];
}

function GetLastPopWin( )
{
	return this.m_popWinArray[ this.m_popWinArray.length ];	
}

function RemoveWin( popWinId )
{
	if ( this.IsPopWin( popWinId ))
	{
		var popWin = this.GetPopWin( popWinId );
		popWin.Close( );
		delete this.m_popWinArray[ popWinId ];
	}
}

var g_popWinManager = new CPopWinManager( );
var g_debugComConsoleWinId = 0;