var WordscramblerFlags = {
    HINT: 1,
    SOLUTION: 2,
    COMPLETED_EASY: 4,
    COMPLETED_MEDIUM: 8,
    COMPLETED_HARD: 16,
};

function onHideTutorial(userInitiated)
{
    if(userInitiated == false)
    {
        if(puzzleTimer)
            puzzleTimer.reset();

        basePuzzle.StartPuzzle(true);
    }
}

var WordscramblerBase = WordPuzzle.extend({

    flickerInterval : null,
    flickerTimeout : null,

    Difficulties : {
        EASY : {
            Name: "EASY",
            ScorePercent : [ 0.35, 0.40, 0.45, 0.50, 0.55]
        },
        MEDIUM : {
            Name: "MEDIUM",
            ScorePercent : [ 0.45, 0.50, 0.55, 0.60, 0.65]
        },
        HARD : {
            Name: "HARD",
            ScorePercent : [ 0.55, 0.60, 0.65, 0.70, 0.75]
        },
    },

    completeWords : [],
    totalWords : [],

    inputInterval : null,
    roundIndex : -1,
    completedRounds : -1,
    currentDB : null,

    currentDifficulty : null,
    roundsToFinish : 5,

    minSubmitScoreText : "You need to find at least one word, before you can submit your score",
    isGameOver : false,

    construct: function ()
    {
        self = this;
    },

    Init : function() {

        self.currentDifficulty = self.Difficulties.MEDIUM;

        self.ClearPuzzle();

        Puzzle.defaults.userInputId = "#word-input";

        self.SetupWordInput();


        // "HINT" BUTTON CLICK
        $(Puzzle.defaults.hintButton).click(function()
        {
            TrackWord.flags |= WordscramblerFlags.HINT;
            self.ShowHint(false);
        });

        // "HINT WORD" BUTTON CLICK
        $(Puzzle.defaults.wordHintButton).click(function()
        {
            TrackWord.flags |= WordscramblerFlags.SOLUTION;
            self.ShowHint(true);
        });

        $('#show-words-btn').click(function() {

            $('#complete-words-wrapper').toggleClass('show');

        });

        $('#difficulty').click(function() {

            self.ShowDifficultyMenu(true);

        });

        self.PuzzleSpecific();

        arguments.callee.$.Init.call(this);
    },

    PuzzleSpecific: function()
    {
        // "SUBMIT SCORE" BUTTON CLICK
        $(Puzzle.defaults.submitScoreButton).click(function() {

            if(self.completedRounds < self.roundsToFinish)
            {
                //alert("You must complete all rounds before submiting your score");

                Puzzle.showMessageBox("You must complete all rounds before submiting your score", Puzzle.messageType.WARNING);
            }
            else
            {
                self.EndPuzzle();
            }
        });

        setTimeout(function() {

            if(isTutorialVisible())
            {
                return;
            }
            self.ShowDifficultyMenu();
        }, 100);
    },

    SetupWordInput: function()
    {
        //self.InsertUserInputField();

        $('.letter').click(function()
        {
            if($(this).hasClass('active'))
                return false;

            var letter = $(this).data('letter');

            var appendLetter = $(this).clone();
            $(this).addClass('active');

            var inputField = $(Puzzle.defaults.userInputId);

            var prev = inputField.val();
            inputField.val(prev + letter);

            if(!self.InputLetter(letter))
            {
                inputField.val(prev);
            }
            else
            {
                self.ClearHint();
                $("#scrambled-word").append(appendLetter);
            }

            if(isClientMobile)
            {
                //self.MoveLetterbox($("#scrambled-word"));
            }
            return false;
        });


        var androidChrome = (navigator.userAgent.toLowerCase().indexOf("android") > -1 && navigator.userAgent.toLowerCase().indexOf("chrome") > -1);

        if (androidChrome)
        {
            $(Puzzle.defaults.userInputId).keyup(function(event)
            {
                self.ValidateInput();
            });
        }
        else
        {
            $(Puzzle.defaults.userInputId).keyup(function(event)
            {
                if (PuzzleInput.isDone(event))
                {
                    self.SubmitWord();
                }
                else
                {
                    self.ValidateInput();
                }
            });
        }

        $('#word-submit').click(function()
        {
            self.SubmitWord();
            return false;
        });

        $('#word-clear').click(function()
        {
            self.ClearWord();
            return false;
        });
    },
    InsertUserInputField: function() {
        var userInput = document.createElement("input");
        userInput.id = Puzzle.defaults.userInputId.replace("#", "");
        userInput.type = "text";
        userInput.maxlength = "1";
        userInput.spellcheck = "false";
        userInput.style.top = "-10000px";
        userInput.style.width = "10px";
        userInput.style.height = "10px";
        userInput.style.fontSize = "1px";
        userInput.style.textTransform = "uppercase";
        userInput.style.position = "absolute";
        userInput.style.zIndex = "-9999";
        userInput.style.fontSize = "10px";
        document.body.innerHTML = userInput.outerHTML + document.body.innerHTML;
    },
    MoveLetterbox: function(elem) {

        $(Puzzle.defaults.userInputId).css("top", $(elem).offset().top);
        $(Puzzle.defaults.userInputId).css("left", $(elem).offset().left);

        $(Puzzle.defaults.userInputId).focus();
    },

    StartPuzzle: function(fromClear) {

        $('#difficulty').html(self.currentDifficulty.Name);

    
        if(self.inputInterval)
        {
            clearInterval(self.inputInterval);
        }

        if (isClientMobile == false)
        {
            self.inputInterval = setInterval(function()
            {
                if(UserManagement.isPending())
                {
                    //console.log("Abort due to userManagement which is pending");
                    return;
                }

                $(Puzzle.defaults.userInputId).focus();
            }, 100);
        }

        self.ClearPuzzle();

        if(puzzleTimer)
            puzzleTimer.resume();

        self.StartRound(aDB.start_index);

        if(fromClear)
        {
            self.ShowDifficultyMenu();
        }
    },

    EndPuzzle: function()
    {
        if(puzzleTimer)
            puzzleTimer.stop();

        self.isGameOver = false;

        if(self.inputInterval)
        {
            clearInterval(self.inputInterval);
        }

        TrackPuzzle.analyticsEvent("puzzle", "end", "completed");


        if (!puzzleId || puzzleId.length === 0)
        {
            alert("This feature cannot be used in preview mode");
            return;
        }
        else
        {
            Puzzle.invokeSubmitScore();
        }

        //Scroll to top
        if (isClientMobile && $(window).height() < 300) {
            $(window).scrollTop($("#puzzle-submit-score").offset().top);
        }
    },

    StartRound: function(round)
    {
        self.roundIndex = round % aDB.rounds.length;

        self.SetWordVisibility(self.roundIndex, true);
        self.currentDB = aDB.rounds[self.roundIndex];

        self.ClearWordHistory();

        self.UpdateRoundStatus(false);

        if (self.completedRounds + 1 > 1)
            self.ShowStartRoundNotifier(self.completedRounds + 1);

        if (self.completedRounds == 1)
            TrackWord.flags |= WordscramblerFlags.COMPLETED_EASY;
        else if (self.completedRounds == 2)
            TrackWord.flags |= WordscramblerFlags.COMPLETED_MEDIUM;
        else if (self.completedRounds == 3)
            TrackWord.flags |= WordscramblerFlags.COMPLETED_HARD;
    },

    ShowStartRoundNotifier: function(round)
    {
        var notifier = $('.next-round-notifier');
        var topOffset = $(window).scrollTop();
        var leftOffset = $(window).scrollLeft();
        var width = $(window).width();
        var height = $(window).height();

        notifier.css('font-size', '15px');
        notifier.css('opacity', '1');
        notifier.text(round);
        notifier.show();

        TweenLite.to(notifier, 1, {
            fontSize: (Math.min(width, height) * 0.8) + 'px',
            opacity: 0,
            onComplete: function() {
                notifier.hide();
            },
            onUpdate: function() {
                notifier.css('left', ((width - notifier.width()) / 2 + leftOffset) + 'px');
                notifier.css('top', ((height - notifier.height()) / 2 + topOffset) + 'px');
            }
        });
    },

    EndRound: function(ignoreTracking)
    {
        ++self.completedRounds;
        
        for(var i = 0; i < self.completeWords.length; ++i)
        {
            self.totalWords.push(self.completeWords[i]);
        }

        self.SetWordVisibility(self.roundIndex, false);

        if(self.completedRounds >= self.roundsToFinish)
        {
            self.EndPuzzle();
            return;
        }

        if(ignoreTracking)
        {

        }
        else
        {
            TrackWord.saveRoundCompleted(self.currentDB.letters, "round-"+self.completedRounds);
        }

        var nextRound = self.roundIndex+1;
        self.StartRound(nextRound);
    },

    UpdateRoundStatus: function(animate)
    {
        var wordCurrent = self.GetScore(false);
        var wordTotal = self.GetMaxScore();
        //var wordCurrent = self.completeWords.length;
        //var wordTotal = self.currentDB.words.length;
        var wordReq = Math.ceil(wordTotal *  self.currentDifficulty.ScorePercent[self.completedRounds]);
        
        // GS BUG# 3365
        $('#round-counter').html("Round: " + (self.completedRounds+1) + " / " + self.roundsToFinish);
        // GS BUG# 3365
        
        //$('#round-counter').html("Round: " + (self.completedRounds+1));
        
        $('#round-status-description').html("Get " + wordReq + " points to go to the next round.");
        //$('#round-status-description').html("Find " + wordReq + " words to go to the next round.");
        //$('#round-status').html(wordCurrent + " of " + wordTotal);



        var progressBar = $('#round-status');
        var bar = progressBar.find('.round-current');
        var barNumber = progressBar.find('.round-current-count');
        var limit = progressBar.find('.round-target');
        var totalNumber = progressBar.find('.round-total-count');

        //var barPercentage = (wordCurrent / wordTotal) * 100;
        var barPercentage = (wordCurrent / wordReq) * 100;

        bar.css('width', barPercentage + "%");
        //barPercentage = 100;
        //barNumber.css('left', barPercentage + "%");

        if(animate)
        {
            bar.addClass('animate');
        }
        else
        {
            bar.removeClass('animate');
        }

        var limitPercentage = (wordReq / wordTotal) * 100;
        limit.css('width', limitPercentage + "%");
        limit.hide();

        barNumber.html(wordCurrent);
        totalNumber.html(wordTotal);
        totalNumber.hide();
    },



    SetWordVisibility: function(round, visible)
    {
        var roundWords = ".round-" + round;
        
        if(visible)
        {
            $(roundWords).show();
        }
        else
        {
            $(roundWords).hide();
        }
    },

    GetRating: function()
    {
        var completeCount = self.GetScore();

        if(completeCount < self.currentDB.gd_count)
        {
            return "Ok";
        }
        if(completeCount < self.currentDB.gr_count)
        {
            return "Good";
        }
        else if(completeCount <  self.currentDB.fn_count)
        {
            return "Great";
        }
        else
        {
            return "Fantastic";
        }
    },

    InputLetter: function(letter)
    {
        var letterValidation = self.IsValidLetter(letter);
        if(letterValidation != true)
        {
            self.ErrorText(letterValidation, true);

            self.FlickerInput("red", "transparent", 150, 1000, function()
            {
                self.ErrorText("", false);
            });

            return false;
        }

        return true;
    },

    GetLengthString: function (length) {
        switch(length){
            case 2:
            return "two";
            case 3:
            return "three";
            case 4:
            return "four";
            case 5:
            return "five";
            case 6:
            return "six";
            case 7:
            return "seven";
            case 8:
            return "eight";
            case 9:
            return "nine";
            case 10:
            return "ten";
            case 11:
            return "eleven";
            case 12:
            return "twelve";

            default:
                return length;
        }
    },

    //Ensure that it's a letter on the wheel, and that it's used only once. ( Remmember that a letter can be represented more then once in the wheel ).
    IsValidLetter: function(letter)
    {
        if(self.isGameOver)
        {
            return "Game is Over";
        }

        if(!_.contains(self.currentDB.letters, letter))
        {   
            return "Only the " + self.GetLengthString(self.currentDB.letters.length) + " given letters can be used";//"Only given letters can be used";
        }

        var currentWord = $(Puzzle.defaults.userInputId).val();
        if(_.contains(currentWord, letter))
        {
            var availables = 0;
            for (var i = self.currentDB.letters.length - 1; i >= 0; i--) {

                if(self.currentDB.letters[i] == letter)
                    ++availables;
            };

            if(self.currentDB.hub_letter == letter)
                ++availables;

            var used = 0;
            for (var i = currentWord.length - 1; i >= 0; i--) {
                if(currentWord[i] == letter)
                    ++used;
            };

            if(used > availables)
            {
                return "Letters can only be used once";
            }
        }

        return true;
    },

    //Send the word off for validation and clear the textbox.
    SubmitWord: function(ignoreTracking)
    {
        var word = $(Puzzle.defaults.userInputId).val();

        if(word == "")
            return false;

        var wordValidation = self.IsValidWord(word);
        if(wordValidation != true)
        {
            self.ErrorText(wordValidation, true);

            if(ignoreTracking){} else {
                TrackWord.saveWrongWord(self.currentDB.letters, word);
            }

            self.FlickerInput("red", "transparent", 150, 1000, function()
            {
                self.ErrorText("", false);
            });

            self.ClearWord();
        }
        else
        {
            //Flash green
            self.FlickerInput("green", "transparent", 150, 500, function()
            {
            });

            self.CompleteWord(word);

            if(self.IsRoundComplete())
            {
                self.EndRound();
            }

            self.ClearWord();
        }
    },

    IsRoundComplete: function()
    {
        if(self.currentDifficulty == undefined
        || self.currentDifficulty.ScorePercent == undefined 
        || self.completedRounds >= self.currentDifficulty.ScorePercent.length)
            return false;

        var maxScore = self.GetMaxScore();
        var currScore = self.GetScore(false);

        //var currentPercent = self.completeWords.length / self.currentDB.words.length;
        var currentPercent = currScore / maxScore;
        if(currentPercent < self.currentDifficulty.ScorePercent[self.completedRounds])
        {
            return false;
        }

        return true;
    },

    GetCompletionPercentage: function()
    {
        if(self.completedRounds < self.roundsToFinish)
        {
            var roundPart = 1 / self.roundsToFinish;
            var roundAdd = self.completedRounds*roundPart;

            var maxScore = self.GetMaxScore();
            var currScore = self.GetScore(false);
            var currentPercent = currScore / maxScore;
            var wordPercentage = currentPercent / self.currentDifficulty.ScorePercent[self.completedRounds];

            //var wordPercentage = self.completeWords.length / self.currentDB.words.length;

            return (roundAdd + wordPercentage * roundPart);
        }
        else
        {
            return 1;
        }
    },

    IsValidWord: function(word)
    {
        if(self.isGameOver)
        {
            return "Game is Over";
        }

        if(word.length < 3)
        {
            return "Words must be at least three letters long";
        }
        
        if(word == self.currentDB.letters)
        {
            return "No points for the given word!";//word + " can not be submitted";
        }

        //Check if word has already been input once.
        if(_.contains(self.completeWords, word))
        {
            return "Words can only be submitted once";
        }

        //Check if the word is represented in "solution" or dictionary
        if(!self.IsDatabaseWord(word))
        {
            return word + " is not a valid word";//"No points for the given word!";
        }

        return true;
    },

    IsDatabaseWord: function(word, dictionaryOnly)
    {
        if(dictionaryOnly)
        {

        }
        else
        {
            if(_.contains(self.currentDB.words, word))
            {
                return true;
            }
        }

        if(dictionary == null)
            return false;

        if(dictionary.length <= word.length)
            return false;

        if(_.contains(dictionary[word.length], word))
        {
            return true;
        }

        return false;
    },

    CompleteWord: function(word, ignoreTracking)
    {
        $('#complete-words').prepend('<p class="capitalize">'+ word.toLowerCase() + '</pr>');
        
        if (self.downScroll) {
            self.downScroll.resize();
            //self.downScroll.scrollTop(99999999);
        }

        if(ignoreTracking)
        {

        }
        else
        {
            TrackWord.saveWordFound(self.currentDB.letters, word);
        }

        self.completeWords.push(word);

        self.UpdateScoreStatus();
        self.UpdateRoundStatus(true);
    },

    UpdateScoreStatus: function()
    {
        var newScore = self.GetScore(true);

        puzzleScore.setScore(newScore);

        return newScore;
    },

    GetScore: function(total)
    {

        var score = 0;
        for(var i = 0; i < self.completeWords.length; ++i)
        {
            score += self.completeWords[i].length;
        }

        if(total)
        {
            for(var i = 0; i < self.totalWords.length; ++i)
            {
                score += self.totalWords[i].length;
            }
        }

        return score;
    },

    GetMaxScore: function(total)
    {
        var score = 0;

        for(var i = 0; i < self.currentDB.words.length; ++i)
        {
            score += self.currentDB.words[i].length;
        }

        return score;
    },

    GetCompleteWords: function()
    {
        if(self.completeWords == null)
            return [];

        return self.completeWords;
    },

    GetTotalWords: function()
    {   
        if(self.totalWords == null)
            return [];

        return self.totalWords;
    },

    ClearPuzzle: function()
    {
        self.isGameOver = false;
        self.completedRounds = 0;

        $('.letter').hide();

        self.ClearWord();

        self.ClearWordHistory(true);

        puzzleScore.setScore(0);

    },

    ClearWord: function()
    {
        $(Puzzle.defaults.userInputId).val("");
        $('#scrambled-word').html("");

        $('.letter.active').removeClass('active');

        self.ClearHint();
    },

    ClearWordHistory: function(includeTotal)
    {
        self.completeWords = [];

        if(includeTotal)
        {
            self.totalWords = [];
        }

        $('#complete-words').html("");
    },

    ValidateInput: function()
    {
        var inputField = $(Puzzle.defaults.userInputId);
        var scrambleWord = $("#scrambled-word");
        var newString = inputField.val();

        inputField.val("");
        scrambleWord.html("");
        
        $('.letter.active').removeClass('active');

        for (var i = 0; i < newString.length; ++i)
        {
            var letter = newString[i].toUpperCase();
            var prev = inputField.val();
            inputField.val(prev + letter);

            if(!self.InputLetter(letter))
            {
                inputField.val(prev);
                break;
            }
            else
            {
                self.ActivateLetter(letter);
            }
        };

        self.ClearHint();
    },

    ActivateLetter: function(letter)
    {
        var selector = '.round-'+ self.roundIndex + '[data-letter="'+letter+'"]';
        var letter = null;

        $(selector).each(function()
        {
            if(!$(this).hasClass('active'))
            {
                letter = $(this);
            }
        });

        if(letter == null)
            return;

        var appendLetter = letter.clone();
        letter.addClass('active');
        $("#scrambled-word").append(appendLetter);
    },

    ShowHint: function(wholeWord)
    {
        self.ClearHint();

        var inputField = $(Puzzle.defaults.userInputId);
        var currentInput = inputField.val();
        var hintWord = "";
        var inputMatchHint = false;
        
        for(var i = 0; i < self.currentDB.words.length; ++i)
        {
            var word = self.currentDB.words[i];

            if(self.IsValidWord(word) == true)
            {
                hintWord = word;
                if(currentInput.length == 0)
                    break;
            }
            else
            {
                continue;
            }

            var subWord = word.substr(0,currentInput.length);
            
            if(subWord == currentInput)
            {
                inputMatchHint = true;
                break;  
            }
        }

        if(hintWord == "")
            return;

        if(!inputMatchHint)
        {
            self.ClearWord();
        }
        else
        {
            if(currentInput.length > 0)
            {
                hintWord = hintWord.substr(currentInput.length, hintWord.length - currentInput.length);
            }
        }

        if(wholeWord)
        {
            var prev = inputField.val();

            for( var i = 0; i < hintWord.length; ++i)
            {
                self.ActivateLetter(hintWord[i]);
            }

            inputField.val(prev + hintWord);
        }
        else
        {
            for( var i = 0; i < hintWord.length; ++i)
            {
                if(i == 0)
                {
                    self.ActivateLetter(hintWord[i]);
                    var prev = inputField.val();
                    inputField.val(prev + hintWord[i]);
                }
                else
                {
                    self.AddHintLetter();
                }
            }
        }

        //Penalize user for using hint button
        if(wholeWord)
        {
            if(puzzleTimer)
                puzzleTimer.addSeconds(60);
        }
        else
        {
            if(puzzleTimer)
                puzzleTimer.addSeconds(10);
        }
    },

    ClearHint: function()
    {
        $('.letter.hint').remove();
    },

    AddHintLetter: function()
    {
        var hintLetter = '<div class="letter hint">?</div>';
        $("#scrambled-word").append(hintLetter);
    },

    ShowDifficultyMenu: function()
    {

        var difficultyMenu = $("#difficulty-menu");
        if (difficultyMenu.length === 0)
        {
            difficultyMenu = $("<div id='difficulty-menu' class='puzzle-box'>\n\
                                           <span>Select Difficulty</span>\n\
                                           <div id='difficulty-menu-content'>\n\
                                           </div>\n\
                                       </div>");

            difficultyMenu.css({
                "color": "#000",
                "font-weight": "bold",
                "font-size": "18px",
                "padding": "30px",
                "top": "75px",
                "border": "2px solid #000",
                "border-radius": "10px",
            });

            var difficultyContent = difficultyMenu.find('#difficulty-menu-content');

            for (var property in self.Difficulties)
            {
                if (self.Difficulties.hasOwnProperty(property))
                {
                    diffObj = self.Difficulties[property];

                    difficultyContent.append('</br><span class="alternative" data-alternative="'+property+'">'+diffObj.Name+'</span>');
                }
            }

            difficultyContent.find('.alternative').click(function()
            {
                var difficultyProperty = $(this).data('alternative');

                self.currentDifficulty = self.Difficulties[difficultyProperty];

                difficultyMenu.fadeOut();
                $('#puzzle-dimmed-layer').fadeOut();
                
                if(puzzleTimer)
                    puzzleTimer.reset();
                self.StartPuzzle();

            });

        }


        difficultyMenu.appendTo($("div.puzzle"));
        difficultyMenu.fadeIn();
        $('#puzzle-dimmed-layer').fadeIn();

    },

    FlickerInput: function(borderColor, backgroundColor, interval, timeout, callback)
    {

        var inputField = $('#scrambled-word .letter');
        var flickerFlag = false;

        clearInterval(self.flickerInterval);
        clearInterval(self.flickerTimeout);    

        self.flickerInterval = setInterval(function() {
            flickerFlag = !flickerFlag;

            if (flickerFlag)
            {
                //inputField.css('background-color', backgroundColor);
                inputField.css('border-color', borderColor);
            }
            else
            {
                //inputField.css('background-color', 'white');
                inputField.css('border-color', 'transparent');
            }
        }, interval);

       self.flickerTimeout = setTimeout(function() {
            clearInterval(self.flickerInterval);

            flickerFlag = true;
            //inputField.css('background-color', 'white');
            inputField.css('border-color', 'black');

            callback();

        }, timeout);

    }

});


var WordscramblerDB = WordscramblerBase.extend({

    construct: function ()
    {
        self = this;
    },

    PuzzleSpecific: function() {

        // "SUBMIT SCORE" BUTTON CLICK
        $(Puzzle.defaults.submitScoreButton).click(function(){

            if(self.completeWords.length > 0)
            {
                if(confirm("Are you sure about quitting early?"))
                {
                    self.EndPuzzle();
                }
            }
            else
            {
                //alert(self.minSubmitScoreText);
                Puzzle.showMessageBox(self.minSubmitScoreText, Puzzle.messageType.WARNING);
            }
           
        });

        setTimeout(function() {
           if(isTutorialVisible())
               return;
           
           self.StartPuzzle();
        }, 100);
    },

    StartPuzzle: function(fromClear)
    {

        if(self.inputInterval)
        {
            clearInterval(self.inputInterval);
        }

        if (isClientMobile == false)
        {
            self.inputInterval = setInterval(function()
            {
                if(UserManagement.isPending())
                {
                    //console.log("Abort due to userManagement which is pending");
                    return;
                }

                $(Puzzle.defaults.userInputId).focus();
            }, 100);
        }

        self.ClearPuzzle();

        
        if(puzzleTimer && isScoreEnabled)
        {
            var prevTime = puzzleTimer.getSeconds();
            if(prevTime == 0 || fromClear)
            {
                prevTime = countdownTime;
            }

            if(countdownTime > 0)
            {
                puzzleTimer.setCountdown(prevTime, self.EndPuzzle);
            }
            else
            {
                puzzleTimer.resume();
            }
        }

        self.StartRound(aDB.start_index);
    },

    EndPuzzle: function()
    {
        if(puzzleTimer)
            puzzleTimer.stop();

        self.isGameOver = true;

        if(self.inputInterval)
        {
            clearInterval(self.inputInterval);
        }

        if(self.completeWords.length == 0)
        {
            //alert(self.minSubmitScoreText);
            Puzzle.showMessageBox(self.minSubmitScoreText, Puzzle.messageType.WARNING);
            return;
        }


        if(puzzleTimer && puzzleTimer.getSeconds() <= 0)
        {
            TrackPuzzle.analyticsEvent("puzzle", "end", "timeout");
        }
        else
        {
            TrackPuzzle.analyticsEvent("puzzle", "end", "user");
        }


        var findMoreText = " Try again and see if you can find more!";

        var wordsEnding = " words!";
        if(self.completeWords.length == 1)
        {
            var wordsEnding = " word!";
        }

        var leaderboardSuccessMess = "Congratulations you completed the game and found " + self.completeWords.length + wordsEnding + findMoreText + "<br/><br/>Your score is <strong>{2}</strong> and time is <strong>{1}</strong> which puts you in <strong>{0}</strong> place on the leaderboard.";
        var leaderboardFailureMess = "Congratulations you completed the game and found " + self.completeWords.length + wordsEnding + findMoreText +  "<br/><br/>Your score is <strong>{2}</strong> and time is <strong>{1}</strong> Unfortunately you didn’t get onto the leaderboard.";
        setLeaderboardMessage(leaderboardSuccessMess, leaderboardFailureMess, {});

        if (!puzzleId || puzzleId.length === 0)
        {
            alert("This feature cannot be used in preview mode");
            return;
        }
        else
        {
            showSubmitScoreTime();
        }
        
        //Scroll to top
        if (isClientMobile && $(window).height() < 300) {
            $(window).scrollTop($("#puzzle-submit-score").offset().top);
        }
    },

    ClearPuzzle: function()
    {
        self.isGameOver = false;

        self.completedRounds = 0;

        $('.letter').hide();

        self.ClearWord();

        self.ClearWordHistory(true);

        puzzleScore.setScore(0);
    },


    StartRound: function (round)
    {
        self.roundIndex = round % aDB.rounds.length;

        self.SetWordVisibility(self.roundIndex, true);
        self.currentDB = aDB.rounds[self.roundIndex];

        self.ClearWordHistory();
    },

    SubmitWord: function(ignoreTracking)
    {
        var word = $(Puzzle.defaults.userInputId).val();

        if(word == "")
            return false;

        var wordValidation = self.IsValidWord(word);
        if(wordValidation != true)
        {
            self.ErrorText(wordValidation, true);
            
            if(ignoreTracking){} else {
                TrackWord.saveWrongWord(self.currentDB.letters, word);
            }

            self.FlickerInput("red", "transparent", 150, 1000, function()
            {
                self.ErrorText("", false);
            });

            self.ClearWord();
        }
        else
        {
            //Flash green
            self.FlickerInput("green", "transparent", 150, 500, function()
            {
            });

            self.CompleteWord(word);
            self.ClearWord();
        }


    },

    IsValidWord: function(word)
    {
        if(self.isGameOver)
        {
            return "Game is Over";
        }

        if(word.length < 3)
        {
            return "Words must be at least three letters long";
        }
        
        if(word == self.currentDB.letters)
        {
            return "No points for the given word!";
        }

        //Check if word has already been input once.
        if(_.contains(self.completeWords, word))
        {
            return "Words can only be submitted once";
        }

        //Check if the word is represented in "solution" or dictionary
        if(!self.IsDatabaseWord(word, true))
        {
            return word + " is not a valid word";
        }

        return true;
    },

    CompleteWord: function (word, ignoreTracking)
    {
        $('#complete-words').prepend('<p class="capitalize">'+ word.toLowerCase() + '</pr>');
        
        if (self.downScroll) {
            self.downScroll.resize();
        }

        if(ignoreTracking)
        {

        }
        else
        {
            TrackWord.saveWordFound(self.currentDB.letters, word);
        }

        self.completeWords.push(word);

        self.UpdateScoreStatus();
    },


    GetCompletionPercentage: function()
    {
        var wordPercentage = self.completeWords.length / self.currentDB.words.length;
        return wordPercentage;
    },

    GetScore: function(total)
    {
        var score = 0;
        for(var i = 0; i < self.completeWords.length; ++i)
        {
            score += self.completeWords[i].length;
        }

        return score;
    }

});


