var debug = 0;

function CMenuItem(id, text, show, selected, locked, item)
{
	this.id = id;
	this.text = text;
	this.show = show;
	this.selected = selected;
	this.locked = locked;
	this.item = item;
	
	this.render = function()
	{
		if(!show)
			return "";
			
		if(this.locked)
			return "<div id=\"menu-"+this.id+"\" class=\"item\"><span>"+this.text+"</span></div>";
		
		var selected = "";
		if(this.selected)
			selected = " class=\"selected\"";
		
		return "<a id=\"menu-"+this.id+"\""+selected+" href=\"javascript:game.menu.select('"+this.id+"')\"><span>"+this.text+"</span></a>";
	}	
}

function CMenu(parent)
{
	this.parent = parent;
	
	this.items = new Array();
	
	this.create = function()
	{
		this.items.push(new CMenuItem("game", l.get("menu-game", []), 1, 1, 0, this.parent));
		this.items.push(new CMenuItem("mazes", l.get("menu-mazes", []), this.parent.detected, 0, 0, this.parent.maze));
		this.items.push(new CMenuItem("activity", l.get("menu-activity", []), this.parent.detected, 0, 0, this.parent.activity));
		this.items.push(new CMenuItem("leaderboard", l.get("menu-leaderboard", []), this.parent.detected, 0, 0, this.parent.stats));
		this.items.push(new CMenuItem("instructions", l.get("menu-instructions", []), this.parent.detected, 0, 0, this.parent.instructions));
	}
	
	this.showItem = function(item, show)
	{
		for(var i = 0; i < this.items.length; i++)
		{
			if(this.items[i].id == item)
			{
				this.items[i].show = show;
				break;
			}
		}
		
		if(this.items[i].name != "game")
			mE("user").hide();
		
		this.render();
	}
	
	this.lockItem = function(item)
	{
		for(var i = 0; i < this.items.length; i++)
		{
			if(this.items[i].id == item)
			{
				this.items[i].locked = 1;
				break;
			}
		}
		
		this.render();
	}
	
	this.unlockItem = function(item)
	{
		for(var i = 0; i < this.items.length; i++)
		{
			if(this.items[i].id == item)
			{
				this.items[i].locked = 0;
				break;
			}
		}
		
		this.render();
	}
	
	this.updateItemFunc = function(item, func)
	{
		for(var i = 0; i < this.items.length; i++)
		{
			if(this.items[i].id == item)
			{
				this.items[i].item = func;
				break;
			}
		}
		
		this.render();
	}
	
	this.render = function()
	{
		var content = "";
		for(var i = 0; i < this.items.length; i++)
			content += this.items[i].render();
		
		if(this.parent.detected)
			content += "<div id=\"menu-user\"><a id=\"menu-connect\" href=\"javascript:game.fb.show()\"><span>"+l.get("menu-connect", [])+"</span></a><a id=\"menu-logout\" href=\"javascript:game.fb.logout()\"><span>"+l.get("menu-logout", [])+"</span></a><a id=\"menu-asset\" href=\"javascript:game.fb.photo.current()\"><span>"+l.get("menu-asset", [])+"</span></a></div>";

		gE("menu").innerHTML = content;

	    if(game.fb.user == null)
	    {
	      mE("menu-connect").show();
	      mE("menu-mazes,menu-activity,menu-asset,menu-logout").hide();
	    }
	    else
	    {
	      mE("menu-connect").hide();
	      mE("menu-mazes,menu-activity,menu-asset,menu-logout").show();
	    }
	}
	
	this.select = function(id)
	{
		//this.parent.messages.hide();
		if(game.messages.isVisible())
			return;
		
		this.parent.hideLoader();
		
		for(var i = 0; i < this.items.length; i++)
		{
			this.items[i].selected = 0;
			
			if(this.items[i].item)
				this.items[i].item.hide();
				
			if(this.items[i].id == id)
			{
				this.items[i].selected = 1;
		
				if(this.items[i].item)
					this.items[i].item.show();
			}
		}

		this.render();
	}
	
	this.getSelected = function(item)
	{
		for(var i = 0; i < this.items.length; i++)
		{
			if(this.items[i].id == item)
			{
				return this.items[i].selected;
			}
		}
		
		return 0;
	}
}

function CUnity()
{
	this.hidden = 0;
	this.forcedHide = 0;
	
	this.detected = false; //unity detection

	this.fb = new CFb();
	
	this.instructions = new CInstructions(this);
	this.stats = new CStats(this);
	this.maze = new CMaze(this);
	this.menu = new CMenu(this);
	this.messages = new CMessages(this);
	this.activity = new CActivity(this);
		
	this.get = function()
	{
		if (navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1)
			return gE("UnityObject");
		else if (navigator.appVersion.toLowerCase().indexOf("safari") != -1)
			return gE("UnityObject");
		else
			return gE("UnityEmbed");
	}

	this.detect = function()
	{
		var tInstalled = false;
		if(navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1)
			tInstalled = DetectUnityWebPlayerActiveX();
		else if(navigator.mimeTypes && navigator.mimeTypes["application/vnd.unity"] && navigator.mimeTypes["application/vnd.unity"].enabledPlugin && navigator.plugins && navigator.plugins["Unity Player"])
			tInstalled = true;
		
		this.detected = tInstalled;
		
		return tInstalled;
	}
	
	this.getInstallerPath = function()
	{
		var tDownloadURL = "";
		var hasXpi = navigator.userAgent.toLowerCase().indexOf( "firefox" ) != -1;
	
		// Use standalone installer
		if(1)
		{
			if (navigator.platform == "MacIntel")
				tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/webplayer-i386.dmg";
			else if (navigator.platform == "MacPPC")
				tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/webplayer-ppc.dmg";
			else if (navigator.platform.toLowerCase().indexOf("win") != -1)
				tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayer.exe";
			return tDownloadURL;
		}
		// Use XPI installer
		else
		{
			if (navigator.platform == "MacIntel")
				tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayerOSX.xpi";
			else if (navigator.platform == "MacPPC")
				tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayerOSX.xpi";
			else if (navigator.platform.toLowerCase().indexOf("win") != -1)
				tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayerWin32.xpi";
			return tDownloadURL;
		}    			
	}
	
	this.autoReload = function()
	{
		navigator.plugins.refresh();
	
		if(game.detect())
			window.location.reload();
		
		setTimeout(game.autoReload, 500);
	}

	this.init = function(build, server, maze, target)
	{
		var content = "";
		
		var detected = this.detect();
		if(detected)
		{		
			content += "<object id=\"UnityObject\" classid=\"clsid:444785F1-DE89-4295-863A-D46C3A781394\" width=\""+c.unity.width+"\" height=\""+c.unity.height+"\">";
			content += "<param name=\"src\" value=\""+server+"/unity/"+build+".unity3d\" />";
			content += "<param name=\"backgroundcolor\" value=\""+c.unity.backgroundColor+"\" />";
			content += "<param name=\"bordercolor\" value=\""+c.unity.borderColor+"\" />";
			content += "<param name=\"textcolor\" value=\""+c.unity.textColor+"\" />";
			content += "<param name=\"disableFullscreen\" value=\""+c.unity.disableFullscreen+"\" />";
			content += "<param name=\"logoimage\" value=\"images/"+c.unity.logoImage+"\" />";
			content += "<param name=\"progressbarimage\" value=\""+c.unity.progressbarImage+"\" />";
			content += "<param name=\"progressframeimage\" value=\""+c.unity.progressbarFrameImage+"\" />";
			content += "<embed id=\"UnityEmbed\" src=\""+server+"/unity/"+build+".unity3d\" width=\""+c.unity.width+"\" height=\""+c.unity.height+"\" disableFullscreen=\""+c.unity.disableFullscreen+"\" logoimage=\"images/"+c.unity.logoImage+"\" progressbarimage=\""+c.unity.progressbarImage+"\" progressframeimage=\""+c.unity.progressbarFrameImage+"\" backgroundcolor=\""+c.unity.backgroundColor+"\" bordercolor=\""+c.unity.borderColor+"\" textcolor=\""+c.unity.textColor+"\" type=\"application/vnd.unity\" pluginspage=\"http://www.unity3d.com/unity-web-player-2.x\" />";
			content += "</object>";
		}
		else
		{
 			content += "<div id=\"unity-install1\"><h2>"+l.get("unity-head", [])+"</h2>";
			content += l.get("unity-text1", [])+"<br /><br />";
			content += l.get("unity-text2", [])+"<br /><br /></div>";
        
			var installerPath = this.getInstallerPath();
			if(installerPath != "")
			{
				// Place a link to the right installer depending on the platform we are on. The iframe is very important! Our goals are:
				// 1. Don't have to popup new page
				// 2. This page still remains active, so our automatic reload script will refresh the page when the plugin is installed
				
				content += "<div align=\"center\" id=\"UnityPrompt\">";
				content += "<a href=\"" + installerPath + "\"><img src=\"http://webplayer.unity3d.com/installation/getunity.png\" border=\"0\"/></a>";
				content += "</div>";
				content += "<iframe name=\"InstallerFrame\" height=\"0\" width=\"0\" frameborder=\"0\"></iframe>";
			}
			else
			{
				content += "<div align=\"center\" id=\"UnityPrompt\">";
				content += "<a target=\"_new\ \"href=\"http://www.unity3d.com/unity-web-player-2.x\"><img src=\"http://webplayer.unity3d.com/installation/getunity.png\" border=\"0\"/></a>";
				content += "</div>";
			}
			
			content += "<div id=\"unity-install2\">"+l.get("unity-text3", [])+"<br /><br />";
			content += "<a target=\"_new\" href=\"/instructions/ie.html\">Internet Explorer</a><br />";
			content += "<a target=\"_new\" href=\"/instructions/firefox.html\">Mozilla Firefox</a><br />";
			content += "<a target=\"_new\" href=\"/instructions/safari.html\">Safari (Mac)</a>";
			content += "</div>";
			
			this.autoReload();
		}
		
		this.detected = detected;
		
		if(detected)
		{
			this.fb.init();
			this.fb.target.uid = target;
		}
		else
			this.hideLoader();
		
		var e = gE('game');
		
		if(e)
			e.innerHTML = content;
			
		e.style.display = "block";
		
		if(maze > 0)
			this.maze.load(maze);
		
		//detect chrome on a mac
		if(isMacChrome())
		{
			var content = "";
			
			content += "<h2>"+l.get("warning-mac-chrome-head")+"</h2>";
			content += "<p>"+l.get("warning-mac-chrome")+"</p>";
			content += "<div style=\"text-align: center;\"><input type=\"button\" value=\""+l.get("warning-mac-chrome-ok")+"\" onclick=\"javascript:game.messages.hide()\" /></div>";
			
			this.messages.show("mac-chrome", content);
		}
		
		this.menu.create();
		this.menu.render();
	}
	
	this.show = function()
	{
		//only if the game tab is selected
		if(!this.menu.getSelected("game"))
			return;

 		if(isIE())
	    {
	    	mE("game").show();
	      
	    	if(game.fb.user != null || game.fb.target.uid != null)
	      	mE("user").show();
	    }

		var u = game.get();
		
		if(u && game.hidden)
		{
			game.hidden = 0;
			game.forcedHide = 0;
			
			u.style.width = c.unity.width+"px";
			u.style.height = c.unity.height+"px";
			
			gE("game").className = "";
			
			//update footer
			/*
			var e = gE("footer");
			if(e)
			{
        		e.style.position = "absolute";
				e.style.bottom = "0px";
				//e.style.top = "750px";
			}
			*/
			window.scroll(0,0);
			
			if(game.fb.user != null || game.fb.target.uid != null)
      		mE("user").show();
		}
	}

	this.hide = function()
	{
		var u = game.get();
		if(u && !game.hidden)
		{
			game.hidden = 1;
			game.forcedHide = 1;
			
			u.style.width = "1px";
			u.style.height = "1px";

			gE("game").className = "hidden";
				
			//update footer
			/*
			var e = gE("footer");
			if(e)
			{
		        e.style.position = "relative";
				e.style.bottom = "";
				e.style.top = "";
			}
			*/
			window.scroll(0,0);
			
			mE("user").hide();
		}
	}
	
	this.hideLoader = function(){	gE('loader').style.display = "none";	}
	this.showLoader = function(){	gE('loader').style.display = "block";	}
	
	this.msg = function(json)
	{
		var msg = JSON.parse(json);
		
		switch(msg.type)
		{
			case "userAuth":
				game.response(msg.type, game.fb.user != null ? 1 : 0);
			break;
			
			case "statsScore":
				game.stats.save(msg);
			break;
			
			case "mazeRead":
				game.maze.read();
			break;
			
			case "mazeRandom":
				game.maze.random(null);
			break;
			
			case "mazeRandomTarget":
				game.maze.random(game.fb.target.uid);
			break;
			
			case "mazeLoad":
				game.maze.load(msg.id);
			break;
			
			case "mazeSave":
				game.maze.save(msg.id);
				game.fb.target.shareMaze(game.fb.target.uid, msg.id);
			break;
			
			case "mazeMeddle":
				game.fb.target.meddle();
			break;
			
			case "selectTarget":
				eval(game.response("userLevel", game.stats.level));
				//game.fb.target.show();
				
				//check if user has the photo selected
				game.fb.target.check();
			break;
			
			case "selectNewTarget":
				game.fb.target.show();
			break;
			
			case "displayPhoto":
				game.fb.photo.display(game.fb.target.uid);
			break;

			case "getFriends":
				game.response("getFriends", JSON.stringify(game.fb.friends));
			break;
			
			case "getTargetPhoto":
				game.response("getTargetPhoto", "api/?cmd=photo.load&target="+game.fb.target.uid);
			break;
			
			case "setDifficultyMods":
				game.fb.setDifficultyMods(msg);
			break;
			
			case "enableMazeList":
				game.menu.unlockItem("mazes");
				mE("target-change-control").show("inline");
			break;
			
			case "disableMazeList":
				game.menu.lockItem("mazes");
				mE("target-change-control").hide();
			break;
			
			case "getLocale":
				game.response("getLocale", c.unity.territory);
			break;
		}
	}
	
	this.response = function(type, response)
	{
		switch(type)
		{
			case "userAuth":
				callbackObj = "WebClient";
				callbackFunc = "SetIsUserAuthorized";
			break;
			
			case "mazeRandom":
			case "mazeRead":
			case "mazeLoad":
				callbackObj = "WebClient";
				callbackFunc = "LoadMazeJS";
			break;
			
			case "getFriends":
				callbackObj = "WebClient";
				callbackFunc = "SetFriendsNames";
			break;
			
			case "userLevel":
				callbackObj = "WebClient";
				callbackFunc = "SetUserLevel";
			break;
			
			case "getTargetPhoto":
				callbackObj = "WebClient";
				callbackFunc = "SetTargetPhoto";
			break;
			
			case "setUserDifficulty":
				callbackObj = "WebClient";
				callbackFunc = "UserDifficulty";
			break;
			
			case "setTargetDifficulty":
				callbackObj = "WebClient";
				callbackFunc = "TargetDifficulty";
			break;
			
			case "getLocale":
				callbackObj = "WebClient";
				callbackFunc = "SetLocale";
			break;
		}
		
		if(debug)
		  alert(type+" "+callbackObj+" "+callbackFunc+" "+response);
		
		var target = this.get();
		if(target)
			target.SendMessage(callbackObj, callbackFunc, response);
	}
}

var game = new CUnity();

