//Methods
var isOpening = false;
var defaultWidth = 1024;
var defaultHeight = 768;

function DetectUnityWebPlayer (){
    var gPluginVersion;
    var gUnityVersion;
    var tInstalled = false;

  if (navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1)
  {
	  try
	  {
      var tControl = new ActiveXObject("UnityWebPlayer.UnityWebPlayer.1");
	  }catch(err){}

    if(tControl != null && tControl != undefined)
    {
	      try {
	            gPluginVersion = tControl.GetPluginVersion();
	            gUnityVersion = tControl.GetUnityVersion("2.x.x");
	            tInstalled = true; //To be removed when we get more specific version checking below
	      } catch( e ) { }

          if(gPluginVersion == "2.5.0f5")
          {
        	  tInstalled = false;
              // 2.5.0f5 on Vista and later has an auto-update issue
              // on Internet Explorer. Detect Vista (6.0 or later)
              // and in that case treat it as not installed
              var ua = navigator.userAgent;
              var re = new RegExp(/Windows NT (\d+)\./);
              var matches = re.exec( ua.toString() );

              if(matches != null)
                  if(parseInt(matches[1].toString()) < 6)
                      tInstalled = true;
          }
      }
  }
  else
  {
      if (navigator.mimeTypes && navigator.mimeTypes["application/vnd.unity"])
      {
          if (navigator.mimeTypes["application/vnd.unity"].enabledPlugin && navigator.plugins && navigator.plugins["Unity Player"])
          {
                if (navigator.appVersion.toLowerCase().indexOf("safari") != -1)
                {
                      $("#main").append( "<embed id='UnityVersionCheck' type='application/vnd.unity' width='1' height='1''> </embed>" );
                }
                else
                {
                      $("#main").append( "<object id='UnityVersionCheck' type='application/vnd.unity'> </object>" );
                }

                try {
                      gPluginVersion = $("#UnityVersionCheck").get(0).GetPluginVersion();
                      gUnityVersion = $("#UnityVersionCheck").get(0).GetUnityVersion("2.x.x");
                      tInstalled = true; //To be removed when we get more specific version checking below
                } catch( e ) { }
          }
      }
  }

  if(gPluginVersion== undefined || gUnityVersion == undefined)
  {
    tInstalled = false;
  }
  else if(gPluginVersion.indexOf("b") >= 0 )
  {
    tInstalled = false;
  }
  else
  {
	  tInstalled = true;
	  	  
	  if(gPluginVersion.indexOf("2.5.0") >= 0 && gPluginVersion.indexOf("f5") < 0)
		  tInstalled = false;
	  else if(gPluginVersion.indexOf("2.5.1") >= 0 && gPluginVersion.indexOf("f5") < 0)
		  tInstalled = false;
	  else if(gPluginVersion.indexOf("2.6.0") >= 0 && gPluginVersion.indexOf("f7") < 0)
		  tInstalled = false;
	  else if(gPluginVersion.indexOf("2.6.1") >= 0 && gPluginVersion.indexOf("f3") < 0)
		  tInstalled = false;
  } 
  /* == Removed until we have an issue with these certain versions ===
  else{
          var splitPluginVersion = gPluginVersion.split("f");
          var splitUnityVersion = gUnityVersion.split("f");

          if( ( (splitPluginVersion[0] == "2.6.0" || splitPluginVersion[0] == "2.6") && splitPluginVersion[1] != "f4" )
                      || ( (splitPluginVersion[0] == "2.5.1") && splitPluginVersion[1] != "f5")
                || ( (splitUnityVersion[0] == "2.6.0" || splitUnityVersion[0] == "2.6") && splitUnityVersion[1] != "f4" )
                      || ( (splitUnityVersion[0] == "2.5.1") && splitUnityVersion[1] != "f5"))
                tInstalled = false;
          else
                tInstalled = true;
    }
    */

  return tInstalled;
}

function startGame(gameMode, startupOptionsString)
{
    window.name = "parentWindow";
	var installed = DetectUnityWebPlayer();
	document.cookie = "TWOCookie[startupOptions]=" + startupOptionsString + ";path=/";
	openUnityWindow(gameMode, installed);
}

function callFacebookDemoPlayGameOptions(defaultGameSettingsId)
{
	startGame("demo", "facebook_demo|" + defaultGameSettingsId);
}

// not logged in, demo game
function callDemoPlayGameOptions(defaultGameSettingsId)
{
	startGame("demo", "demo|" + defaultGameSettingsId);
}

// normal single player game
function callPlayGameOptions(gameMode)
{
	startGame(gameMode, "fe_menu");
}

// resuming games
function callPlayGame(gameMode)
{
	startGame(gameMode, "resume");
}

function callMultiplayerPlayGameOptions(gameMode, sessionId, characterId, outfitId, genderId)
{
	startGame(gameMode, "multiplayer|" + sessionId + '|' + characterId + '|' + outfitId + '|' + genderId);
}

function callTournamentPlayGameOptions(gameMode, tournamentId)
{
	startGame(gameMode, "tournament|" + tournamentId);
}

//
// Common code to open the unity game window
//
function openUnityWindow(gameMode, isUnityInstalled)
{

	if(!isOpening)
	{
		isOpening = true;
		
		// if not demo, need to make sure we are logged in before opening window
		if (gameMode != 'demo')
		{
			html = $.ajax
			(
				{
					url: "/users/ping",
					async: false,
					cache: false
				}
			).responseText;
		}
		// demo mode, no session check
		else
		{
			html = '1';
		}
		
		// 0 means no user session, so anything but that is good to go...
		if (html != "0")
		{
			//load cookies	
			//split out cookies to actual values
			var windowType;
			var resWindowWidth;
			var resWindowHeight;
			var WindowX;
			var WindowY;
			
			if(getCookie("TWOCookie[window_type]") != null)
				windowType = getCookie("TWOCookie[window_type]");
			if(getCookie("TWOCookie[game_resolution]") != null)
			{
				resWindowWidth = getCookie("TWOCookie[game_resolution]").split('x')[0];
				resWindowHeight = getCookie("TWOCookie[game_resolution]").split('x')[1];
			}
				
			//setup defaults
			if(windowType == undefined)
				windowType = "PopUpWindow";
			if(resWindowWidth == undefined)
				resWindowWidth = defaultWidth;
			if(resWindowHeight == undefined)
				resWindowHeight = defaultHeight;		
				
			var resContentWidth;
			var resContentHeight;
		
			  if($.browser.msie)
			  {
				//alert("IE");
				resWindowWidth = resWindowWidth - 12;
				resWindowHeight = resWindowHeight - 60;
				resContentWidth = resWindowWidth;
				resContentHeight = resWindowHeight;	
			  }
			  if($.browser.mozilla)
			  {
				//alert("Mozilla");
				resWindowWidth = resWindowWidth - 8;
				resWindowHeight = resWindowHeight - 110;
				resContentWidth = resWindowWidth;
				resContentHeight = resWindowHeight;	
			  }
			  if($.browser.safari)
			  {
				//alert("safari");
				//hasn't been tweaked yet
				resWindowWidth = resWindowWidth - 6;
				resWindowHeight = resWindowHeight - 60;
				resContentWidth = resWindowWidth;
				resContentHeight = resWindowHeight;	
			  }
			  if($.browser.opera)
			  {
				//alert("opera");
				//hasn't been tweaked yet
				resWindowWidth = resWindowWidth - 10;
				resWindowHeight = resWindowHeight - 74;
				resContentWidth = resWindowWidth;
				resContentHeight = resWindowHeight;	
			  }
			  
			  //set cookies for next page
			  document.cookie = "TWOCookie[game_mode]=" + gameMode + ";path=/";
			  
			  //Calculate centering the window
			  WindowX = parseInt((screen.availWidth /2) - (resWindowWidth/2));
			  WindowY = parseInt((screen.availHeight /2) - (resWindowHeight/2));
			  			

            var url = '/play/popupwindow?w=' + resContentWidth + '&h=' + resContentHeight;

            if(windowType == "PopUpWindow") //show game window based on selected
			{
				var newWin = window.open(url, 'gamewindow','toolbar=0,menubar=0,statusbar=0,resizable=1,width=' + resWindowWidth + ',height=' + resWindowHeight + ',left=' + WindowX + ',top=' + WindowY);
				newWin.REFERRER = document.referrer; // So we can detect where we're coming from, e.g.; Facebook
                //newWin.focus();
			}
			
			//disable slider on main page
			allowSliderScrolling = false;
			isOpening = false;
		}
		// session expired, do a redirect back to login instead of game opener popup
		else
		{
			window.location = '/users/viewAltLogin/INACTIVITY';
		}
	}
}

function updateCanRefreshData(newFlag)
{
	canRefreshData = newFlag;
}

function getUrlVars()
{
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

// The registerUser function opens the registration window in a pop-up based on the parameters that are passed. Use this when 
// the user clicks on any button to register. 
function registerUser(gameSettingsId, roundId, promotionTemplate, promotionSlug, email)
{
	// Launch the registration window
	var startupOptions = 'promotion|' + gameSettingsId + '|' + roundId + '|' + promotionTemplate;
	var parameters = '&startupOptions=' + startupOptions + '&email=' + email + '&game_mode=demo&pre';
	var paramsArray = getUrlVars();
	if(paramsArray["surl"] != undefined)
		parameters += "&surl=" + paramsArray["surl"];
	
	openPromotionalGameWindow('/newuser/register', parameters, promotionSlug);
}

var canRefreshData = true;

$(function() {
	
	// Launch the game from any href with a class name of "gamelauncher"
	$("a.gamelauncher").click(function () 
	{
		callPlayGame("normal");
	});
});

// displaying the proper setting in the 'play now' button
var windowRes;

if(getCookie('TWOCookie[game_resolution]') != null)
{
	windowRes = getCookie('TWOCookie[game_resolution]');
}



