enyo.kind({
	name: "MathGame",
	kind: enyo.Control,
	style: "width:100%;height:100%;",
	components: [
		// main panel
		{name: "main", kind: enyo.Control, fit: true, style: "background:black;width:100%;height:100%;", components: [
			// space where users of this kind can insert controls.
			{kind: "Canvas", fit: true, name: "playfield", style: "position:absolute;left:0px;top:0px;", attributes: {width: 300, height: 500}, ontap: "clickHandler"},
			{tag: "div", name: "Pause", content: "Pause", style: "width:120px;height:40px;position:absolute;left:-120px;top:-40px;", class: "goal-hidden pause", ontap: "pauseHandler"},
			{tag: "div", name: "Question", style: "width:120px;height:40px;", class: "goal-hidden question"},
			{tag: "div", name: "Answer1", style: "width:40px;height:40px;", class: "goal-hidden answer", ontap: "correctHandler"},
			{tag: "div", name: "Answer2", style: "width:40px;height:40px;", class: "goal-hidden answer", ontap: "wrongHandler"},
			{tag: "div", name: "Answer3", style: "width:40px;height:40px;", class: "goal-hidden answer", ontap: "wrongHandler"},
			{tag: "div", name: "Answer4", style: "width:40px;height:40px;", class: "goal-hidden answer", ontap: "wrongHandler"},
			{tag: "div", name: "Answer5", style: "width:40px;height:40px;", class: "goal-hidden answer", ontap: "wrongHandler"}
		]},
		{tag: "div", name: "advert", style: "position:absolute;left:0px;bottom:0px;width:100%;height:48px;"},
		{kind: "onyx.Popup", name: "NewGamePopup", centered: true, modal: true, scrim: true, scrimWhenModal: false, floating: true,
			onHide: "hidePopup", autoDismiss: false,  style: "width:220px;",components: [
			{kind: "onyx.Groupbox", components: [
			    {kind: "onyx.GroupboxHeader", style: "font-size: 18px;", content: "Select difficulty:"},
				{kind: "onyx.Button", content: "Easy", style: "font-weight: bold; background-color:#afa; width:100%; margin:1px;", onclick: "EasyClick"},
				{kind: "onyx.Button", content: "Medium", style: "font-weight: bold; background-color:#faa; width:100%; margin:1px;", onclick: "MediumClick"},
				{kind: "onyx.Button", content: "Hard", style: "font-weight: bold; background-color:#ffa; width:100%; margin:1px;", onclick: "HardClick"},
				{tag: "div", style: "height: 10px;"},
				{kind: "onyx.Button", name: "InstallButton", content: "Install", style: "font-weight: bold; background-color:#aaf; width:100%; margin:1px;", onclick: "onInstallClick"}
			]}
		]},
		{kind: "onyx.Popup", name: "NameInputPopup", centered: true, modal: true, scrim: true, scrimWhenModal: false, floating: true,
			onHide: "hidePopup", autoDismiss: false,  style: "width:300px;",components: [
			{kind: "onyx.Groupbox", components: [
				{tag: "div", allowHtml: true, content: "Please enter your name:"},
				{kind: "onyx.InputDecorator", alwaysLooksFocused: true, components: [
					{kind: "onyx.Input", name: "NameInput", style: "width:100%;"}
				]},
				{kind: "onyx.Button", content: "Continue", style: "font-weight: bold; background-color:#afa; width:100%; margin:1px;", onclick: "NameEnteredClick"},
			]}
		]},
		{kind: "onyx.Popup", name: "GameOverPopup", centered: true, modal: true, scrim: true, scrimWhenModal: false, floating: true,
			onHide: "hidePopup", autoDismiss: false,  style: "width:300px;",components: [
			{kind: "onyx.Groupbox", components: [
			    {kind: "onyx.GroupboxHeader", style: "font-size: 18px;", content: "Your results:"},
				{name: "GameOverContent", allowHtml: true, content: ""},
				{kind: "onyx.Button", name: "SameGameButton", content: "Continue", style: "font-weight: bold; background-color:#afa; width:100%; margin:1px;", onclick: "ContinueClick"},
				{kind: "onyx.Button", name: "OtherGameButton", content: "Other Game", style: "font-weight: bold; background-color:#ffa; width:100%; margin:1px;", onclick: "NewGameClick"},
			]}
		]},
		{kind: "onyx.Popup", name: "AboutBox", centered: true, modal: true, scrim: true, scrimWhenModal: false, floating: true,
			onHide: "hidePopup", autoDismiss: false,  style: "width:220px;",components: [
			{kind: "onyx.Groupbox", components: [
			    {kind: "onyx.GroupboxHeader", style: "font-size: 18px;", content: "Math This"},
				{content: "", style: "height: 10px;"},
				{content: "(c) 2013, MetaViewSoft", style: "font-size: 18px;"},
				{content: "", style: "height: 10px;"},
				{kind: "onyx.Button", content: "Email", style: "font-weight: bold; background-color:#aaa; width:100%; margin:1px;", onclick: "onEmailClick"},
				//{kind: "onyx.Button", content: "Homepage", style: "font-weight: bold; background-color:#aaa; width:280px; margin:1px;", onclick: "onHomepageClick"},
				{content: "", style: "height: 10px;"},
				{kind: "onyx.Button", content: "Restart", style: "font-weight: bold; background-color:#aaf; width:100%; margin:1px;", onclick: "onRestartClick"},
				{content: "", style: "height: 10px;"},
				{kind: "onyx.Button", content: "Clear", style: "font-weight: bold; background-color:#faa; width:100%; margin:1px;", onclick: "onClearClick"},
				{content: "", style: "height: 10px;"},
				{kind: "onyx.Button", content: "Close", style: "font-weight: bold; background-color:#afa; width:100%; margin:1px;", onclick: "onAboutClose"}
			]}
		]},
		{kind: "onyx.Menu", name: "appMenu", components: [
			{caption: "About", onclick: "openAboutBox"}
		]},
		{content: "?", style: "font-weight:bold; font-size:24px; text-shadow:2px 2px #000000; position:absolute; top:5px; right:10px;", onclick: "openAboutBox"},
		{kind: "Signals", ondeviceready: "deviceReady", onbackbutton: "backButton"}
	],
	Games: [{label: "Easy"},
			  {label: "Medium"},
			  {label: "Hard"}],
	Results: [],
	LastGameType: 0,
	NO_TURN: 0,
	MY_TURN: 1,
	YOUR_TURN: 2,
	REMOVED: 0,
	HIDDEN: 1,
	OPEN: 2,
	DEBUG: false,
	gblTileHeight: 48,
	gblSquares: 6,
	gblOldOrient: 0,
	gblYourPairs: 0,
	gblYourWrongs: 0,
	gblYourRights: 0,
	gblMyPairs: 0,
	gblMyWrongs: 0,
	gblWhosTurn: 2,
	gblPointsMax: 0,
	gblDynamicDifficulty: 2, // starts somewhere in the middle
	gblTileset: 0,
	gblCardBack: 0,
	gblBackground: null,
	gblTiles: null,
	gblTileBack: null,
	gblRemoveTimeOut: 4,
	gblComputerTimeOut: 2,
	gblEmptySpace: false,
	gblDeactivate: false,
	gblSinglePlayer: false,
	gblMonsterLeft: 0,
	gblMonsterWidth: 40,
	gblPrincessLeft: 0,
	gblPrincessWidth: 20,
	gblPrinceLeft: 0,
	gblPrinceWidth: 20,
	gblInQuestionCounter: 0,
	gblResultCorrect: 0,
	gblResultWrong: 0,
	gblResultMissed: 0,
	EndSequence: false,
	EndSequenceCounter: 0,
	gblScore: 0,
	GameOver: true,
	Pause: false,
	create: function() {
		this.inherited(arguments);
		this.gblBackground = new Image();
		this.gblBackground.src = "images/background.jpg";
		this.gblBackground.onload = enyo.bind(this, "BackgroundLoaded");
		console.error("gblAndroid: " + gblAndroid);
		if (gblAndroid) {
			this.correctSound = new Media("sounds/card01.wav");
			this.wrongSound = new Media("sounds/mm.wav");
			this.wonSound = new Media("sounds/end.wav");
			this.lostSound = new Media("sounds/browser01.wav");
		} else {
			this.correctSound = new Audio("sounds/card01.wav");
			this.wrongSound = new Audio("sounds/mm.wav");
			this.wonSound = new Audio("sounds/end.wav");
			this.lostSound = new Audio("sounds/browser01.wav");
		}
		this.$.Question.addClass("goal-hidden question");
		this.$.Answer1.addClass("goal-hidden answer");
		this.$.Answer2.addClass("goal-hidden answer");
		this.$.Answer3.addClass("goal-hidden answer");
		this.$.Answer4.addClass("goal-hidden answer");
		this.$.Answer5.addClass("goal-hidden answer");
		this.$.Pause.addClass("goal-hidden pause");
		//Reassign onSwipeDown event - if menuBar is closed, and swipe down occurs, open the menu.
		if ((typeof window.blackberry !== "undefined") && (typeof blackberry.app !== "undefined")) {
			blackberry.app.event.onSwipeDown(enyo.bind(this, "openAboutBox"));
		}

		this.lastTime = 0;
		var vendors = ['ms', 'moz', 'webkit', 'o'];
		for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
			this.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
			this.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
		}
		if (!this.requestAnimationFrame) {
			this.requestAnimationFrame = function(callback, element) {
				var currTime = new Date().getTime();
				var timeToCall = Math.max(0, 16 - (currTime - this.lastTime));
				var id = setTimeout(enyo.bind(this, function() { callback(currTime + timeToCall); }), timeToCall);
				this.lastTime = currTime + timeToCall;
				return id;
	        };
		}
		if (!this.cancelAnimationFrame) {
			this.cancelAnimationFrame = function(id) {
				clearTimeout(id);
			};
		}
		this.MonsterAnim = [];
		this.PrincessAnim = [];
		this.PrinceAnim = [];
		for (var i=0; i<4; i++) {
			var img = new Image();
			img.src = "images/monster" + i + ".png";
			this.MonsterAnim.push(img);
			var img = new Image();
			img.src = "images/princess" + i + ".png";
			this.PrincessAnim.push(img);
			var img = new Image();
			img.src = "images/prince" + 0 + ".png";
			this.PrinceAnim.push(img);
		}
		for (var game=0; game<3; game++) {
			this.Results[game] = [];
			for (var i=0; i<5; i++) {
				var name = localStorage.getItem("Name_" + game + "_" + i);
				var score = localStorage.getItem("Score_" + game + "_" + i);

				if ((typeof name === "undefined") || (name === null)) {
					break;
				}

				this.Results[game].push({Score: score, Name: name});
			}
		}
	},
	//* called after this control is rendered
	rendered: function() {
		this.inherited(arguments);
		this.validateLayout();
		this.InitialGameStart();
		//enyo.job("InitialGameStart", enyo.bind(this, "InitialGameStart"), 500);
		//setTimeout(enyo.bind(this, "InitialGameStart"), 500);
		if (navigator.mozApps) {
			var that = this;
			var checkIfInstalled = navigator.mozApps.getSelf();
			checkIfInstalled.onsuccess = function () {
				console.error("checkIfInstalled.onsuccess");
				if (checkIfInstalled.result) {
					// Already installed
					that.$.InstallButton.hide();
				}
			}
			checkIfInstalled.onerror = function () {
				console.error("checkIfInstalled.onerror");
			}
		} else {
			this.$.InstallButton.hide();
		}
		this.AnswerArray = [];
		this.AnswerArray.push({node: this.$.Answer1, x: 0, y:0, value: 0, r: 150, g:150, b:200, dir: 1});
		this.AnswerArray.push({node: this.$.Answer2, x: 0, y:0, value: 0, r: 150, g:150, b:200, dir: 1});
		this.AnswerArray.push({node: this.$.Answer3, x: 0, y:0, value: 0, r: 150, g:150, b:200, dir: 1});
		this.AnswerArray.push({node: this.$.Answer4, x: 0, y:0, value: 0, r: 150, g:150, b:200, dir: 1});
		this.AnswerArray.push({node: this.$.Answer5, x: 0, y:0, value: 0, r: 150, g:150, b:200, dir: 1});
		this.Question = {node: this.$.Question, x: 0, y: 0, value: 0};
		this.Pause = {node: this.$.Pause, x: 0, y: 0, value: 0};

		this.canvas = this.$.playfield.node;
		this.width = this.canvas.width;
		this.height = this.canvas.height;
		this.ctx = this.canvas.getContext('2d');

		getInnerActiveAd(this.$.advert.hasNode(), "");
	},
	//* called after this control is resized
	resizeHandler: function() {
		this.inherited(arguments);
		this.validateLayout();
		this.DrawPlayfield();
	},
	//* update layout based on size changes
	validateLayout: function() {
		this.$.playfield.node.height = window.innerHeight;//this.getBounds().height;//-7;
		this.$.playfield.node.width = window.innerWidth;//this.getBounds().width;//-10;
		this.canvas = this.$.playfield.node;
		this.width = this.canvas.width;
		this.height = this.canvas.height;
	},
	resume: function() {
		this.validateLayout();
		this.DrawPlayfield();
		console.error("resume called");
	},
	pause: function() {
		this.PauseFlag = true;
	},
	pauseHandler: function() {
		this.PauseFlag = false;
	},
	openAppMenuHandler: function() {
		this.PauseFlag = true;
		this.$.appMenu.open();
	},
	closeAppMenuHandler: function() {
		this.$.appMenu.close();
		this.PauseFlag = false;
	},
	openAboutBox: function() {
		this.PauseFlag = true;
		this.showPopup("AboutBox");
	},
	onAboutClose: function() {
		this.$.AboutBox.hide();
		this.PauseFlag = false;
	},
	onEmailClick: function() {
		window.open("mailto:metaview@web.de?subject=MathGame");
	},
	onHomepageClick: function() {
		window.open("http://www.metaviewsoft.de/wordpress", "_blank");
	},
	onInstallClick: function() {
	    var installApp = navigator.mozApps.install("http://78.46.106.20/MathGame/hosted.webapp");
	    installApp.onsuccess = function(data) {
	    };
	    installApp.onerror = function() {
	        alert("Install failed\n\n:" + installApp.error.name);
	    };
	},
	backButton: function() {
		console.error("backButton");
		if (this.$.AboutBox.getShowing()) {
			this.$.AboutBox.hide();
		} else if (this.$.GameOverPopup.getShowing()) {
			this.$.GameOverPopup.hide();
			this.RestartGame();
		} else if (this.$.NameInputPopup.getShowing()) {
			this.$.NameInputPopup.hide();
			this.OnStatistic();
		} else if (!this.$.NewGamePopup.getShowing()) {
			console.error("backButton: InitialGameStart");
			this.InitialGameStart();
		} else {
			if (navigator) {
				// for android
				navigator.app.exitApp();
			} else {
				// for windows
				this.close();
			}
		}
	},
	InitGameData: function() {
		this.gblMonsterLeft = 0;
		this.gblPrinceLeft = this.width - this.gblPrinceWidth;
		this.gblInQuestionCounter = 0;
		this.gblResultCorrect = 0;
		this.gblResultWrong = 0;
		this.gblResultMissed = 0;
		this.EndSequence = 0;
		this.EndSequenceCounter = 0;
		this.GameWon = false;
		this.gblScore = 0;
		this.GameOver = false;
		this.PauseFlag = false;
		this.gblGameStartTime = new Date().getTime();
		this.requestAnimationFrame(enyo.bind(this, "DrawPlayfield"));
	},
	InitialGameStart: function() {
		console.error("InitialGameStart");
		this.showPopup("NewGamePopup");
	},
	BackgroundLoaded: function() {
		this.DrawPlayfield();
	},
	EasyClick: function(inSender) {
		this.LastGameType = 0;
		this.StartTimeOut = 9;
		this.$.NewGamePopup.hide();
		this.validateLayout();
		this.InitGameData();
	},
	MediumClick: function(inSender) {
		this.LastGameType = 1;
		this.StartTimeOut = 6;
		this.$.NewGamePopup.hide();
		this.InitGameData();
	},
	HardClick: function(inSender) {
		this.LastGameType = 2;
		this.StartTimeOut = 3;
		this.$.NewGamePopup.hide();
		this.InitGameData();
	},
	SortFct: function(a, b) {
		if ((b.Score == null) || (a.Score < b.Score)) {
			return 1;
		} else if ((a.Score > b.Score) || (a.Score == null)) {
			return -1;
		}
		return 0;
	},
	NameEnteredClick: function(inSender) {
		this.$.NameInputPopup.hide();

		var name = this.$.NameInput.getValue();
		var score = Math.floor(this.gblScore);

		if (name != "") {
			this.Results[this.LastGameType].push({Score: score, Name: name});
			this.Results[this.LastGameType].sort(this.SortFct);
			if (this.Results[this.LastGameType].length > 5) {
				this.Results[this.LastGameType].length = 5;
			}
			for (var i=0; i<5; i++) {
				localStorage.setItem("Name_" + this.LastGameType + "_" + i, (i < this.Results[this.LastGameType].length) ? this.Results[this.LastGameType][i].Name : "");
				localStorage.setItem("Score_" + this.LastGameType + "_" + i, (i < this.Results[this.LastGameType].length) ? this.Results[this.LastGameType][i].Score : 0);
			}
		}
		this.OnStatistic();
	},
	ContinueClick: function() {
		this.$.GameOverPopup.hide();
		this.RestartGame();
	},
	NewGameClick: function() {
		this.$.GameOverPopup.hide();
		this.showPopup("NewGamePopup");
	},
	onRestartClick: function() {
		this.$.AboutBox.hide();
		this.showPopup("NewGamePopup");
	},
	onClearClick: function() {
		for (var game=0; game<3; game++) {
			this.Results[game].length = 0;
			for (var i=0; i<5; i++) {
				localStorage.setItem("Name_" + game + "_" + i, (i < this.Results[game].length) ? this.Results[game][i].Name : "");
				localStorage.setItem("Score_" + game + "_" + i, (i < this.Results[game].length) ? this.Results[game][i].Score : 0);
			}
		}
		this.$.AboutBox.hide();
	},
	correctHandler: function() {
		if (this.PauseFlag) {
			return;
		}
		this.correctSound.play();
		this.AnswerArray[0].node.removeClass("answer");
		this.AnswerArray[0].node.addClass("correct");
		this.gblResultCorrect++;
		var now = new Date().getTime();
		var score = ((this.StartTimeOut * 1000) - (now - this.StartTime)) / this.StartTimeOut;
		if (score < 0) {
			score = 0;
		}
		this.gblScore += score;
		this.gblScore += 1000 / (this.gblResultWrong + 1);
		this.gblPrinceLeft -= this.width / 20;
		this.gblInQuestionCounter = -20;
	},
	wrongHandler: function(inSender) {
		if (this.PauseFlag) {
			return;
		}
		this.wrongSound.play();
		inSender.removeClass("answer");
		inSender.addClass("wrong");
		this.AnswerArray[0].node.removeClass("answer");
		this.AnswerArray[0].node.addClass("correct");
		this.gblResultWrong++;
		this.gblMonsterLeft += this.width / 20;
		this.gblInQuestionCounter = -20;
		this.gblScore -= 100;
		if (this.gblScore < 0) {
			this.gblScore = 0;
		}
	},
	DrawPlayfield: function() {
		if (this.GameOver) {
			return;
		}

		var id = this.requestAnimationFrame(enyo.bind(this, "DrawPlayfield"));
		var now = new Date().getTime();

		if (this.PauseFlag) {
			this.Pause.x = window.innerWidth / 2 - 85;
			this.Pause.y = window.innerHeight / 2 - 80;
			this.SetVisible(this.Pause, true);
			return;
		} else {
			this.SetVisible(this.Pause, false);
		}

		if ((this.width <= 1024) && (this.height <= 1024)) {
			this.ctx.drawImage(this.gblBackground, 0, 0);
		} else {
			this.ctx.clearRect(0, 0, this.width, this.height);
		}

		if (this.EndSequence == 0) {
			// Monster
			//this.gblMonsterLeft += this.width / 5000;
			this.gblMonsterTop = this.height - 120 - 62;
			//if (this.gblMonsterLeft < 0) {
			//	this.gblMonsterLeft = 0;
			//}

			// Prinzessin
			this.gblPrincessLeft = this.width / 2 - this.gblPrincessWidth;
			this.gblPrincessTop = this.height - 120 - 62;

			// Prinz
			this.gblPrinceTop = this.height - 80 - 45;

			if ((this.gblMonsterLeft + this.gblMonsterWidth) >= this.gblPrincessLeft) {
				this.gblMonsterLeft = this.gblPrincessLeft - this.gblMonsterWidth;
				this.EndSequence = 1;
				this.EndSequenceCounter = 0;
				this.GameWon = false;
				this.lostSound.play();
			}

			if ((this.gblPrincessLeft + this.gblPrincessWidth) >= this.gblPrinceLeft) {
				this.gblPrinceLeft = this.gblPrincessLeft + this.gblPrincessWidth;
				this.EndSequence = 1;
				this.EndSequenceCounter = 0;
				this.GameWon = true;
				this.wonSound.play();
			}
		} else if (this.EndSequence == 1) {
			if (this.EndSequenceCounter == 0) {
				this.SetVisible(this.Question, false);
				for (var i=0; i<this.AnswerArray.length; i++) {
					this.SetVisible(this.AnswerArray[i], false);
				}
			}

			this.EndSequenceCounter++;

			if (this.GameWon) {
				this.gblMonsterTop = this.height - 120 - 62;
			} else {
				this.gblMonsterTop = this.height - 120 - 62 - 20 * Math.abs(Math.sin(this.EndSequenceCounter / 5));
			}

			if (this.GameWon) {
				this.gblPrincessLeft += this.width / 1000;
			} else {
				this.gblPrincessLeft += this.width / 500;
			}
			this.gblPrincessTop += this.width / 10000 * (this.EndSequenceCounter - 25);
			this.gblPrinceTop = this.height - 80 - 45;

			if (this.GameWon) {
				if (this.gblPrincessTop > this.gblPrinceTop) {
					this.gblPrincessTop = this.gblPrinceTop;
					this.EndSequenceCounter = 0;
					this.EndSequence = 2;
				}
			}

			if (this.gblPrincessTop > (this.height + 100)) {
				this.EndSequence = 3;
			}
		} else if (this.EndSequence == 2) {
			// Prinz und Prinzessin flüchten
			this.EndSequenceCounter++;
			this.gblPrincessLeft++;
			this.gblPrinceLeft++;

			// Monster wird versinkt
			this.gblMonsterTop = this.height - 120 - 62 + this.EndSequenceCounter;

			if (this.gblPrinceLeft > this.width) {
				this.GameOver = true;
			}
		} else if (this.EndSequence == 3) {
			// Prinz versinkt
			this.EndSequenceCounter++;
			this.gblPrinceTop++;

			// Monster hüpft weiter
			this.gblMonsterTop = this.height - 120 - 62 - 20 * Math.abs(Math.sin(this.EndSequenceCounter / 5));

			if (this.gblPrinceTop > (this.height + 100)) {
				this.GameOver = true;
			}
		}

		// Monster
		if (this.gblInQuestionCounter >= 0) {
			this.MonsterAnimIdx = Math.floor(this.gblInQuestionCounter / 8) % this.MonsterAnim.length;
		}
		this.ctx.drawImage(this.MonsterAnim[this.MonsterAnimIdx], Math.floor(this.gblMonsterLeft), Math.floor(this.gblMonsterTop));

		// Prinzessin
		if (this.gblInQuestionCounter >= 0) {
			this.PrincessAnimIdx = Math.floor(this.gblInQuestionCounter / 8) % this.PrincessAnim.length;
		}
		if (this.EndSequence && !this.GameWon) {
			this.ctx.save();
			this.ctx.translate(Math.floor(this.gblPrincessLeft), Math.floor(this.gblPrincessTop));
			this.ctx.rotate(this.EndSequenceCounter * Math.PI/90);
			this.ctx.drawImage(this.PrincessAnim[this.PrincessAnimIdx], 0, 0);
			this.ctx.restore();
		} else {
			this.ctx.drawImage(this.PrincessAnim[this.PrincessAnimIdx], Math.floor(this.gblPrincessLeft), Math.floor(this.gblPrincessTop));
		}

		// Prinz
		if (this.gblInQuestionCounter >= 0) {
			this.PrinceAnimIdx = Math.floor(this.gblInQuestionCounter / 8) % this.PrinceAnim.length;
		}
		this.ctx.drawImage(this.PrinceAnim[this.PrinceAnimIdx], Math.floor(this.gblPrinceLeft), Math.floor(this.gblPrinceTop));

		var clr1 = "#0000FF";
		var clr2 = "#4444FF";
		var clr3 = "#2222FF";
		var clr4 = "#4444FF";
		if (((now - this.gblGameStartTime) % 1200) < 301) {
			clr1 = "#4444FF";
			clr2 = "#2222FF";
			clr3 = "#4444FF";
			clr4 = "#0000FF";
		} else if (((now - this.gblGameStartTime) % 1200) < 601) {
			clr1 = "#2222FF";
			clr2 = "#4444FF";
			clr3 = "#0000FF";
			clr4 = "#4444FF";
		} else if (((now - this.gblGameStartTime) % 1200) < 801) {
			clr1 = "#4444FF";
			clr2 = "#0000FF";
			clr3 = "#4444FF";
			clr4 = "#2222FF";
		}

		// Wasser
		this.ctx.strokeStyle = clr1;
		this.ctx.lineWidth = "48";
		this.ctx.beginPath();
		this.ctx.moveTo(0, this.height - 24);
		this.ctx.lineTo(this.width, this.height - 24);
		this.ctx.stroke();

		this.ctx.strokeStyle = clr2;
		this.ctx.lineWidth = "20";
		this.ctx.beginPath();
		this.ctx.moveTo(0, this.height - 58);
		this.ctx.lineTo(this.width, this.height - 58);
		this.ctx.stroke();

		this.ctx.strokeStyle = clr3;
		this.ctx.lineWidth = "16";
		this.ctx.beginPath();
		this.ctx.moveTo(0, this.height - 66);
		this.ctx.lineTo(this.width, this.height - 66);
		this.ctx.stroke();

		this.ctx.strokeStyle = clr4;
		this.ctx.lineWidth = "10";
		this.ctx.beginPath();
		this.ctx.moveTo(0, this.height - 71);
		this.ctx.lineTo(this.width, this.height - 71);
		this.ctx.stroke();

		this.ctx.strokeStyle = clr1;
		this.ctx.lineWidth = "8";
		this.ctx.beginPath();
		this.ctx.moveTo(0, this.height - 75);
		this.ctx.lineTo(this.width, this.height - 75);
		this.ctx.stroke();

		this.ctx.strokeStyle = clr2;
		this.ctx.lineWidth = "4";
		this.ctx.beginPath();
		this.ctx.moveTo(0, this.height - 77);
		this.ctx.lineTo(this.width, this.height - 77);
		this.ctx.stroke();

		this.ctx.strokeStyle = clr3;
		this.ctx.lineWidth = "2";
		this.ctx.beginPath();
		this.ctx.moveTo(0, this.height - 78);
		this.ctx.lineTo(this.width, this.height - 78);
		this.ctx.stroke();

		this.ctx.strokeStyle = clr4;
		this.ctx.lineWidth = "1";
		this.ctx.beginPath();
		this.ctx.moveTo(0, this.height - 79);
		this.ctx.lineTo(this.width, this.height - 79);
		this.ctx.stroke();

		// Filling
		this.ctx.fillStyle = "black";
		this.ctx.fillRect(0, this.height, this.width / 2, -120);

		// Kante
		this.ctx.strokeStyle = "white";
		this.ctx.lineWidth = "5";
		this.ctx.beginPath();
		this.ctx.moveTo(0, this.height - 120);
		this.ctx.lineTo(this.width / 2, this.height - 120);
		this.ctx.lineTo(this.width / 2, this.height);
		this.ctx.stroke();

		// Brett
		this.ctx.strokeStyle = "brown";
		this.ctx.lineWidth = "10";
		this.ctx.beginPath();
		this.ctx.moveTo(0, this.height - 120 - 7);
		this.ctx.lineTo(this.width / 2 + 2, this.height - 120 - 7);
		this.ctx.stroke();

		this.ctx.font = "20px sans-serif";
		this.ctx.textBaseline = "middle";
		this.ctx.textAlign = "center";
		this.ctx.fillStyle = "rgb(200,200,200)";
		this.ctx.fillText("Points: " + Math.floor(this.gblScore), this.width / 4, this.height - 90);

		if (this.EndSequence == 0) {
			if (this.gblInQuestionCounter == 0) {

				// hide everything
				this.SetVisible(this.Question, false);
				for (var i=0; i<this.AnswerArray.length; i++) {
					this.SetVisible(this.AnswerArray[i], false);

					if (i == 0) {
						this.AnswerArray[i].node.removeClass("correct");
					} else {
						this.AnswerArray[i].node.removeClass("wrong");
					}
					this.AnswerArray[i].node.addClass("answer");
				}

				// reset question
				this.EquationLeft = Math.floor(Math.random() * 10) + 1;
				this.EquationRight = Math.floor(Math.random() * 10) + 1;
				this.EquationSign = Math.floor(Math.random() * ((this.LastGameType == 0) ? 2 : ((this.LastGameType == 1) ? 4 : 5)));
				if (this.EquationSign == 0) {
					this.EquationLeft = Math.floor(Math.random() * 20) + 1;
					this.EquationRight = Math.floor(Math.random() * 20) + 1;
					this.Question.value = this.EquationResult = this.EquationLeft + this.EquationRight;
					this.$.Question.setContent(this.EquationLeft + " + " + this.EquationRight);
				} else if (this.EquationSign == 1) {
					this.EquationLeft = Math.floor(Math.random() * 20) + 1;
					this.EquationRight = Math.floor(Math.random() * 20) + 1;
					if (this.EquationLeft < this.EquationRight) {
						var tmp = this.EquationRight;
						this.EquationRight = this.EquationLeft;
						this.EquationLeft = tmp;
					}
					this.Question.value = this.EquationResult = this.EquationLeft - this.EquationRight;
					this.$.Question.setContent(this.EquationLeft + " - " + this.EquationRight);
				} else if (this.EquationSign == 2) {
					this.Question.value = this.EquationResult = this.EquationLeft * this.EquationRight;
					this.$.Question.setContent(this.EquationLeft + " x " + this.EquationRight);
				} else if (this.EquationSign == 3) {
					this.Question.value = this.EquationResult = this.EquationLeft;
					this.$.Question.setContent((this.EquationLeft * this.EquationRight) + " / " + this.EquationRight);
				} else if (this.EquationSign == 4) {
					this.Question.value = this.EquationResult = this.EquationLeft * this.EquationLeft;
					this.$.Question.setContent(this.EquationLeft + "²");
				}
				this.SetAnswerValue(0, this.EquationResult);
				var value = 5 - Math.floor(Math.random() * 10);
				this.SetAnswerValue(1, this.EquationResult + value);
				value = (Math.random() < 0.5) ? 1 : -1;
				this.SetAnswerValue(2, this.EquationResult + value);
				value = 10 - Math.floor(Math.random() * 20);
				this.SetAnswerValue(3, this.EquationResult + value);
				value = Math.floor(this.EquationResult / 10) + (this.EquationResult % 10) * 10;
				this.SetAnswerValue(4, this.EquationResult + value);

				this.Question.x = window.innerWidth / 2 - 85;
				this.Question.y = window.innerHeight / 2 - 80;
				this.SetVisible(this.Question, true);
				for (var i=0; i<this.AnswerArray.length; i++) {
					this.AnswerArray[i].r = 100 + Math.floor(Math.random() * 50);
					this.AnswerArray[i].g = 100 + Math.floor(Math.random() * 50);
					this.AnswerArray[i].b = 200 + Math.floor(Math.random() * 50);
					this.AnswerArray[i].dir = 0;
					this.AnswerArray[i].node.setContent(this.AnswerArray[i].value);
					this.AnswerArray[i].node.applyStyle("color", "rgb(" + this.AnswerArray[i].r + "," + this.AnswerArray[i].g + ", " + this.AnswerArray[i].b + ")");
					this.AnswerArray[i].x = 10 + i * (window.innerWidth - 90) / 4;
					this.AnswerArray[i].y = 5 + Math.random() * window.innerHeight / 10;
					this.AnswerArray[i].speed = 0.1 + Math.random() * window.innerHeight / 10000;
				}
				// randomize columns
				for (var i=0; i<this.AnswerArray.length; i++) {
					var k = Math.floor(Math.random() * this.AnswerArray.length);
					var tmp = this.AnswerArray[k].x;
					this.AnswerArray[k].x = this.AnswerArray[i].x;
					this.AnswerArray[i].x = tmp;
				}

				this.StartTime = new Date().getTime();

				// show everything
				this.SetVisible(this.Question, true);
				for (var i=0; i<this.AnswerArray.length; i++) {
					this.SetVisible(this.AnswerArray[i], true);
				}

				getInnerActiveAd(this.$.advert.hasNode(), "");
			}

			this.gblInQuestionCounter++;

			if ((now - this.StartTime)  < (this.StartTimeOut * 1000)) {
				this.ctx.font = "bold 48px sans-serif";
				this.ctx.textBaseline = "middle";
				this.ctx.textAlign = "center";
				this.ctx.fillStyle = "rgb(" + (25 + Math.floor((now - this.StartTime) / 100)) + "," + (50 + Math.floor((now - this.StartTime) / 50)) + "," + (25 + Math.floor((now - this.StartTime) / 100)) + ")";
				this.ctx.fillText(this.StartTimeOut - Math.floor((now - this.StartTime) / 1000), this.width / 2, this.height / 2 + 20);
			} else if ((now - this.StartTime)  < ((this.StartTimeOut+1) * 1000)) {
				this.ctx.font = "bold 48px sans-serif";
				this.ctx.textBaseline = "middle";
				this.ctx.textAlign = "center";
				this.ctx.fillStyle = "rgb(" + (25 + Math.floor((now - this.StartTime) / 100)) + "," + (50 + Math.floor((now - this.StartTime) / 50)) + "," + (25 + Math.floor((now - this.StartTime) / 100)) + ")";
				this.ctx.fillText("Hurry up!", this.width / 2, this.height / 2 + 20);
			} else {
				var cont = false;
				for (var i=0; i<this.AnswerArray.length; i++) {
					var elm = this.AnswerArray[i];
					elm.y += this.AnswerArray[i].speed;
					if (this.AnswerArray[i].speed < 5) {
						this.AnswerArray[i].speed += this.AnswerArray[i].speed / 100;
					}
					if (elm.y < window.innerHeight) {
						cont = true;
					}
					elm.node.applyStyle('left', Math.floor(elm.x) + 'px');
					elm.node.applyStyle('top', Math.floor(elm.y) + 'px');

					/*
					if (this.AnswerArray[i].dir == 1) {
						this.AnswerArray[i].r += 4;
						this.AnswerArray[i].g += 4;
						this.AnswerArray[i].b += 5;
						if ((this.AnswerArray[i].r > 250) || (this.AnswerArray[i].g > 250) || (this.AnswerArray[i].b > 250)) {
							this.AnswerArray[i].dir = -1;
						}
					} else {
						this.AnswerArray[i].r -= 4;
						this.AnswerArray[i].g -= 4;
						this.AnswerArray[i].b -= 5;
						if ((this.AnswerArray[i].r < 150) || (this.AnswerArray[i].g > 150) || (this.AnswerArray[i].b > 150)) {
							this.AnswerArray[i].dir = 1;
						}
					}
					this.AnswerArray[i].node.applyStyle("color", "rgb(" + this.AnswerArray[i].r + "," + this.AnswerArray[i].g + ", " + this.AnswerArray[i].b + ")");
					*/
				}
				if (!cont) {
					// too late, all answers out of screen
					this.EndSequence = 1;
					this.EndSequenceCounter = 0;
					this.GameWon = false;
					/*
					this.gblInQuestionCounter = 0;
					this.gblResultMissed++;
					this.gblMonsterLeft += this.width / 10;
					*/
				}
			}
		}

		if (this.GameOver) {
			this.cancelAnimationFrame(id);
			if (this.GameWon && (this.gblScore > 0)) {
				this.showPopup("NameInputPopup");
			} else {
				this.OnStatistic();
			}
		}
	},
	RestartGame: function() {
		// init a new game
		this.InitGameData();
		this.DrawPlayfield();
	},
	OnStatistic: function() {
		var content = "<table style='width:100%;'>";
		content += "<tr><td align='center'><b>Last</b></td>" +
			"<td width:'50%' align='right'>" + ((this.gblScore > 0) ? Math.floor(this.gblScore) : "") + "</td>" +
			"</tr>";
		content += "<tr><td align='center'></td><td></td></tr>";
		content += "<tr><td align='center'><b>Best</b></td><td></td></tr>";
		for (var i=0; i<this.Results[this.LastGameType].length; i++) {
			if (this.Results[this.LastGameType][i].Score > 0) {
				content += "<tr>" +
					"<td>" + this.Results[this.LastGameType][i].Name + "</td>" +
					"<td align='right'>" + this.Results[this.LastGameType][i].Score + "</td>" +
					"</tr>";
			}
		}
		content += "</table>";
		this.$.GameOverContent.setContent(content);
		this.$.SameGameButton.setContent(this.Games[this.LastGameType].label);
		this.showPopup("GameOverPopup");
	},
	SetVisible: function(elm, visible) {
		if (visible) {
			elm.node.applyStyle('left', elm.x + 'px');
			elm.node.applyStyle('top', elm.y + 'px');
			elm.node.removeClass('goal-hidden');
			elm.node.addClass('goal-display');
		} else {
			elm.node.removeClass('goal-display');
			elm.node.addClass('goal-hidden');
		}
	},
	SetAnswerValue: function(idx, value) {
		for (var i=0; i<idx; i++) {
			if ((this.AnswerArray[i].value == value) || (value < 0)) {
				// try another value, restart loop
				value++;
				i = -1;
			}
		}
		this.AnswerArray[idx].value = value;
	},
	showPopup: function(popup) {
		var p = this.$[popup];
		if (p) {
			p.show();
		}
		p.applyStyle("opacity", 1);
		p.updatePosition();

		var transitionEvent = this.whichTransitionEvent();

		if (transitionEvent !== undefined) {
			var listener = function( event ) {
				p.node.removeEventListener( transitionEvent, listener );
			}
			p.node.addEventListener( transitionEvent, listener );
		}
	},
	hidePopup: function(inSender) {
		inSender.applyStyle("display", "none");
		inSender.applyStyle("opacity", 0);
	},
	whichTransitionEvent: function(){
		var t;
		var el = document.createElement('el');
		var transitions = {
		  'transition':'transitionEnd',
		  'OTransition':'oTransitionEnd',
		  'MSTransition':'msTransitionEnd',
		  'MozTransition':'transitionend',
		  'WebkitTransition':'webkitTransitionEnd'
		}

		for(t in transitions){
			if( el.style[t] !== undefined ){
				return transitions[t];
			}
		}
		return transitions[0];
	}
});
