//      AX-4481.2       Oct 28, 2020        arr                         Changes to an iForm can be lost with no warning message - back button

// need jquery (1.7.1+) to run current page
// need general.js to run current page

// toggle instructions based on current visiblity of content
// 1. add/remove class "active" to button
// 2. update title of button to "Show Instructions" or "Hide Instructions"
// 3. resizes content iframe height
// 4. if form ID is set (ID > 0) sets a cookie "InstructionsHidden_{formId}" for external use
function toggleInstructions(buttonId, contentId, docId, formId, userId) {
    const $contentId = $(`#${contentId}`);
    const $buttonId = $(`#${buttonId}`);
    
    if ($contentId.is(":visible")) {
        $contentId.slideUp(function () {
            $buttonId.attr("title", "Show Instructions");
            $buttonId.removeClass("active");
            resizeParentIframe(docId, window);

            if (formId != 0)
                setCookie("InstructionsHidden_" + formId + "_" + userId, "1");
        });
    } else {
        $contentId.slideDown(function () {
            $buttonId.attr("title", "Hide Instructions");
            $buttonId.addClass("active");
            resizeParentIframe(docId, window);

            if (formId != 0)
                setCookie("InstructionsHidden_" + formId + "_" + userId, "0");
        });
    }
}

// toggle page control window based on visiblity of content
// 1. disables buttons and window clicks from propagation
// 2. hide page control window OR
// 3. show page control window WITH click event listener in the page to close the popop window
function togglePageJumpWindow(buttonId, contentId, docId) {
    // prevent button click from propagation
    // body with class "jumpWindowListener" will have a event listener
    // clicking the button will prevent the event from triggering 
    $("#" + buttonId).click(function (e) {
        e.stopPropagation();
    });

    // prevent popup window content from propagation
    // body with class "jumpWindowListener" will have a event listener
    // clicking the window content will prevent the event from triggering
    
    const $contentId = $(`#${contentId}`);
    
    $contentId.click(function (e) {
        e.stopPropagation();
    });

    // If current window is visible, hide the window
    // If the window is hidden, show the window
    if ($contentId.is(":visible")) {
        hidePageJumpWindow(buttonId, contentId, docId);
    }
    else {
        if ($contentId.is(":hidden")) {
            // Get button width to offset the content
            // button width retrieved from $("#" + buttonId).width() only holds width of page text
            // Need to add +alpha to offset icon width as well
            // var p = $("#" + buttonId).offset();
            var top = 20; // 51750183 - update the position of the popup's initial position. Original: (p.top - 5);
            var left = 0; // 51750183 - update the position of the popup's initial position. Original: (p.left + $("#" + buttonId).width() + 25);
            $contentId.css({ top: top, left: left, position: 'absolute' });

            // Trigger fade in
            $contentId.fadeIn(function () {
                $("#" + buttonId).addClass("active");
                resizeParentIframe(docId, window);

                // Add a class "jumpWindowListener" to current body
                // If the class name is being added (for the first time), add event listener to close the window
                if (!$("body").hasClass("jumpWindowListener")) {
                    // temporary variable to store current window
                    var currentWindow = window;
                    var counter = 0; // fail-safe counter for while loop

                    while (currentWindow && currentWindow !== currentWindow.parent && counter <= 10) { // add failsafe counter
                        $("body", currentWindow.document).addClass("jumpWindowListener");
                        $(".jumpWindowListener", currentWindow.document).click(function () {
                            hidePageJumpWindow(buttonId, contentId, docId);
                        });
                        currentWindow = window.parent;
                        counter++;

                        // Catch possible cross domain access to window.parent if
                        // parent is kiosk iframe
                        //---------------------------------------------------------------------
                        try {
                            var test = currentWindow.parent.document;
                            var a = document.createElement('a');
                            a.href = currentWindow.parent.window.location;
                            if (window.location.host !== a.host) {
                                // Cross domain caught: Internet Explorer
                                break;
                            }
                        } catch (e) {
                            // Cross domain caught: Chrome/Firefox/Safari
                            break;
                        }
                        //---------------------------------------------------------------------

                    }

                    // as final step, add event listener to current iframe
                    $("body", currentWindow.document).addClass("jumpWindowListener");
                    $(".jumpWindowListener", currentWindow.document).click(function () {
                        hidePageJumpWindow(buttonId, contentId, docId);
                    });
                }
            });
        }
    }
}

// Toogle control panel containing child question of a given id
// 1. Resizes iframe after showing/hiding event
// 2. If is a "hide", clears all sub questions belonging to the container to blank value
// 3. If is a "hide", removes all error icon currently being displayed
function toggleChildQuestions(input, trigger, id) {
    var containerId = "Child_" + id;
    if ($(input).val() == trigger) {
        $("#" + containerId).slideDown(function () {
            resizeParentIframe('', window);
        });
        $("#limitLabel_" + id).show();
    } else {
        $("#" + containerId).slideUp(function () {
            resizeParentIframe('', window);

            //bank all date controls
            $("#childItems_" + id).find(".dateControl").each(function () {
                $(this).find(".monthControl").val("0");
                $(this).find(".dayControl").val("0");
                $(this).find(".yearControl").val("");
                $(this).find("input:hidden").val("");
            });

            //blank all input controls
            $("#childItems_" + id).find(".yesNoControl").val("-1");
            $("#childItems_" + id).find(".shortTextControl").val("");
            $("#childItems_" + id).find(".numberControl").val("");
            $("#childItems_" + id).find(".listControl").val("");
            $("#childItems_" + id).find(".longTextControl").val("");
        });
        //$("#limitLabel_" + id).hide();
        //$("#limitLabel_" + id).removeClass("checkListError");

        $("#" + containerId).find("input:checkbox").each(function () {
            if (this.checked && !this.disabled) {
                this.checked = false;

                // if the checkbox is being unchecked
                // any child items should be hidden (checklist items and additional information belonging to them)
                // Get ID of currently being unchecked FITEM ID and hide all sub-questions belonging to that item
                var str = $(this).parent().find("input[id$='_original']").first().attr("id");
                var arr = str.split("_"); // id format is ctl13_ctl11_FormItem_39764_original
                var childId = arr[arr.length - 2]; // getting the "39764" from the id string

                if (childId != "")
                    $("#childItems_" + childId).hide();
            }
        });

        $("#" + containerId).find(".limitLabel").each(function () {
            $(this).hide();
            $(this).removeClass("checkListError");
        });

        $("#" + containerId + " label").each(function () {
            $(this).removeClass("checkListError");
        });
    }
}

// Toggle container panel containing sub questions of a header type item
// 1. Resizes iframe after showing/hiding event
// 2. only show/hide the panel (does not clear elements)
function toggleHeaderChildQuestions(elmt, buttonId, containerId, userId) {
    if ($("#" + containerId).is(":visible")) {
        setCookie("HeaderHidden_" + containerId + "_" + userId, "1");
        $("#" + containerId).slideUp(function () {
            $(elmt).attr("title", "Show Sub-Questions");
            $("#" + buttonId).removeClass("active");
            resizeParentIframe('', window);
        });
    } else {
        setCookie("HeaderHidden_" + containerId + "_" + userId, "0");
        $("#" + containerId).slideDown(function () {
            $(elmt).attr("title", "Hide Sub-Questions");
            $("#" + buttonId).addClass("active");
            resizeParentIframe('', window);
        });
    }
}

// Toggle checklist item
// 1. Resizes iframe after showing/hiding event
// 2. If is a "hide", clears all sub questions belonging to the container to blank value
// 3. If is a "hide", removes all error icon currently being displayed
function toggleCheckList(checkbox, id) {

    if (checkbox.checked) {
        $("#childItems_" + id).slideDown(function () {
            resizeParentIframe('', window);
        });
        $("#limitLabel_" + id).show();

    } else {
        $("#childItems_" + id).slideUp(function () {
            resizeParentIframe('', window);

            //bank all date controls
            $("#childItems_" + id).find(".dateControl").each(function () {
                $(this).find(".monthControl").val("0");
                $(this).find(".dayControl").val("0");
                $(this).find(".yearControl").val("");
                $(this).find("input:hidden").val("");
            });

            //blank all input controls
            $("#childItems_" + id).find(".yesNoControl").val("-1");
            $("#childItems_" + id).find(".shortTextControl").val("");
            $("#childItems_" + id).find(".numberControl").val("");
            $("#childItems_" + id).find(".listControl").val("");
            $("#childItems_" + id).find(".longTextControl").val("");
        });
        $("#limitLabel_" + id).hide();
        $("#limitLabel_" + id).removeClass("checkListError");

        //Uncheck all child checkboxes if it is not disabled
        $("#childItems_" + id).find("input:checkbox").each(function () {
            if (this.checked && !this.disabled) {
                this.checked = false;

                // if the checkbox is being unchecked
                // any child items should be hidden (checklist items and additional information belonging to them)
                // Get ID of currently being unchecked FITEM ID and hide all sub-questions belonging to that item
                var str = $(this).parent().find("input[id$='_original']").first().attr("id");
                var arr = str.split("_"); // id format is ctl13_ctl11_FormItem_39764_original
                var childId = arr[arr.length - 2]; // getting the "39764" from the id string

                if (childId != "") {
                    $(this).parent().find("input[id$='_FormItem_" + childId + "'").val("0");
                    $("#childItems_" + childId).hide();
                }
            }
        });

        $("#childItems_" + id).find(".limitLabel").each(function () {
            $(this).hide();
            $(this).removeClass("checkListError");
        });

        $("#childItems_" + id + " label").each(function () {
            $(this).removeClass("checkListError");
        });
    }
}

function toggleReadOnlyText(element, resizeIframe = true) {
    //find sibling labels for secondLabel, and concatLabel
    const firstLabel = $(element).parent().find(".firstLabel");
    const secondLabel = $(element).parent().find(".secondLabel");

    if ($(secondLabel).is(":visible")) {
        $(element).text("Read more");
        $(element).removeClass("active");
        $(firstLabel).show();
        $(secondLabel).hide();
    } else {
        $(element).text("Hide");
        $(element).addClass("active");
        $(firstLabel).hide();
        $(secondLabel).show();
    }

    if (resizeIframe) resizeParentIframe("", window);
}

function showSubmitMessage(message) {
    $(".urgentMessage").hide();
    $(".successMessage").html(message);
    $(".successMessage").show();
    setTimeout(function () {
        resizeParentIframe('formDetailPage', window);
    }, 1000);
}

function initSpreadsheetCell() {
    $("tr[id^=mainRow_]").each(function () {
        var rowId = $(this).attr("id").split("_")[1];
        resizeSpreadsheetCell(rowId);
    });
}

function disableSpreadsheetButtons() {
    $("input[type=submit]").addClass("loading");
    $("input[type=submit]").attr("disabled", "disabled");
}

function resizeSpreadsheetCell(id) {
    //Find sibling button control heights
    var height = 0;
    var mainRowId = "mainRow_" + id;
    $("#" + mainRowId).find(".buttonControl").css("height", "auto");
    $("#" + mainRowId).find(".buttonControl").each(function () {
        var h = $(this).height();
        if (height < h)
            height = h;

    });
    $("#" + mainRowId).find(".buttonControl").each(function () {
        var h = $(this).height();
        if (h < height)
            $(this).height(height);
    });
}

function toggleSpreadsheetQuestion(elmt, rowId, fColumnId, pColumnId) {
    var inputContentId = "inputContent_" + rowId;

    if ($(".buttonControl.active").length == 0) {
        openSpreadsheetQuestion(rowId, fColumnId, pColumnId);
    } else {
        if (validateActiveSpreadsheet()) {
            if ($(elmt).is(".active")) {

                // Same cell has been clicked:
                closeSpreadsheetQuestion(rowId, fColumnId, pColumnId);

            } else if ($("#" + inputContentId).is(":visible")) {

                // Same row but different column in same row is clicked:
                openSpreadsheetQuestion(rowId, fColumnId, pColumnId);

            } else {

                // Differnt row and different column is clicked
                closeAllSpreadsheetQuestions();
                openSpreadsheetQuestion(rowId, fColumnId, pColumnId);
            }
        }
    }
}

function showSpreadsheetColumnMessage(msg) {
    $(".errorMessage").html(msg);
    $(".errorMessage").show();
}

function hideSpreadsheetColumnMessage() {
    $(".errorMessage").hide();
}

function showSpreadsheetMessage(msg, level) {
    $(".buttonControl.active").each(function () {
        var itemId = $(this).parent().find("input[id^=SpreadsheetItem_]").attr("id");
        var rowId = itemId.split("_")[1];

        var inputContentId = "inputContent_" + rowId;
        $("#" + inputContentId).find(".spreadsheetMessage").html(msg);
        $("#" + inputContentId).find(".spreadsheetMessage").show();

        $("#" + inputContentId).find(".spreadsheetMessage").removeClass("level1");
        $("#" + inputContentId).find(".spreadsheetMessage").removeClass("level2");
        $("#" + inputContentId).find(".spreadsheetMessage").addClass("level" + level);

        var height = $("#" + inputContentId).find(".spreadsheetMessage").height();
        if (height < 20) //single line
        {
            $("#" + inputContentId).find(".spreadsheetMessage").removeClass("doubleLine");
            $("#" + inputContentId).find(".spreadsheetMessage").addClass("singleLine");
        } else {
            $("#" + inputContentId).find(".spreadsheetMessage").removeClass("singleLine");
            $("#" + inputContentId).find(".spreadsheetMessage").addClass("doubleLine");
        }
    });
}

function hideSpreadsheetMessage(level) {

    $(".buttonControl.active").each(function () {
        var itemId = $(this).parent().find("input[id^=SpreadsheetItem_]").attr("id");
        var rowId = itemId.split("_")[1];

        var inputContentId = "inputContent_" + rowId;

        if (level >= 1) {
            for (var i = 1; i <= level; i++) {
                $("#" + inputContentId).find(".spreadsheetMessage.level" + i).hide();
                $("#" + inputContentId).find(".spreadsheetMessage").removeClass("level" + i);
            }
        }
    });
}

function validateActiveSpreadsheet() {
    var error = 0;

    $(".buttonControl.active").each(function () {
        var itemId = $(this).parent().find("input[id^=SpreadsheetItem_]").attr("id");
        var rowId = itemId.split("_")[1];
        var fColId = itemId.split("_")[2];
        var pColId = itemId.split("_")[3];

        var controlId = "FormItem_" + rowId;
        var hiddenFieldId = "SpreadsheetItem_" + rowId + "_" + fColId + "_" + pColId;

        //Update cell display value and hidden field value from input control
        var input = $("#" + controlId).val();
        var original = $("#" + hiddenFieldId).val();
        var isHeader = $(this).parent().is(".headerRow");

        if (isHeader && input == "") {
            var msg1 = $('input[id$="SettingInputRequiredMessage"]').val();
            if (msg1 == "")
                msg1 = "Please enter a value.";

            showSpreadsheetMessage(msg1, 1);
            error += 1;
            return;
        }

        if (input != original) {
            var msg2 = $('input[id$="SettingConfirmationRequiredMessage"]').val();
            if (msg2 == "")
                msg2 = "Please click OK to confirm your changes.";

            showSpreadsheetMessage(msg2, 2);
            error += 1;
            return;
        }

        var result;
        var currentItem = $("#" + controlId);
        if ($(currentItem).is(".yesNoControl")) {
            validateShortText(currentItem);
        }
        else if ($(currentItem).is(".shortTextControl")) {
            validateShortText(currentItem);
        }
        else if ($(currentItem).is(".numberControl")) {
            result = validateNumber(currentItem);
            if (result.invalidNumber > 0) {
                var msg3 = $('input[id$="SettingInvalidNumberMessage"]').val();
                if (msg3 == "")
                    msg3 = "Please enter a valid number.";

                showSpreadsheetMessage(msg3, 1);
                error += 1;
                return;
            } else if (result.invalidRange) {
                var msg4 = $('input[id$="SettingInvalidNumberRangeMessage"]').val();
                if (msg4 == "")
                    msg4 = "Please enter a number in the specified range.";

                showSpreadsheetMessage(msg4, 1);
                error += 1;
                return;
            }
        }
        else if ($(currentItem).is(".listControl")) {
            validateList(currentItem);
        }
        else if ($(currentItem).parent().is(".dateControl")) {
            result = validateDate($(currentItem).parent(), false);
            if (result.invalidYear > 0) {
                var msg5 = $('input[id$="SettingInvalidYearRangeMessage"]').val();
                if (msg5 == "")
                    msg5 = "The year is out of range (1900 - 2100).";

                showSpreadsheetMessage(msg5, 1);
                error += 1;
                return;
            } else if (result.invalidDate > 0) {
                var msg6 = $('input[id$="SettingInvalidDateMessage"]').val();
                if (msg6 == "")
                    msg6 = "Please enter a valid date.";

                showSpreadsheetMessage(msg6, 1);
                error += 1;
                return;
            }
        }
    });

    return error == 0;
}

function openSpreadsheetQuestion(rowId, fColumnId, pColumnId) {
    var mainRowId = "mainRow_" + rowId;
    var additionalRowId = "additionalRow_" + rowId;
    var inputContentId = "inputContent_" + rowId;
    var spreadsheetItemId = "SpreadsheetItem_" + rowId + "_" + fColumnId + "_" + pColumnId;

    clearSpreadsheetTemplateControl(rowId);

    $("#" + mainRowId).find(".buttonControl").removeClass("active");
    $("#" + spreadsheetItemId).parent().children(".buttonControl").addClass("active");

    if ($("#" + inputContentId).is(":hidden")) {
        $("#" + mainRowId + " .headerColumn").attr("rowspan", 2);
        $("#" + additionalRowId).show();
        $("#" + inputContentId).slideDown(function () {
            focusSpreadsheetTemplateControl(rowId);
            updateSpreadsheetTemplateControl(rowId, fColumnId, pColumnId);
            resizeParentIframe('', window);
        });
    } else {
        focusSpreadsheetTemplateControl(rowId);
        updateSpreadsheetTemplateControl(rowId, fColumnId, pColumnId);
    }

    //Disable column delete buttons
    $("#DeleteColButton1").attr("disabled", "disabled");
    $("#DeleteColButton2").attr("disabled", "disabled");
    $("#DeleteColButton3").attr("disabled", "disabled");
    $("#DeleteColButton4").attr("disabled", "disabled");
}

function focusSpreadsheetTemplateControl(rowId) {
    var formItemId = "FormItem_" + rowId;
    if ($("#" + formItemId).is(".shortTextControl") ||
    $("#" + formItemId).is(".numberControl")) {
        $("#" + formItemId).trigger('focus');        // AX-24898.24919.2 .focus();
    }
}

function closeSpreadsheetQuestion(rowId, fColumnId, pColumnId) {
    var mainRowId = "mainRow_" + rowId;
    var additionalRowId = "additionalRow_" + rowId;
    var inputContentId = "inputContent_" + rowId;
    var spreadsheetItemId = "SpreadsheetItem_" + rowId + "_" + fColumnId + "_" + pColumnId;

    if ($("#" + inputContentId).is(":visible")) {
        $("#" + inputContentId).slideUp(0, function () {
            $("#" + spreadsheetItemId).parent().children(".buttonControl").removeClass("active");
            $("#" + additionalRowId).hide();
            $("#" + mainRowId + " .headerColumn").attr("rowspan", 1);
            resizeParentIframe('', window);
        });
    }

    // Enable delete buttons for columns
    // Css class "loading" get appended when the button is disabled because the page needs to re re-loaded
    // In case of this, the button should not be enabled in any cases until the page has been fully re-loaded
    $("#DeleteColButton1:not(.loading)").prop("disabled", false);		// AX-24898.24919.3 don't use .removeAttr("disabled");
    $("#DeleteColButton2:not(.loading)").prop("disabled", false);		// AX-24898.24919.3 don't use .removeAttr("disabled");
    $("#DeleteColButton3:not(.loading)").prop("disabled", false);		// AX-24898.24919.3 don't use .removeAttr("disabled");
    $("#DeleteColButton4:not(.loading)").prop("disabled", false);		// AX-24898.24919.3 don't use .removeAttr("disabled");
}

function clickSpreadsheetOkButton(isColumnHeader) {

    if (!getParentWindow(window).isErrorWindowOpened()) {
        hideSpreadsheetMessage(2);

        $(".buttonControl.active").each(function () {
            var itemId = $(this).parent().find("input[id^=SpreadsheetItem_]").attr("id");
            var rowId = itemId.split("_")[1];
            var fColId = itemId.split("_")[2];
            var pColId = itemId.split("_")[3];
            var controlId = "FormItem_" + rowId;

            var result;
            var currentItem = $("#" + controlId);
            if ($(currentItem).is(".yesNoControl")) {
                result = validateShortText(currentItem);
            }
            else if ($(currentItem).is(".shortTextControl")) {
                result = validateShortText(currentItem);
            }
            else if ($(currentItem).is(".numberControl")) {
                result = validateNumber(currentItem);
                if (result.invalidNumber > 0) {
                    var msg1 = $('input[id$="SettingInvalidNumberMessage"]').val();
                    if (msg1 == "")
                        msg1 = "Please enter a valid number.";

                    showSpreadsheetMessage(msg1, 1);
                    return;
                } else if (result.invalidRange) {
                    var msg2 = $('input[id$="SettingInvalidNumberRangeMessage"]').val();
                    if (msg2 == "")
                        msg2 = "Please enter a number in the specified range.";

                    showSpreadsheetMessage(msg2, 1);
                }
            }
            else if ($(currentItem).is(".listControl")) {
                result = validateList(currentItem);
            }
            else if ($(currentItem).parent().is(".dateControl")) {
                result = validateDate($(currentItem).parent(), false);
                if (result.invalidYear > 0) {
                    var msg3 = $('input[id$="SettingInvalidYearRangeMessage"]').val();
                    if (msg3 == "")
                        msg3 = "The year is out of range (1900 - 2100).";

                    showSpreadsheetMessage(msg3, 1);
                    return;
                } else if (result.invalidDate > 0) {
                    var msg4 = $('input[id$="SettingInvalidDateMessage"]').val();
                    if (msg4 == "")
                        msg4 = "Please enter a valid date.";

                    showSpreadsheetMessage(msg4, 1);
                    return;
                }
            }

            if (result != null && result.error > 0)
                return;

            //If current row is a column header row, check if the answer is blank
            if (isColumnHeader) {
                var value = $("#" + controlId).val();
                if (!validateRequired(value)) {
                    var msg5 = $('input[id$="SettingInputRequiredMessage"]').val();
                    if (msg5 == "")
                        msg5 = "Please enter a value.";

                    showSpreadsheetMessage(msg5, 1);
                    return;
                }
            }

            //remove all "new column" classes if currently selected column is part of the new column
            if ($(this).parent().is(".newColumn"))
                $(".newColumn").removeClass("newColumn");

            updateSpreadsheetCellControl(rowId, fColId, pColId);
            closeSpreadsheetQuestion(rowId, fColId, pColId);
        });
    }

    enableSubmitButton();
}

function clickSpreadsheetCancelButton(isColumnHeader) {
    if (!getParentWindow(window).isErrorWindowOpened()) {
        hideSpreadsheetMessage(2);

        $(".buttonControl.active").each(function () {

            var itemId = $(this).parent().find("input[id^=SpreadsheetItem_]").attr("id");
            var rowId = itemId.split("_")[1];
            var fColId = itemId.split("_")[2];
            var pColId = itemId.split("_")[3];
            var originalFieldId = "OriginalItem_" + rowId + "_" + fColId + "_" + pColId;

            //If current row is a column header row, check if the answer is blank
            if (isColumnHeader) {
                var value = $("#" + originalFieldId).val();
                if (!validateRequired(value)) {
                    var msg1 = $('input[id$="SettingInputRequiredMessage"]').val();
                    if (msg1 == "")
                        msg1 = "Please enter a value.";

                    showSpreadsheetMessage(msg1, 1);
                    return;
                }
            }

            closeSpreadsheetQuestion(rowId, fColId, pColId);
        });
    }
}

function clearSpreadsheetTemplateControl(rowId) {
    var controlId = "FormItem_" + rowId;

    //Update hidden field value to input control
    $("#" + controlId).val('');

    //If current control is for date, update dropdowns and input fields for month, day and year
    if ($("#" + controlId).parent().is(".dateControl")) {
        var container = $("#" + controlId).parent();
        clearDate(container);
    }
}

function updateSpreadsheetTemplateControl(rowId, fColumnId, pColumnId) {
    var hiddenFieldId = "SpreadsheetItem_" + rowId + "_" + fColumnId + "_" + pColumnId;
    var controlId = "FormItem_" + rowId;

    //Update hidden field value to input control
    var answer = $("#" + hiddenFieldId).val();
    $("#" + controlId).val(answer);

    //If current control is for date, update dropdowns and input fields for month, day and year
    if ($("#" + controlId).parent().is(".dateControl")) {
        var container = $("#" + controlId).parent();
        if (answer == "")
            clearDate(container);
        else
            updateYearMonthDay(container);
    }

    //Disable Cancel button and OK button
    disableSpreadsheetCellButtons(rowId);
}

function updateSpreadsheetCellControl(rowId, fColumnId, pColumnId) {
    var controlId = "FormItem_" + rowId;
    var hiddenFieldId = "SpreadsheetItem_" + rowId + "_" + fColumnId + "_" + pColumnId;

    //Update cell display value and hidden field value from input control
    var answer = $("#" + controlId).val();
    $("#" + hiddenFieldId).val(answer);

    //Get display value for special controls
    if ($("#" + controlId).parent().is(".dateControl")) {
        if (answer != "") {
            var dateArray = answer.split("-");
            var d = new Date(dateArray[0], dateArray[1]-1, dateArray[2]);
            var f = $.datepicker.formatDate("M dd, yy", d);
            answer = f;
        }
    }
    else if ($("#" + controlId).is(".yesNoControl")) {
        if (answer == "1")
            answer = "Yes";
        else if (answer == "0")
            answer = "No";
        else if (answer == "2")
            answer = "Don't Know";
        else {
            answer = "";
        }
    }

    if (answer != "") {
        $("#" + hiddenFieldId).parent().children(".buttonControl").removeClass("error");
    }

    //trim answer to check if needs to display &nbsp; instead for display control
    var trimAnswer = answer.replace(/^\s+|\s+$/g, '');
    if (trimAnswer == "")
        $("#" + hiddenFieldId).parent().children(".buttonControl").children(".displayValue").html("&nbsp;");
    else
        $("#" + hiddenFieldId).parent().children(".buttonControl").children(".displayValue").text(answer);

    resizeSpreadsheetCell(rowId);
}

function closeAllSpreadsheetQuestions() {
    $(".buttonControl.active").each(function () {
        var itemId = $(this).parent().find("input[id^=SpreadsheetItem_]").attr("id");
        var rowId = itemId.split("_")[1];
        var fColId = itemId.split("_")[2];
        var pColId = itemId.split("_")[3];
        closeSpreadsheetQuestion(rowId, fColId, pColId);
    });
}

function enableSpreadsheetCellButtons(forceEnable) {
    $(".buttonControl.active").each(function () {
        var itemId = $(this).parent().find("input[id^=SpreadsheetItem_]").attr("id");
        var rowId = itemId.split("_")[1];
        var fColId = itemId.split("_")[2];
        var pColId = itemId.split("_")[3];

        var inputBoxId = "inputContent_" + rowId;
        var controlId = "FormItem_" + rowId;
        var hiddenFieldId = "SpreadsheetItem_" + rowId + "_" + fColId + "_" + pColId;

        if ($("#" + controlId).val() != $("#" + hiddenFieldId).val() || forceEnable)
            $("#" + inputBoxId).children(".buttonControlBox").children("input[type=submit]").prop("disabled", false);		// AX-24898.24919.3 don't use .removeAttr("disabled");
    });
}

function disableSpreadsheetCellButtons(rowId) {
    var inputBoxId = "inputContent_" + rowId;
    $("#" + inputBoxId).children(".buttonControlBox").children(".ok").attr("disabled", "disabled");
}

function markSpreadsheetOnFile(id) {
    var iconId = "OnFile_" + id;

    // Show "On File" Icon
    $("#" + iconId).show();

    // Update hidden field
    $("#" + iconId).parent().find("input[type=hidden]").val("On File");

    //remove "Error" Icon
    $("#" + iconId).parent().parent().find(".errorIcon").first().hide();
}

function markSpreadsheetNotOnFile(id) {
    var iconId = "OnFile_" + id;

    // hide "On File" Icon
    $("#" + iconId).hide();

    // Update hidden field
    $("#" + iconId).parent().find("input[type=hidden]").val("");
}

// helper function to hide page control window
function hidePageJumpWindow(buttonId, contentId, docId) {
    if ($("#" + contentId).is(":visible")) {
        $("#" + contentId).fadeOut(function () {
            $("#" + buttonId).removeClass("active");
            resizeParentIframe(docId, window);
        });
    }
}

function closeSpreadsheetWindowFromMain() {
    var iframe = getParentWindow(window).document.getElementById("popupFrameSpreadsheet");
    if (iframe != null) {
        iframe.contentWindow.validateClose();
    }
}

function closeSpreadsheetWindow() {
    var maskId = "maskSpreadsheet";
    var windowId = "windowLargeSpreadsheet";
    var currentWindow = getParentWindow(window);

    // prevent IE from throwing error when trying to finish process after window is closed
    setTimeout(function () {
        currentWindow.deleteLayer(maskId);
        currentWindow.deleteLayer(windowId);
        currentWindow.enablePage();
    }, 500);
}

function closeSpreadsheetColumnWindow() {
    var maskId = "maskSpreadsheetNewCol";
    var windowId = "windowSmallSpreadsheetNewCol";
    var currentWindow = getParentWindow(window);

    // prevent IE from throwing error when trying to finish process after window is closed
    setTimeout(function () {
        currentWindow.deleteLayer(maskId);
        currentWindow.deleteLayer(windowId);
        currentWindow.enablePage();
    }, 500);
}

function focusColumnWindowControl() {
    $(document).ready(function () {
        var input = $("input[id^=FormItem_]");
        if ($(input).is(".shortTextControl") || $(input).is(".numberControl")) {
            $(input).trigger('focus');        // AX-24898.24919.2 .focus();
        }
    });
}

function highlightSpreadsheetColumn(number) {
    $("tr[id^=mainRow_] td:nth-child(" + (number + 1) + ")").addClass("deleteColumn");
}

function unhighlightSpreadsheetColumn(number) {
    $("tr[id^=mainRow_] td:nth-child(" + (number + 1) + ")").removeClass("deleteColumn");
}

function getButtonText(id, defaultValue) {
    var result = $("#" + id).length > 0 ? $("#" + id).attr("value") : defaultValue;
    result = result.replace(/[^0-9 a-zA-Z]+/g, "");
    return result;
}

function getSettingMessage(key) {
    var msg = $('input[id$="' + key + '"]').val();
    return msg;
}

function updateCheckboxValue(checkbox, id) {
    var value = ($(checkbox).is(':checked')) ? "1" : "0";
    $('input[id$="' + id + '"]').val(value);
}


// AX-4481.2
function checkCanGoBackForm(e) {

    //console.log("=== at TOP checkCanGoBackForm() saveBackend:" + saveBackend);
    var textNoSavedItems = backBtnValidateiFormNoSaved(e);  // AX-4481.5 Get if something change

    var saveBackend = $("#HiddenSaveBtn").attr("saving");
    if (saveBackend === "0" && !textNoSavedItems) {         // AX-4481.5 not in Saving mode and nothing changed, then go back
        // AX-4481.5 use go back
        if (window.history.length > 0)
            window.history.back();
        // AX-4481.5 history.pushState(null, null, null);
        //console.log("=== go back bacause saveBackend === 0 " );
        return;
    }

   if (textNoSavedItems) {
      // Use jquery Confirm dialog!
      if (confirm(textNoSavedItems)) {
         getParentWindow(window).hideSpinner();
         
         //console.log("=== at checkCanGoBackForm() goBack!!! ");
         history.back(); // no trigger
         return;
      } else {
         history.pushState(null, null, null);

         //console.log("=== at checkCanGoBackForm() saveBackend: " + saveBackend);
         if (saveBackend === "1") {
             $("#hiddenRespond").trigger('click');	        // AX-24898.24919.2 $("#hiddenRespond").click(); // To call serverside function
         }
      }
      return;
   } else {
      if (saveBackend === "0") {
         //console.log("=== at checkCanGoBackForm() saveBackend === 0 before history.pushState() ");
         if (window.history.length > 0)
             window.history.back();
         //history.pushState(null, null, null);
         return;
      }
   }

   //console.log("=== at checkCanGoBackForm() before validateiFormSavingProcess() savedBackend: " + saveBackend);
   if (validateiFormSavingProcess(e)) {
      //console.log("=== at checkCanGoBackForm() after validateiFormSavingProceess ====");
      getParentWindow(window).hideSpinner();
      //console.log("=== at checkCanGoBackForm() because validate goBack!!! ");
      history.back();                  // no trigger
   } else {
      //console.log("=== at checkCanGoBackForm() location.href: " + location.href);
      history.pushState(null, null, null);
      
      var spreadsheetFrame = window.parent.document.getElementById('popupFrameSpreadsheet');    // AX-4481.3      
      if (spreadsheetFrame === null)      // AX-4481.3
          $("#hiddenRespond").trigger('click');	        // AX-24898.24919.2 $("#hiddenRespond").click();     // To call serverside function
   }
   //console.log("=== at checkCanGoBackForm() last line!!! ");
}



