var g_params = new Object();

var playersOnlineRefresh = false;

("?" + document.cookie.replace(/;[ ]*/g, "&")).replace(/([^?=&]+)(=([^&]*))?/g, function( $0, $1, $2, $3 ){ g_params[ $1 ] = unescape( $3 ); });
window.location.search.replace(/([^?=&]+)(=([^&]*))?/g, function( $0, $1, $2, $3 ){ g_params[ $1 ] = unescape( $3 ); });


var g_sessionId = null;

function tabEventHandler(tabId, activatedHandler, deactivatedHandler)
{
	this.tabId = tabId;
	this.activatedHandler = activatedHandler;
	this.deactivatedHandler = deactivatedHandler;
}

var g_arrayTabEventHandlers = new Array();

function addTabEventHandler(tabId, activatedHandler, deactivatedHandler)
{
	var handler = new tabEventHandler( tabId, activatedHandler, deactivatedHandler );
	g_arrayTabEventHandlers.push( handler );
}

function OnClickTab( tab )
{
	var table = tab.parentNode;
	var deactivatedTabId;
	if (!((table.getAttribute( 'currentTab' ) == null) || (table.getAttribute( 'currentTab' ) == '')))
	{
		document.getElementById( table.getAttribute( 'currentTab' )).className = "Tab";
		deactivatedTabId = table.getAttribute( 'currentTab' );
	}
	
	if (!((table.getAttribute( 'currentTabBody' ) == null) || (table.getAttribute( 'currentTabBody' ) == '')))
	{
		document.getElementById( table.getAttribute( 'currentTabBody' )).style.display = "none";	
	}
	
	table.setAttribute( 'currentTab', tab.id );
	table.setAttribute( 'currentTabBody', document.getElementById( tab.getAttribute( 'tabbody' )).id );
	
	document.getElementById( table.getAttribute( 'currentTab' )).className = "SelectedTab";
	document.getElementById( table.getAttribute( 'currentTabBody' )).style.display = "block";
	
	for (var i=0; i<g_arrayTabEventHandlers.length; i++)
	{
		var handler = g_arrayTabEventHandlers[ i ];
		if (handler.tabId == deactivatedTabId)
		{
			handler.deactivatedHandler();
		}
		else if (handler.tabId == tab.id)
		{
			handler.activatedHandler();
		}
	}
}

function getMethodUrl( service, method )
{
	return "/dsuss.Server/" + service + ".asmx/" + method;
}

function call( service, method, parameters )
{
	var xml = callXml( service, method, parameters );

	if (xml == null)
	{
		return null;
	}

	var objectType = xml.tagName;
	var json = xml2json( xml, "" ).replace( "{\r\tunnamed" );
	
	eval( "var o = " + json );
	if ( eval( "o." + objectType + "['diffgr:diffgram']" ) == null )
	{
		return eval( "o." + objectType );
	}

	return eval( "o." + objectType + "['diffgr:diffgram']." + objectType );
}

function callXml( service, method, parameters )
{
	window.status = "Calling " + service + method + "...";
	var xmlHttp = new XMLHttpRequest();
	var returnValue = null;

	try
	{
		xmlHttp.open( "POST", getMethodUrl( service, method ), false);

		xmlHttp.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

		if ( parameters )
		{
			xmlHttp.send( parameters );
		}
		else
		{
			xmlHttp.send( null );
		}

		// this is a temporary workaround for "xmlHttp.onreadystatechange = function()" notation to work in both firefox and IE 
		// consider changing callText also
		if (xmlHttp.readyState == 4)
		{
			if (xmlHttp.status == 200)
			{
				// this is different in firefox and IE, firefox gives only 1 element, the actual return object while IE gives 2, header(I guess) and a return object.
				if (xmlHttp.responseXML != null) {
					if (xmlHttp.responseXML.childNodes.length == 1) {
						returnValue = xmlHttp.responseXML.childNodes[0];
					} else {
						returnValue = xmlHttp.responseXML.childNodes[1];				
					}
				}
			}			
			else
			{
				returnValue = null;
			}
			
			window.status = "Done";
		}
		
	}
	catch (e)
	{
		window.status = service + method + " error: " + e;
	}

	return returnValue;
}

function callText( service, method, parameters )
{
	window.status = "Calling " + service + method + "...";
	var xmlHttp = new XMLHttpRequest();
	var returnValue = false;
	xmlHttp.open( "POST", getMethodUrl( service, method ), false);
	xmlHttp.onreadystatechange = function()
	{
		if (xmlHttp.readyState == 4)
		{
			if (xmlHttp.status == 200)
			{
				returnValue = xmlHttp.responseText;
			}
			else
			{
				returnValue = null;
			}
			
			window.status = "Done";
		}
	}
	
	xmlHttp.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
	
	if ( parameters )
	{
		xmlHttp.send( parameters );
	}
	else
	{
		xmlHttp.send();
	}

	return returnValue;
}

function getSessionId()
{
	if (g_sessionId != null)
	{
		return g_sessionId;
	}
	
	return g_params[ "sid" ];
}

function getCurrentUserName()
{
	if (getSessionId() == null)
	{
		return null;
	}
	
	return g_params[ "userName" ];
}

function getCurrentName()
{
	if (getSessionId() == null)
	{
		return null;
	}

	return g_params[ "name" ];
}

function getCurrentDisplayName()
{
	if (getSessionId() == null)
	{
		return null;
	}

	return g_params[ "displayName" ];
}


function getGameId()
{
	if (getSessionId() == null)
	{
		return null;
	}

	return g_params[ "gid" ];
}

function isGuest()
{
	return g_params[ "isGuest" ] == "true";
}

// WebServiceParameters class
function WebMethodParameters( addSessionId )
{
	this.all = addSessionId == true ? "sessionId=" + getSessionId() : "";
	
	this.add = function(name, value)
	{
		if (this.all.length > 0)
		{
			this.all += "&" + name + "=" + value;
		}
		else
		{
			this.all += name + "=" + value;
		}
	}
}
// WebServiceList class
function CommaSeparatedList()
{
	this.items = "";
	
	this.add = function(item)
	{
		if (this.items.length > 0)
		{			
			this.items += "," + item;
		}
		else
		{
			this.items += item;
		}
	}
}

function includeCSS( fileName )
{
	var cssLinkElement  = document.createElement('link');
	cssLinkElement.rel = 'stylesheet'
	cssLinkElement.type = 'text/css';
	cssLinkElement.href = fileName;
	document.getElementsByTagName('head')[0].appendChild( cssLinkElement );
}

function includeStringTable( stringTableName )
{
	var locale = g_params['locale'];
	if (locale != null)
	{
		setLanguage( locale, true );
	}
	var scriptElement  = document.createElement('script');
	scriptElement.language = 'javascript'
	scriptElement.src = 'js/Localization/' + (locale == null ? 'da-DK' : locale) + '/' + stringTableName + '.js';
	document.getElementsByTagName('head')[0].appendChild( scriptElement );
}

function addEvent(element, evt, func) {

	element = document.getElementById(element);
	if (navigator.appName == "Microsoft Internet Explorer") {
		element.atachEvent("on" + evt, func);
	} else {
		element.addEventListener(evt, func, false);
	}
}

var g_gameBriefData = null;
var g_gameBriefDataGameId = -1;

function getGameBriefData(noCached)
{
	var gameId = getGameId();
	if (gameId == null) {
		return null;
	}
	
	if ((g_gameBriefDataGameId == gameId) && ((noCached == null) || (noCached == false)))
	{
		return g_gameBriefData;
	}
	
	var parameters = new WebMethodParameters( true );
	parameters.add("gameId", gameId);

	var gameBriefData = call("Game/Game", "GetActiveGameBriefData", parameters.all);
	if (gameBriefData == null) {
		return null;
	} else {
		g_gameBriefData = gameBriefData["GameBrief"];
		g_gameBriefDataGameId = gameId;
		return g_gameBriefData;
	}
}

function removeElement(element) {
	if (element.parentNode && element.parentNode.removeChild) {
		element.parentNode.removeChild(element); 
	}
}

function getRadioValue(radioGroupName) {
	var value;
	var radioGroup = document.getElementsByName(radioGroupName);
	for (var i=0; i < radioGroup.length; i++) {
		if (radioGroup[i].checked) {
			value = radioGroup[i].value;
		}
	}

	return value;
}

function backLink() {

	var gameData = getGameBriefData( true );
	if (gameData != null && (compareUserNames( gameData.WhiteUsername, getCurrentUserName()) || compareUserNames( gameData.BlackUsername, getCurrentUserName()))) {
		var abandon = confirm( dsuss_WebClient.NavigatingOffGame );

		if (abandon == true) {
			var parameters = new WebMethodParameters( true );
			parameters.add( "gameId", getGameId());

			call("Game/Game","Resign",parameters.all);

			g_params["gid"] = null;
			document.location = "Welcome.aspx?sid=" + getSessionId();
		}
	} else {
		if (gameData != null) {
			var parameters = new WebMethodParameters( true );
			parameters.add( "gameId", getGameId());

			call("Game/Game","StopWatching",parameters.all);
		}

		document.location = "Welcome.aspx?sid=" + getSessionId();
	}
}

function profileLink() {

	stopEventsProcessing();
	document.location = "Profile.aspx?sid=" + getSessionId();
}

function setLanguage( localeId, doNotReload )
{
	date = new Date();
	date.setFullYear( date.getFullYear() + 5 );
	document.cookie = "locale=" + escape( localeId ) + "; expires=" + date.toGMTString();
	
	if (!doNotReload)
	{
		stopEventsProcessing();
		document.location.reload();
	}
}

function startRefreshingControl( tabId )
{
	if (tabId == "PlayersOnlineTab")
	{
		playersOnlineRefresh = true;
		getOnlineUsers();
	}
	
	if (tabId == "PlayerDetailsTab")
	{
		playersOnlineRefresh = false;
	}
	
	if (tabId == "all")
	{
		playersOnlineRefresh = true;
		getOnlineUsers();
	}
}

function compareUserNames(userName1, userName2)
{
	if ((userName1 == null) || (userName2 == null))
	{
		return false;
	}
	
	try
	{
		return userName1.toLowerCase() == userName2.toLowerCase();
	}
	catch (e)
	{
		return false;
	}
}

function showPleaseWaitPopup(buttonId)
{
	if (buttonId != null)
	{
		document.getElementById( buttonId ).disabled = true;
	}
	
	var popup = new popupWindow( null, dsuss_WebClient.PleaseWaitCaption, "myPopupStyle" );		
	popup.show( "pleaseWaitPopup", dsuss_WebClient.ProcessingRequestText, 200, 64 );
}

includeStringTable( "dsuss.WebClient" );

function dsuss_WebClient_StringsLoaded()
{
}