"use strict";
function peek(array) {
    return array[array.length-1];
};

function simKey(code) {
    var keyDown = document.createEvent("Events");
    var keyUp = document.createEvent("Events");
    //note that we use this for both the keydown and keyup init mehtod
    //if you have a browser that has a different init property for keyup than it does
    //for keydown there is no hope for you
    //var initMethod = typeof keyDown.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
    

    if(keyDown.initEvent && keyUp.initEvent) {
        keyDown.initEvent("keydown", true, true);
        keyUp.initEvent("keyup", true, true);
    }
    keyDown.keyCode = code;
    keyDown.which = code;
    keyUp.keyCode = code;
    keyUp.which = code;
    window.dispatchEvent(keyDown);
    //ig.input.keydown(keyDown);
    window.setTimeout(function() {
        window.dispatchEvent(keyUp);
    }, 200);

}

window.UI = {
    //the windows that are displayed
    //when a window opens it should push
    //itself onto the stack and when one
    //closes it should pop itself
    windowStack: [],
    bonusScore: 0 ,
    
    //TODO: SET TO 15000
    BONUSFORNEWLIFE: 15000,  
    //set up events and other such
    //page state
    init: function () {
    	
		UI.registerVisibilityChanged();
        ig.Sound.use = [ig.Sound.FORMAT.MP3, ig.Sound.FORMAT.OGG, ig.Sound.FORMAT.WAV];
        ig.Sound.channels = 5;
        var musicVol = sessionStorage.getItem("musicVolume") || 1;
        var soundVol = sessionStorage.getItem("soundVolume") || 1;
        UI.Options.setVolume("music", musicVol * 100.0);
        UI.Options.setVolume("sound", soundVol * 100.0);
        if (window.innerWidth > window.innerHeight) {
            UI.Stick.setStickSize(0.35);
        } else {
            UI.Stick.setStickSize(0.17);
        }
        document.getElementById("menumusic").play();
        UI.Credits.addLinkListeners();
        UI.Stick.addListeners();
        //window.addEventListener("touchmove", UI.controls.handleTouchMove);
        //window.addEventListener("touchstart", UI.controls.handleTouchStart);
        //window.addEventListener("touchend", UI.controls.handleTouchEnd);
        //window.addEventListener("touchstart", function (e) { e.preventDefault() });
        //window.addEventListener("resize", UI.Sizeing.handleRotate);
        /*window.screen.addEventListener("mozorientationchange", function () {
        if (window.screen.mozLockOrientation) {
        var locked = window.screen.mozLockOrientation("portrait-primary");
        }
        });*/
       
        window.onfocus = function(){
        	console.log("FOCUSED");
        }
        
        window.onblur = function(){
        	console.log("UNFOCUSED");
        }
       
       	document.addEventListener('mozvisibilitychange', function() {
   			console.log('locked');
		});
        var splash = document.getElementById("splash"); //the disney logo
        var wir = document.getElementById("wirSplash"); //the wir logo

        //these even listeners set the display of the logos to none
        //so that we can click through them
        splash.addEventListener("transitionend", function () {
            splash.style.display = 'none';
            //once the disney logo is gone we want to
            //start the wir logo transition
            window.setTimeout(function () {
                wir.style.opacity = '0';
            }, 500);
        });
        wir.addEventListener("transitionend", function () {
            wir.style.display = 'none';

        });

        window.setTimeout(function () {
            splash.style.opacity = '0';
        }, 500);
	//stats.js stuff
	/*var stats = new Stats();
	stats.setMode(1);
	stats.domElement.style.position = "absolute";
	stats.domElement.style.left = '0px';
	stats.domElement.style.top = '0px';
	document.body.appendChile(stats.domElement);
	*/
    },
    registerVisibilityChanged: function () {
        var hidden;
        var visibilityChanged;
        if (typeof document.hidden !== "undefined") {
            hidden = "hidden";
            visibilityChanged = "visibilitychange";
        } else if (typeof document.mozHidden !== "undefined") {
            hidden = "mozHidden";
            visibilityChanged = "mozvisibilitychange";
        } else if (typeof document.msHidden !== "undefined") {
            hidden = "msHidden";
            visibilityChanged = "msvisibilitychange";
        } else if (typeof document.webkitHidden !== "undefined") {
            hidden = "webkitHidden";
            visibilityChanged = "webkitvisibilitychange";
        }
        document.addEventListener("mozvisibilitychange", function () {
            //we want to pass in a bool from the correct page property
            console.log(document[hidden] === true);
            //console.log(document[mozVisibilityState]);
            console.log(ig.music);
            console.log(ig);
            if (document[hidden] === true) {
                if (ig.music) {
                    ig.music.stop();
		    document.getElementById("gamemusic").pause();
    		    document.getElementById("gamemusic").load(); 
                }

                var audio = document.getElementsByTagName("audio")[0];
                audio.pause();
                if (UI.MainMenu.isRunning) {
                    UI.Pause.showPauseMenu();
                }
            } else {
                if (UI.MainMenu.isRunning) {
                    if (ig.music) {
                        //ig.music.play();
			document.getElementById("gamemusic").play();
                    }
                    //UI.Pause.hidePauseMenu();
                } else {
                    var audio = document.getElementsByTagName("audio")[0];
                    audio.play();
                }
            }

        }, false);
        //window.addEventListener("blur", function () { callback(true); });
        //window.addEventListener("focus", function () { callback(false); });
    },
    changeLevel: function () {
        var levelDiv = document.getElementsByTagName("input")[0];
        var level = parseInt(levelDiv.value, 10);
        UI.startLevel = level;
        UI.Timer.pauseTimer();
        UI.Pause.restartGame();
    },
    //called when ralph starts climing up
    //off the top of the building
    levelChangeStart: function () {
        UI.controls.hideControls();
    },
    //called when ralph is done climing and breaks the windows
    levelChangeEnd: function () {
        UI.controls.showControls();
        UI.Timer.resetTimer(60);
        UI.Timer.resumeTimer();
    },
    addScore: function (amount) {
        var curScore = document.getElementById("score").innerHTML;
        var curScoreInt = parseInt(curScore, 10);
        var newScore = curScoreInt + amount;


        document.getElementById("score").innerHTML = UI.formatScore(newScore);
    },
    formatScore: function (score) {
        var string = score.toString();
        var lengthDif = 6 - string.length;
        var retval = "";
        for (var i = 0; i < lengthDif; ++i) {
            retval += 0;
        }
        retval += string;
        return retval;
    },
    setScore: function (newval) {
        document.getElementById("score").innerHTML = newval.toString();
    },
    getScore: function () {
        return parseInt(document.getElementById("score").innerHTML, 10);
    },

    updateBonusScore: function(amount){
	this.bonusScore += amount; 

	//console.log("Basile Test: scoreBeing Passed: " + amount); 
	//
	//console.log("Basile Test: BonusScore Passed: " + this.bonusScore); 

	if(this.bonusScore >= this.BONUSFORNEWLIFE){
	       this.bonusScore = this.bonusScore - this.bonusScore ;
	       ig.game.player.addLife(); 	
	}
    
	}, 
	addScoreAnimated: function (amount) {
		UI.updateBonusScore(amount); 
        UI.updateScore(UI.getScore() + amount);
    },
    updateScore: function (target) {
        var initScore = UI.getScore();
        var awardedLife = false;
        var scoreDoc = document.getElementById("score");
        var curScore = initScore;
        var scoreInter = function () {
            curScore += 25; //time bonus
            scoreDoc.innerHTML = UI.formatScore(curScore);
            if (curScore > target) {
                scoreDoc.innerHTML = UI.formatScore(target);
            } else {
                window.setTimeout(scoreInter, 10);
            }
            
            if(this.bonusScore >= this.BONUSFORNEWLIFE){
	    	   this.bonusScore = this.bonusScore - this.bonusScore ;
	    	   ig.game.player.addLife(); 	
			}
            
            
        };
        window.setTimeout(scoreInter, 10);
    },
    addTimeScore: function () {
        UI.Timer.pauseTimer();
        var timeLeft = UI.Timer.getTime();
        UI.Timer.setTimerAnimated(0);

		//TODO: Add life during this time period
        UI.addScoreAnimated(timeLeft * 100);
    },

    /*
    addLife: function(){
	var lifeWidth = 60;
        var lifeScale = 0.5;
        var lifeDiv = document.getElementById("lives");
        var regexp = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/
        var width = lifeDiv.style.width.match(regexp);
        var right = lifeDiv.style.right.match(regexp);
        var widthNum = parseInt(width[1], 10);
        var rightNum = parseInt(right[1], 10);
        //we dont want to move the element so we
        //have to increase the right spacing if
        //we decrease the width
        var newWidth = widthNum + lifeWidth;
        var newRight = 0
        lifeDiv.style.width = newWidth + "px";
        lifeDiv.style.right = newRight + "px";	
    },
    */ 

    updateLivesBar: function(lives){
		var lifeWidth = 60;
        var lifeDiv = document.getElementById("lives");
        //we dont want to move the element so we
        //have to increase the right spacing if
        //we decrease the width
		console.log("Basile Test:: Nuber of Lives:: " + lives); 
		
		
        lifeDiv.style.width = (lifeWidth* lives) + "px";
        var livesRight = -40;
        if(lives == 2){
        	livesRight = 0;
        }
        if(lives == 1){
        	livesRight = 40;
        }
       lifeDiv.style.right = livesRight + "px";	
    },

    /*
    //remove a life from the life display
    looseLife: function () {
        var lifeWidth = 60;
        var lifeScale = 0.5;
        var lifeDiv = document.getElementById("lives");
        var regexp = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/
        var width = lifeDiv.style.width.match(regexp);
        var right = lifeDiv.style.right.match(regexp);
        var widthNum = parseInt(width[1], 10);
        var rightNum = parseInt(right[1], 10);
        //we dont want to move the element so we
        //have to increase the right spacing if
        //we decrease the width
        var newWidth = widthNum - lifeWidth;
        var newRight = 0
        lifeDiv.style.width = newWidth + "px";
        lifeDiv.style.right = newRight + "px";
    },
    */ 
    resetLives: function () {
        var lifeWidth = 60;
        var lifeScale = 0.5;
        var lifeDiv = document.getElementById("lives");
        lifeDiv.style.width = lifeWidth * 3 + "px";
        lifeDiv.style.right = "-40px";
    },
    getOffset: function (element) {
        var x = 0;
        var y = 0;
        while (element && !isNaN(element.offsetLeft) && !isNaN(element.offsetTop)) {
            x += element.offsetLeft - element.scrollLeft;
            y += element.offsetTop - element.scrollTop;
            element = element.offsetParent;
        }
        return { top: y, left: x };
    },
    //| this regex is for extracting numerical values
    //| from CSS
    posRx: /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/,
    gameOverTimeout: null,
    showGameOver: function () {
        UI.Timer.pauseTimer();
        var gameOverDiv = document.getElementById("gameover");
        gameOverDiv.style.visibility = "visible";
        UI.gameOverTimeout = window.setTimeout(UI.MainMenu.showMainMenu, 5000);
    },
    hideGameOver: function () {
        var gameOverDiv = document.getElementById("gameover");
        gameOverDiv.style.visibility = "hidden";
        window.clearTimeout(UI.gameOverTimeout);
    },
    showLevelChange: function (level) {
        //we dont want to do anything
        //we we are already showing the level change
        if (peek(UI.windowStack) !== "levelChange") {
            var newText = "Level " + level;
            var levelDiv = document.getElementById("newlevel");
            var message = levelDiv.getElementsByTagName("h1")[0];
            UI.windowStack.push("levelChange");
            message.innerHTML = newText;
            levelDiv.style.visibility = "visible";
        }
    },
    hideLevelChange: function () {
        if (peek(UI.windowStack) === "levelChange") {
            var levelDiv = document.getElementById("newlevel");
            levelDiv.style.visibility = "hidden";
            UI.windowStack.pop();
        }

    },
    fadeToBlack: function () {
        var overlay = document.getElementById("overlay");
        overlay.style.backgroundColor = "#000";
        overlay.addEventListener("transitionend", function () {
            overlay.style.backgroundColor = "rgba(0, 0, 0, 0.00)";
        });
    }
};
UI.Stick = {
    dragging: false,
    hasMoved: false,
    stick: undefined,
    fingerIdentifier: undefined,
    //this function adds the proper event listeners to the sticks,
    //it handles locking the stick during level transitions
    addListeners: function () {
        var fix = document.getElementById("fix_button");
        var stick = document.getElementById("leftButtons");
        var fixDown = function (e) {
            //ig.game.soundFixButton.play();
            simKey(32); //32 is the space bar
            fix.style.backgroundImage = "url('UI/FixActive.png')";
        }
        var fixUp = function (e) {
            fix.style.backgroundImage = "url('UI/FixNormal.png')";
        }
        fix.addEventListener("touchstart", fixDown);
        fix.addEventListener("touchend", fixUp);
        fix.addEventListener("mousedown", fixDown);
        fix.addEventListener("mouseup", fixUp);
        //fix.addEventListener("mousedown", fixDown);
        //fix.addEventListener("mouseup", fixUp);
    },
    //this function sets the dimensions of the sick based on a target percent
    //note that both width and height are set to the height of the window * the 
    //target percent. This is because we want the aspect ration to be 1:1
    setStickSize: function (targetPct) {
        var stick = document.getElementById("leftButtons");
        var fix = document.getElementById("fix_button");
        var realHeight = window.innerHeight * targetPct;
        fix.style.height = realHeight + "px";
        fix.style.width = realHeight + "px";
        stick.style.width = realHeight + "px"
        stick.style.height = realHeight + "px";
    },
    handleTouchStart: function (evt) {
        evt.preventDefault();
        UI.Stick.dragging = true;
        
        
        //There is more than one finger on the screen
        if(evt.touches.length > 1){
        	for(var i = 0; i < evt.touches.length;i++){
        		
        		
        		if(evt.touches[i].clientX < window.innerWidth/2){
        			//console.log("THIS TOUCH X: " + evt.touches[i].clientX);
       				UI.Stick.fingerIdentifier = evt.touches[i].identifier;
       				if(i == 0){
       					evt.touches.splice(1, 1);
       				} else {
       					evt.touches.splice(0, 1);
       				}
       				
        		}
        		
        	}
        } else {
       		UI.Stick.fingerIdentifier = evt.touches[0].identifier;
        }
        
        
        
        console.log(evt.touches);

    },
    handleMouseDown: function (evt) {
        evt.preventDefault();
       
        UI.Stick.dragging = true;
        // to receive further mouse events when the mouse
        // leaves our control, we'll have to have the
        // top-level window receive them
        window.onmousemove = UI.Stick.handleMouseMove;
        window.onmouseup = UI.Stick.handleMouseUp;
    },
    handleTouchEnd: function (evt) {
        evt.preventDefault();
        UI.Stick.handleControlEnded();
    },
    handleMouseUp: function (evt) {
        evt.preventDefault();
        UI.Stick.handleControlEnded();
    },
    handleControlEnded: function() {
        UI.Stick.dragging = false;
        var stick = document.getElementById("stick");
        window.requestAnimationFrame(function () {
            stick.style.transform = "translate(0,0)";
        });
        UI.Stick.lastDirection = { x: 0, y: 0 };
        UI.Stick.hasMoved = false;
    },
    handleTouchMove: function (evt) {
        evt.preventDefault();
        //because the touch object provides pageX and pageY properties
        //we can just pass it to handleMouseMove and pretend it is an event
        //acts like a duck....
        var touch = evt.touches.identifiedTouch(UI.Stick.fingerIdentifier);
        UI.Stick.handleControlMove(touch.clientX, touch.clientY);
    },
    handleMouseMove: function (event) {
        event.preventDefault();
         console.log("REGISTERED TOUCH EVENT");
        UI.Stick.handleControlMove(event.clientX, event.clientY);
    },
    handleControlMove: function (clientX, clientY) {
        if (!UI.Stick.dragging)
            return;
        
        if (!UI.Stick.stick) {
            UI.Stick.stick = document.getElementById("stick");
        }
        
        //console.log("CLIENT Y: " + clientY);
        
        var stick = UI.Stick.stick;
        var viewportWidth = window.innerWidth;
        var viewportHeight = window.innerHeight;
        var halfSize = stick.offsetWidth / 2;
        var moffx = stick.offsetParent.offsetLeft;
        var moffy = stick.offsetParent.offsetTop;
        var mouseX = parseInt(clientX, 10) - moffx - halfSize;
        var mouseY = window.innerHeight - parseInt(clientY, 10) - halfSize;
        //clamp the values of mouseX and mouseY between the edges of the avalible stick space
        //we want to stick to keep moveing when the user drags off the stick though
        //Math.max(a, Math.min(x,b)) = x.clamp(a,b) if clamp existed
        var stickAngle = Math.atan2(mouseX, mouseY);
        //console.log((stickAngle / (2* Math.PI)) * 360);

        //this is the radius we want
        var radius = Math.sqrt(Math.pow(halfSize, 2) + Math.pow(halfSize, 2));
        var maxx = (radius * Math.sin(stickAngle)) / 2;
        var maxy = (radius * Math.cos(stickAngle)) / 2;
        if (mouseX > 0) {
            var cmouseX = Math.max(0, Math.min(mouseX, maxx));
        } else {
            var cmouseX = Math.max(maxx, Math.min(mouseX, 0));
        }
        if (mouseY > 0) {
            var cmouseY = Math.max(0, Math.min(mouseY, maxy));
        } else {
            var cmouseY = Math.max(maxy, Math.min(mouseY, 0));
        }

        var movementX = Math.round(cmouseX) + "px";
        var movementY = (-1 * Math.round(cmouseY)) + "px";
        
        //console.log("MOVEMENT Y: " + movementY);
        
        window.requestAnimationFrame(function () {
            stick.style.transform = "translate(" + movementX + "," + movementY + ")";
        });

        //ig.game.player.handleMove(UI.Stick.getStickDirection());
        var direction = UI.Stick.getStickDirection(Math.round(cmouseX), -Math.round(cmouseY));
        if (direction) {
            simKey(direction.code);
        }


    },
    convertFromPctToPx: function (total, percent) {
        return total * (percent / 100);
    },
    convertStyleToOffset: function (style, total) {
        var parsed = style.match(UI.posRx);

        //check if we have a percent offset and
        //parse it
        if (parsed[2] === "%") {
            return this.convertFromPctToPx(total, parsed[1]);
        } else {
            //we are assuming that the only other option
            //is pixels (not true but reasonable in this case)
            return parsed[1];
        }
    },
    lastDirection: { x: 0, y: 0 },
    getStickDirection: function (x, y) {
        if (!UI.Stick.stick) {
            UI.Stick.stick = document.getElementById("stick");
        }
        var hasMoved = UI.Stick.hasMoved;
        var stick = UI.Stick.stick;
        var stickx = x;
        var sticky = y;
        var greatestDir = Math.max(Math.abs(stickx), Math.abs(sticky));
        var xthresh = stick.offsetWidth / 6;
        var ythresh = stick.offsetHeight / 6;
        //we want to return both the name of the key and its keycode
        var retval = { name: "", code: 0 };
        //we do not want to do the calculations the first time the stick moves
        if (UI.Stick.lastDirection.x !== 0 || UI.Stick.lastDirection.y !== 0) {
            var diffx = stickx - UI.Stick.lastDirection.x;
            var diffy = sticky - UI.Stick.lastDirection.y;


            if (greatestDir === Math.abs(sticky) && Math.abs(sticky) >= ythresh) {
                var retval;
                if (sticky < 0 && (hasMoved || diffy < -5)) {
                    retval.name = "up";
                    retval.code = 38;

                } else if (hasMoved || diffy > 5) {
                    retval.name = "down";
                    retval.code = 40;
                }
                UI.Stick.hasMoved = true;
            } else if (greatestDir === Math.abs(stickx) && Math.abs(stickx) >= xthresh) {
                var retval;
                if (stickx > 0 && (hasMoved || diffx > 5)) {
                    retval.name = "right";
                    retval.code = 39;
                } else if (hasMoved || diffx < -5) {
                    retval.name = "left";
                    retval.code = 37
                }
                UI.Stick.hasMoved = true;
            }
        }
        UI.Stick.lastDirection.x = stickx;
        UI.Stick.lastDirection.y = sticky;
        if (retval.name === "" && retval.code === 0) {
            return undefined;
        } else {
            ig.show("Diff: ", diffx + ":" + diffy);
            return retval;

        }
    }
};
UI.Timer = {
    intervalHandle: null,
    gameTime: null,
    startTimer: function (time) {
        var timerDiv = document.getElementById("timer");
        UI.Timer.gameTime = new ig.Timer();
        timerDiv.innerHTML = time.toString();
        //start the "time loop"
        UI.Timer.intervalHandle = window.setInterval(UI.Timer.handleTimeEvent, 200);
    },
    pauseTimer: function () {
        window.clearInterval(UI.Timer.intervalHandle);
        delete UI.Timer.intervalHandle;
    },
    resumeTimer: function () {
        UI.Timer.intervalHandle = window.setInterval(UI.Timer.handleTimeEvent, 200);
    },
    resetTimer: function (time) {
        var timerDiv = document.getElementById("timer");
        timerDiv.innerHTML = time.toString();
    },
    getTime: function () {
        var timerDiv = document.getElementById("timer");
        var retval = parseInt(timerDiv.innerHTML, 10);
        return retval;
    },
    setTime: function (newTime) {
        var timerDiv = document.getElementById("timer");
        timerDiv.innerHTML = newTime;
    },
    setTimerAnimated: function (target, direction) {
        var curTime = UI.Timer.getTime();
        if (direction === undefined) {
            var computedDir = 0;
            if (target < curTime) {
                computedDir = -1;
            } else if (target > curTime) {
                computedDir = 1;
            } else {
                return;
            }
            UI.Timer.setTimerAnimated(target, computedDir);

        } else {
            if (direction > 0 && curTime < target) {
                UI.Timer.setTime(curTime + 1);
                window.setTimeout(UI.Timer.setTimerAnimated, 1, target, direction);
            } else if (direction < 0 && curTime > target) {
                UI.Timer.setTime(curTime - 1);
                window.setTimeout(UI.Timer.setTimerAnimated, 1, target, direction);
            }
        }
    },
    handleTimeEvent: function () {
        //update the content of the timer display
        var timerDiv = document.getElementById("timer");
        var currentTime = parseInt(timerDiv.innerHTML, 10);
        if (UI.Timer.gameTime.delta() >= 1) {
            var newTime = currentTime - 1;
            UI.Timer.gameTime.reset();
            timerDiv.innerHTML = newTime.toString();
        }


        //check if we are out of time and if so, end the game
        if (currentTime < 1) {
            UI.showGameOver();
            window.clearInterval(UI.Timer.intervalHandle);
            ig.game.pauseCount += 1;
        }

    }
};
UI.Sizeing = {
    calculateSize: function (target) {
        var targetHeight = target || IMG.SIZE(1840);
        var winX = window.innerWidth;
        var winY = window.innerHeight;
        var targetHeight = IMG.SIZE(1700);
        var scalePct = (0.85 * winY) / targetHeight;
        var retval = {
            x: winX / scalePct,
            y: targetHeight
        };
        return retval;
    },
    //handle phone rotation on mobile platforms
    handleRotate: function () {
        var newSize = UI.Sizeing.calculateSize();
        var oldSize = { x: ig.system.width, y: ig.system.height };
        var isLandscape = (window.innerWidth > window.innerHeight);
        if (ig.game.level) {
            ig.game.level.updateOffset();
        }
        if (ig.game.transition.nextLevel()) {
            ig.game.transition.nextLevel().updateOffset();
        }
        ig.system.resize(newSize.x, newSize.y);
        if (ig.game.level) {
            ig.game.level.reposition();
        }
        if (ig.game.transition.nextLevel()) {
            ig.game.transition.nextLevel().reposition();
        }
        var bricks = ig.game.getEntitiesByType(EntityBrick);
        for (var i = 0; i < bricks.length; ++i) {
            bricks[i].reposition();
        }
        //force the player and ralph to move to their new position
        if (ig.game.player) {
            ig.game.player.pos = ig.game.level.getPosition(ig.game.player.gridPosition);
        }
        if (ig.game.ralph) {
            ig.game.ralph.pos = ig.game.level.getPosition(ig.game.ralph.gridPosition);
        }
        if (isLandscape) {
            UI.Stick.setStickSize(0.35);
        } else {
            UI.Stick.setStickSize(0.17);
        }
        

    },
    //rescales the canvas by increaseing the width and height, 
    //note that this will cause parts of the canvas to be cut off
    scale: function (newScale) {
        var canvas = document.getElementById("canvas");
        var currentHeight = canvas.offsetHeight;
        var currentWidth = canvas.offsetWidth;
        var newWidth = currentWidth * newScale;
        var newHeight = currentHeight * newScale;
        canvas.style.height = newHeight + "px";
        canvas.style.width = newWidth + "px";
    },
    resetScale: function () {
        var canvas = document.getElementById("canvas");
        canvas.style.width = "100%";
        canvas.style.height = "80%";
    }
};
UI.Pause = {
    //flag to tell weather the game was 
    //paused when the pause menu opened or
    //weather it was paused beforehand
    isPaused: false,
    wasPaused: false,
    showPauseMenu: function () {
        if (!UI.Pause.isPaused) {
            UI.windowStack.push("pause");
            ig.game.pauseCount += 1;
            if (UI.Timer.intervalHandle) {
                UI.Timer.pauseTimer();
                UI.Pause.wasPaused = true;
            }
            var pauseDiv = document.getElementById("pause");
            pauseDiv.style.visibility = "visible";
            UI.Pause.isPaused = true;
        }

    },
    hidePauseMenu: function () {
        if (peek(UI.windowStack) === "pause") {
            UI.windowStack.pop();
            if (UI.windowStack.length === 0 && !ig.game.transition.isEnding && UI.Pause.wasPaused) {
                UI.Timer.resumeTimer();
                UI.Pause.wasPaused = false;
            }
            ig.game.pauseCount -= 1;
            var pauseDiv = document.getElementById("pause");
            pauseDiv.style.visibility = "hidden";
            UI.Pause.isPaused = false;
        }
    },
    restartGame: function () {
        //note that the order of these next two calls is important
        //in order to avoid having two timer running
        if (peek(UI.windowStack) === "pause") {
            UI.Pause.hidePauseMenu();
            UI.Sizeing.resetScale();
            UI.Timer.pauseTimer();
            UI.setScore("000000");
            UI.hideGameOver();
            UI.resetLives();
            Effects.windowBreakPool = [];
            ig.system.setGame(MyGame);
            UI.hideLevelChange();
        }
    },
    showWarningMenu: function () {
        var warning = document.getElementById("warning");
        warning.style.visibility = "visible";
        UI.windowStack.push("warning");
        
        //Have to hide the pause menu at teh same time
        var pause = document.getElementById("pause");
        pause.style.visibility = "hidden";
        
    },
    hideWarningMenu: function () {
        if (peek(UI.windowStack) === "warning") {
            UI.windowStack.pop();
            var warning = document.getElementById("warning");
            warning.style.visibility = "hidden";
            
            var pause = document.getElementById("pause");
       		 pause.style.visibility = "visible";
        }
    }
};
UI.MainMenu = {
    isRunning: false,
    hasLoaded: false,

    startGame: function () {
        if (!UI.MainMenu.isRunning && UI.windowStack.length === 0) {
            var audio = document.getElementsByTagName("audio")[0];
            audio.pause();
            var menu = document.getElementById("mainmenu");
            menu.style.opacity = "0";
            var listener = function () {
                menu.style.visibility = "hidden";
                menu.removeEventListener('transitionend', listener);
            }
            menu.addEventListener('transitionend', listener);
            if (!UI.MainMenu.hasLoaded) {
                ig.main('#canvas', MyGame, 60, UI.Sizeing.calculateSize().x, UI.Sizeing.calculateSize().y, 1);
                UI.MainMenu.hasLoaded = true;
            } else {
                ig.system.setGame(MyGame);
            }
            UI.MainMenu.isRunning = true;


        }
    },
    showMainMenu: function () {
        if (UI.MainMenu.hasLoaded) {
            
            UI.Pause.hideWarningMenu();
            UI.Pause.hidePauseMenu();
            UI.hideLevelChange();
            UI.hideGameOver();
            UI.resetLives();
            ig.game.pauseCount += 1;
            UI.Timer.pauseTimer();
            UI.setScore("000000");
            ig.game.scoreEnt = undefined;
            ig.music.stop();
	    document.getElementById("gamemusic").pause();
	    document.getElementById("gamemusic").load(); 
            Effects.windowBreakPool = [];
            var audio = document.getElementsByTagName("audio")[0];
            audio.play();
            var menu = document.getElementById("mainmenu");
            menu.style.visibility = "visible";
            menu.style.opacity = "1";
            UI.MainMenu.isRunning = false;
	    UI.Sizeing.resetScale();

        }
    },
    showOptionsMenu: function () {
        if (UI.windowStack.length === 0) {
            UI.Options.openMenu();
        }
    },
    showHelpMenu: function () {
        if (UI.windowStack.length === 0) {
            UI.Help.showHelp();
        }
    }
};
window['UI'] = UI;
