//require('receiptverifier.js');
//require('receiptverifier-ui.js');

( Game = function() {
	var SCREEN_SPLASH = "SCREEN_SPLASH";
	var SCREEN_START = "SCREEN_START";
	var SCREEN_GAME = "SCREEN_GAME";
	var currentScreen = SCREEN_SPLASH;

	var SHARE_DEFAULT = "SHARE_DEFAULT";
	var SHARE_SCORE = "SHARE_SCORE";
	var currentShare = SHARE_DEFAULT;

	var isDocked = false;

	var myThis = this;

	var tw = new createjs.Tween();

	var accelerometer;
	var keyboard;
	var reportInterval;
	var shakeCount = 0;

	var winW = 1330, winH = 700, maxWid = 1330, maxHeight = 768;

	var images = new Object();
	var stage = null;
	var cont = null;
	var table = new Table();

	var gameScreen = null;
	var smallScreen = null;
	var ready = false;

	var bearSx = 0;
	var animStart = null;
	var animEnd = null;
	var homeLogo = null;

	var tstDomElement = null;

	var lockScreen = null;
	var scoreData = null;

	var inGame = false;
	var flakeInterval = null;
	var shareEnabled = false;

	var scales = null;

	/*PUBLIC OBJECTS*/
	this.inputText = new createjs.DOMElement(document.getElementById("inputText"));
	this.bearHome = null;
	this.bearAnimation = null;
	this.borderAnimation = null;
	this.clock = null;

	var firstLoad = true;
	var firstStart = true;
	this.animHomeIn = new TimelineLite();
	this.animGameIn = new TimelineLite();

	this.init = function() {
		//        var extendedCanvas = new createjs.DOMElement( document.getElementById( "extendedSplashScreen" ) );
		//        extendedCanvas._style.posLeft = ( window.outerWidth - 620 ) / 2 + 2;
		//        extendedCanvas._style.posTop = ( window.outerHeight - 300 ) / 2 + 1;

		var request = navigator.mozApps.getSelf();
		request.onerror = function() {
			console.log(request.error.name);
		};
		request.onsuccess = function() {
			var appRecords = request.result;
			console.log(appRecords);
			if (appRecords) {
				sendToBackEnd(appRecords);
			} else {
				console.log('No receipts were found on the device');
			}
		};

		mozmarket.receipts.verify(function(verifier) {
			if (verifier.state instanceof verifier.states.NeedsInstall) {
				forcePurchase("You must install this app");
				return;
			}
			if (verifier.state instanceof verifier.states.NetworkError) {
				// it was some kind of network or server error
				// i.e., not the fault of the user
				// you may want to let the user in, but for a limited time
			} else if (verifier.state instanceof verifier.states.InternalError) {
				// The verifier library itself got messed up; this shouldn't happen!
				// It's up to you if you want to reject the user at this point
				logToServer(verifier.app, verifier.error);
			} else if (verifier.state instanceof verifier.states.OK) {
				// Everything is cool
			} else {
				// Some other error occurred; maybe it was never a valid receipt, maybe
				// the receipt is corrupted, or someone is trying to mess around.
				// It would not be a bad idea to log this.
				logToServer(verifier.app, verifier.receiptErrors);
				forcePurchase("Your purchase is invalid; please purchase again, or reinstall from the Marketplace");
			}
		});

		var loader = new createjs.PreloadJS(false);
		loader.installPlugin(createjs.SoundJS);
		loader.onFileLoad = handleFileLoad;
		loader.onComplete = handleComplete;
		loader.loadManifest(Utils.mainfest);

		loadRankingFile();
	}
	function forcePurchase(reason) {
		// Of course, this is kind of terrible, but you can do better yourself ;)
		alert('You must install!\n' + reason);
		location.href = 'https://marketplace.firefox.com/app/candypot-pocket';
	}

	function logToServer(app, data) {
		try {
			app = JSON.stringify(app);
		} catch (e) {
			app = app + '';
		}
		try {
			data = JSON.stringify(data);
		} catch (e) {
			data = data + '';
		}
		var req = new XMLHttpRequest();
		req.open('POST', '/receipt-error-log');
		req.send('app=' + encodeURIComponent(app) + '&error=' + encodeURIComponent(data));
	}


	this.updateView = function() {
		var statusText;
		updateCanvas();
		if (currentScreen == SCREEN_SPLASH)
			return;

		showGameScreen();
		commonAdjusts();
	}

	this.onDeactivate = function() {
		if (table) {
			table.pause();
			table.saveState();
		}
		disableSharing();
	}

	this.onStartGame = function() {
		inGame = true;
		removeStartEndAnimations()
		clearAnimationContainer();
		gameScreen.countdownContainer.addChild(animStart);
		animStart.setTransform(0, 0);
		animStart.gotoAndPlay(1);
	}

	this.onEndGame = function(scrData) {
		inGame = false;

		scoreData = scrData;
		scoreData.position = Tools.ranking.checkPostion(scoreData.score);
		gameScreen.countdownContainer.addChild(animEnd);
		animEnd.gotoAndPlay(1);
		Tools.ranking.lastScore = scrData.score;

		var tween = new createjs.Tween();
		if (scoreData.position > 0) {
			tween.wait(3000).call(showRankedScoreScreen, null, this);
		} else {
			tween.wait(3000).call(showNormalScoreScreen, null, this);
		}
	}

	this.startSnowCombo = function() {
		if (inGame)
			startSnow();
	}

	this.stopSnowCombo = function() {
		if (inGame)
			stopSnow();
	}
	function sendToBackEnd(app) {
		var appRecord = {};
		// Make the App object into something we can JSONify.
		for (var attr in app) {
			appRecord[attr] = app[attr];
		}
		var req = new XMLHttpRequest();
		req.onload = function() {
			if (this.status == 200) {
				console.log('OK ' + this.responseText);
				// The receipt is valid! Remove the disabled banner.
				// Pro tip: on a real paid app you'd probably want to be more
				// clever here like load premium content from the server.
				var el = document.getElementById('app-disabled');
				el.parentNode.removeChild(el);
				document.write('<p>Receipt validated: this app is enabled</p>');
			} else {
				console.log('Failed: code: ' + this.status + ' response: ' + this.responseText);
			}
		};
		req.onerror = function() {
			console.log('App disabled: Failed to verify receipt on the server');
		}
		req.open('POST', '/', true);
		req.setRequestHeader("Content-type", "application/json");
		req.send(JSON.stringify(appRecord));
	}

	/*INIT*/
	function handleComplete() {
		var extendedCanvas = new createjs.DOMElement(document.getElementById("extendedSplashScreen"));
		TweenLite.to(extendedCanvas._style, 1, {
			opacity : 0,
			onComplete : setup
		});
	}

	function handleFileLoad(o) {

		if (o.type == "image") {
			Images.setImage(o.result, o.id);
		}

	}

	function initCanvas() {
		var canvas = document.createElement("canvas");
		canvas.setAttribute('id', "canvas");
		canvas.setAttribute('style', "background-color:#ffffff; position:absolute; top:0px; left:0px; z-index:10;");

		document.body.appendChild(canvas);

		Images.canvas = canvas;
		Images.context = canvas.getContext("2d");

		stage = new createjs.Stage(canvas);
		stage.onTick = update;
		stage.onMouseDown = onMouseDown;
		stage.onMouseMove = onMouseMove;
		document.onkeypress = onKeyDown;

		stage.update();

		createjs.Ticker.setFPS(60);
		createjs.Ticker.addListener(stage);
		createjs.Touch.enable(stage, false, false);
		updateCanvas();

	}

	function updateCanvas() {
		if (document.body && document.body.offsetWidth) {
			winW = document.body.offsetWidth;
			winH = document.body.offsetHeight;
		}
		if (document.compatMode == 'CSS1Compat' && document.documentElement && document.documentElement.offsetWidth) {
			winW = document.documentElement.offsetWidth;
			winH = document.documentElement.offsetHeight;
		}
		if (window.innerWidth && window.innerHeight) {
			winW = window.innerWidth;
			winH = window.innerHeight;
		}
		winW = Math.min(winW, maxWid);

		//winW = 480;
		//winH = 320;

		Images.canvas.setAttribute('width', winW);
		Images.canvas.setAttribute('height', winH);
		Images.canvas.setAttribute('maxWidth', maxWid);
		Images.canvas.setAttribute('maxHeight', maxHeight);
	}

	function setup() {
		document.body.removeChild(document.getElementById("extendedSplashScreen"));
		initCanvas();
		scales = Images.calculateScale();
		currentScreen = SCREEN_START;

		myThis.bearHome = new lib.AniIntroHappyBear();

		gameScreen = new lib.GameScreen(winW, winH);
		smallScreen = new lib.SmallScreen();

		animStart = new lib.AnimCountdown();
		animEnd = new lib.AnimEndGame();

		myThis.clock = new lib.Clock();

		myThis.bearAnimation = new lib.BearAnimations();
		myThis.bearAnimation.setTransform(0, 0, -2, 2);
		myThis.bearAnimation.animStay();

		myThis.borderAnimation = gameScreen.tableBg.borderAnimation;

		homeLogo = new createjs.Bitmap(Images.getImage(Images.HOME_LOGO));

		gameScreen.clockContainer.addChild(myThis.clock);
		gameScreen.bearContainer.addChild(myThis.bearAnimation);
		gameScreen.btnPlay.onClick = playClick;
		gameScreen.btnReset.onClick = resetClick;
		gameScreen.btnExit.onClick = exitClick;
		gameScreen.btnShutdown.onClick = shutdownClick;
		//gameScreen.btnFacebook.onClick = facebookClick;

		myThis.updateView();

		homeMotionIn();

	}

	/*SNOW*/
	function startSnow() {
		if (flakeInterval != null)
			return;
		flakeInterval = setInterval(createFlake, 20);
	}

	function stopSnow() {
		clearInterval(flakeInterval);
		flakeInterval = null;
	}

	function createFlake() {

		if (isDocked)
			return;

		//for ( var i = 0; i < 100; i++ )
		{
			var flake = Tools.getSnowFlake();
			flake.x = Math.random() * winW;
			flake.y = -30;
			gameScreen.flakesContainer.addChild(flake);
			Tools.flakes.push(flake);
		}
	}

	/*MAIN SCREENS*/
	function setupStartWindow() {
		clearContentContainer()

		gameScreen.contentContainer.addChild(homeLogo, myThis.bearHome, gameScreen.btnPlay, gameScreen.btnShutdown);
		myThis.bearHome.gotoAndStop(0);
		gameScreen.background.visible = false;
	}

	function setupGameWindow() {
		clearContentContainer();
		gameScreen.contentContainer.x = 0;
		gameScreen.contentContainer.addChild(gameScreen.clockContainer, gameScreen.bearContainer, gameScreen.scoreBoard, gameScreen.btnReset, gameScreen.btnExit, gameScreen.tableBg);
		gameScreen.btnReset.alpha = 1;
		myThis.bearAnimation.setTransform(0, 0, -2, 2);
		myThis.bearAnimation.setState(myThis.bearAnimation.STATE_NORMAL);
		gameScreen.background.visible = true;
	}

	function homeMotionIn() {

		currentScreen = SCREEN_START;
		setupStartWindow();
		TweenLite.to(homeLogo, 2, {
			alpha : 1,
			delay : 1
		});
		homeLogo.alpha = 0;

		if (firstLoad) {
			firstLoad = false;

			TweenLite.to(gameScreen.picture, 1, {
				alpha : 1
			});
			gameScreen.picture.alpha = 0;

			myThis.animHomeIn.append(new TweenLite(gameScreen.btnPlay, .01, {
				alpha : 1
			}), 4);
			gameScreen.btnPlay.alpha = 0;

			myThis.animHomeIn.append(new TweenLite(gameScreen.btnShutdown, .01, {
				alpha : 1
			}), 0);
			gameScreen.btnShutdown.alpha = 0;

			// myThis.animHomeIn.append( new TweenLite( gameScreen.btnFacebook, .01, { alpha: 1 } ), 0);
			//  gameScreen.btnFacebook.alpha = 0;

			myThis.animHomeIn.append(new TweenLite(myThis.bearHome, .01, {
				alpha : 1,
				onComplete : myThis.bearHome.gotoAndPlay,
				onCompleteParams : [1],
				onCompleteScope : myThis.bearHome
			}), -.01);
			myThis.bearHome.alpha = 0;

			myThis.animHomeIn.append(new TweenLite(homeLogo, 2, {
				y : winH / 20,
				ease : Elastic.easeOut
			}));
			//            TweenLite.to(homeLogo, 1, {y: 100});
			//            homeLogo.y = ( winH - (homeLogo.image.naturalHeight * scales.y) ) / 2;

		}

		TweenLite.delayedCall(4, GameSounds.playFireworks);
		TweenLite.delayedCall(4.5, startSnow);
		GameSounds.playBgMusic();
		myThis.animHomeIn.play();
	}

	function homeMotionOut() {
		//myThis.animHomeIn.reverse();
		TweenLite.to(gameScreen.contentContainer, .4, {
			alpha : 1,
			x : -winW,
			ease : Back.easeIn,
			onStart : stopSnow
		});

		for (var i = 0; i < Tools.flakes.length; i++) {
			var delay = Math.abs(Tools.flakes[i].y - winH / 2) / 1100;
			TweenLite.delayedCall(.45 + delay, blowOut, [Tools.flakes[i]]);
		}
		TweenLite.delayedCall(1, gameMotionIn);
	}

	function blowOut(flake) {
		flake.wind = -Math.random() - 1.3;
		flake.setWindyMode();
	}

	function gameMotionIn() {
		setupGameWindow();
		updateDisplayData();

		if (firstStart) {
			firstStart = false;
			var bg = gameScreen.background;
			//TweenLite.to( bg, .6, { alpha: 1 } );
			//bg.alpha = 0;

			var openingTime = .3;
			var closingDistance = -150;

			myThis.animGameIn.append(new TweenLite(bg.top, openingTime, {
				y : bg.top.y
			}));
			bg.top.y += closingDistance;

			myThis.animGameIn.append(new TweenLite(bg.left.top_1, openingTime, {
				y : bg.left.top_1.y
			}), -openingTime);
			bg.left.top_1.y += closingDistance;

			myThis.animGameIn.append(new TweenLite(bg.right.top_1, openingTime, {
				y : bg.right.top_1.y
			}), -openingTime);
			bg.right.top_1.y += closingDistance;

			myThis.animGameIn.append(new TweenLite(bg.left.bottom, openingTime, {
				y : bg.left.bottom.y
			}), -openingTime);
			bg.left.bottom.y -= closingDistance;

			myThis.animGameIn.append(new TweenLite(bg.right.bottom, openingTime, {
				y : bg.right.bottom.y
			}), -openingTime);
			bg.right.bottom.y -= closingDistance;

			//var fadeBarsTime = .2;

			//myThis.animGameIn.append( new TweenLite( bg.left.side, fadeBarsTime, { alpha: 1 } ), -.1 );
			//bg.left.side.alpha = 0;

			//myThis.animGameIn.append( new TweenLite( bg.right.side, fadeBarsTime, { alpha: 1 } ), -fadeBarsTime );
			//bg.right.side.alpha = 0;

			var positionBarsTime = .3;

			myThis.animGameIn.append(new TweenLite(bg.left.side, positionBarsTime, {
				x : bg.left.side.x
			}), -.1);
			bg.left.side.x = -50;

			myThis.animGameIn.append(new TweenLite(bg.right.side, positionBarsTime, {
				x : bg.right.side.x
			}), -positionBarsTime);
			bg.right.side.x = -50;

			myThis.animGameIn.append(new TweenLite(gameScreen.contentContainer, .5, {
				alpha : 1
			}));
			gameScreen.contentContainer.alpha = 0
		}
		gameScreen.contentContainer.alpha = 0
		myThis.animGameIn.play();
		TweenLite.delayedCall(myThis.animGameIn.totalDuration(), startGame);
		//startGame();
	}

	function gameMotionOut() {
		table.destroy();
		clearAnimationContainer();
		clearContentContainer();
		removeStartEndAnimations();
		homeMotionIn();
	}

	function clearContentContainer() {
		var cont = gameScreen.contentContainer;
		cont.alpha = 1;
		while (cont.getNumChildren() > 0) {
			cont.removeChildAt(0);
		}
	}

	function startGame() {
		Tools.clickFeedback(this);
		if (!ready) {
			table.init(10, 5, myThis, gameScreen.tableBg.container, gameScreen.tableBg.particlesContainer);
			ready = true;
		} else {
			reset()
		}

	}

	/*RESIZE EVENT HANDLERS*/
	function showGameScreen() {
		isDocked = false;
		if (stage) {
			stage.addChild(gameScreen);
			stage.update();
		}
	}

	function commonAdjusts() {
		var logoW = homeLogo.image.width * scales.x;
		var logoH = homeLogo.image.height * scales.y;

		var x = (winW - logoW ) / 2;
		var y = (winH - logoH) / 2;

		homeLogo.setTransform(x, y, scales.x, scales.y);

		myThis.bearHome.setTransform(winW / 2, winH / 2.5 + winH / 4, scales.x, scales.y);

		var playWidth = gameScreen.btnPlay.children[0].image.width * scales.x;
		var playHeight = gameScreen.btnPlay.children[0].image.height * scales.y;
		gameScreen.btnPlay.x = (winW - playWidth) / 2;
		gameScreen.btnPlay.y = (winH - playHeight) / 2 + (winH / 5);

		//gameScreen.btnFacebook.x = gameScreen.btnPlay.x;
		//gameScreen.btnFacebook.y = gameScreen.btnPlay.y + playHeight + ( playHeight * 0.10);

		gameScreen.btnShutdown.x = gameScreen.btnPlay.x;
		gameScreen.btnShutdown.y = gameScreen.btnPlay.y + playHeight + 30 + (playHeight * 0.10);

		if (currentScreen == SCREEN_START)
			GameSounds.playBgMusic();

	}

	/*ACCELEROMETER*/
	function setupAccelerometer() {
		//        accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();
		/*if ( accelerometer )
		 {
		 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
		 // This value will be used later to activate the sensor.
		 var minimumReportInterval = accelerometer.minimumReportInterval;
		 reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
		 }*/
	}

	function enableAccelerometer() {
		/*if ( accelerometer )
		 {
		 accelerometer.reportInterval = reportInterval;
		 //accelerometer.addEventListener( "readingchanged", onAccelerationData );
		 //accelerometer.addEventListener( "shaken", onShakeData );
		 }*/
	}

	function disableAccelerometer() {
		/*if ( accelerometer )
		 {
		 //accelerometer.removeEventListener( "readingchanged", onAccelerationData );
		 //accelerometer.removeEventListener( "shaken", onShakeData );
		 accelerometer.reportInterval = 0;
		 }*/
	}

	function onAccelerationData(e) {
		//var reading = e.reading;
		//gameScreen.scoreBoard.txtP1Score.text = ( 1 + reading.accelerationX ).toFixed( 2 );
		//gameScreen.scoreBoard.txtP2Score.text = ( 1 + reading.accelerationY ).toFixed( 2 );
		//gameScreen.scoreBoard.txtP3Score.text = ( 1 + reading.accelerationZ ).toFixed( 2 );
	}

	function onShakeData(e) {
		shakeCount++;
		//gameScreen.scoreBoard.txtBestScore.text = shakeCount;
	};

	/*MOUSE ADN KEY HANDLERS*/
	function playClick() {
		Tools.clickFeedback(this);
		myThis.animHomeIn.reverse();
		TweenLite.delayedCall(myThis.animHomeIn.totalDuration() - 3.3, homeMotionOut);
		GameSounds.fadeOutBGM();
		GameSounds.stopFireworks();
		currentScreen = SCREEN_GAME;
	}

	//function facebookClick()
	//{
	//	Tools.clickFeedback(this);
	//	FB.login(function(response) {
	//	  if (response.status === 'connected') {
	// Logged into your app and Facebook.
	//	  } else if (response.status === 'not_authorized') {
	// The person is logged into Facebook, but not your app.
	//	  } else {
	// The person is not logged into Facebook, so we're not sure if
	// they are logged into this app or not.
	//	  }
	//	});
	// }

	function resetClick() {
		Tools.clickFeedback(this);
		reset();
	}

	function reset() {
		currentShare = SHARE_DEFAULT;
		if (table) {
			table.destroy();
			table.reset();
		}
	}

	function exitClick() {
		ready = false;
		inGame = false;
		Tools.clickFeedback(this);
		exit();
	}

	function shutdownClick() {
		this.window.close();
	}

	function exit() {
		currentShare = SHARE_DEFAULT;
		stopSnow();
		myThis.animGameIn.reverse();
		TweenLite.delayedCall(myThis.animGameIn.totalDuration(), gameMotionOut);
	}

	function onMouseDown(evt) {
		table.clickJewel(evt.stageX, evt.stageY);
		if (myThis.inputText._style.display == "block") {
			removeVirtualKeyboard();
		}
	}

	function onMouseMove(evt) {

		for (var i = 0; i < Tools.flakes.length; i++) {
			var d = Tools.getDistance({
				x : evt.stageX,
				y : evt.stageY
			}, Tools.flakes[i]);
			if (d < 100) {
				var influence = (100 - d ) / 100 / 2;
				var angle = Math.atan2(Tools.flakes[i].y - evt.stageY, Tools.flakes[i].x - evt.stageX);
				Tools.flakes[i].sx += Math.cos(angle) * influence;
				Tools.flakes[i].sy += Math.sin(angle) * influence;
			}
		}

	}

	function onKeyDown(evt) {
		if (evt.key == "Enter" && myThis.inputText._style.display == "block") {
			removeVirtualKeyboard()
		}
	}

	function update() {
		if (gamePaused) {
			table.pause();
		} else {
			table.unpause();
		}

		if (table && ready) {
			table.ef();
		}
		if (myThis.bearAnimation && accelerometer) {
			var g = new createjs.Point()
			var angle = accelerometer.getCurrentReading().accelerationX * Math.PI / 2;
			g.x = Math.sin(angle);
			g.y = Math.cos(angle);
			Tools.gravity.x += (g.x - Tools.gravity.x ) / 5;
			Tools.gravity.y += (g.y - Tools.gravity.y ) / 5;

			//if ( Math.abs( reading.accelerationX ) > .2 )
			//{
			//    bearSx += ( ( reading.accelerationX * 15 ) - bearSx ) / 5;

			//}
			//myThis.bearAnimation.x += bearSx;
			//bearSx *= .90;
			//myThis.bearAnimation.x = Math.max( -myThis.bearAnimation.parent.x, Math.min( myThis.bearAnimation.x, winW - myThis.bearAnimation.parent.x ) );
		}

	}

	function removeVirtualKeyboard() {
		var txtElement = document.getElementById("txtName");
		if (txtElement != "") {
			txtElement.blur();
		}
	}

	/*GAME SCREENS*/
	function showNormalScoreScreen() {
		if (inGame)
			return;
		currentShare = SHARE_SCORE;

		removeStartEndAnimations();
		clearAnimationContainer();
		//showLockScreen();
		var screen = new lib.AnimScoreNormal();
		gameScreen.animContainer.addChild(screen);
		screen.mcScore.txt_1.text = Tools.formatVal(scoreData.score);
		GameSounds.playHighScore();
	}

	function showRankedScoreScreen() {
		if (inGame)
			return;
		currentShare = SHARE_SCORE;

		removeStartEndAnimations();
		clearAnimationContainer();
		showLockScreen();

		var screen = new lib.AnimScoreRecord();
		gameScreen.animContainer.addChild(screen);
		screen.score_1.txt.text = Tools.formatVal(scoreData.score);
		screen.position.updatePosition(scoreData.position, screen.position);

		screen.btnOk.onClick = showNextRecordScreen;
		GameSounds.playHighScore();

	}

	function showNextRecordScreen() {
		Tools.clickFeedback(this);

		clearAnimationContainer()

		reset();
		hideLockScreen();
		hideRankingScreen();

		//        showLockScreen();
		//        var tween = new createjs.Tween();
		//        tween.wait( 1000 ).call( showRegisterScoreScreen, null, this );
	}

	function showRegisterScoreScreen() {
		if (inGame)
			return;
		var screen = new lib.AnimScoreRanking();
		screen.callback = showInputText;
		screen.setTransform(320, 250);
		gameScreen.animContainer.addChild(screen);
		screen.texts_1.score.text = Tools.formatVal(scoreData.score);
		screen.texts_1.pos_1.gotoAndStop(scoreData.position - 1);
		screen.btnClose.onClick = hideRankingScreen;
		screen.btnOk.onClick = hideRankingScreen;

	}

	function showInputText() {
		myThis.inputText._style.display = "block";
	}

	function hideRankingScreen() {
		var txtElement = document.getElementById("txtName")
		if (txtElement.value != "") {
			myThis.inputText._style.display = "none";
			var name = txtElement.value;
			txtElement.value = "";
			Tools.ranking.writeScore(scoreData.score, name);
			updateDisplayData();
			saveRankingData();
			Tools.clickFeedback(this);
			hideLockScreen();
			clearAnimationContainer();
		}
	}

	function showLockScreen() {
		removeStartEndAnimations();

		hideLockScreen();

		var g = new createjs.Graphics();
		g.beginFill("#000000")
		g.drawRect(0, 0, winW, winH);
		g.endFill();
		lockScreen = new createjs.Shape(g);
		lockScreen.alpha = .6;
		lockScreen.onClick = (function() {
		} );
		gameScreen.animContainer.addChildAt(lockScreen, 0);
		var pt = lockScreen.localToGlobal(0, 0);
		lockScreen.x = -pt.x;
		lockScreen.y = -pt.y;
	}

	function hideLockScreen() {
		if (lockScreen && lockScreen.parent) {
			lockScreen.parent.removeChild(lockScreen);
			lockScreen = null;
		}
	}

	function removeStartEndAnimations() {
		if (animEnd.parent)
			animEnd.parent.removeChild(animEnd);
		if (animStart.parent)
			animStart.parent.removeChild(animStart);
		animStart.gotoAndStop(0);
		animEnd.gotoAndStop(0);
	}

	function clearAnimationContainer() {
		while (gameScreen.animContainer.getNumChildren() > 0) {
			gameScreen.animContainer.removeChildAt(0);
		}

	}

	/*RANKING*/
	function updateDisplayData() {
		//gameScreen.scoreBoard.txtBestScore.text = Tools.formatVal( Tools.ranking.firstScore );
		gameScreen.scoreBoard.txtP1Score.text = Tools.formatVal(Tools.ranking.firstScore);
		gameScreen.scoreBoard.txtP2Score.text = Tools.formatVal(Tools.ranking.secondScore);
		gameScreen.scoreBoard.txtP3Score.text = Tools.formatVal(Tools.ranking.thirdScore);

		//gameScreen.scoreBoard.txtBestName.text = Tools.ranking.firstName;
		gameScreen.scoreBoard.txtP1Name.text = Tools.ranking.firstName;
		gameScreen.scoreBoard.txtP2Name.text = Tools.ranking.secondName;
		gameScreen.scoreBoard.txtP3Name.text = Tools.ranking.thirdName;
	}

	//LOAD RANKING FILE
	function loadRankingFile() {
		//        Windows.Storage.KnownFolders.documentsLibrary.getFileAsync( "rnk.dat" ).done( loadFileOk, loadFileError )
	}

	function loadFileOk(file) {
		Tools.rankingFile = file;
		loadRankingData();
	}

	function loadFileError(err) {
		Tools.rankingFile = null;
		createRankingFile();
	}

	//CREATE RANKING FILE
	function createRankingFile() {
		//        Windows.Storage.KnownFolders.documentsLibrary.createFileAsync(
		//            "rnk.dat",
		//            Windows.Storage.CreationCollisionOption.replaceExisting ).done( createFileOk, createFileError
		//            );
	}

	function createFileOk(file) {
		Tools.rankingFile = file;
		saveRankingData()
	}

	function createFileError(error) {
		//TODO
	}

	//SAVE RANKING
	function saveRankingData() {
		var newContent = Tools.ranking.getData();
		if (Tools.rankingFile !== null && newContent !== "") {
			//            Windows.Storage.FileIO.writeTextAsync( Tools.rankingFile, newContent ).done( writeFileOk, writeFileError );
		}
	}

	function writeFileOk() {
		//TODO
	}

	function writeFileError(error) {
		//TODO
	}

	//LOAD RANKING
	function loadRankingData() {
		if (Tools.rankingFile !== null) {
			//            Windows.Storage.FileIO.readTextAsync( Tools.rankingFile ).done( readFileOk, readFileError );
		}
	}

	function readFileOk(fileContent) {
		Tools.ranking.setData(fileContent);
		try {
			updateDisplayData();
		} catch ( error ) {

		}
	}

	function readFileError(error) {
		//TODO
	}

	/*SHARING*/
	function enableSharing() {
		if (!shareEnabled) {
			shareEnabled = true;
			//            var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
			//            dataTransferManager.addEventListener( "datarequested", dataRequested );
			//document.getElementById( "shareButton" ).addEventListener( "click", showShareUI, false );
		}
	}

	function disableSharing() {
		shareEnabled = false;
		//        var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
		//        dataTransferManager.removeEventListener( "datarequested", dataRequested );
	}

	function dataRequested(e) {
		//
		//        var request = e.request;
		//        var dataPackageTitle = "";
		//        var dataPackageLink = "http://www.candypot.com.br";;
		//        var dataPackageDescription = "Venha jogar comigo e ver quem é o melhor! Disponível para Android, Facebook, e Intel Ultrabook";
		//
		//        if ( currentShare == SHARE_DEFAULT )
		//        {
		//            dataPackageTitle = "Estou Jogando Candypot! no Intel Ultrabook.";
		//        }
		//        if ( currentShare == SHARE_SCORE )
		//        {
		//            dataPackageTitle = "Acabei de fazer " + Tools.formatVal( scoreData.score ) + " pontos em Candypot! no Intel Ultrabook";
		//        }
		//
		//
		//        request.data.properties.title = dataPackageTitle;
		//        request.data.properties.description = dataPackageDescription;
		//        try
		//        {
		//            request.data.setUri( new Windows.Foundation.Uri( dataPackageLink ) );
		//            WinJS.log && WinJS.log( "", "candypot", "error" );
		//        } catch ( ex )
		//        {
		//            WinJS.log && WinJS.log( "Exception occured: the uri provided " + dataPackageLink + " is not well formatted.", "candypot", "error" );
		//        }
	}

} ); 