/// <reference path="../../../Content/GamesDownloadTemplate/lib/ScormHelper.js" />
/// <reference path="http://code.createjs.com/createjs-2013.12.12.min.js" />
var stage;
var Game = Game || (function (createjs) {

    ////Main Function////
    function Game(canvas, gameData) {
        var gameState = {
            twoPlayers: false,
            currentPlayer: "purplePlayer",
            outs: 0,
            runs: 0,
            cpuRuns: 0,
            teamAtBat: 1,
            numberOfInnings: 5, //5
            inning: 1,
            currentQuestion: null,
            currentQuestionIndex: 0,
            correctAnswer: ""
        }
        stage = new createjs.Stage(canvas);
        stage.enableMouseOver(10);

        var isLmsConnected = false;

        if (typeof ScormHelper !== 'undefined') {
            isLmsConnected = ScormHelper.initialize();

        }

        createjs.Touch.enable(stage, false, true);
        gameData = gameData || {};
        var assetsPath = gameData.assetsPath || "";
        var badAndroidDevice = navigator.userAgent.indexOf("Android") > -1 && !(navigator.userAgent.indexOf("Chrome") > -1);
        if (badAndroidDevice && createjs.Touch.isSupported()) {
            stage.enableDOMEvents(false);
        }
        var isMobileInterfaceApp = gameData.IsMobileInterfaceApp;
        //var canvas; //Will be linked to the canvas on index.html 
        var myCrowd = createjs.Sound.createInstance("crowd");
        var bg; //The background graphic
        var mainBG; //The Main Ball diamond Background
        var isTwoPlayer = false;
        var startB; //The Start button 
        var closeB; //The close button 
        var isClickEnabled = true;
        //sounds
        var myCrowd; myOrgan = createjs.Sound.createInstance("organ");
        var myOrgan;
        var musicOn = true;
        //[Game View]
        var pupleHelmet; //static purple helmet
        var yellowhelmet; //static yellow helmet
        var purplePlayer; //The purple helmet player graphic
        var yellowPlayer; //The yellow helmet player graphic
        var currentPlayer; //eventually determines purple or yellow-------------------
        var ball; //The ball graphic
        var cpu; //The CPU player/
        var yellowWin; //The yellow winning popup
        var purpleWin; //The purple winning popup
        var lose; //The losing popup

        //[Score]
        var playerScore; //The main player score
        var cpuScore; //The CPU score
        var playerOuts; //outs

        //ticker
        var ticker;

        //preloaderJS object
        var preloader;
        //manifest will hold the list of files we need to load.
        var manifest;
        //total loaded: this variable will hold the number of files already loaded.
        var totalLoaded = 0;

        //display object container
        var TitleView = new createjs.Container();
        var nextQuestionIndex = 0;
        var questionArea;
        //var gameData;
        var queue = new createjs.LoadQueue(false);

        var playerOptionsView = new createjs.Container();
        var winnerView = new createjs.Container();
        /////create bases with coordinates and runner////
        var startBase = { x: 352, y: 320, runner: null };
        var firstBase = { x: 525, y: 165, runner: null };
        var secondBase = { x: 365, y: 20, runner: null };
        var thirdBase = { x: 192, y: 170, runner: null };
        var homeBase = { x: 345, y: 320, runner: null };

        // Randomize Questions/Answers
        
        if (gameData.RandomizeQuestions || gameData.RandomizeQuestions === undefined) {
            gameData.Questions = shuffle(gameData.Questions);
        }


        for (var i = 0; i < gameData.Questions.length; i++) {
            if (gameData.Questions[i].RandomizeAnswers) {
                gameData.Questions[i].Answers = shuffle(gameData.Questions[i].Answers);
            }
        }

        function shuffle(array) {
            var currentIndex = array.length, temporaryValue, randomIndex;

            while (0 !== currentIndex) {
                randomIndex = Math.floor(Math.random() * currentIndex);
                currentIndex -= 1;
                temporaryValue = array[currentIndex];
                array[currentIndex] = array[randomIndex];
                array[randomIndex] = temporaryValue;
            }
            return array;
        }

        //collection of bases
        var bases = [startBase, firstBase, secondBase, thirdBase, homeBase]; // 0 -> 4

        stage.enableMouseOver();

        var gameData = gameData;
        stage.mouseEventsEnabled = true;

        queue.installPlugin(createjs.Sound);
        queue.addEventListener("complete", function (event) {
            initializeGame();
        });

        var assetsPath = gameData.assetsPath || "";

        manifest = [
                    { src: assetsPath + "PlainBackground.png", id: "bg" },
                    { src: assetsPath + "Background.png", id: "mainBG" },
                    { src: assetsPath + "startButton.png", id: "startB" },
                    { src: assetsPath + "baseBallSpinner.png", id: "ball" },
                    { src: assetsPath + "closeButton.png", id: "closeB" },
                    { src: assetsPath + "purpleHelmet.png", id: "purplePlayer" },
                    { src: assetsPath + "yellowHelmet.png", id: "yellowPlayer" },
                    { src: assetsPath + "purpleHelmet.png", id: "purpleHelmet" },
                    { src: assetsPath + "yellowHelmet.png", id: "yellowHelmet" },
                    { src: assetsPath + "Info.png", id: "info" },
                    { src: assetsPath + "sound_on.png", id: "musicOn" },
                    { src: assetsPath + "no_sound.png", id: "musicOff" },
                    { src: assetsPath + "baseballInstructions.jpg", id: "instructions" },
                    { src: assetsPath + "PlayBall.mp3", id: "PlayBall" },//|PlayBall.ogg
                    { src: assetsPath + "organ.mp3", id: "organ" },//|organ.ogg
                    { src: assetsPath + "Cheer.mp3", id: "Cheer" },//|Cheer.ogg
                    { src: assetsPath + "Small_Cheer.mp3", id: "Small_Cheer" },//|Small_Cheer.ogg
                    { src: assetsPath + "Hit_loud.mp3", id: "Hit" },//|Hit_Loud.ogg
                    { src: assetsPath + "YerOut1.mp3", id: "YerOut1" },//|YerOut1.ogg
                    { src: assetsPath + "YerOut2.mp3", id: "YerOut2" },//|YerOut2.ogg
                    { src: assetsPath + "YerOut3.mp3", id: "YerOut3" },//|YerOut3.ogg
                    //{ src: "out2.mp3|out2.ogg", id: "out2" },
                    { src: assetsPath + "crowd.mp3", id: "crowd" },//|crowd.ogg
                     { src: assetsPath + "Outro.mp3", id: "Outro" }//|Outro.ogg
        ];

        preloader = new createjs.LoadQueue(false);
        preloader.installPlugin(createjs.SoundJS);
        preloader.addEventListener("complete", addTitleView);
        preloader.loadManifest(manifest);

        createjs.Sound.registerSound({ src: assetsPath + "PlayBall.mp3", id: "PlayBall" });//|PlayBall.ogg
        createjs.Sound.registerSound({ src: assetsPath + "crowd.mp3", id: "crowd" });//|crowd.ogg
        createjs.Sound.registerSound({ src: assetsPath + "Hit_loud.mp3", id: "Hit" });//|Hit_Loud.ogg
        createjs.Sound.registerSound({ src: assetsPath + "organ.mp3", id: "organ" });//|organ.ogg
        createjs.Sound.registerSound({ src: assetsPath + "Cheer.mp3", id: "Cheer" });//|Cheer.ogg
        createjs.Sound.registerSound({ src: assetsPath + "Small_Cheer.mp3", id: "Small_Cheer" });//|Small_Cheer.ogg
        createjs.Sound.registerSound({ src: assetsPath + "YerOut1.mp3", id: "YerOut1" });//|YerOut1.ogg
        createjs.Sound.registerSound({ src: assetsPath + "YerOut2.mp3", id: "YerOut2" });//|YerOut2.ogg
        createjs.Sound.registerSound({ src: assetsPath + "YerOut3.mp3", id: "YerOut3" });//|YerOut3.ogg
        createjs.Sound.registerSound({ src: assetsPath + "Outro.mp3", id: "Outro" });//|Outro.ogg

        var YerOut1 = createjs.Sound.createInstance("YerOut1");
        YerOut1.volume = YerOut1.volume * 0.50;

        var myCrowd = createjs.Sound.createInstance("crowd");

        /* Ticker */
        createjs.Ticker.setFPS(30);
        createjs.Ticker.addEventListener("tick", updateStage);
        function updateStage() {
            stage.update();
        }

        function handleFileLoad(event) {
            //triggered when an individual file completes loading

            switch (event.type) {
                case PreloadJS.IMAGE:
                    //image loaded
                    var img = new Image();
                    img.src = event.src;
                    img.onload = handleLoadComplete;
                    window[event.id] = new Bitmap(img);
                    break;

                case PreloadJS.SOUND:
                    //sound loaded
                    handleLoadComplete();
                    break;
            }
        }
        //after all is loaded and ready to go!!!!
        function handleLoadComplete(event) {
            // check if the number of items in our manifest is the same as the number of total loaded assets, and if so, go to Main menu / view
            totalLoaded++;

            if (manifest.length == totalLoaded) {
                addTitleView();
            }


        }
        var volumeLevel = createjs.Sound.getVolume();
        createjs.Sound.setVolume(.1);
        //Starting View....  place the images for Background, Start Button and on the stage 
        function addTitleView() {
            var background = new createjs.Bitmap(preloader.getResult("bg"));
            TitleView.addChild(background);

            var titleText = new createjs.Text(gameData.Title, "36px Arial Black", "#7649AE");
            titleText.shadow = new createjs.Shadow("gray", 1, 1, 3);
            titleText.textAlign = "center";
            titleText.x = 400;
            titleText.lineWidth = 780;
            //titleText.x = 10;
            titleText.y = 10;
            TitleView.addChild(titleText);

            var descriptionText = new createjs.Text(gameData.Description, "20px Arial Black", "gray");
            descriptionText.lineWidth = 600;
            descriptionText.textAlign = "center";
            descriptionText.x = 400;
            descriptionText.y = 150;
            TitleView.addChild(descriptionText);

            ////Green start button
            var startB = new createjs.Bitmap(preloader.getResult("startB"));
            startB.textAlign = "center";
            startB.x = 350;
            // startB.x = 340 - 31.5;
            startB.y = 300;
            startB.shadow = new createjs.Shadow("gray", 0, 1, 1);
            startB.addEventListener("click", function (event) {
                //playball!

                myCrowd.play({ offset: 0, loop: 4, pan: 0 });    // options as object properties


                createjs.Sound.play("PlayBall");
                createjs.Sound.play("Cheer");

                addGameView();

            });
            startB.addEventListener("mouseover", function () {
                startB.alpha *= .80;
            });
            startB.on("mouseout", function (event) {
                startB.alpha = 1;
            });

            TitleView.addChild(startB);

            stage.addChild(TitleView);
            getUserControls();
        }

        function tweenTitleView() {
            // Start Game

            var thingsToAnimate = {
                y: -320,
                alpha: 0
            }

            var duration = 300; // in milliseconds!

            createjs.Tween.get(TitleView)
                          .to(thingsToAnimate, duration)
                          .call(addGameView);
        }

        function showScore() {
            // Show score
            score.x = 480;

            stage.addChild(score);
            stage.update();
            Tween.get(score).to({ x: 0 }, 300);
        }

        function addGameView() {
            stage.removeAllChildren();
            score = null;

            mainBG = new createjs.Bitmap(preloader.getResult("mainBG"));
            purplePlayer = new createjs.Bitmap(preloader.getResult("purplePlayer"));
            yellowPlayer = new createjs.Bitmap(preloader.getResult("yellowPlayer"));
            purpleHelmet = new createjs.Bitmap(preloader.getResult("purpleHelmet"));
            yellowHelmet = new createjs.Bitmap(preloader.getResult("yellowHelmet"));
            ball = new createjs.Bitmap(preloader.getResult("ball"));
            //helmet icons for scoreboard
            purpleHelmet.x = 25;
            purpleHelmet.y = 90;
            yellowHelmet.x = 25;
            yellowHelmet.y = 165;

            currentPlayer = gameState.currentPlayer;
            bases[0].runner = currentPlayer;

            // Score
            playerScore = new createjs.Text('0', 'bold 26px Arial', '#662D91');
            playerScore.x = 140;
            playerScore.y = 110;

            cpuScore = new createjs.Text('0', 'bold 26px Arial', '#666666');
            cpuScore.x = 140;
            cpuScore.y = 190;

            // Outs
            playerOuts = new createjs.Text('0', 'bold 26px Arial', '#662D91');
            playerOuts.x = 700;
            playerOuts.y = 190;

            // Innings
            innings = new createjs.Text('1', 'bold 26px Arial', '#662D91');
            innings.x = 700;
            innings.y = 110;

            //add yellowPlayer if / when cpu plays
            stage.addChild(mainBG, playerScore, cpuScore, playerOuts, innings, purpleHelmet, yellowHelmet, cpu);

            questionArea = getDisplayQuestionArea();
            questionArea.alpha = 0;

            showNextQuestion();
            createjs.Tween.get(questionArea).wait(500).to({ alpha: 1 }, 300);

            stage.addChild(questionArea);
            getUserControls();
        }

        function createInstructionsView() {
            var view = new createjs.Container();
            view.name = "instructionsContainer";
            var image = new createjs.Bitmap(preloader.getResult("instructions"));

            var hit = new createjs.Shape();
            var exitContainer = new createjs.Container();
            var exitBox = new createjs.Shape();

            exitContainer.x = 720;
            exitContainer.y = 570;
            var exitText = new createjs.Text("BACK", 'bold 18px Arial', "#fff");
            exitText.x = 8;
            exitText.y = 8;
            exitContainer.hitArea = new createjs.Shape(new createjs.Graphics().beginFill("#7449AE").beginStroke("#000").setStrokeStyle(1).drawRoundRect(0, 0, 70, 37, 5).endFill().endStroke());
            hit.graphics.beginFill("#000").drawRect(0, 0, exitText.getMeasuredWidth(), exitText.getMeasuredHeight());
            exitBox.graphics.beginFill("#7449AE").beginStroke("#000").setStrokeStyle(1).drawRoundRect(0, 0, 70, 37, 5).endFill().endStroke();
            exitText.hitArea = hit;
            exitContainer.addChild(exitBox, exitText);

            view.addChild(image, exitContainer);//, 

            exitContainer.addEventListener("click", function (event) {
                stage.removeChild(event.target.parent);
            });

            return view;
        }

        var instructionsView = null;

        //Gamestate to keep track of strikes outs and runs...
        function handleAnswerClick(event) {
            if (isClickEnabled) {
                isClickEnabled = false;

                var clickedAnswer = event.currentTarget.answer;
                var isCorrect = clickedAnswer.IsCorrect;

                if (currentLmsInteraction != null) {
                    currentLmsInteraction.stop();
                    currentLmsInteraction.result = isCorrect ? ScormHelper.results.correct : ScormHelper.results.incorrect;
                    currentLmsInteraction.learnerResponse = clickedAnswer.Text;

                    currentLmsInteraction.save();
                }

                if (isCorrect) {
                    createjs.Sound.play("Hit");
                    createjs.Sound.play("Small_Cheer");
                    ballHit();

                    for (var i = 3; i >= 0 ; i--) {

                        //move runner from base i to i + 1
                        if (bases[i].runner != null) {

                            bases[i + 1].runner = bases[i].runner;

                            // animate the move
                            if (bases[i + 1] == homeBase) {
                                createjs.Tween.get(bases[i].runner).to({ x: bases[i + 1].x, y: bases[i + 1].y }, 1100)
                                                                   //.to({ scaleX: 1.5, scaleY: 1.50 }, 300)
                                                                   .to({ scaleX: 0, scaleY: 0, alpha: 0 }, 100)
                                                                   .call(function (event) {
                                                                       if (event.target.parent != null) {
                                                                           event.target.parent.removeChild(event.target)
                                                                       }
                                                                   });
                            }
                            else {
                                createjs.Tween.get(bases[i].runner).to({ x: bases[i + 1].x, y: bases[i + 1].y }, 1000);
                            }

                            //runner has left the base
                            bases[i].runner = null;

                        }

                    }

                    //after looping through bases check for scoring run
                    if (homeBase.runner != null) {
                        //SCORE!!
                        createjs.Sound.play("Cheer");
                        if (gameState.currentPlayer == "purplePlayer") {
                            gameState.runs += 1;
                            //display score
                            playerScore.text = gameState.runs.toString();

                            ////                   //play organ sound after 3rd hit
                            if (gameState.runs == 1 | gameState.runs == 3 | gameState.runs == 6 | gameState.runs == 9 | gameState.runs == 12) {
                                myOrgan = createjs.Sound.createInstance("organ");
                                myOrgan.play({ delay: 3000 }, createjs.Sound.INTERRUPT_ANY);

                            }

                        }
                        else {
                            gameState.cpuRuns += 1;
                            //display score
                            cpuScore.text = gameState.cpuRuns.toString();
                        }


                        //set homebase runner back to null
                        homeBase.runner = null
                        stage.removeChild(homeBase.runner)

                        //score 
                        var runScoredText = new createjs.Text("RUN SCORED!", "42px Arial Black", "White");
                        runScoredText.shadow = new createjs.Shadow("gray", 1, 1, 3);
                        runScoredText.lineWidth = 780;
                        runScoredText.x = 240;
                        runScoredText.y = 100;
                        stage.addChild(runScoredText);
                        //animate run scored text
                        createjs.Tween.get(runScoredText).to({ alpha: 0 }, 6000);
                    }
                    //next question
                    //showNextQuestion();

                }
                else {

                    ///                //inncorrect answer
                    gameState.outs += 1;
                    getIncorrectAnswerArea();
                    var youreOutText = new createjs.Text("You're Out!!", "30px Arial Black", "red");
                    youreOutText.shadow = new createjs.Shadow("grey", 1, 1, 3);
                    youreOutText.lineWidth = 780;
                    youreOutText.x = 280;
                    youreOutText.y = 240;


                    //animate you're out text
                    createjs.Tween.get(youreOutText)
                    .to({ scaleX: 1.25, scaleY: 1.25, alpha: 0 }, 800)
                    stage.addChild(youreOutText);

                    //yer out
                    //
                    playerOuts.text = gameState.outs.toString();


                }



                var container = new createjs.Container();
                container.name = "responseBox";
                container.x = 10;
                container.y = 460;
                var feedback = new createjs.Shape(new createjs.Graphics().beginFill("#F8E197").beginStroke("#000").drawRoundRect(0, 0, 782, 137, 5));
                var feedbackText = gameData.Questions[(nextQuestionIndex - 1)].Feedback || "";

                var resultText = isCorrect ? "Correct" : "Incorrect";
                var userResultText = new createjs.Text(resultText, "bold 36px Arial", "#000");
                userResultText.x = (785 - userResultText.getBounds().width) / 2;
                userResultText.y = 5;

                var nextBackground = new createjs.Shape(new createjs.Graphics().beginFill("#1F9954").beginStroke("#000").drawRoundRect(0, 0, 80, 30, 5));

                var nextText = new createjs.Text("Next", "bold 20px Arial", "#F4CD51");
                nextText.x = 20;
                nextText.y = 3;
                var nextContainer = new createjs.Container();
                nextContainer.x = 700;
                nextContainer.y = 10;

                var CorrectAnswerText = new createjs.Text("The correct answer is:", "bold 16px Arial", "#000");

                CorrectAnswerText.lineWidth = 780;
                CorrectAnswerText.x = (785 - CorrectAnswerText.getBounds().width) / 2;
                CorrectAnswerText.y = 50;



                var AnswerText = new createjs.Text(gameState.correctAnswer, "bold 16px Arial", "#000");
                AnswerText.lineWidth = 780;
                var answerTextwidth = AnswerText.getBounds() != null ? AnswerText.getBounds().width : 0;
                var answerTextheight = AnswerText.getBounds() != null ? AnswerText.getBounds().height : 0;
                AnswerText.x = (785 - answerTextwidth) / 2;
                AnswerText.y = 70;
                if (feedbackText) {
                    var feedbackAddText = new createjs.Text(feedbackText, "bold 16px Arial", "#000");
                    feedbackAddText.lineWidth = 780;
                    feedbackAddText.x = (785 - feedbackAddText.getBounds().width) / 2;
                    feedbackAddText.y = answerTextheight + 70 + 10;
                }
                nextContainer.addChild(nextBackground);
                nextContainer.addChild(nextText);
                nextContainer.addEventListener("click", function () {

                    var responseBox = stage.getChildByName("responseBox")
                    stage.removeChild(responseBox);
                    questionArea.answerArea.removeAllChildren();
                    createjs.Tween.get(responseBox).call(showNextQuestion)

                });


                container.addChild(feedback, userResultText, nextContainer, CorrectAnswerText, AnswerText, feedbackAddText);
                stage.addChild(container);



            }
        }
        function getIncorrectAnswerArea() {
            isClickEnabled = false;

            playerOuts.text = gameState.outs.toString();

            //display Number of outs
            if (gameState.outs >= 3) {
                //last out before changing team at bat
                createjs.Sound.play("YerOut3");

                gameState.outs = 0;
                playerOuts.text = gameState.outs.toString();

                //switch team at bat
                gameState.teamAtBat += 1;

                ////players leave field...
                stage.removeChild(firstBase.runner, secondBase.runner, thirdBase.runner, homeBase.runner, startBase.runner);

                ////set runners to null
                for (var i = 4; i >= 0 ; i--) {

                    if (bases[i].runner != null) {

                        bases[i].runner = null;
                    }
                }

                //change inning
                if ((gameState.teamAtBat % 2) != 0) {

                    gameState.inning += 1;
                    innings.text = gameState.inning.toString();
                    //organ UNLESS end of game
                    if (gameState.inning <= gameState.numberOfInnings) {

                        //  createjs.Sound.play("organ");
                        myOrgan = createjs.Sound.createInstance("organ");
                        // options as object properties
                        //  myOrgan.stop();
                        myOrgan = createjs.Sound.createInstance("organ");
                        myOrgan.play(createjs.Sound.INTERRUPT_ANY);    // should not play if organ sound is already playing

                    }
                }

                //determine end of the game!
                if (gameState.inning == (gameState.numberOfInnings + 1)) {
                    // old end of game
                    createjs.Sound.play("Outro");
                    // myCrowd.stop();

                }
                else {
                    //switch team at bat
                    if (gameState.currentPlayer == "purplePlayer") {
                        gameState.currentPlayer = "yellowPlayer";
                    }
                    else {
                        gameState.currentPlayer = "purplePlayer";
                    }
                    reset(1);
                }
            }


            //you're out!
            if (gameState.outs == 1) {
                createjs.Sound.play("YerOut1");
            }
            if (gameState.outs == 2) {
                createjs.Sound.play("YerOut2");
            }


            //return container;
        }

        function addWinnerView() {

            // short cheer and then stop crowd sound
            createjs.Sound.play("Cheer");
            myCrowd.stop();
            // createjs.Sound.stop("crowd");

            if (isLmsConnected) {
                ScormHelper.cmi.completionStatus(ScormHelper.completionStatus.completed);
            }

            var background = new createjs.Bitmap(preloader.getResult("bg"));
            winnerView.addChild(background);

            var titleText = new createjs.Text("One Swing Baseball", "36px Arial Black", "#7649AE");
            titleText.shadow = new createjs.Shadow("gray", 1, 1, 3);
            titleText.textAlign = "center";
            titleText.x = 400;
            titleText.lineWidth = 780;
            titleText.y = 10;
            winnerView.addChild(titleText);

            //Game Over
            var gameOverText = new createjs.Text("GAME OVER", "36px Arial Black", "gray");
            gameOverText.textAlign = "center";
            gameOverText.x = 400;
            gameOverText.y = 90;
            winnerView.addChild(gameOverText);
            createjs.Tween.get(gameOverText).to({ alpha: 0 }, 7000);



            //winner score
            var winnerOneText = new createjs.Text("Purple Team wins " + gameState.runs.toString() + " to " + gameState.cpuRuns.toString(), "36px Arial Black", "purple");
            winnerOneText.shadow = new createjs.Shadow("gray", 3, 3, 4);

            var winnerCPUText = new createjs.Text("Yellow Team wins " + gameState.cpuRuns.toString() + " to " + gameState.cpuRuns.toString(), "36px Arial Black", "#FFCC00");
            winnerCPUText.shadow = new createjs.Shadow("gray", 2, 2, 3);

            var winnerTieText = new createjs.Text("Tie Game " + gameState.cpuRuns.toString() + " to " + gameState.cpuRuns.toString() + "!", "36px Arial Black", "gray");
            winnerTieText.shadow = new createjs.Shadow("gray", 2, 2, 3);

            var points = gameState.runs + gameState.cpuRuns;
            if (points > 0) {
                submitScore(points);
            }

            //winnertext = determine winner
            if (gameState.runs == gameState.cpuRuns) {
                var winnerText = winnerTieText;
            }
            if (gameState.runs > gameState.cpuRuns) {
                var winnerText = winnerOneText;
            }
            if (gameState.runs < gameState.cpuRuns) {
                var winnerText = winnerCPUText;
            }

            winnerText.textAlign = "center";
            winnerText.x = 400;
            winnerText.y = 160;
            winnerView.addChild(winnerText);

            //add new start and exit buttons

            var startB = new createjs.Bitmap(preloader.getResult("startB"));

            startB.regX = startB.getBounds().width / 2;
            startB.regY = startB.getBounds().height / 2;
            startB.x = stage.canvas.width / 2;
            startB.y = 280;
            startB.shadow = new createjs.Shadow("gray", 3, 3, 3);

            startB.addEventListener("click", startOver); ///////addPlayerOptionsView()//////////////////// start over 
            startB.addEventListener("mouseover", function () {
                startB.alpha *= .80;
            });
            startB.on("mouseout", function (event) {
                startB.alpha = 1;
            });
            if (!isLmsConnected) {
                winnerView.addChild(startB);
            }
            // only show the quit text if we're on a mobile device!
            if ((!isMobileInterfaceApp) &&
            isLmsConnected || navigator.userAgent.match(/Android/i)
            || navigator.userAgent.match(/webOS/i)
            || navigator.userAgent.match(/iPhone/i)
            || navigator.userAgent.match(/iPad/i)
            || navigator.userAgent.match(/iPod/i)
            || navigator.userAgent.match(/BlackBerry/i)
            || navigator.userAgent.match(/Windows Phone/i)
            ) {
                var closeB = new createjs.Bitmap(preloader.getResult("closeB"));
                closeB.regX = startB.regX;
                closeB.regY = startB.regY;
                closeB.x = startB.x;
                closeB.y = startB.y + 150;
                closeB.shadow = new createjs.Shadow("gray", 3, 3, 3);
                closeB.addEventListener("click", quit); //exit
                closeB.addEventListener("mouseover", function () {
                    closeB.alpha *= .80;
                });
                closeB.on("mouseout", function (event) {
                    closeB.alpha = 1;
                });
                winnerView.addChild(closeB);

            }

            return winnerView;

        }
        //random hit into the outfield
        function ballHit(event) {
            //hit sound?
            createjs.Sound.play("batHitsBall");
            //ball animation
            createjs.Tween.get(ball, { loop: false })
                .to({ y: -100, x: (Math.random() * (800 - 100)), scaleX: 1.35, scaleY: 1.35, alpha: .70 }, 600)
                                                 .call(function (event) {
                                                     if (event.target.parent != null) {
                                                         event.target.parent.removeChild(event.target)
                                                     }
                                                 });

        }

        var currentLmsInteraction = null;

        function showNextQuestion() {
            questionArea.answerArea.removeAllChildren();

            if (nextQuestionIndex < gameData.Questions.length) {
                if (isLmsConnected) {
                    var question = gameData.Questions[nextQuestionIndex];

                    currentLmsInteraction = ScormHelper.cmi.interactions().new();

                    currentLmsInteraction.id = question.Id;
                    currentLmsInteraction.description = question.Text;
                    currentLmsInteraction.type = ScormHelper.interactions.choice;
                }

                isClickEnabled = true;
                questionArea.prompt.text = gameData.Questions[nextQuestionIndex].Text;
                var curpx = 24;
                while (questionArea.prompt.getMeasuredHeight() > 60) {
                    questionArea.prompt.font = curpx + "px Arial Black";
                    curpx = curpx - 1
                    if (curpx == 10) break;
                }
                var answers = gameData.Questions[nextQuestionIndex].Answers;
                var y = 0;
                for (var i = 0; i < answers.length; ++i) {

                    //answer button
                    var answerButton = new createjs.Container();
                    answerButton.answer = answers[i];
                    answerButton.y = y;

                    //answer button background clickable 
                    var background = new createjs.Shape();
                    background.graphics.beginStroke(1).beginFill("white").drawRoundRect(-10, 0, 783, 30, 5);
                    answerButton.addChild(background);

                    //answer text added to buttons
                    var answerText = new createjs.Text(answers[i].Text, "20px Arial", "centered", "black");
                    answerButton.addChild(answerText);
                    if (answers[i].IsCorrect) {
                        gameState.correctAnswer = answers[i].Text;

                    }
                    answerButton.addEventListener("click", handleAnswerClick);

                    questionArea.answerArea.addChild(answerButton);
                    y += 35;

                }

                ++nextQuestionIndex;
                //add new runner at bat
                reset(0);
            } else {
                stage.removeAllChildren();
                var winnerView = addWinnerView();
                stage.addChild(winnerView);
            }
        }

        //play ball!
        function startGame(e) {
            mainBG.onPress = null;
            Ticker.addListener(tkr, false);
            tkr.tick = update;
        }

        // Reset Game View
        function reset(isTeamSwitch) {
            //remove any runner from homeplate
            stage.removeChild(startBase.runner, homeBase.runner);
            homeBase.runner = null;
            startBase.runner = null;

            ball = new createjs.Bitmap(preloader.getResult("ball"));
            ball.x = 345;
            ball.y = 305;

            currentPlayer = new createjs.Bitmap(preloader.getResult(gameState.currentPlayer));
            currentPlayer.x = bases[0].x;
            currentPlayer.y = bases[0].y;

            ////get new runner
            bases[0].runner = currentPlayer;

            startBase.runner.alpha = 0;
            ball.alpha = 0;
            createjs.Tween.get(ball).wait(500).to({ alpha: 1 }, 600);
            createjs.Tween.get(startBase.runner).wait(600).to({ alpha: 1 }, 600);
            if (isTeamSwitch == 1) {

                var switchContainer = new createjs.Container();

                if (currentPlayer == 'purplePlayer') {
                    var background = new createjs.Shape(new createjs.Graphics().beginFill("#E0E2CC").beginStroke("#000").drawRoundRect(0, 0, 300, 237, 5));
                    var orderText = new createjs.Text("Top of the order!", "36px Arial Black", "#8633A5");
                } else {
                    var background = new createjs.Shape(new createjs.Graphics().beginFill("#E0E2CC").beginStroke("#000").drawRoundRect(0, 0, 300, 237, 5));
                    var orderText = new createjs.Text("Bottom of the order!", "36px Arial Black", "#E5B83C");
                }
                orderText.x = 150;
                orderText.lineWidth = 100;
                orderText.textAlign = "center";

                currentPlayerHelmet = new createjs.Bitmap(preloader.getResult(gameState.currentPlayer));
                currentPlayerHelmet.regX = currentPlayerHelmet.getBounds().width / 2;
                currentPlayerHelmet.x = 150;
                currentPlayerHelmet.y = 170;

                switchContainer.addChild(background, orderText, currentPlayerHelmet);
                switchContainer.x = 250;
                switchContainer.y = 60;
                createjs.Tween.get(switchContainer).wait(1000).to({ scaleX: 1, scaleY: 1, alpha: 1 }, 500)
                                                   .wait(1000).call(function (event) {
                                                       if (event.target.parent != null) {
                                                           event.target.parent.removeChild(event.target)
                                                       }
                                                   });


            }
            stage.addChild(ball, startBase.runner, currentPlayer, switchContainer);
            stage.onMouseMove = null;
        }

        //Question area 
        function getDisplayQuestionArea() {

            var container = new createjs.Container();
            container.x = 0;
            container.y = 410;

            //Large Question prompt
            var promptText = new createjs.Text("", "24px Arial Black", currentPlayer.color);
            promptText.textAlign = "center";
            promptText.textBaseline = "middle";
            promptText.lineWidth = stage.canvas.width - 20;

            promptText.x = stage.canvas.width / 2;
            var curpx = 24;
            while (promptText.getMeasuredHeight() > 60) {
                promptText.font = curpx + "px Arial Black";
                curpx = curpx - 1
                if (curpx == 10) break;
            }
            container.prompt = promptText;
            var answerArea = new createjs.Container();
            answerArea.x = 20;
            answerArea.y = 53;

            container.answerArea = answerArea;

            container.addChild(promptText, answerArea);

            return container;

        }

        //NEW Game
        function startOver() {
            gameState.submitedScore = false;
            nextQuestionIndex = 0;
            stage.removeAllChildren();
            gameState = {
                twoPlayers: false,
                currentPlayer: "purplePlayer",
                outs: 0,
                runs: 0,
                cpuRuns: 0,
                teamAtBat: 1,
                numberOfInnings: 5, //5
                inning: 1,
                currentQuestion: null,
                currentQuestionIndex: 0,
                correctAnswer: ""
            }
            addTitleView();
        }

        var quit;

        if (isLmsConnected) {
            quit = function () {
                ScormHelper.cmi.score.min(0);
                ScormHelper.cmi.score.max(gameData.Questions.length);
                ScormHelper.cmi.score.raw(gameState.runs + gameState.cpuRuns);

                if (gameData.Questions.length > 0) {
                    ScormHelper.cmi.score.scaled((1.0 * (gameState.runs + gameState.cpuRuns)) / gameData.Questions.length);
                }
                ScormHelper.cmi.successStatus(ScormHelper.successStatus.passed);
                ScormHelper.cmi.exit("");
                ScormHelper.adl.nav.request("exitAll");
                ScormHelper.terminate();
            }
        }
        else {
            quit = function () {
                window.location = "http://www.wisc-online.com";
            }
        }

        function getUserControls() {

            var instructionsContainer = new createjs.Container();
            instructionsContainer.x = 0;
            instructionsContainer.y = 280;
            instructionsContainer.hitArea = new createjs.Shape(new createjs.Graphics().beginFill("#F00").drawCircle(0, 50, 50));
            instructionsContainer.cursor = 'pointer';



            var questionMark = new createjs.Bitmap(preloader.getResult("info"));
            //questionMark.regX = 25;
            //questionMark.regY = 25;

            instructionsContainer.addChild(questionMark);

            var soundContainer = new createjs.Container();
            soundContainer.x = 742;
            soundContainer.y = 280;
            soundContainer.visible = true;
            soundContainer.name = "theSoundContainer";
            soundContainer.hitArea = new createjs.Shape(new createjs.Graphics().beginFill("#F00").drawCircle(0, 50, 50));
            soundContainer.cursor = 'pointer';
            var bg = new createjs.Bitmap(preloader.getResult("instructions_background"));
            bg.rotation = 90;
            bg.x = 50;
            bg.y = 0;
            soundContainer.addChild(bg);
            var sound = new createjs.Bitmap(preloader.getResult("musicOn"));
            sound.name = "musicOnImage"
            soundContainer.addChild(sound);
            soundContainer.addEventListener("click", function (evt) {
                if (musicOn == true) {

                    musicOn = false;
                    var sound = new createjs.Bitmap(preloader.getResult("musicOff"));
                    sound.name = "musicOffImage"
                    var destroy = evt.currentTarget.getChildByName("musicOnImage");
                    evt.currentTarget.removeChild(destroy);
                    evt.currentTarget.addChild(sound);
                    createjs.Sound.setMute(true);

                } else {
                    musicOn = true;
                    var sound = new createjs.Bitmap(preloader.getResult("musicOn"));
                    sound.name = "musicOnImage"
                    var destroy = evt.currentTarget.getChildByName("musicOffImage");
                    evt.currentTarget.removeChild(destroy);
                    evt.currentTarget.addChild(sound);
                    createjs.Sound.setMute(false);

                }
            });

            instructionsContainer.addEventListener("click", function () {
                var view = createInstructionsView();
                stage.addChild(view);
            });

            stage.addChild(instructionsContainer, soundContainer);
        }
        $(window).bind('beforeunload', function () {
            var points = gameState.runs + gameState.cpuRuns;
            if (points > 0)
                submitScore(points)
        })

        function submitScore(score) {
            if (gameState.submitedScore)
                return false;
            gameState.submitedScore = true;

            var url = gameData.leaderboardUrl;

            if (url) {

                var data = {
                    gameId: gameData.id,
                    score: score
                };

                $.ajax(url, {
                    type: "POST",
                    data: data,
                    success: function (x) {

                    },
                    error: function (x, y, z) {


                    }
                });

            }
        }
    }
    return Game;
})(createjs, $);
(function () {

    var stageMouseDownHandler = createjs.Stage.prototype._handlePointerDown;
    var stageMouseUpHandler = createjs.Stage.prototype._handlePointerUp;
    var mouseInterval = {};
    var MIN_CLICK_TIME = 20;

    if (navigator.userAgent.indexOf("Android") > -1) {
        createjs.Stage.prototype._handlePointerDown = function (event) {
            var lastTime = mouseInterval.mousedown;
            var now = new Date().getTime(); // Slower than Date.now(), but compatible with IE8 and others.
            if (lastTime == null || now - lastTime > MIN_CLICK_TIME) {
                mouseInterval.mousedown = now;
                stageMouseDownHandler.call(this, event);
            }
        }
        createjs.Stage.prototype._handlePointerUp = function (event) {
            var lastTime = mouseInterval.mouseup;
            var now = new Date().getTime();
            if (lastTime == null || now - lastTime > MIN_CLICK_TIME) {
                mouseInterval.mouseup = now;
                stageMouseUpHandler.call(this, event);
            }
        }
    }

}())
