var mySkin : GUISkin;

var levelTitle : String;
var levelTutorial : String;

var showHelp : boolean = false;

var nextLevel : String;

private var totalTiles = 10;
private var tilesFound = 0;

private var levelDone = false;
private var nextLevelTime = 0.0;

private var defaultHelp = "Move - A, W, S, D, main joystick\nOrbit Camera - Q, E, R, F, secondary joystick\nReset Camera - TAB, Joypad button 3 \nJump - SPACE, Joypad button 4\nUse Glimpse - G, Joypad button 1\nF1 - Toggle Help, Joypad button 2\n\nThe Joypad is the recommended controller! :)\nPlay through the tutorials to learn how to play the game.";

private var random = 0.0;
private var randomDone = false;

private var escPressed = false;


function Update () {
	if (levelDone) {
		nextLevelTime -= Time.deltaTime;
		if (nextLevelTime < 0.0) {
			levelDone = false;
			if (nextLevel != "") {
				Application.LoadLevel(nextLevel);
			} else {
				Application.LoadLevel(Application.loadedLevel+1);
			}
		}
	}
	
	if (Input.GetButtonDown("Fire2")) {
		showHelp = !showHelp;
	}
	
	if (Input.GetKeyDown("escape")) {
		escPressed = !escPressed;
	}
}

function Start() {
	var allObjs : GameObject[] = GameObject.FindGameObjectsWithTag("tile");
 	totalTiles = allObjs.length;
}

function OnGUI () {
	GUI.skin = mySkin;
	
	var w = Screen.width;
	var h = Screen.height;
	if (w < 1024 && h < 768) {
		GUI.matrix = Matrix4x4.TRS (Vector3.zero, Quaternion.identity, Vector3(w / 1024.0, h / 768.0, 1)); 
		w = 1024;
		h = 768;
	} else if (w < 1024) {
		GUI.matrix = Matrix4x4.TRS (Vector3.zero, Quaternion.identity, Vector3(w / 1024.0, 1, 1)); 
		w = 1024;
	} else if (h < 768) {
		GUI.matrix = Matrix4x4.TRS (Vector3.zero, Quaternion.identity, Vector3(1, h / 768.0, 1)); 
		h = 768;
	}  
  
	
	var playerControl : PlayerControl = GameObject.Find("Player").GetComponent("PlayerControl");

	GUI.Label (Rect (10, 10, 400, 100), "Tiles found " + tilesFound + " / " + totalTiles);
	GUI.Label (Rect (w - 300, 10, 300, 100), "Glimpses: " + playerControl.GetGlimpseNb());

	GUI.Label (Rect (10, 60, 400, 100), levelTitle);
	if (showHelp) {
		GUI.Label (Rect (10, 95, w * 2/ 3, 600), levelTutorial != "" ? levelTutorial : defaultHelp);
	}


	GUI.Label (Rect (10, h - 35, w - 20, 50), "" + (1.0 / Time.smoothDeltaTime).ToString("#.") + "fps (press F1 for HELP)");
	
	
	if (levelDone) {
		GUI.Label (Rect (w / 2 - 200, h / 2  - 50, 400, 1000), "LEVEL COMPLETE!");
	}
	
	if (escPressed) {
		if (GUI.Button (Rect (w/4,h/4,w/2,h/7), "Continue playing")) {
			escPressed = false;
		}
		if (GUI.Button (Rect (w/4,h/4 + h/6,w/2,h/7), "Back to the main menu")) {
			Application.LoadLevel("intro");
		}
	}
}

function NewTileFound() {
	tilesFound++;
}

function LevelComplete() {
	levelDone = true;
	nextLevelTime = 2.5;
}

function GetGlobalRandom() {
	if (!randomDone) {
		random = Random.value;
		randomDone = true;
	}
	return random;
}