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 class=\"item\">"+this.text+"</div>";
			
		var selected = "";
		if(this.selected)
			selected = " class=\"selected\"";
		
		return "<a id=\"menu-"+this.id+"\""+selected+" href=\"javascript:game.menu.select('"+this.id+"')\">"+this.text+"</a>";
	}	
}

function CMenu(parent)
{
	this.parent = parent;
	
	this.items = new Array();
	
	this.create = function()
	{
		this.items.push(new CMenuItem("game", "Game", 1, 1, 0, this.parent));
		this.items.push(new CMenuItem("leaderboard", "Leaderboard", this.parent.detected, 0, 0, this.parent.stats));
		this.items.push(new CMenuItem("instructions", "Instructions", this.parent.detected, 0, 0, this.parent.instructions));
		//this.items.push(new CMenuItem("unlock", "Community unlock", 1, 0, 0, this.parent.unlock));
		//this.items.push(new CMenuItem("sharing", "Sharing", 1, 0, 0, this.parent.sharing));
		//this.items.push(new CMenuItem("settings", "Settings", 1, 0, 0, null));
	}
	
	this.showItem = function(item)
	{
		for(var i = 0; i < this.items.length; i++)
		{
			if(this.items[i].name == item)
			{
				this.items[i].show ? this.items[i].show = 1 : this.items[i].show = 0;
				break;
			}
		}
		
		this.render();
	}
	
	this.lockItem = function(item)
	{
		for(var i = 0; i < this.items.length; i++)
		{
			if(this.items[i].name == item)
			{
				this.items[i].locked = 1;
				break;
			}
		}
		
		this.render();
	}
	
	this.updateItemFunc = function(item, func)
	{
		for(var i = 0; i < this.items.length; i++)
		{
			if(this.items[i].name == item)
			{
				this.items[i].item = func;
				break;
			}
		}
		
		this.render();
	}
	
	this.render = function()
	{
    //twitter has leaderboard locked
    /*
    if(this.items.length && this.parent.authService && this.parent.authService.name == "tw")
      this.lockItem("leaderboard");
		*/
		var content = "";
		for(var i = 0; i < this.items.length; i++)
		{
			content += this.items[i].render();

			if(i < this.items.length - 1)
				content += "<div class=\"spacer\"></div>";
		}
		
		if(this.parent.detected)
			content += "<div id=\"user-bar\"><a class=\"connect\" href=\"javascript:game.sharing.show()\">Connect and share!</a></div>";
		else
			content += "<div id=\"user-bar\"><div class=\"connect\">Connect and share!</div></div>";
		
		gE("menu").innerHTML = content;
		
		if(this.parent.authService)
			this.parent.authService.renderBar();
	}
	
	this.select = function(id)
	{
		this.parent.messages.hide();
		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.userAuth = 0;
	this.authService = null;
	
	this.setTargetUid = null;
	
	this.hidden = 0;
	this.forcedHide = 0;
	
	this.detected = false; //unity detection

	this.fb = new CFb(this);
	this.tw = new CTw(this);
	
	this.instructions = new CInstructions(this);
	this.sharing = new CSharing(this);
	this.stats = new CStats(this);
	this.unlock = new CUnlock(this);
	this.maze = new CMaze(this);
	this.menu = new CMenu(this);
	this.messages = new CMessages(this);
	
	this.auth = function(auth, service)
	{
		this.userAuth = auth;
		this.authService = service;
		
		this.menu.render();
		
		if(this.authService.name == "fb" && this.setTargetUid != null)
			this.fb.target.selectUid(this.setTargetUid);
		
		this.response("userAuth", auth);
	}
	
	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, auth)
	{
		this.setTargetUid = target;
		
		this.fb.init();
		
		var content = "";
		
		var detected = this.detect();
		if(detected)
		{		
			content += "<object id=\"UnityObject\" classid=\"clsid:444785F1-DE89-4295-863A-D46C3A781394\" width=\"800\" height=\"600\">";
			content += "<param name=\"src\" value=\""+server+"/unity/"+build+".unity3d\" />";
			content += "<param name=\"backgroundcolor\" value=\"000000\" />";
			content += "<param name=\"bordercolor\" value=\"000000\" />";
			content += "<param name=\"textcolor\" value=\"999999\" />";
			content += "<param name=\"disableFullscreen\" value=\"true\" />";
			content += "<param name=\"logoimage\" value=\"images/logo.png\" />";
			content += "<param name=\"progressbarimage\" value=\"images/progressbar.png\" />";
			content += "<param name=\"progressframeimage\" value=\"images/progressframe.png\" />";
			content += "<embed id=\"UnityEmbed\" src=\""+server+"/unity/"+build+".unity3d\" width=\"800\" height=\"600\" disableFullscreen=\"true\" logoimage=\"images/logo.png\" progressbarimage=\"images/progressbar.png\" progressframeimage=\"images/progressframe.png\" backgroundcolor=\"000000\" bordercolor=\"000000\" textcolor=\"999999\" type=\"application/vnd.unity\" pluginspage=\"http://www.unity3d.com/unity-web-player-2.x\" />";
			content += "</object>";
			
			gE("fan").style.display = "block";
		}
		else
		{
      content += "<div id=\"unity-install1\"><h2>You are about to play Mind Crime!</h2>";
		  content += "Mind Crime requires the Unity Web Player plug-in for your Internet browser. Unity enables you to view 3D content directly in your browser.<br /><br />";
		  content += "Click here to install the Unity:<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\">Need help installing the Unity? Please select your browser for detailed instructions:<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;
		
		var e = gE('game');
		
		if(e)
			e.innerHTML = content;
			
		e.style.display = "block";
		
		if(maze > 0)
			this.maze.load(maze);
		
		if(!auth && !this.authService && detected)
			this.sharing.show();
		
		this.menu.create();
		this.menu.render();
	}
	
	this.show = function()
	{
 		if(isIE())
    {
      var g = gE("game");
      if(g)
        g.style.display = "block";
    }

		//only if the game tab is selected
		if(!this.menu.getSelected("game"))
			return;

		var u = game.get();
		
		if(u && game.hidden)
		{
			game.hidden = 0;
			game.forcedHide = 0;
			
			u.style.width = "800px";
			u.style.height = "600px";
			
			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);
		}
	}

	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);
		}
	}
	
	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.userAuth);
			break;
			
			case "statsScore":
				game.stats.save(msg);
			break;
			
			case "mazeRead":
				game.maze.read();
			break;
			
			case "mazeRandom":
				game.maze.load();
			break;
			
			case "mazeLoad":
				game.maze.load(msg.id);
			break;
			
			case "mazeSave":
				game.maze.save(game.fb.target.uid, msg.data);
			break;
			
			case "mazeShare":
				game.maze.share();
			break;
			
			case "selectTarget":
				//game.fb.target.show();
				
				//check if user has the photo selected
				if(game.fb.connected == 1 && game.fb.photo.photoLink == null && game.fb.photo.selected != 1)
					game.fb.photo.setPhoto(game.fb.photo.photoLink);
				
				game.fb.target.check();
			break;
			
			case "displayPhoto":
				game.fb.photo.display(game.fb.target.uid, game.maze.photoLink);
			break;
			
			case "getFriends":
				game.fb.getFriends();
			break;
		}
	}
	
	this.response = function(type, response)
	{	
		switch(type)
		{
			case "userAuth":
				callbackObj = "WebClient";
				callbackFunc = "SetIsUserAuthorized";
			break;
			
			case "mazeRead":
			case "mazeLoad":
				callbackObj = "WebClient";
				callbackFunc = "LoadMazeJS";
			break;
			
			case "getFriends":
				callbackObj = "WebClient";
				callbackFunc = "SetFriendsNames";
			break;
		}
		
		if(debug)
		  alert(type+" "+callbackObj+" "+callbackFunc+" "+response);
		
		var target = this.get();
		if(target)
			target.SendMessage(callbackObj, callbackFunc, response);
	}
}

var game = new CUnity();

