var isScoreSubmitted = false;
var leaderboardId = null;
var leaderboardOrderString = null;
var leaderboardMessage = "";
var hasExternalMessage = false;
var externalMessageBaseSucc = "";
var externalMessageBaseFail = "";
var externalMessageOptions = null;
var reverseHighscoreTimer = false;
var submitFlags = 0;
var SUBMIT_FLAG_NONE = 1;
var SUBMIT_FLAG_LEADERBOARD = 2;
var SUBMIT_FLAG_FACEBOOK = 4;
var SUBMIT_FLAG_TWITTER = 8;
var SUBMIT_FLAG_MAIL = 16;

/***
*Message where {x} is replaced with values, {0} is position, {1} is time, {2} is score.
*Modifiers can include modifications to values before format and insertion. 
***/
function setLeaderboardMessage(messageSuccess, messageFalse, modifiers)
{
    hasExternalMessage = true;
    externalMessageBaseSucc = messageSuccess;
    externalMessageBaseFail = messageFalse;
    externalMessageOptions = modifiers;
}

function getFormatedMessage()
{
    var scoreVal = puzzleScore.getScore();
    var timeVal = puzzleTimer.getSeconds();
    var positionVal = leaderboardOrderString;

    var message = externalMessageBaseSucc;
    if(leaderboardOrderString == null || leaderboardOrderString == "")
        message = externalMessageBaseFail;

    if(externalMessageOptions.score)
        scoreVal += externalMessageOptions.score;

    if(externalMessageOptions.time)
        timeVal += externalMessageOptions.time;

    timeVal = formatSecondsBetter(timeVal);

    message = message.replace('{0}', positionVal);

    message = message.replace('{1}', timeVal);    

    message = message.replace('{2}', scoreVal);

    return "<p>" + message + "</p>";
}

function formatSecondsBetter(sec)
{
    var date = new Date();
    date.setTime(Math.floor(sec) * 1000 + date.getTimezoneOffset() * 60 * 1000);

    if (sec < 3600)
        return date.toTimeString().substr(3,5);
    else
        return date.toTimeString().substr(0,8);
}

function formatSeconds(secVal)
{
    if(secVal == 0)
        return "0";

    var hours = 0, mins = 0, secs = 0;

    var hourVal = Math.floor(secVal / 3600);
    hours = hourVal;
    secVal %= 3600;

    var minVal = Math.floor(secVal / 60);
    mins = minVal;
    secVal %= 60;

    secs = secVal;

    if(hourVal < 10)
        hours = "0" + hourVal;

    if(minVal < 10)        
        mins = "0" + minVal;

    if(secVal < 10)
        secs = "0" + secVal;

    var timeStr = "" + (hourVal > 0 ? (hours + ":") : "");

    if(timeStr.length > 0)
    {
        timeStr += (minVal > 0 ? (mins + ":") : "");
    }
    else
    {
        timeStr = (minVal > 0 ? (mins + ":") : "");
    }

    if(timeStr.length == 0)
    {
        secs = secVal;
    }

    timeStr += secs;

    return timeStr;
}

function showSubmitScore()
{
    showSubmitScoreWithPopup(true);
}


function showSubmitScoreWithPopup(scorePopupsEnabled)
{
    if (!navigator.onLine) {
        alert("You have no internet connection");
        return;
    }

    if (!isScoreEnabled)
    {
        if(scorePopupsEnabled)
        {
            // GS BUG# 3365
            alert("Congratulations, you finished!");
            // GS BUG# 3365
        }
        return;
    }

    if(UserManagement.isRequired())
    {
        UserManagement.submitLeaderboard(function(didLogin) {
            if(didLogin)
            {
                showSubmitScore();
            }
        });
        return;
    }

    if (!isScoreSubmitted) {
        //Stop timer
        console.log("Time BEFORE stop"  + puzzleTimer.getSeconds());
        puzzleTimer.stop();
        pauseTimer();
        console.log("Time AFTER stop"  + puzzleTimer.getSeconds());


        submitFlags |= SUBMIT_FLAG_NONE;
        //console.log('Sending ' + submitFlags);
        TrackPuzzle.sendPuzzleStatistics();

        canRegister(puzzleTimer.getSeconds(), function(success) {
            if (success) {
                if (isClientMobile) {
                    $('#puzzle-submit-score').css("position", "absolute");
                }

                //Show form fields, hide close button
                $("#scoreForm").show();
                $('#puzzle-submit-score').find('#txtName').show();
                $('#puzzle-submit-score').find('.buttons').show();
                $("#div-social-share").hide();
                $('#puzzle-submit-score').find('.close-btn').show();

                var message = "Congratulations! You've completed the game.";
                if (leaderboardMessage.length > 0)
                {
                    message = "<p>" + leaderboardMessage + "</p>";
                }

                if(hasExternalMessage)
                {
                    message = getFormatedMessage();
                }
                
                $('#puzzle-submit-score').find('.score').html(message);
                $('#puzzle-submit-score').fadeIn();
                $('#puzzle-dimmed-layer').fadeIn();
            }
            else {
                submitScoreWithoutNotification();
            }
        });
    }
    else {
        alert("You've already submitted your score. Thank you!");
    }
}

function showSubmitScoreTime()
{
    showSubmitScoreTimeWithPopup(true);
}
function showSubmitScoreTimeWithPopup(scorePopupsEnabled)
{
    if (!navigator.onLine) {
        alert("You have no internet connection");
        return;
    }

    if (!isScoreEnabled)
    {

        if(scorePopupsEnabled)
        {
            // GS BUG# 3365
            alert("Congratulations, you finished!");
            // GS BUG# 3365
        }
        
        return;
    }

    if(UserManagement.isRequired())
    {
        UserManagement.submitLeaderboard(function(didLogin) {
            if(didLogin)
            {
                showSubmitScoreTime();
            }
        });
        return;
    }

    if (!isScoreSubmitted) {
        //Stop timer
        puzzleTimer.stop();
        pauseTimer();

        submitFlags |= SUBMIT_FLAG_NONE;
        //console.log('Sending ' + submitFlags);
        TrackPuzzle.sendPuzzleStatistics();

        var scoreValue =  puzzleScore.getScore();
        var isCountdown = puzzleTimer.isCountdown();
        if(scoreValue == undefined)
        {
            return;
        }

        if (canRegisterScore(puzzleTimer.getSeconds(), scoreValue, isCountdown))
        {
            if (isClientMobile) {
                $('#puzzle-submit-score').css("position", "absolute");
            }

            //Show form fields, hide close button
            $("#scoreForm").show();
            $('#puzzle-submit-score').find('#txtName').show();
            $('#puzzle-submit-score').find('.buttons').show();
            $("#div-social-share").hide();
            $('#puzzle-submit-score').find('.close-btn').show();

            var message = "Congratulations! You've completed the game.";
            if (leaderboardMessage.length > 0)
            {
                message = "<p>" + leaderboardMessage + "</p>";
            }

            if(hasExternalMessage)
            {
                message = getFormatedMessage();
            }
            
            $('#puzzle-submit-score').find('.score').html(message);
            $('#puzzle-submit-score').fadeIn();
            $('#puzzle-dimmed-layer').fadeIn();
        }
        else {
            submitScoreWithoutNotification();
        }
    }
    else {
        alert("You've already submitted your score. Thank you!");
    }
}

function showGameIncomplete(customMessage)
{
    if (!isScoreEnabled)
        return;

    if (!isScoreSubmitted) {
        if (isClientMobile) {
            $('#puzzle-submit-score').css("position", "absolute");
        }
            
        //Hide form fields
        $("#scoreForm").show();
        $('#puzzle-submit-score').find('#txtName').hide();
        $('#puzzle-submit-score').find('.buttons').hide();
        $('#div-social-share').hide();
        $('#puzzle-submit-score').find('.close-btn').show();

        var message = "<p>All answers must be correct in order to submit your score.</p>";
        
        if (typeof customMessage != 'undefined')
            message = customMessage;

        if ($(window).scrollTop() != 0)
            $('#puzzle-submit-score').css('top',  ($(window).scrollTop() + 0) + 'px');

        $('#puzzle-submit-score').find('.score').html(message);
        $('#puzzle-submit-score').fadeIn();
        $('#puzzle-dimmed-layer').fadeIn();
    }
    else {
        alert("You've already submitted your score. Thank you!");
    }
}

function submitScoreWithoutNotification()
{
    if (!isScoreEnabled)
        return;
    
    if (!isScoreSubmitted) {
        if (isClientMobile) {
            $('#puzzle-submit-score').css("position", "absolute");
        }

        submitScore(false, function(success) {
        
            var messageHTML;
            
            if (success) {
                messageHTML = "<p>" + leaderboardMessage + "<br/><br/>Try again to see if you can reach the top twenty and see your name on the leaderboard.</p>";
                messageHTML += "<br><span class='buttons'><input type='submit' class='btn btn-green' value='Share Your Score' onclick='showShareScore(); return false;'></span>";
            } else {
                messageHTML = "<p>Unfortunately, it seems like an error occured when loading the leaderboard. Please try again later.</p>";
            }
            
            //Hide form fields
            $("#scoreForm").show();
            $('#puzzle-submit-score').find('#txtName').hide();
            $('#puzzle-submit-score').find('.buttons').hide();
            $('#div-social-share').hide();
            $('#puzzle-submit-score').find('.close-btn').show();
            $('#puzzle-submit-score').find('.score').html(messageHTML);
            $('#puzzle-submit-score').fadeIn();
            $('#puzzle-dimmed-layer').fadeIn();
        });
    }
}

function showShareScore()
{
    var shareBlock = $("#div-social-share");

    if (shareBlock && shareBlock.length > 0) {
        $("#scoreForm").hide();
        $("#div-social-share").children("h3").first().html("Your score has been saved.");
        $("#div-social-share").show();
        $('#puzzle-submit-score').find('.close-btn').show();
    }
    else {
        hideSubmit();
        //alert("Your score has been saved.");
    }

    submitFlags |= SUBMIT_FLAG_LEADERBOARD;
}

function hideSubmit() {
    if (submitFlags > 0)
    {
       TrackPuzzle.saveStat('share', submitFlags);
       TrackPuzzle.sendPuzzleStatistics();
    }

    $('#puzzle-submit-score').fadeOut();
    $('#puzzle-submit-score-error').fadeOut();
    $('#puzzle-dimmed-layer').fadeOut();
}

function submitScore(userNotice, onDone)
{
    if (!navigator.onLine) {
        alert("You have no internet connection");
        return false;
    }

    if (!isScoreEnabled)
        return;

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

    //If the game token is missing, then return error
    if (!gameToken || gameToken.length === 0)
    {
        if (userNotice) {
            alert("We couldn't submit your score. Please try again later.");
        }
        
        return;
    }
    
    var playerName = $.trim($("#txtName").val());
    if (userNotice) {
        //Check player name
        if (!playerName || playerName.length === 0)
        {
            alert("Please enter your name.");
            $("#txtName").focus();
            return;
        }
    }

    var countdown = (typeof puzzleTimer != 'undefined' && puzzleTimer.isCountdown());

    //Get time value
    var time = puzzleTimer.getSeconds();
    //Attempt saving the score

    var ajaxData =  {
        save: true,
        player_name: playerName,
        game_token: gameToken,
        game_time: time,
        name_req: userNotice,
    };

    if (countdown)
    {
        ajaxData =  {
            save: true,
            player_name: playerName,
            game_token: gameToken,
            game_time: time,
            name_req: userNotice,
            countdown: true
        };
    }
    
    if (onDone == undefined)
    {
        onDone = function(x) { console.log("onDone:" + x); }
    }
    
    $.ajax({
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "json",
        type: "POST",
        async: true,
        url: leaderboardURL,
        data: ajaxData,
        timeout: 10000,
        success: function(response)
        {
            showShareScore();
            if (response.success === true) {
                isScoreSubmitted = true;
                leaderboardId = response.leaderboard_id;
                leaderboardOrderString = response.leaderboard_order;
                leaderboardMessage = response.msg;
                puzzleTimer.stop();
                onDone(true);
            } else {
                //GS BUG# 2603
                 if(response.is_token === false){
                    
                    var messageHTML = '';
                     messageHTML += "Something went wrong, Please try again or restart your browser.<br><br>";
                     messageHTML += "<input type='submit' class='btn-error' value='Ok' onclick='clearCookiedData(); return false;'>";
                    
                    //Hide form fields
                    $("#scoreForm").show();
                    $('#puzzle-submit-score').find('#txtName').hide();
                    $('#puzzle-submit-score').find('.buttons').hide();
                    $('#div-social-share').hide();
                    $('#puzzle-submit-score').find('.close-btn').hide();
                    $('#puzzle-submit-score').find('.score').html(messageHTML);
                    $('#puzzle-submit-score').fadeIn();
                    $('#puzzle-dimmed-layer').fadeIn();
                } else {
                    onDone(false);
                }
                //GS BUG# 2603
            }
        },
        error: function()
        { 
            onDone(false);
        },
        complete: function()
        {
        }
    });
}

function submitScoreTime(userNotice)
{
    if (!navigator.onLine) {
        alert("You have no internet connection");
        return false;
    }

    if (!isScoreEnabled)
        return;

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

    //If the game token is missing, then return error
    if (!gameToken || gameToken.length === 0)
    {
        if (userNotice) {
            alert("We couldn't submit your score. Please try again later.");
        }
        
        return;
    }
    
    var playerName = $.trim($("#txtName").val());
    if (userNotice) {
        //Check player name
        if (!playerName || playerName.length === 0)
        {
            alert("Please enter your name.");
            $("#txtName").focus();
            return;
        }
    }
    
    //Get time value
    var time = puzzleTimer.getSeconds();
    var score = puzzleScore.getScore();
    var countdown = (typeof puzzleTimer != 'undefined' && puzzleTimer.isCountdown()) ? '1' : '0';

    var dataObj = null;
        dataObj = {
            save: true,
            player_name: playerName,
            game_token: gameToken,
            game_score: score,
            game_time: time,
            name_req: userNotice
        };

    if (countdown)
    {
        dataObj = {
            save: true,
            player_name: playerName,
            game_token: gameToken,
            game_score: score,
            game_time: time,
            countdown: true,
            name_req: userNotice
        };
    }

    leaderboardMessage = "Error: Failed to load leaderboard";

    //Attempt saving the score
    $.ajax({
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "json",
        type: "POST",
        async: false,
        timeout: 10000,
        url: scoreboardURL,
        data: dataObj,
        success: function(response)
        {
            showShareScore();

            if (response.success === true) {
                isScoreSubmitted = true;
                leaderboardId = response.leaderboard_id;
                leaderboardOrderString = response.leaderboard_order;
                leaderboardMessage = response.msg;
                puzzleTimer.stop();
            } else {
                leaderboardMessage += " (2)";
            }
        },
        error: function()
        {
            leaderboardMessage += " (3)";
        },
        complete: function()
        {
        }
    });
}

function pauseTimer()
{
    $.ajax({
        type: "POST",
        url: leaderboardURL,
        async: true,
        timeout: 5000,
        data: {
            pause: true,
            game_token: gameToken
        }
    });
}

function canRegister(time, resultFn)
{
    if (!navigator.onLine)
        return false;

    var countdown = (typeof puzzleTimer != 'undefined' && puzzleTimer.isCountdown());

    var ajaxData = {
        can_reg: true,
        game_token: gameToken,
        game_time: time,
    };

    if (countdown)
    {
        ajaxData = {
            can_reg: true,
            game_token: gameToken,
            game_time: time,
            countdown: true
        };
    }

    var returnVal = false;
    $.ajax({
        dataType: "json",
        type: "POST",
        url: leaderboardURL,
        async: false,
        timeout: 5000,
        data: ajaxData,
        success: function(response) {
            returnVal = response.success;
            leaderboardOrderString = response.leaderboard_order;
            leaderboardMessage = response.msg;
        },
        complete: function() {
            resultFn(returnVal);
        }
    });
}

function canRegisterScore(time, score)
{
    if (!navigator.onLine)
        return false;

    var countdown = (typeof puzzleTimer != 'undefined' && puzzleTimer.isCountdown());

    var returnVal = false;

    var ajaxData = {
        can_reg: true,
        game_token: gameToken,
        game_score: score,
        game_time: time,
    };

    if (countdown)
    {
        ajaxData = {
            can_reg: true,
            game_token: gameToken,
            game_score: score,
            game_time: time,
            countdown: true
        };
    }

    $.ajax({
        dataType: "json",
        type: "POST",
        url: scoreboardURL,
        async: false,
        timeout: 5000,
        data: ajaxData,
        success: function(response) {
            
            if(response != null)
            {
                returnVal = response.success;
                leaderboardOrderString = response.leaderboard_order;
                leaderboardMessage = response.msg;
            }
        }
    });

    return returnVal;
}

function showToplist(puzzleId)
{
    if (!navigator.onLine) {
        alert("You have no internet connection");
        return;
    }

    if (!isScoreEnabled)
        return;
    
    var isCountdown = puzzleTimer.isCountdown() ? '&countdown=true' : '';

    $('#puzzle-toplist').css("position", "absolute");
    $('#puzzle-dimmed-layer, #puzzle-toplist').fadeIn();
    $('#puzzle-toplist #toplist-table').load(showLeaderboardURL + "?puzzle_id=" + puzzleId + isCountdown, function(responseText, textStatus, req) {
        if (textStatus === "error") {
            alert("You have no internet connection");
            return;
        }
    });
}

function showTopScorelist(puzzleId)
{
    if (!navigator.onLine) {
        alert("You have no internet connection");
        return;
    }

    if (!isScoreEnabled)
        return;
    
    $('#puzzle-toplist').css("position", "absolute");
    $('#puzzle-dimmed-layer, #puzzle-toplist').fadeIn();

    var isCountdown = puzzleTimer.isCountdown() ? '&countdown=true' : '';

    var url = showScoreboardURL + "?puzzle_id=" + puzzleId + isCountdown;
    
    $('#puzzle-toplist #toplist-table').load(url, function(responseText, textStatus, req) {
        if (textStatus === "error") {
            alert("You have no internet connection");
            return;
        }
    });
}

function showToplistWithUser(puzzleId, leaderboardId)
{
    if (!navigator.onLine) {
        return;
    }

    if (!isScoreEnabled)
        return;
    
    $('#puzzle-toplist').css("position", "absolute");
    $('#puzzle-dimmed-layer, #puzzle-toplist').fadeIn();
    $('#puzzle-toplist #toplist-table').load(showLeaderboardURL + "?puzzle_id=" + puzzleId + "&lb_id=" + leaderboardId, function(responseText, textStatus, req) {
        if (textStatus === "error") {
            alert("You have no internet connection");
            return;
        }
    });
}

function hideToplist()
{
    $('#puzzle-dimmed-layer, #puzzle-toplist').fadeOut();
}

//GS BUG# 2603
function clearCookiedData(){
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
    var backlen = history.length;
    if(backlen > 0)
        history.go(-(backlen));
    
    hideSubmit();
     
    var url = document.getElementById("iframeGame").src;
    if(url != '' && url != undefined)
        window.open(url, '_blank');
    
   
}
//GS BUG# 2603