/* Minification failed. Returning unminified contents.
(1482,21-22): run-time warning JS1195: Expected expression: >
(1482,97-98): run-time warning JS1004: Expected ';': )
(1496,10-11): run-time warning JS1195: Expected expression: )
(1500,10-11): run-time warning JS1195: Expected expression: )
(1514,21-22): run-time warning JS1195: Expected expression: >
(1514,105-106): run-time warning JS1004: Expected ';': )
(1529,10-11): run-time warning JS1195: Expected expression: )
(1534,10-11): run-time warning JS1195: Expected expression: )
 */
function saveAnswer(optionId, optionType) {

    var scId = getCurrentSCId();
    var optionValue = "";

    if ($("#liveEventRespondentIds").length) {
        $("#liveEventRespondentIds").attr("data-saving-answer", "true");

        if (respondentConnection != null && respondentConnection.state == "Connected" && $("#liveEventRespondentIds").length > 0) {

            var surveyPageId = $("#liveEventRespondentIds").attr("data-surveyPageId");
            respondentConnection.invoke("SetSavingAnswer", scId, surveyPageId);
        }
    }

    if (optionType == "textbox" || optionType == "matchingTextbox" || optionType == "fillInTheBlanks" || optionType == "fileUpload") {
        optionValue = $("#option_" + optionId).val();
    }
    else if (optionType == "radioButton" || optionType == "checkbox" || optionType == "pictureChoice") {
        optionValue = "'" + $("#option_" + optionId).prop("checked") + "'";
    }
    else if (optionType == "matching") {
        optionValue = $("#option_" + optionId + " option:selected").text();

        if (optionValue == '- Select -') {
            optionValue = "";
        }
    }
    else if (optionType == "coding") {
        var codingLanguage = $("#codingTestLanguage_" + optionId).val();
        var editor = ace.edit("option_" + optionId);

        optionValue = codingLanguage + " " + editor.getValue();
    }


    // TODO: May have to escape the optionValue
    var argData = 
        {
            scId: scId,
            optionId: optionId,
            optionValue: optionValue
        };

    var sitePath = $('head base').attr('href');

    $.ajax({
        type: "POST",
        url: sitePath + "/SC/SaveAnswer",
        data: argData,
        cache: false,
        success: function (msg) {
            if (optionType == "pictureChoice") {
                highlightSelectedPictureChoice(optionId);
            }

            setProgressPercentage(scId, null, optionId, optionValue);

            if (typeof (globalSaveAnswerCallback) != 'undefined' && globalSaveAnswerCallback != null && globalSaveAnswerCallback != "") {

                var newCallback = new Function(globalSaveAnswerCallback);
                globalSaveAnswerCallback = null;
                newCallback();
            }

            if ($("#liveEventRespondentIds").length) { $("#liveEventRespondentIds").attr("data-saving-answer", "false"); }
        },
        error: function (msg) {
            var displayMsg = "There was an issue saving your answer, please check your Internet connection and answer the question again. \n \n" + msg;
            alert(displayMsg);

            if (optionType == "matchingTextbox" || optionType == "fillInTheBlanks" || optionType == "fileUpload") {
                $("#option_" + optionId).val("");
            }
            else if (optionType == "radioButton" || optionType == "checkbox" || optionType == "pictureChoice") {
                $("#option_" + optionId).prop("checked", false);
            }
        }
    });
}

function saveCurrentRandomUserLoginDetails(sl, ha) {

    var sitePath = $('head base').attr('href');

    if ($("#dialogRegisterCurrentUsername").length == 0 || $("#dialogRegisterCurrentUsername").length == 0) {
        loginName = $("#dialogRegisterCurrentUsername3").val().trim();
        password = $("#dialogRegisterCurrentPassword3").val().trim();
    } else {
        var loginName = $("#dialogRegisterCurrentUsername").val().trim();
        var password = $("#dialogRegisterCurrentPassword").val().trim();
    }

    var marketingConsent = false;
    if ($("#dialogRegisterCurrentMarketingConsent").length) {
        marketingConsent = $("#dialogRegisterCurrentMarketingConsent").prop("checked");
    }

    $("#dialogRegisterCurrentUsernameAndPasswordWarning").hide();
    $("#dialogRegisterCurrentUsernameIsNotCorrectFormat").hide();
    $("#dialogRegisterCurrentUsernameIsUsed").hide();
    $("#dialogRegisterCurrentUsernameNotValidPassword").hide();

    if (loginName == "" || password == "") {
        $("#dialogRegisterCurrentUsernameAndPasswordWarning").show();
    }
    else {
        var isValidEmail = validateEmail(loginName);

        if (isValidEmail) {

            var argData = {
                loginName: loginName,
                password: password,
                marketingConsent: marketingConsent
            };

            $.ajax({
                type: "POST",
                url: sitePath + "/Account/SaveFastSignupLoginDetails",
                data: argData,
                success: function (result) {
                    if (result.type == "USERNAMEINUSE") {
                        $("#dialogRegisterCurrentUsernameIsUsed").show();
                    }
                    else if (result.type == "NOTVALIDPASSWORD") {
                        $("#dialogRegisterCurrentUsernameNotValidPassword").show();
                    }
                    else if (result.type = "LOGIN-AUTO") {

                        window.location.href = "/auth/loginauto?token=" + result.token +
                            "&rememberme=false" +
                            "&returnUrl=" + window.location.pathname;
                    }
                    else {

                        $("#registerCurrentRandomUserPopup").modal('hide');

                        $("#randomUserRegisterNow").hide();

                        $("#randomUserLogout").attr("onclick", "window.location='" + sitePath + "/Account/LogOff'");

                        $("#dialogRegisterCurrentDetails").html("");
                        $("#isTmpAccount").html("False");
                        window.location.reload();
                        logGAEvent('join', 'rg', '', sl, ha);
                    }
                },
                error: function (msg) {
                    alert('error: ' + msg);
                }
            });
        }
        else {
            $("#dialogRegisterCurrentUsernameIsNotCorrectFormat").show();
        }
    }
}

function saveAnswerFillInTheBlanksDisplay(optionId, fillInTheBlanksAnswerId) {

    saveAnswer(optionId, 'fillInTheBlanks');

    var newWord = $('#option_' + optionId).val();

    if ($.trim(newWord) == "") {
        newWord = "<span style='color:#dddddd;'>__</span>";
    }

    $('#' + fillInTheBlanksAnswerId).html(newWord + ' ');
    $('#option_' + optionId).hide();
    $('#' + fillInTheBlanksAnswerId).show();
}

function highlightSelectedPictureChoice(optionId) {
    var optionsName = $("#option_" + optionId + " .optionsName").html();
    $("div." + optionsName).hide();
    $("#optionOverlay_" + optionId).show();
    $("#optionPoint_" + optionId).show();
}

function mouseOverSelectedPictureChoice(optionId) {
    $("#optionMouseOverOverlay_" + optionId).show();
    $("#optionMouseOverPoint_" + optionId).show();
}

function mouseOutSelectedPictureChoice(optionId) {
    $("#optionMouseOverOverlay_" + optionId).hide();
    $("#optionMouseOverPoint_" + optionId).hide();
}

function deleteAllAnswers(questionId) {

    var scId = getCurrentSCId();

    var argData = 
        {
            scId: scId,
            questionId: questionId
        };

    var sitePath = $('head base').attr('href');

    $.ajax({
        type: "GET",
        url: sitePath + "/SC/DeleteAllAnswers",
        data: argData,
        cache: false,
        success: function(msg) {
            setProgressPercentage(scId, questionId, null, "");
        },
        error: function (msg) {
            alert('error: ' + msg);
        }
    });
}

function saveDropDownListAnswer(dropDownListId) {

    var optionId = $('#options_' + dropDownListId).val().replace("option_", "");

    if (optionId == '- Select -') {
        deleteAllAnswers(dropDownListId);
    }
    else {
        saveAnswer(optionId, "dropdownlist");
    }
}

function setPlanTypeDisplayed(plan) {

    if (plan == "PREMIUM") {
        $(".pfPremium").removeClass("pfH");
        $(".pfProfessional").addClass("pfH");
        $(".pfEnterprise").addClass("pfH");

        $("#premiumPlanSelect").addClass("active");
        $("#professionalPlanSelect").removeClass("active");
        $("#enterprisePlanSelect").removeClass("active");
    }
    else if (plan == "PROFESSIONAL") {
        $(".pfPremium").addClass("pfH");
        $(".pfProfessional").removeClass("pfH");
        $(".pfEnterprise").addClass("pfH");

        $("#premiumPlanSelect").removeClass("active");
        $("#professionalPlanSelect").addClass("active");
        $("#enterprisePlanSelect").removeClass("active");
    }
    else if (plan == "ENTERPRISE") {
        $(".pfPremium").addClass("pfH");
        $(".pfProfessional").addClass("pfH");
        $(".pfEnterprise").removeClass("pfH");

        $("#premiumPlanSelect").removeClass("active");
        $("#professionalPlanSelect").removeClass("active");
        $("#enterprisePlanSelect").addClass("active");
    }
}

function setCodingLanguage(questionId, optionId) {

    var sitePath = $('head base').attr('href');

    var codingLanguage = $("#codingTestLanguage_" + optionId).val();

    var argData = {
        questionId: questionId,
        codingLanguage: codingLanguage
    };

    $.ajax({
        type: "POST",
        url: sitePath + "/SC/GetCodingTemplate",
        data: argData,
        error: function (msg) {
            alert('error: ' + msg);
        },
        success: function (msg) {

            $("#buildOutput_" + optionId).hide();

            var editor = ace.edit("option_" + optionId);
            editor.setValue(msg, -1);

            saveAnswer(optionId, 'coding');
        }
    });

}

function runCodingTests(questionId, optionId) {

    var sitePath = $('head base').attr('href');


    $("#runCodingTests_" + optionId).text("Running ....");
    $("#runCodingTests_" + optionId).addClass("disabled");
    $("#buildOutput_" + optionId).hide();


    var scId = getCurrentSCId();
    var editor = ace.edit("option_" + optionId);
    var optionValue = editor.getValue();
    var codingLanguage = $("#codingTestLanguage_" + optionId).val();

    var argData = {
        scId: scId,
        questionId: questionId,
        optionValue: optionValue,
        codingLanguage: codingLanguage
    };


    $.ajax({
        type: "POST",
        url: sitePath + "/SC/RunCodingTests",
        data: argData,
        error: function (msg) {
            alert('error: ' + msg);

            $("#runCodingTests_" + optionId).text("Run code");
            $("#runCodingTests_" + optionId).removeClass("disabled");
        },
        success: function (msg) {
            
            var buildOutput = "<table class='codingResults'>";

            if (msg.passedTestCases > 0 || msg.failedTestCases > 0) {
                buildOutput += "<tr class='codingResultsSection'><td><strong>Test cases:</strong></td><td>Passed - " + msg.passedTestCases + ", Failed - " + msg.failedTestCases + "</td></tr>";
            }

            if (msg.buildErrors != "") {

                buildOutput += "<tr class='codingResultsSection'><td><strong>Errors:</strong></td>";
                buildOutput += "<td class='codingResultsOutput'>" + msg.buildErrors[0] + "</td></tr>";

                for (var beIndex = 1; beIndex < msg.buildErrors.length; beIndex++) {
                    buildOutput += "<tr><td></td><td class='codingResultsOutput'>" + msg.buildErrors[beIndex] + "</td></tr>";
                }

            }

            if (msg.buildWarnings != "") {

                buildOutput += "<tr class='codingResultsSection'><td><strong>Warnings:</strong></td>";
                buildOutput += "<td class='codingResultsOutput'>" + msg.buildWarnings[0] + "</td></tr>";

                for (var bwIndex = 1; bwIndex < msg.buildWarnings.length; bwIndex++) {
                    buildOutput += "<tr><td></td><td class='codingResultsOutput'>" + msg.buildWarnings[bwIndex] + "</td></tr>";
                }

            }

            buildOutput += "</table>";


            $("#buildOutput_" + optionId).html(buildOutput);


            $("#runCodingTests_" + optionId).text("Run code");
            $("#runCodingTests_" + optionId).removeClass("disabled");
            $("#buildOutput_" + optionId).show();
        }
    });
}

function getElementWithFocus() {
    globalElementWithFocus = $(document.activeElement);
}

function checkRequiredSubmitQuestionsOnPage(currentPageId, currentScId) {

    var sitePath = $('head base').attr('href');

    $('#saveAllQuestions').attr('disabled', 'disabled');

    var argData = {
        scId: currentScId,
        pageId: currentPageId
    };

    $.ajax({
        type: "POST",
        url: sitePath + "/SC/HasRequiredUnCompletedQuestions",
        data: argData,
        error: function (msg) {
            alert('error: ' + msg);
            $('#saveAllQuestions').removeAttr('disabled');
        },
        success: function (msg) {

            if (msg == "True") {
                showPreviousNextPage(currentPageId, currentScId, "CURRENT", true, true, false);
            }
            else {
                submitQuestionsOnPage(currentScId);
            }
        }
    });
}

function setSubmitQuestionOnPageStatus(scId, pageId) {

    var sitePath = $('head base').attr('href');

    var argData = { pageId: pageId };

    var callData = {
        "type": "POST",
        "url": sitePath + "/SC/SetSubmitQuestionOnPageCacheStatus/" + scId,
        "data": argData,
        "error": "setSubmitQuestionOnPageStatusError",
        "errorParam": "",
        "success": "",
        "successParam": ""
    }
    cacheCallQueue.enqueue(callData);
}

function setSubmitQuestionOnPageStatusError(msg) {
    alert('error: ' + msg);
}

function submitQuestionsOnPage(currentScId) {

    $("#saveAllQuestions").attr('disabled', 'disabled');

    var pageId = $("#currentPage>div").attr("id").replace("surveyPage_", "");
    setSubmitQuestionOnPageStatus(currentScId, pageId);

    var focusQuestionId = "";
    if (typeof (globalElementWithFocus) != 'undefined' && globalElementWithFocus != null && $(globalElementWithFocus).attr("onblur") != 'undefined') {

        var closestElementId = $(globalElementWithFocus).closest(".surveyEditorQuestion>div>div").attr("id");

        if (typeof (closestElementId) != 'undefined' && (closestElementId.indexOf("question_") > -1)) {
            focusQuestionId = closestElementId.replace('question_', '');
        }
    }

    $(".surveyEditorQuestion>div>div").each(function () {

        var currentQuestionId = $(this).attr('id').replace('question_', '');
        

        if (currentQuestionId == focusQuestionId) {
            
            var focusElementOnblur = $(globalElementWithFocus).attr("onblur");
            
            if (typeof (focusElementOnblur) != 'undefined' && (focusElementOnblur.indexOf("saveAnswer") > -1)) {

                globalSaveAnswerCallback = "submitQuestion('" + currentScId + "', '" + currentQuestionId + "');";

                var runOnblur = new Function(focusElementOnblur);
                runOnblur();

                globalElementWithFocus = null;
            }
            else {
                submitQuestion(currentScId, currentQuestionId);
            }
        }
        else {
            submitQuestion(currentScId, currentQuestionId);
        }
    });

    $("#nextPageWithMessage").hide();
    $("#submitSurveyWithMessage").hide();
    $("#nextPage").show();
    $("#submitSurvey").show();

    $("#nextPage").removeAttr('disabled');
    $("#submitSurvey").removeAttr('disabled');
}

function submitQuestion(currentScId, currentQuestionId) {

    var sitePath = $('head base').attr('href');

    var argData = {
        scId: currentScId,
        questionId: currentQuestionId
    };

    var callData = {
        "type": "POST",
        "url": sitePath + "/SC/SubmitQuestion",
        "data": argData,
        "error": "submitQuestionError",
        "errorParam": "",
        "success": "submitQuestionSuccess",
        "successParam": currentQuestionId
    }
    cacheCallQueue.enqueue(callData);
}

function submitQuestionError(msg) {
    if (msg.status != 0) {
        alert('error: (sc.sqe)' + msg);
    }
}

function submitQuestionSuccess(msg, currentQuestionId) {
    $("#question_" + currentQuestionId).parents(".surveyEditorQuestion").html(msg);
    setQuestionFormating(msg);
}

function checkRequiredQuestionsForPage(currentPageId, currentScId, pageDirection) {

    var sitePath = $('head base').attr('href');


    if (pageDirection == "NEXT") {
        $('#nextPage').attr('disabled', 'disabled');
    }
    else {
        $('#previousPage').attr('disabled', 'disabled');
    }


    var argData = {
        scId: currentScId,
        pageId: currentPageId
    };

    $.ajax({
        type: "POST",
        url: sitePath + "/SC/HasRequiredUnCompletedQuestions",
        data: argData,
        error: function (msg) {
            alert('error: ' + msg);

            if (pageDirection == "NEXT") {
                $('#nextPage').removeAttr('disabled');
            }
            else {
                $('#previousPage').removeAttr('disabled');
            }
        },
        success: function (msg) {
            
            if (msg == "True") {
                showPreviousNextPage(currentPageId, currentScId, "CURRENT", true, true, false);
            }
            else {
                showPreviousNextPage(currentPageId, currentScId, pageDirection, false, false);
            }
        }
    });
}

function showNextPage(currentPageId, currentScId, highlightRequiredQuestions) {

    $('#nextPage').attr('disabled', 'disabled');
    showPreviousNextPage(currentPageId, currentScId, "NEXT", highlightRequiredQuestions);

}

function showPreviousPage(currentPageId, currentScId, highlightRequiredQuestions) {

    $('#previousPage').attr('disabled', 'disabled');
    showPreviousNextPage(currentPageId, currentScId, "PREVIOUS", highlightRequiredQuestions);

}

function showPreviousNextPage(currentPageId, currentScId, pageDirection, highlightRequiredQuestions, showRequiredQuestionsDialog, showAllRequiredQuestions, scrollToId) {

    if (typeof highlightRequiredQuestions == 'undefined') {
        highlightRequiredQuestions = false;
    }

    if (typeof showRequiredQuestionsDialog == 'undefined') {
        showRequiredQuestionsDialog = false;
    }

    if (typeof showAllRequiredQuestions == 'undefined') {
        showAllRequiredQuestions = true;
    }

    if (typeof scrollToId == 'undefined' || scrollToId == null) {
        scrollToId = "";
    }

    var currentOnblur = $(document.activeElement).attr("onblur");
    if (currentOnblur != null) {
        var runOnblur = new Function(currentOnblur);
        runOnblur();
    }


    var sitePath = $('head base').attr('href');

    var argData = {
        currentPageId: currentPageId,
        currentScId: currentScId,
        pageDirection: pageDirection,
        highlightRequiredQuestions: highlightRequiredQuestions,
        showRequiredQuestionsDialog: showRequiredQuestionsDialog,
        showAllRequiredQuestions: showAllRequiredQuestions
    };

    if ($("#doNotUseSCPageCaching").length == 0) {

        var callData = {
            "type": "POST",
            "url": sitePath + "/SC/GetPreviousNextPageNew",
            "data": argData,
            "error": "showPreviousNextPageError",
            "errorParam": pageDirection,
            "success": "showPreviousNextPageSuccess",
            "successParam": { "showRequiredQuestionsDialog": showRequiredQuestionsDialog, "scrollToId": scrollToId }
        }
        cacheCallQueue.enqueue(callData);
    }
    else {

        $.ajax({
            type: "POST",
            url: sitePath + "/SC/GetPreviousNextPage",
            data: argData,
            error: function (msg) {
                showPreviousNextPageError(msg, pageDirection);
            },
            success: function (msg) {
                showPreviousNextPageSuccess(msg, { "showRequiredQuestionsDialog": showRequiredQuestionsDialog, "scrollToId": scrollToId });
            }
        });
    }
}

function showPreviousNextPageError(msg, pageDirection) {
    var displayMsg = "The connection to the server was lost. \n \n" + msg;
    alert(displayMsg);

    if (pageDirection == "NEXT") {
        $('#nextPage').removeAttr('disabled');
    }
    else {
        $('#previousPage').removeAttr('disabled');
    }
}

function showPreviousNextPageSuccess(msg, previousNextParams) {

    var timeLimitBarSwap = $("#timeLimitBar").html();
    $('#currentPage').replaceWith('<div id="currentPage">' + msg + '</div>');
    $("#timeLimitBar").html(timeLimitBarSwap);

    window.scroll(0, 0);
    setTextAreaAutoExpand();
    setQuestionFormating(msg);

    if (msg.indexOf("fileUploadQuestion") != -1) {
        setFileUploadQuestions();
    }

    if (msg.indexOf("textarea") != -1) {
        setFreeTextboxAutoSave();
    }

    if (msg.indexOf("applyCustomScript()") != -1) {
        applyCustomScript();
    }

    if (previousNextParams.showRequiredQuestionsDialog) {
        $("#modalRequiredQuestions").modal('show');
    }
    else {
        scChangedPage();
    }

    if (previousNextParams.scrollToId != "") {
        document.getElementById(previousNextParams.scrollToId).scrollIntoView({
            behavior: 'smooth'
        });
    }
}

function setQuestionFormating(changedHtml) {

    if (changedHtml.indexOf("math-tex") != -1) {
        addMathJax();
    }

    if (changedHtml.indexOf("<code") != -1) {
        highlightCode();
    }

    if (changedHtml.indexOf("codeEditor") != -1) {
        setCodeEditors();
    }

    if (changedHtml.indexOf("fileUploadQuestion") != -1 || changedHtml.indexOf("Uploads/Files") != -1) {

        if (!$("link[href='https://d2a1lk4nhrwv0k.cloudfront.net/content/font-awesome-4.3.0/css/font-awesome.min.css']").length) {
            $('<link href="https://d2a1lk4nhrwv0k.cloudfront.net/content/font-awesome-4.3.0/css/font-awesome.min.css" rel="stylesheet">').appendTo("head");
        }
    }
}

function scChangedPage() {

    if ('parentIFrame' in window) {
        window.parentIFrame.sendMessage('changedPage');
        window.parentIFrame.size(1);
    }
}

function addMathJax()
{
    if ($('#containsMathJax').length) {
        MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
    else {
        var mathJax = '<div id="containsMathJax" style="display:none;"></div>';
        mathJax += '<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML"></script>';

        $('body').append(mathJax);
    }
}

function confirmSubmitSurvey(currentSCId, emailResults, emailCertificate, currentPageId, emailResultsToRespondent, submitMessage, submitButtonText, cancelButtonText, submitButtonStyle, cancelButtonStyle) {

    showGenericModal(
        submitMessage,
        submitButtonText,
        cancelButtonText,
        true,
        false,
        true,
        'submitSurvey(\'' + currentSCId + '\',\'' + 
                        emailResults + '\', \'' + 
                        emailCertificate + '\', \'' + 
                        currentPageId + '\', \'' + 
                        emailResultsToRespondent + '\')',
        null,
        true,
        true,
        submitButtonStyle,
        cancelButtonStyle);
}

function submitSurvey(currentSCId, emailResults, emailCertificate, currentPageId, emailResultsToRespondent) {

    if (typeof emailResults == 'undefined') {
        emailResults = 'True';
    }

    if (typeof emailCertificate == 'undefined') {
        emailCertificate = 'False';
    }

    if (typeof currentPageId == 'undefined') {
        currentPageId = '00000000-0000-0000-0000-000000000000';
    }

    if (typeof emailResultsToRespondent == 'undefined') {
        emailResultsToRespondent = 'False';
    }

    var ajc = "";
    if (typeof (URLSearchParams) != 'undefined') {
        ajc = (new URLSearchParams(window.location.search)).get('ajc');
    }

    $("#submitSurvey").attr('disabled', 'disabled');
    $("#overlay").css("visibility", "visible");

    var argData = { currentSCId: currentSCId };

    if (ajc != null && ajc != "") {
        argData = {
            currentSCId: currentSCId,
            ajc: ajc
        };
    }

    var sitePath = $('head base').attr('href');

    var submitParam = "";
    if (self !== top) { submitParam = "?f=t" }
    
    $.ajax({
        type: "POST",
        url: sitePath + "/SC/SubmitSC" + submitParam,
        data: argData,
        error: function (msg) {
            $("#overlay").hide();
            alert('error: ' + msg);
        },
        success: function (msg) {

            if (msg == "UNCOMPLETED-QUESTIONS") {
                $("#overlay").hide();
                
                showPreviousNextPage(currentPageId, currentSCId, "CURRENT", true, true);
            }
            else if (msg != "") {

                var waitForEmails = 0;

                if (emailResults != 'False') {
                    $.ajax({
                        type: "POST",
                        url: sitePath + "/SC/EmailResults/" + currentSCId
                    });

                    waitForEmails = 200;
                }

                if (emailResultsToRespondent != 'False') {
                    $.ajax({
                        type: "POST",
                        url: sitePath + "/SC/EmailResultsToRespondent/" + currentSCId + "?sendSingleEmail=false"
                    });

                    waitForEmails = waitForEmails + 200;
                }
                else if (emailCertificate != 'False') {
                    $.ajax({
                        type: "POST",
                        url: sitePath + "/SC/EmailCertificate/" + currentSCId
                    });

                    waitForEmails = waitForEmails + 200;
                }


                // TODO: Should this close the browser tab
                if (msg == "CLOSEBROWSERWINDOW") {
                }
                else {
                    setTimeout(function () {

                        if (ajc != null && ajc != "" && ((msg.indexOf("/RT?") > -1) || (msg.indexOf("/T?") > -1)) && (!(msg.indexOf("ajc=") > -1))) {
                            msg += "&ajc=" + ajc;
                        }

                        window.onbeforeunload = null;
                        scChangedPage();
                        window.location.href = msg;
                    }, waitForEmails);
                }
            }
        }
    });
}

function submitSurveyTimeLimit(currentSCId, emailResults, emailCertificate) {

    var ajc = "";
    if (typeof (URLSearchParams) != 'undefined') {
        ajc = (new URLSearchParams(window.location.search)).get('ajc');
    }

    var argData = { currentSCId: currentSCId };

    if (ajc != null && ajc != "") {
        argData = {
            currentSCId: currentSCId,
            ajc: ajc
        };
    }


    var sitePath = $('head base').attr('href');

    var currentOnblur = $(document.activeElement).attr("onblur");
    if (currentOnblur != null)
    {
        var runOnblur = new Function(currentOnblur);
        runOnblur();
    }

    var submitParams = "?rq=false";
    if (self !== top) { submitParams += "&f=t" }

    $.ajax({
        type: "POST",
        url: sitePath + "/SC/SubmitSC" + submitParams,
        data: argData,
        error: function (msg) {
            alert('error: ' + msg);
        },
        success: function (msg) {
            $("#modelTimeLimitSubmit").modal({ backdrop: 'static', keyboard: false })
                .one('click', '#modelTimeLimitSubmitOk', function (e) {
                    if (msg != "") {
                    
                        if (emailResults != 'False') {
                            $.ajax({
                                type: "POST",
                                url: sitePath + "/SC/EmailResults/" + currentSCId
                            });
                        }

                        if (emailCertificate != 'False') {
                            $.ajax({
                                type: "POST",
                                url: sitePath + "/SC/EmailCertificate/" + currentSCId
                            });
                        }

                        // TODO: Should this close the browser tab
                        if (msg == "CLOSEBROWSERWINDOW") {
                        }
                        else {

                            if (ajc != null && ajc != "" && ((msg.indexOf("/RT?") > -1) || (msg.indexOf("/T?") > -1)) && (!(msg.indexOf("ajc=") > -1))) {
                                msg += "&ajc=" + ajc;
                            }

                            window.onbeforeunload = null;
                            scChangedPage();

                            if (msg.indexOf("w=top") > -1) {
                                window.top.location.href = msg;
                            }
                            else {
                                window.location.href = msg;
                            }
                        }
                    }
                });
        }
    });
}

function sendQuizLink(Link, userName, scId) {
    var sitePath = $('head base').attr('href');
    $("#overlay").css("visibility", "visible");
    var addressEmail = "";
    var emailAddress = "";
    $('#btnEmailAddress').prop('disabled', true);
    $('#emailAddress').prop('disabled', true);

    emailAddress = $('#emailAddress').val();
    if (emailAddress == undefined) {
        publishedSurveyLinkId = $("#saveAndContinueEmailAndPublishId").attr("data-publish-id");
    } else {
        publishedSurveyLinkId = $("#emailAddress").attr("data-publish-id");
    }

    if ($("#saveAndContinueEmailAndPublishId").attr("data-email") != undefined) {
        addressEmail = $("#saveAndContinueEmailAndPublishId").attr("data-email");
    }

    // this is to set the email address when user registers before taking the quiz
    if (emailAddress == "" || emailAddress == undefined) {
        emailAddress = addressEmail;
    }

    if (emailAddress != undefined && isValidatedEmailAddress(emailAddress) && userName == "") {

        var argData = { emailAddress: emailAddress, Link: Link, userName: userName, scId: scId, publishedSurveyLinkId: publishedSurveyLinkId };

        $.ajax({
            type: "POST",
            url: sitePath + "/SC/SendLink",
            data: argData,
            error: function (msg) {
                alert('error: ' + msg);
            },
            success: function (msg) {
                $("#overlay").css("visibility", "hidden");
                switch (msg) {
                    case "FAIL": {
                        alert("Please enter an email address");
                        break;
                    }
                    case "MaxEmails": {
                        showGenericModal(
                            'You have reached the maximum number of emails allowed to be sent',
                            '',
                            'Ok',
                            true,
                            false,
                            true,
                            '',
                            null,
                            false,
                            true, '', 'success');
                        break;
                    }
                    default: {
                        showGenericModal(
                            'Email has been sent',
                            '',
                            'Ok',
                            true,
                            false,
                            true,
                            '',
                            null,
                            false,
                            true, '', 'success');

                        break;
                    }
                }
            }
        });
    //}
    //else if (userName != "") {

    //    emailAddress = "";

    //    //var argData = {Link: Link, userName: userName, quizName: quizName };
    //    var argData = { Link: Link, userName: userName, scId: scId };

    //    $.ajax({
    //        type: "POST",
    //        url: sitePath + "/SC/SendLink",
    //        data: argData,
    //        error: function (msg) {
    //            alert('error: ' + msg);
    //        },
    //        success: function (msg) {
    //            $("#overlayEmail").css("visibility", "hidden");
    //            switch (msg) {
    //                case "FAIL": {
    //                    alert("Please enter an email address");
    //                    break;
    //                }
    //                case "MaxEmails": {
    //                    showGenericModal(
    //                        'You have reached the maximum number of emails allowed to be sent',
    //                        '',
    //                        'Ok',
    //                        true,
    //                        false,
    //                        true,
    //                        '',
    //                        null,
    //                        false,
    //                        true, '', 'success');
    //                    break;
    //                }
    //                default: {
    //                    showGenericModal(
    //                        'Email has been sent',
    //                        '',
    //                        'Ok',
    //                        true,
    //                        false,
    //                        true,
    //                        '',
    //                        null,
    //                        false,
    //                        true, '', 'success');

    //                    break;
    //                }
    //            }
    //        }
    //    });
    } else {
        $("#overlay").css("visibility", "hidden");
        $('#btnEmailAddress').prop('disabled', false);
        $('#emailAddress').prop('disabled', false);
        /*alert("Please enter a valid email address");*/
        showGenericModal(
            'Please enter a valid email address',
            '',
            'Ok',
            true,
            false,
            true,
            '',
            null,
            false,
            true, '', 'success');
    }
}

function saveAndContineLater(currentSCId) {

    var sitePath = $('head base').attr('href');

    window.onbeforeunload = null;
    scChangedPage();
    window.location.href = sitePath + "/SC/CL?scId=" + currentSCId;
}

function registerParticipant(publishedSurveyId, publishedSurveyLinkId, passbackParams) {

    var sitePath = $('head base').attr('href');

    var requiredWarningMessage = "";
    var emailWarningMessage = "";
    var warningMessage = "";

    $(".scRegistrationItemRequired").each(
        function (index, data) {
            if ($.trim($(this).val()) == "") {
                requiredWarningMessage += "<li>" + $(this).attr("data-itemName") + "</li>";
            }
    });

    $(".scRegistrationItemTypeDropdown.scRegistrationItemRequired").each(
        function (index, data) {
            if ($.trim($(this).val()) == "- Select -") {
                requiredWarningMessage += "<li>" + $(this).attr("data-itemName") + "</li>";
            }
        });

    $(".scRegistrationItemTypeCheckbox.scRegistrationItemRequired").each(
        function (index, data) {
            if (!$(this).prop("checked")) {
                requiredWarningMessage += "<li>" + $(this).attr("data-itemName") + "</li>";
            }
        });

    $(".scRegistrationItemTypeEmail").each(
        function (index, data) {
            if ($.trim($(this).val()) != "" && !isValidatedEmailAddress($(this).val())) {
                emailWarningMessage += "<li>" + $(this).val() + "</li>";
            }
        });

    if (requiredWarningMessage != "" || emailWarningMessage != "") {

        if ($.trim(requiredWarningMessage) != "")
        {
            requiredWarningMessage = "<p>The following details are required:</p><ul>" + requiredWarningMessage + "</ul><br />";
        }

        if ($.trim(emailWarningMessage) != "")
        {
            emailWarningMessage = "<p>The following is not a valid email address</p><ul>" + emailWarningMessage + "</ul>";
        }

        warningMessage = "<div class='alert alert-warning' role='alert'>" + requiredWarningMessage + emailWarningMessage + "</div>";
        $("#warningContent").html(warningMessage);
    }
    else {
        var registrationItems = "";
        $(".scRegistrationItem").each(
            function (index, data) {
                if ($(this).attr("type") == "checkbox") {

                    var checkboxValue = "";
                    if ($(this).is(':checked')) {
                        checkboxValue = "Yes";
                    }

                    registrationItems += $(this).attr("id") + "$d(|" + checkboxValue + ";[)*";
                }
                else {
                    registrationItems += $(this).attr("id") + "$d(|" + $(this).val() + ";[)*";
                }
            });

        var argData = {
            "publishedSurveyId": publishedSurveyId,
            "registrationItems": registrationItems,
            "publishedSurveyLinkId": publishedSurveyLinkId
        }


        $(".btn").prop("disabled", true);

        $.ajax({
            type: "POST",
            url: sitePath + "/SC/RegisterParticipant",
            data: argData,
            error: function (msg) {
                alert('error: ' + msg);
                $(".btn").prop("disabled", false);
            },
            success: function (msg) {
                if (msg == "MATCH") {
                    warningMessage = "<div class='alert alert-warning' role='alert'>Registration details have been previously used for this " + GetProductTypeLowerCase() + "</div>";
                    $("#warningContent").html(warningMessage);
                    $(".btn").prop("disabled", false);
                }
                else if (msg == "PASSWORD") {
                    warningMessage = "<div class='alert alert-warning' role='alert'>Incorrect password</div>";
                    $("#warningContent").html(warningMessage);
                    $(".btn").prop("disabled", false);
                }
                else {

                    var fullRegisteredPath = sitePath + "/SC/S?p=" + msg + "&rg=t";

                    if (typeof (URLSearchParams) != 'undefined') {
                        var inIFrame = (new URLSearchParams(window.location.search)).get('i');

                        if (inIFrame != null && inIFrame == "t") {
                            fullRegisteredPath += "&i=t";
                        }
                    }

                    if (passbackParams != "") {
                        fullRegisteredPath += "&" + passbackParams;
                    }

                    scChangedPage();
                    window.location.href = fullRegisteredPath;
                }
            }
        });
    }
}

function startSC(scId) {

    var sitePath = $('head base').attr('href');
    var redirectURL = sitePath + "/SC/StartSC?scId=" + scId;

    if (typeof (URLSearchParams) != 'undefined') {
        var ajc = (new URLSearchParams(window.location.search)).get('ajc');
        if (ajc != null) {
            redirectURL += "&ajc=" + ajc;
        }
    }

    window.location.href = redirectURL;
}

function getQuestionId(optionId) {

    var questionId;
    $(".surveyEditorQuestion div[id*=question_]").each(function () {

        if ($(this).find("[id*=" + optionId + "],[value*=" + optionId + "]").length != 0) {
            questionId = $(this).attr("id").replace("question_", "");
        }
    });
    
    return questionId;
}

function getSurveyPageId() {

    return $("#currentPage div[id*=surveyPage_]").attr("id").replace("surveyPage_", "");
}

function moveToQuestion(scId, pageId, highlightRequiredQuestions, showRequiredQuestionsDialog, showAllRequiredQuestions, scrollToId)
{
    showPreviousNextPage(pageId, scId, "CURRENT", highlightRequiredQuestions, showRequiredQuestionsDialog, showAllRequiredQuestions, scrollToId);

    $("#modalQuestionFlags").modal("hide");
    $("#modalRequiredQuestions").modal("hide");
    $(".modal-backdrop").remove();
    $("body").removeClass("modal-open");
}

function showQuestionFlags(scId, questionScope) {

    var sitePath = $('head base').attr('href');

    var argData = { questionScope: questionScope };

    $.ajax({
        type: "POST",
        url: sitePath + "/SC/QuestionFlags/" + scId,
        data: argData,
        error: function (msg) {
            alert('error: ' + msg);
        },
        success: function (msg) {
            $("#allQuestionFlags").html(msg);
            $("#modalQuestionFlags").modal("show");

            $("#questionFlagsModalAll").removeClass("questionsWithFlagsDialogMenuSelected");
            $("#questionFlagsModalUnanswered").removeClass("questionsWithFlagsDialogMenuSelected");
            $("#questionFlagsModalSet").removeClass("questionsWithFlagsDialogMenuSelected");

            if (questionScope == "ALL") {
                $("#questionFlagsModalAll").addClass("questionsWithFlagsDialogMenuSelected");
            }
            else if (questionScope == "UNANSWERED") {
                $("#questionFlagsModalUnanswered").addClass("questionsWithFlagsDialogMenuSelected");
            }
            else {
                $("#questionFlagsModalSet").addClass("questionsWithFlagsDialogMenuSelected");
            }
        }
    });

}

function setQuestionFlag(scId, questionId) {

    var sitePath = $('head base').attr('href');
    var flagOn = false;

    if ($("#flag_" + questionId + " .fa-bookmark").length == 0) {
        $("#flag_" + questionId + " .fa-bookmark-o").addClass("fa-bookmark").removeClass("fa-bookmark-o");
        flagOn = true;
    }
    else {
        flagOn = false;
        $("#flag_" + questionId + " .fa-bookmark").addClass("fa-bookmark-o").removeClass("fa-bookmark");
    }

    var argData =
            {
                scId: scId,
                questionId: questionId,
                flagOn: flagOn
            };

    var callData = {
        "type": "POST",
        "url": sitePath + "/SC/SetQuestionFlag",
        "data": argData,
        "error": "",
        "errorParam": "",
        "success": "",
        "successParam": ""
    }
    cacheCallQueue.enqueue(callData);
}

function setProgressPercentage(scId, questionId, optionId, optionValue) {

    if ($(".scProgressBarPercentCompleted").length != 0
        || $("#scQuestionFlagsBar").length != 0
        || $("#isLiveEvent").length != 0
        || $("#doNotUseSCPageCaching").length == 0) {

        if (questionId == null) {
            questionId = getQuestionId(optionId);
        }


        var sitePath = $('head base').attr('href');

        if (questionId == null) {
            var argData =
            {
                scId: scId,
                optionId: optionId
            };

            $.ajax({
                type: "POST",
                url: sitePath + "/SC/LogProgressBarResponsesOptionId",
                data: argData
            });
        }
        else {

            if ($("#liveEventRespondentIds").length) { $("#liveEventRespondentIds").attr("data-setting-progress-bar-responses", "true"); }

            var hasResponse = questionHasResponse(questionId);

            var argData =
                {
                    scId: scId,
                    questionId: questionId,
                    hasResponse: hasResponse,
                    optionId: optionId,
                    optionValue: optionValue
                };


            var callData = {
                "type": "POST",
                "url": sitePath + "/SC/SetProgressBarResponses",
                "data": argData,
                "error": "",
                "errorParam": "",
                "success": "setProgressPercentageSuccess",
                "successParam": ""
            }
            cacheCallQueue.enqueue(callData);
        }
    }
}

function setProgressPercentageSuccess(msg) {

    if ($("#liveEventRespondentIds").length) {

        if (respondentConnection != null && respondentConnection.state == "Connected" && $("#liveEventRespondentIds").length > 0) {

            var scId = $("#liveEventRespondentIds").attr("data-scId");
            var surveyPageId = $("#liveEventRespondentIds").attr("data-surveyPageId");
            respondentConnection.invoke("CompleteSavingAnswer", scId, surveyPageId);
        }

        $("#liveEventRespondentIds").attr("data-setting-progress-bar-responses", "false");
    }

    $(".scProgressBarQuestionsCompleted").html(msg.split(" ")[0]);
    $(".scProgressBarPercentCompleted").html(msg.split(" ")[1]);
}

function questionHasResponse(questionId) {

    var hasResponse = false;
    var currentQuestion = $("#question_" + questionId);

    if (currentQuestion.find(".matchingOptions").length > 0) {
        hasResponse = true;

        $(currentQuestion).find(".matchingOptions select").each(function () {
            if ($(this).val() == "0") {
                hasResponse = false;
            }
        });
    }
    else {

        $(currentQuestion).find("input[type=radio],input[type=checkbox]").each(function () {
            if ($(this).is(":checked")) {
                hasResponse = true;
            }
        });

        if (!hasResponse) {
            var selectOption = $(currentQuestion).find('#options_' + questionId);
            if ($(selectOption).val() != null && $(selectOption).val().replace("option_", "") != '- Select -') {
                hasResponse = true;
            }

            if (!hasResponse) {
                $(currentQuestion).find("textarea,input[type=text]").each(function () {
                    if ($.trim($(this).val()) != "") {
                        hasResponse = true;
                    }
                });

                if (!hasResponse) {
                    $(currentQuestion).find(".option-overlaySelected").each(function () {
                        if ($(this).css("display") != "none") {
                            hasResponse = true;
                        }
                    });

                    if (!hasResponse) {
                        if ($(currentQuestion).find(".fileUploadQuestionName").length != 0) {
                            hasResponse = true;
                        }
                    }
                }
            }
        }
    }

    return hasResponse;
}

function reviewAnswers(scId) {
    
    $("#reviewAnswersButton").attr('disabled', 'disabled');

    var sitePath = $('head base').attr('href');

    $.ajax({
        type: "POST",
        url: sitePath + "/SC/GetReviewAnswers/" + scId,
        error: function (msg) {
            alert('error: ' + msg);
            $("#reviewAnswersButton").removeAttr('disabled');
        },
        success: function (msg) {
            $("#reviewAnswersDialog .modal-body").html(msg);
            $('#reviewAnswersDialog').modal('show');
            setQuestionFormating(msg);

            $("#reviewAnswersButton").removeAttr('disabled');
        }
    });
}

function reviewAnswersAsPDF(scId) {
    
    $("#reviewAnswersDialog .modal-header button[onclick*=reviewAnswersAsPDF]").attr("disabled", "disabled");

    var sitePath = $('head base').attr('href');
    var url = sitePath + "/SC/GetReviewAnswersPDF/" + scId;

    //window.location = url;
    
    fetch(url)
        .then(resp => resp.status === 200 ? resp.blob() : Promise.reject('Error generating PDF'))
        .then(blob => {
            const pdfUrl = window.URL.createObjectURL(blob);

            const pdfDownload = document.createElement('a');
            pdfDownload.style.display = 'none';
            pdfDownload.href = pdfUrl;
            pdfDownload.download = 'Report - Responses.pdf';
            document.body.appendChild(pdfDownload);
            pdfDownload.click();

            window.URL.revokeObjectURL(pdfUrl);

            $("#reviewAnswersDialog .modal-header button[onclick*=reviewAnswersAsPDF]").removeAttr("disabled");
        })
        .catch(() => {
            alert('Error generating PDF, please try again');
            $("#reviewAnswersDialog .modal-header button[onclick*=reviewAnswersAsPDF]").removeAttr("disabled");
        });
}

function certificateDownload(scId) {
    
    $(".rtButtons .btn[onclick*=certificateDownload]").attr("disabled", "disabled");
    $(".respondentLiveEventBase #resultCertificate[onclick*=certificateDownload]").attr("disabled", "disabled");

    var sitePath = $('head base').attr('href');
    var url = sitePath + "/SC/CRTP/" + scId;

    //window.location = url;

    fetch(url)
        .then(resp => resp.status === 200 ? resp.blob() : Promise.reject('Error generating certificate'))
        .then(blob => {
            const pdfUrl = window.URL.createObjectURL(blob);

            const pdfDownload = document.createElement('a');
            pdfDownload.style.display = 'none';
            pdfDownload.href = pdfUrl;
            pdfDownload.download = 'certificate.pdf';
            document.body.appendChild(pdfDownload);
            pdfDownload.click();

            window.URL.revokeObjectURL(pdfUrl);

            $(".rtButtons .btn[onclick*=certificateDownload]").removeAttr("disabled");
            $(".respondentLiveEventBase #resultCertificate[onclick*=certificateDownload]").removeAttr("disabled");
        })
        .catch(() => {
            alert('Error generating certificate, please try again');
            $(".rtButtons .btn[onclick*=certificateDownload]").removeAttr("disabled");
            $(".respondentLiveEventBase #resultCertificate[onclick*=certificateDownload]").removeAttr("disabled");
        });
}

//function showRetakeSurveyPopUp(scId, retakeQuizPopupMessage) {

//    $('#retakeQuizDialog').modal('show');

//}

function retakeSurvey(scId) {


    var argData =  { scId: scId };
    var sitePath = $('head base').attr('href');

    $.ajax({
        type: "POST",
        url: sitePath + "/SC/SetRetakeSurvey",
        data: argData,
        error: function (msg) {
            alert('error: ' + msg);
        },
        success: function (msg) {
            scChangedPage();
            window.location.href = sitePath + msg;
        }
    });
}

function ie_ver() {
    var iev = 0;
    var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
    var trident = !!navigator.userAgent.match(/Trident\/7.0/);
    var rv = navigator.userAgent.indexOf("rv:11.0");

    if (ieold) iev = new Number(RegExp.$1);
    if (navigator.appVersion.indexOf("MSIE 10") != -1) iev = 10;
    if (trident && rv != -1) iev = 11;

    return iev;
}

function isValidatedEmailAddress(emailAddress) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(emailAddress);
}

function joinWithoutSignup() {

    var sitePath = $('head base').attr('href');
    var origButtonMessage = $("#bannerText a.btn-lg").html();

    $("#bannerText a.btn-lg").css("width", "209.09");
    $("#bannerText a.btn-lg").html("Starting <i class=\"fa fa-refresh fa-spin fa-3x fa-fw\" style=\"font-size:14px;\"></i>");
    $("#bannerText a.btn-lg").attr("disabled", "disabled");

    $.ajax({
        type: "POST",
        url: sitePath + "/Account/RegisterRandomUser",
        success: function (msg) {
            window.location = sitePath + "/" + msg;
        },
        error: function (msg) {
            alert('error: ' + msg);
            $("#bannerText a.btn-lg").removeAttr("disabled");
            $("#bannerText a.btn-lg").html(origButtonMessage);
        }
    });
}

function resetPassword() {
    document.querySelector("#btnResetPassword").disabled = true;

    var sitePath = $('head base').attr('href');

    var loginUserName = $("#UserName").val();

    if ($.trim(loginUserName) == "") {
        showGenericModal(
            'Please enter a valid username',
            'Ok',
            '',
            true,
            false,
            true,
            null,
            null,
            true,
            false,
            'primary',
            null,
            true,
            false);
        document.querySelector("#btnResetPassword").disabled = false;
    }
    else {

        var argData = { emailAddress: loginUserName };

        $.ajax({
            type: "POST",
            url: sitePath + "/Account/ResetPassword",
            data: argData,
            error: function (msg) {
                alert('error: ' + msg);
            },
            success: function (msg) {

                var displayMessage = "";

                if (msg == "USERISINVALID") {

                    displayMessage = 'Please enter a valid username';

                } else if (msg == "PASSWORDRESETDENIED") {

                    displayMessage = '<strong>Thank you</strong><br /><br />If there is an email linked to this username we will send an email with instructions.<br /><br />If you are still having trouble, please contact your account administrator who is usually the person who manages your quizzes.';

                } else {

                    displayMessage = '<div style=\'text-align: center; font-size: 20px; color: green;\'><i class=\"fa fa-check-circle-o\" style=\' font-size: 48px;\'></i><br />Success</div><div style=\'font-size: 16px; text-align: center;\'><br />Check your email, we have sent you an email about resetting your password.';

                }


                showGenericModal(
                    displayMessage,
                    'Ok',
                    '',
                    true,
                    false,
                    true,
                    null,
                    null,
                    true,
                    false,
                    'primary',
                    null,
                    true,
                    false);

                document.querySelector("#btnResetPassword").disabled = false;
            }
        });
    }
}

function newPassword(passwordToken) {

    var sitePath = $('head base').attr('href');

    var password = $("#Password").val();

    var argData =
        {
            passwordToken: passwordToken,
            password: password
        };

    $.ajax({
        type: "POST",
        url: sitePath + "/Account/NewPassword",
        data: argData,
        error: function (msg) {
            alert('error: ' + msg);
        },
        success: function (msg) {
            if (msg == 'ERRORRESETTINGPASSWORD') {
                alert("There was en error resetting your password");
            }
            else if (msg == 'NOTVALIDPASSWORD') {
                alert("Password must be at least 6 characters long");
            }
            else {
                alert("New password successfully set");

                if ($("#mainCompanyGroup").html() == "LMS")
                {
                    window.location = sitePath;
                }
                else
                {
                    window.location = sitePath + "/Account/Login";
                }
            }
        }
    });
}

function optOutFromAllComms(p, u, s) {

    var argData =
        {
            p: p,
            u: u,
            s: s
        }

    $.ajax({
        type: "POST",
        url: "OptOutFromAllComms",
        data: argData,
        error: function (msg) {
            alert('error: ' + msg);
        },
        success: function (msg) {
            window.location.href = "NSComplete";
        }
    });
}


function clearCurrentStart(scId) {

    var argData = {
        scId: scId
    };

    $.ajax({
        type: "POST",
        url: "/SC/CCS",
        data: argData
    });
}

function setCurrentStart(scId) {
                            
    var argData = {
        scId: scId
    };

    $.ajax({
        type: "POST",
        url: "/SC/SCS",
        data: argData
    });
}

function setHeaderForTitleAndLogo() {

    var titleAndLogoHeight = $(".surveyNameBackground").height() - 75;
    $(".scContentContainer").css("padding-top", titleAndLogoHeight + "px");
}

function selectedFileUploadQuestions(optionId) {

    var scId = getCurrentSCId();
    var fileId = "browseFiles_" + optionId;
    var formId = "selectFiles" + optionId;

    if (GetFileSize(fileId) <= 20971520) {

        document.getElementById('uploading_' + optionId).style.display = 'block';

        var filesLoaded = "selectedFilesUploaded('" + scId + "', '" + optionId + "');";
        $("#browseFilesSelected-" + optionId).attr("onload", filesLoaded);

        document.forms[formId].submit();
    }
    else {
        alert('Maximum file size is 20MB');
    }
}

function selectedFilesUploaded(scId, optionId) {

    $.ajax({
        url: '/SC/GetFileUploads?scId=' + scId + '&oid=' + optionId,
        method: 'post',
        error: function (response) {
            alert('error: ' + response);
        },
        success: function (response) {

            if (response != null) {

                $("#option_" + optionId).replaceWith(response);

                setFileUploadQuestions('option_' + optionId);
            }
        }
    });

}

function GetFileSize(fileid) {
    try {
        var fileSize = 0;
        fileSize = $("#" + fileid)[0].files[0].size; //size in kb
    }
    catch (e) {
        alert("Error is :" + e);
    }

    return fileSize;
}

function setFileUploadQuestions(uploadId) {

    $(document).ready(function () {
        
        jQuery.event.props.push('dataTransfer');

        var fileUploadQuestionSelectors = ".fileUploadQuestion";
        if (typeof uploadId != 'undefined' && uploadId != "") {
            fileUploadQuestionSelectors = "#" + uploadId + ".fileUploadQuestion";
        }

        $(fileUploadQuestionSelectors).bind('drop', function (e) {
            e.preventDefault();
            $("#" + e.currentTarget.id).css("background-color", "#f8f8f8");

            var files = e.originalEvent.dataTransfer.files;

            var totalFiles = $("#" + e.currentTarget.id + " .fileUploadQuestionName").size();
            totalFiles += files.length;

            if (totalFiles > 10) {
                alert('Maximum of 10 files can be uploaded to a question')
            }
            else {

                var hasLargeFile = false;
                for (var x = 0; x < files.length; x++) {
                    if (files[x].size > 20971520) {
                        hasLargeFile = true;
                        break;
                    }
                }
                
                if (hasLargeFile) {
                    alert('Maximum file size is 20MB');
                }
                else {
                    var scId = getCurrentSCId();
                    var optionId = e.currentTarget.id.substr(e.currentTarget.id.length - 36);

                    document.getElementById('uploading_' + optionId).style.display = 'block';

                    var formData = new FormData();
                    for (var x = 0; x < files.length; x++) {
                        formData.append("file" + x, files[x]);
                    }

                    $.ajax({
                        url: '/SC/SaveFileUploads?scId=' + scId + '&oid=' + optionId,
                        method: 'post',
                        data: formData,
                        processData: false,
                        contentType: false,
                        error: function (response) {
                            alert('error: ' + response);
                        },
                        success: function (response) {

                            if (response != null) {

                                $("#" + e.currentTarget.id).replaceWith(response);

                                setFileUploadQuestions(e.currentTarget.id);
                            }

                            setProgressPercentage(scId, null, optionId, "");
                        }
                    });
                }
            }
        });

        $(fileUploadQuestionSelectors).bind('dragover', function (e) {
            $("#" + e.currentTarget.id).css("background-color", "#f2f2f2");
        });

        $(fileUploadQuestionSelectors).bind('dragleave', function (e) {
            $("#" + e.currentTarget.id).css("background-color", "#f8f8f8");
        });
    });
}

function deleteFileUpload(displayFileId, optionId) {
    
    var fileId = $("#fileId_" + displayFileId).html();

    var argData = {
        fileId: fileId
    };

    $.ajax({
        url: '/SC/DeleteFileUpload',
        method: 'post',
        data: argData,
        error: function (msg) {
            alert('error: ' + msg);
        },
        success: function (msg) {
            $("#file_" + displayFileId).remove();

            var scId = getCurrentSCId();
            setProgressPercentage(scId, null, optionId, "");
        }
    });
}

function setFreeTextboxAutoSave() {

    if ($("#runningTextboxAutosave").length == 0) {
        var intervalSave = function () {
            if (document.activeElement && document.activeElement.tagName == "TEXTAREA") {
                var currentOnblur = $(document.activeElement).attr("onblur");
                if (currentOnblur != null) {
                    var runOnblur = new Function(currentOnblur);
                    runOnblur();
                }
            }
        }

        var currentIntervalCountDown = setInterval(intervalSave, 60000);
    }

    $("#currentSCId").after("<div id='runningTextboxAutosave' />");
}

function highlightCode() {

    if (!$("link[href='https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css']").length) {
        $('<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css" rel="stylesheet">').appendTo("head");
    }

    if (!$("script[src='https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js']").length) {

        $('<script id="highlightJS" src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>').appendTo("body");

        $.holdReady(true);
        $.getScript("https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function () {

            $('pre code').each(function (i, block) {
                hljs.highlightBlock(block);

                $('pre:has(code)').css('background', '#F0F0F0');
            });

            $.holdReady(false);
        });
    }
    else {

        $(document).ready(function () {

            $('pre code').each(function (i, block) {
                hljs.highlightBlock(block);

                $('pre:has(code)').css('background', '#F0F0F0');
            });
        });
    }
}

function setCodeEditors(isViewOnly) {
    
    if (typeof (isViewOnly) == 'undefined') {
        isViewOnly = false;
    }

    if (!$("script[src='https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/ace.js']").length) {

        $('<script id="aceEditor" src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/ace.js"></script>').appendTo("body");

        $.holdReady(true);
        $.getScript("https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/ace.js", function () {

            setCodeEditorsProperties();

            $.holdReady(false);
        });
    }
    else {
        setCodeEditorsProperties();
    }
}

function setCodeEditorsProperties(isViewOnly) {

    $(".codeEditor").each(function (index) {
        var editor = ace.edit(this);
        editor.setTheme("ace/theme/github");
        editor.getSession().setMode("ace/mode/csharp");
        editor.setShowPrintMargin(false);

        editor.setAutoScrollEditorIntoView(true);
        editor.setOption("minLines", 20);
        editor.setOption("maxLines", 1000);

        if (isViewOnly) {
            editor.setOptions({
                maxLines: Infinity
            });
        }
        else {
            editor.on('blur', function () {
                var currentOptionId = editor.container.id;
                currentOptionId = currentOptionId.replace("option_", "");
                saveAnswer(currentOptionId, 'coding');
            });

            $(".codingArea").css('height', 'auto');
        }
    })
}

function GSCS(sKey, sAccount, Id, scId, scUrl, redirectTo) {

    document.querySelector("#btnPurchase").disabled = true;
    $("#overlayGroupPurchase").css("visibility", "visible");

    var discountCode = $("#presetDiscountCode input").val();
    
    $.ajax({
        //url: '/SC/GSCS?surveyId=' + surveyId + '&scId=' + scId + '&dc=' + discountCode + '&scUrl=' + scUrl,
        url: '/SC/GSCS?Id=' + Id + '&scId=' + scId + '&dc=' + discountCode + '&scUrl=' + scUrl + '&redirectTo=' + redirectTo,
        method: 'GET',
        error: function (response) {
            alert('error: ' + response);
        },
        success: function (response) {
            if (response == "wrongDiscountCode") {
                $('#presetPurchaseButtonCenter > button')[0].disabled = false;
                if (document.getElementById("usrError") != null) {
                    document.getElementById("usrError").innerHTML = "The code is not recognized.";
                    document.getElementById("usrError").style.display = "block";
                }
            } else {

                var stripe = Stripe(sKey, {
                    stripeAccount: sAccount
                });

                stripe.redirectToCheckout({
                    sessionId: response
                }).then(function (result) {
                    // If `redirectToCheckout` fails due to a browser or network
                    // error, display the localized error message to your customer
                    // using `result.error.message`.
                    alert(result.error.message);
                });
            }
        }
    });
}

function setTextAreaAutoExpand() {

    $('textarea.autoExpand').each(function () {
        var savedValue = this.value;
        this.value = '';
        this.baseScrollHeight = this.scrollHeight;
        this.value = savedValue;

        var minRows = this.getAttribute('data-min-rows') | 0,
            rows;
        this.rows = minRows;
        rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 20);

        this.style.height = 'auto';
        this.style.height = (this.scrollHeight + 2) + "px";
        this.rows = minRows + rows;
    });

    $(document)
        .one('focus.textarea', '.autoExpand', function () {

            var savedRows = this.rows;
            var minRows = this.getAttribute('data-min-rows') | 0,
                rows;
            this.rows = minRows;

            this.baseScrollHeight = this.clientHeight;
            this.rows = savedRows;
        })
        .on('input.textarea', '.autoExpand', function () {
            var minRows = this.getAttribute('data-min-rows') | 0,
                rows;
            this.rows = minRows;
            rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 20);

            this.style.height = 'auto';
            this.style.height = (this.scrollHeight + 2) + "px";
            this.rows = minRows + rows;
        });
}

function getCurrentSCId() {
    var scId = $.trim($("#currentSCId").attr("data-scid"));

    if (scId == "" || scId.length > 36) {
        scId = $.trim($("#currentSCId").html());

        if (scId.length > 36) {
            scId = $(scId).text().replace(' ', '');
        }
    }

    return scId;
}

function GetProductTypeLowerCase() {

    return "quiz";
}

function showGenericModal(message,
                          button1Text, button2Text,
                          button1IsPrimary, button2IsPrimary,
                          showCloseButton,
                          button1Action, button2Action,
                          showButton1, showButton2,
                          button1Style, button2Style,
                          button1CloseModal, button2CloseModal,
                          displayType) {

    if (typeof button1Style == 'undefined') { button1Style = ""; }
    if (typeof button2Style == 'undefined') { button2Style = ""; }
    if (typeof button1CloseModal == 'undefined') { button1CloseModal = true; }
    if (typeof button2CloseModal == 'undefined') { button2CloseModal = true; }
    if (typeof displayType == 'undefined') { displayType = 'GENERIC'; }


    $('#modalGenericText').html(message);
    $('#modalGenericButton1').html(button1Text);
    $('#modalGenericButton2').html(button2Text);

    $('#modalGenericButton1').prop('disabled', false);
    $('#modalGenericButton2').prop('disabled', false);

    if (button1Text == "") {
        $('#modalGenericButton1').hide();
    }
    else {
        $('#modalGenericButton1').show();
    }

    if (button2Text == "") {
        $('#modalGenericButton2').hide();
    }
    else {
        $('#modalGenericButton2').show();
    }

    $('#modalGenericButton1').removeClass();
    $('#modalGenericButton1').addClass('btn');
    if (button1Style != "") {
        $('#modalGenericButton1').addClass('btn-' + button1Style);
    }
    else if (button1IsPrimary) {
        $('#modalGenericButton1').addClass('btn-primary');
    }

    $('#modalGenericButton2').removeClass();
    $('#modalGenericButton2').addClass('btn');
    if (button2Style != "") {
        $('#modalGenericButton2').addClass('btn-' + button2Style);
    }
    else if (button2IsPrimary) {
        $('#modalGenericButton2').addClass('btn-primary');
    }

    if (button1CloseModal == true) {
        $('#modalGenericButton1').attr("data-dismiss", "modal");
    }
    else {
        $('#modalGenericButton1').removeAttr("data-dismiss");
    }

    if (button2CloseModal == true) {
        $('#modalGenericButton2').attr("data-dismiss", "modal");
    }
    else {
        $('#modalGenericButton2').removeAttr("data-dismiss");
    }

    if (showCloseButton) {
        $('#modalGenericCloseButton').show();
    }
    else {
        $('#modalGenericCloseButton').hide();
    }

    if (button1Action != null) {
        $('#modalGenericButton1').attr("onclick", button1Action);
    }
    else {
        $('#modalGenericButton1').removeAttr("onclick");
    }

    if (button2Action != null) {
        $('#modalGenericButton2').attr("onclick", button2Action);
    }
    else {
        $('#modalGenericButton2').removeAttr("onclick");
    }

    if (showButton1 == true) {
        $('#modalGenericButton1').show();
    }
    else {
        $('#modalGenericButton1').hide();
    }

    if (showButton2 == true) {
        $('#modalGenericButton2').show();
    }
    else {
        $('#modalGenericButton2').hide();
    }

    $('#modalGeneric').css("z-index", "9999");
    $('#modalGeneric').modal({ backdrop: 'static', keyboard: false });
}

function startCountDown(scId, startTime, emailResults, emailCertificate) {

    var display = document.getElementById("countDown"),
        hours, mins, seconds;

    var currentTime = new Date().getTime();
    var expectedEndTime = new Date(currentTime + (startTime * 1000)).getTime();
    
    if (display != null) {

        var intervalCountDown = function () {

            display = document.getElementById("countDown");

            if (startTime <= 0) {
                display.innerHTML = "0:00:00";
                clearInterval(currentIntervalCountDown);

                submitSurveyTimeLimit(scId, emailResults, emailCertificate);
            }
            else {

                startTime--;

                var nowTime = new Date().getTime();

                if (nowTime - currentTime > 1500) {
                    expectedStartTime = Math.round((expectedEndTime - nowTime) / 1000);

                    if ((expectedStartTime + 2) < startTime) {
                        startTime = expectedStartTime;
                    }
                }

                currentTime = nowTime;

                if (startTime > 0)
                {
                    hours = parseInt(startTime / 3600);
                    mins = parseInt((startTime - (hours * 3600)) / 60);
                    seconds = startTime - ((hours * 3600) + (mins * 60));

                    if (seconds == 60) {
                        seconds = 0;
                        mins += 1;
                    }
                    if (mins == 60) {
                        mins = 0;
                        hours += 1;
                    }

                    //hours = hours < 10 ? "0" + hours : hours;
                    mins = mins < 10 ? "0" + mins : mins;
                    seconds = seconds < 10 ? "0" + seconds : seconds;

                    display.innerHTML = hours + ":" + mins + ":" + seconds;
                }
            }
        }

        var currentIntervalCountDown = setInterval(intervalCountDown, 1000);
    }
}

function showSavePriorWarning() {
    showGenericModal(
        'Please Save prior to continuing',
        'Ok',
        '',
        true,
        false,
        true,
        null,
        null,
        true,
        false,
        'primary',
        null,
        true,
        false);
}

function startPageCountDown(scId, startTime, emailResults, emailCertificate) {

    var display = document.getElementById("pageCountDown"),
        hours, mins, seconds;

    var currentTime;
    var expectedEndTime;

    if (display != null) {
        var intervalCountDown = function () {

            var display = document.getElementById("pageCountDown");

            var initalTimeRemaining = $("#initialPageTimeRemaining").val();
            var initalTimeLimit = $("#initialPageTimeLimit").val();

            if (initalTimeRemaining != '') {
                if (initalTimeRemaining >= 0) {
                    startTime = initalTimeRemaining;

                    currentTime = new Date().getTime();
                    expectedEndTime = new Date(currentTime + (startTime * 1000)).getTime();

                    $("#initialPageTimeRemaining").val('');
                }
            }


            var nowTime = new Date().getTime();

            if (nowTime - currentTime > 1500) {
                var expectedStartTime = Math.round((expectedEndTime - nowTime) / 1000);

                if ((expectedStartTime + 2) < startTime) {
                    startTime = expectedStartTime;
                }
            }

            currentTime = nowTime;


            if (initalTimeRemaining == '-1' && initalTimeLimit == "") {
                display.innerHTML = "unlimited";
            }
            else if (startTime <= 0 || (initalTimeRemaining != '' && parseInt(initalTimeRemaining) <= 0)) {
                display.innerHTML = "0:00:00";
                var pageId = $("#currentPageId").val();

                if ($("#nextPage").length) {
                    $("#modelPageTimeLimitExpired").modal("show");
                    showNextPage(pageId, scId);
                }
                else if ($("#previousPage").length) {
                    showPreviousPage(pageId, scId);
                }
                else {
                    clearInterval(currentIntervalCountDown);
                    submitSurveyTimeLimit(scId, emailResults, emailCertificate);
                }
            }
            else {
                startTime--;

                hours = parseInt(startTime / 3600);
                mins = parseInt((startTime - (hours * 3600)) / 60);
                seconds = startTime - ((hours * 3600) + (mins * 60));

                if (seconds == 60) {
                    seconds = 0;
                    mins += 1;
                }
                if (mins == 60) {
                    mins = 0;
                    hours += 1;
                }

                mins = mins < 10 ? "0" + mins : mins;
                seconds = seconds < 10 ? "0" + seconds : seconds;

                display.innerHTML = hours + ":" + mins + ":" + seconds;
            }
        }

        var currentIntervalCountDown = setInterval(intervalCountDown, 1000);
    }
}


var cacheCallQueue = new CallQueue();

function CallQueue() { this.elements = []; };
CallQueue.prototype.enqueue = function (e) { this.elements.push(e); this.run(); };
CallQueue.prototype.dequeue = function () { return this.elements.shift(); };
CallQueue.prototype.isEmpty = function () { return this.elements.length == 0; };
CallQueue.prototype.peek = function () { return !this.isEmpty() ? this.elements[0] : undefined; };
CallQueue.prototype.length = function () { return this.elements.length; };

CallQueue.prototype.isRunning = false;
CallQueue.prototype.run = function () {

    var self = this;

    if (!self.isRunning && !self.isEmpty()) {

        self.isRunning = true;

        var callData = self.dequeue();

        $.ajax({
            type: callData.type,
            url: callData.url,
            data: callData.data,
            error: function (msg) {
                if (callData.error != "" && callData.errorParam != "") {
                    window[callData.error](msg, callData.errorParam);
                }
                else if (callData.error != "") {
                    window[callData.error](msg);
                }

                self.isRunning = false;
                self.run();
            },
            success: function (msg) {
                if (callData.success != "" && callData.successParam != "") {
                    window[callData.success](msg, callData.successParam);
                }
                else if (callData.success != "") {
                    window[callData.success](msg);
                }

                self.isRunning = false;
                self.run();
            }
        });
    };
};

function setMainMenuState() {

    if ($(".navbar-collapse.in").length > 0) {
        //$(".fqo-navbar-shading-fixed").removeClass("fqo-main-menu-shading-fixed-expanded");
        $("#fqo-navbar-shading-fixed").show();
        $("#fqo-navbar-shading-absolute").hide();
    }
    else {
        //$(".fqo-navbar-shading-fixed").addClass("fqo-main-menu-shading-fixed-expanded");
        $("#fqo-navbar-shading-fixed").hide();
        $("#fqo-navbar-shading-absolute").show();
    }
}
;