var PlayNowController = {
	Command : '',
	GameVersion : 0,
	UpdatePollRef : null,
	Cancelled : false,
	
	IsInitialRequest : false,
	UpdateInterval : 1500,

	Search : function(cmd, gameVersion)
	{
		if (!IsAvailable())
			return ShowUnavailableLightbox();

		cmd = GetCompleteSearchCommand(cmd, gameVersion);
		
		PlayNowController.Command = cmd;
		PlayNowController.GameVersion = gameVersion;
		PlayNowController.Cancelled = false;
		PlayNowController.IsInitialRequest = true;

		// Show Waiting Screen
		$('PlayNowStatus').innerHTML = "Searching for an optimal server to join...";
		$('PlayNowInformation').hide();
		$('PlayNowInGameConnectWarning').hide();
		$('PlayNowCancelButton').innerHTML = 'Cancel Search';
		ShowLightbox('PlayNowLightbox');
		
		PlayNowController.SearchInternal(cmd, gameVersion);
	},
	
	SearchInternal : function(cmd, gameVersion) {
		var req = CreateAjaxRequest();
		req.onreadystatechange = function() {
			if (req.readyState != 4)
				return;
			
			// Show Waiting Screen
			$('PlayNowInformation').show();

			var bits = req.responseText.split('\t');
			switch(bits[0]) {
				case 'ACK':
					// ACK Description
					// Keep trying
					$('PlayNowDescription').innerHTML = bits[1];

					// Re-request immediately if we just finished our initial info gather request
					var nextInterval = PlayNowController.IsInitialRequest ? 0 : PlayNowController.UpdateInterval;
					if (PlayNowController.IsInitialRequest)
						PlayNowController.IsInitialRequest = false;
					
					if (!PlayNowController.Cancelled)
						PlayNowController.UpdatePollRef = window.setTimeout('PlayNowController.SearchInternal("' + PlayNowController.Command + '", ' + PlayNowController.GameVersion + ')', nextInterval);
					break;
				case 'CONNECT':
					if (PlayNowController.Cancelled)
						return;
						
					// CONNECT Description ServerDetails ConnectUrl
					$('PlayNowDescription').innerHTML = bits[1];
					$('PlayNowStatus').innerHTML = "Connecting to " + bits[2];
					$('PlayNowCancelButton').innerHTML = 'Close Window';

					if (ShowJoinRetryInfo())
						$('PlayNowInGameConnectWarning').show();

					JoinServerAndUpdateUI(bits[3]);
					break;
				case 'NAK':
				default:
					alert("Play Now request failed");
					break;
			}
		};

		req.open("POST", "/play.php?cmd=" + escape(cmd) + '&game=' + gameVersion + (PlayNowController.IsInitialRequest ? '&init=1' : '') + '&cb=' + GetRandomNumber(), true);
		req.send(null);
	},
	
	Cancel : function() {
		PlayNowController.Cancelled = true;

		if (PlayNowController.UpdatePollRef)
			window.clearTimeout(PlayNowController.UpdatePollRef);

		PlayNowController.UpdatePollRef = null;
		HideLightbox();
	}
};
