$(document).ready(function () {
    // Custom messages and labels for iform

    $(".shortTextControl").each(function () {
        // Create maxlength condition
        $(this).maxlength({
            events: [], //Array of events to be triggered
            maxCharacters: 40,
            status: true, // True to show status indicator below the element
            statusClass: "remainingCount", // The class on the status div
            statusText: "/40", // The status text
            notificationClass: "", // the class added when maxlength is reached
            showAlert: false, // true to show a regular alert message
            alertText: "Cannot enter more than 40 characters", // text in alert message
            slider: true // true use counter slider
        });
        $(this).attr("maxlength", "40");
        //$(this).attr("onblur", "validateShortText(this);");
        $(this).attr("onchange", "enableSpreadsheetCellButtons(true);");

        // Disable enter from submitting the form
        $(this).on('keypress', function (e) {		// AX-24898.24919.2 .keypress(function (e) {
            hideSpreadsheetMessage(1);
            enableSpreadsheetCellButtons();
            disableEnter(e);
        });

        // there are cases where backspace is not registered as part of "on input" event in IE
        // this keyup handles the specific case to trigger validation
        $(this).on('keyup', function (e) {			// AX-24898.24919.2 .keyup(function (e) {
            // backspace
            if (e.which == 8) {
                //validateShortText(this);
                hideSpreadsheetMessage(1);
                enableSpreadsheetCellButtons();
            }
        });

        // Create validation and update of submit button
        $(this).on("input", function () {
            //validateShortText(this);
            hideSpreadsheetMessage(1);
            enableSpreadsheetCellButtons();
        });
    });

    $(".numberControl").each(function () {
        // Create maxlength condition
        $(this).maxlength({
            events: [], //Array of events to be triggered
            maxCharacters: 10,
            status: true, // True to show status indicator below the element
            statusClass: "remainingCount", // The class on the status div
            statusText: "/10", // The status text
            notificationClass: "", // the class added when maxlength is reached
            showAlert: false, // true to show a regular alert message
            alertText: "Cannot enter more than 10 characters", // text in alert message
            slider: true // true use counter slider
        });
        $(this).attr("maxlength", "10");
        //$(this).attr("onblur", "validateNumber(this);");
        // $(this).numeric();       // AX-24898.24918
        $(this).on("numeric");      // AX-24898.24918


        // Disable enter from submitting the form
        $(this).on('keypress', function (e) {		// AX-24898.24919.2 .keypress(function (e) {
            hideSpreadsheetMessage(1);
            enableSpreadsheetCellButtons();
            disableEnter(e);
        });

        // there are cases where backspace is not registered as part of "on input" event in IE
        // this keyup handles the specific case to trigger validation
        $(this).on('keyup', function (e) {			// AX-24898.24919.2 .keyup(function (e) {
            // backspace
            if (e.which == 8) {
                hideSpreadsheetMessage(1);
                enableSpreadsheetCellButtons();
            }
        });

        // Disable tab when number validation fails
        /*
        $(this).live("keydown", function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode == 9) {
        var result = validateNumber(current);
        if (result.error > 0) {
        e.preventDefault();
        }
        }
        });
        */

        // Create validation and update of submit button
        $(this).on("input", function () {
            hideSpreadsheetMessage(1);
            enableSpreadsheetCellButtons();
        });
    });

    $(".listControl").each(function () {
        var current = this;
        $(current).on('change', function () {     	// AX-24898.24919.2 .change(function () {
            //validateList(this);
            hideSpreadsheetMessage(1);
            enableSpreadsheetCellButtons();
        });
    });

    $(".yesNoControl").each(function () {
        var current = this;
        $(current).on('change', function () {     	// AX-24898.24919.2 .change(function () {
            //validateYesNo(current);
            hideSpreadsheetMessage(1);
            enableSpreadsheetCellButtons();
        });
    });

    $(".dateControl").each(function () {
        var current = this;
        // $(current).find('.yearControl').numeric(false);          // AX-24898.24918
        $(current).find('.yearControl').on("numeric", false);       // AX-24898.24918
        $(current).find('.yearControl').attr("maxlength", "4");
        $(current).find('.yearControl').on('keypress', function (e) {		// AX-24898.24919.2 .keypress(function (e) {
            hideSpreadsheetMessage(1);
            enableSpreadsheetCellButtons(true);
            disableEnter(e);
        });

        // there are cases where backspace is not registered as part of "on input" event in IE
        // this keyup handles the specific case to trigger "Enable Submit Button"
        $(this).on('keyup', function (e) {			// AX-24898.24919.2 .keyup(function (e) {
            // backspace
            if (e.which == 8) {
                hideSpreadsheetMessage(1);
                enableSpreadsheetCellButtons(true);
            }
        });

        $(current).find('input[type=hidden]').datepicker({
            minDate: new Date(1900, 0, 1),
            maxDate: new Date(2100, 11, 31),
            beforeShow: function (input, inst) {
                inst.dpDiv.css({
                    marginTop: (-40 - input.offsetHeight) + 'px',
                    marginLeft: input.offsetWidth + 'px'
                });
            },
            onSelect: function () {
                hideSpreadsheetMessage(1);
                updateYearMonthDay(current);
                enableSpreadsheetCellButtons();
            },
            dateFormat: 'yy-mm-dd',
            showOn: "button", // since the field is a hidden field, it should show only when button is clicked
            buttonImage: "/PatientAccess/Includes/Images/datepicker/calendar.png",
            buttonImageOnly: true,
            yearRange: '1900, 2100',
            onClose: function () { }
        });

        $(current).find('.monthControl').on('change', function () {     	// AX-24898.24919.2 .change(function () {
            hideSpreadsheetMessage(1);
            updateDate(current);
            enableSpreadsheetCellButtons(true);
        });
        $(current).find('.dayControl').on('change', function () {     	// AX-24898.24919.2 .change(function () {
            hideSpreadsheetMessage(1);
            updateDate(current);
            enableSpreadsheetCellButtons(true);
        });

        // Create validation and update of submit button
        $(current).find('.yearControl').on("input", function () {
            hideSpreadsheetMessage(1);
            updateDate(current);
            enableSpreadsheetCellButtons(true);
        });

        // there are cases where backspace is not registered as part of "on input" event in IE
        // this keyup handles the specific case to trigger validation
        $(current).find('.yearControl').on('keyup', function (e) {			// AX-24898.24919.2 .keyup(function (e) {
            // backspace
            if (e.which == 8) {
                hideSpreadsheetMessage(1);
                enableSpreadsheetCellButtons(true);
            }
            updateDate(current);
        });

        $(current).find('.clearButton').click(function () {
            clearDate(current);
            hideSpreadsheetMessage(1);
            enableSpreadsheetCellButtons(true);
        });

        // Initialize date
        updateDate(current);
    });

    // Disable submitbutton when page is loaded
    // $('input[name="SubmitButton"].save').attr('disabled', true);
});

function validateYear(elmt) {
    var value = $(elmt).val();

    if (!validateInteger(value)) {
        var pattern = /[^0-9]/g;
        value = value.replace(pattern, "");

        $(elmt).val(value);
    }

    var current = $(elmt).parent();
    updateDate(current);
    validateDate(current, true);
    enableSpreadsheetCellButtons();
}

function updateYearMonthDay(container) {
    var date = $(container).find("input[type=hidden]").val();
    if (date != null) {
        var ymd = date.split("-");
        if (ymd.length == 3) {
            var year = parseInt(ymd[0]);
            var month = parseInt(ymd[1].replace(/\D/g, ''), 10); // parseInt(ymd[0]);
            var day = ymd[2];

            //Update month dropdown
            
            // AX-307
            var daysInMonth = 32 - new Date(year, month - 1, 32).getDate();

            $(container).find(".dayControl option").remove();
            var ddl = $(container).find(".dayControl");
            $(ddl).append('<option value="0"></option>');
            for (var i = 1; i <= daysInMonth; i++) {
                var d = (i < 10) ? "0" + i : i;
                $(ddl).append('<option value="' + d + '">' + d + '</option>');
            }

            if (day > daysInMonth) {
                day = daysInMonth;
            }

            $(container).find(".yearControl").val(year);
            $(container).find(".monthControl").val(month);
            $(container).find(".dayControl").val(day);
        }
    }
}

function updateDate(container) {

    var year = $(container).find(".yearControl").val();
    var month = $(container).find(".monthControl").val();
    var day = $(container).find(".dayControl").val();

    if (month != "") {
        // AX-307
        var daysInMonth = 32 - new Date(year, month - 1, 32).getDate();

        $(container).find(".dayControl option").remove();
        var ddl = $(container).find(".dayControl");
        $(ddl).append('<option value="0"></option>');
        for (var i = 1; i <= daysInMonth; i++) {
            var d = (i < 10) ? "0" + i : i;
            $(ddl).append('<option value="' + d + '">' + d + '</option>');
        }

        if (day > daysInMonth) {
            day = daysInMonth;
        }

        $(ddl).val(day);
    }

    var isValid;

    if (year == "" || month == "0" || day == "0") {
        isValid = false;
    }
    else if (!validateInteger(year)) {
        isValid = false;
    } else {
        if (year < 1900 || year > 2100)
            isValid = false;
        else {
            isValid = true;
        }
    }

    if (isValid) {
        var date = "";
        date += year + "-";
        date += (month < 10) ? "0" : "";
        date += month + "-";
        date += day;

        $(container).find("input[type=hidden]").val(date);
    } else {
        $(container).find("input[type=hidden]").val("");
    }
}

function clearDate(container) {
    $(container).find(".yearControl").val("");
    $(container).find(".monthControl").val("0");
    $(container).find(".dayControl").val("0");
    $(container).find("input[type=hidden]").val("");
}

// Enable submit button if value of input field is different from original value
function enableSubmitButton() {
    var counter = checkUnsavedItems();
    if (counter == 0) {
        $("input[name=ContButton]").show();
        $("input[name=SaveButton]").hide();
    } else {
        $("input[name=ContButton]").hide();
        $("input[name=SaveButton]").show();
    }
}

function validateSave(ignoreEmpty) {
    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened() || getParentWindow(window).isConfirmWindowOpened())
        return false;

    //Remove column highlight
    $(".newColumn").removeClass("newColumn");

    var empty = validateInputs();
    if (empty > 0 && !ignoreEmpty) {
        //create confirmation window
        var confirmHeader = getSettingMessage("SettingEmptyFormSubmitHeader");
        var confirmMessage = getSettingMessage("SettingEmptyFormSubmitMessage");
        var cancelButtonText = "Cancel";
        var okButtonText = getButtonText("SaveButton", "Save");

        getParentWindow(window).createConfirmWindow(confirmHeader, confirmMessage, cancelButtonText, okButtonText,
                function () { $(".ignoreBlankSaveButton").trigger('click'); });  	        // AX-24898.24919.2 $(".ignoreBlankSaveButton").click();
        return false;
    }
    // AX-8776 Show spinner 
    // ------------------------------------------------------    
    showSpinner();

    return true;
}

function validateInputs() {
    var emptyCount = 0;
    $("input[name^=SpreadsheetItem_]").each(function () {
        var itemId = $(this).attr("id");
        var rowId = itemId.split("_")[1];
        var templateControlId = "FormItem_" + rowId;

        var value = $(this).val();
        var isValid = true;
        //check if current control is yes/No control
        if ($("#" + templateControlId).is(".yesNoControl")) {
            if (value == "" || value == "-1")
                isValid = false;
        } else {
            if (value == "")
                isValid = false;
        }

        if (!isValid) {
            emptyCount += 1;
            $(this).parent().children(".buttonControl").addClass("error");
        }
    });

    return emptyCount;
}

// validate if navigating away from the form is valid
function validateNav(ignoreButtonClass) {
    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened() || getParentWindow(window).isConfirmWindowOpened())
        return false;

    if (validateActiveSpreadsheet()) {
        // error and empty counter
        var counter = checkUnsavedItems();

        if (counter > 0) {
            var confirmHeader = getSettingMessage("SettingLeaveUnsavedFormHeader");
            var confirmMessage = getSettingMessage("SettingLeaveUnsavedFormMessage");
            var cancelButtonText = "No";
            var okButtonText = "Yes";

            getParentWindow(window).createConfirmWindow(confirmHeader, confirmMessage, cancelButtonText, okButtonText,
                function () { $("." + ignoreButtonClass).trigger('click'); });  	        // AX-24898.24919.2 $("." + ignoreButtonClass).click();

            return false;
        }

        return true;
    }

    return false;
}

function validateClose() {
    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened() || getParentWindow(window).isConfirmWindowOpened())
        return;

    if (validateActiveSpreadsheet()) {
        var counter = checkUnsavedItems();
        if (counter > 0) {
            var confirmHeader = getSettingMessage("SettingCloseSpreadsheetHeader");
            var confirmMessage = getSettingMessage("SettingCloseSpreadsheetMessage");
            var cancelButtonText = "Cancel";
            var okButtonText = getButtonText("CloseButton", "Close");

            getParentWindow(window).createConfirmWindow(confirmHeader, confirmMessage, cancelButtonText, okButtonText, closeSpreadsheetWindow);
        } else {
            closeSpreadsheetWindow();
        }
    }
}

function validateReset() {
    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened() || getParentWindow(window).isConfirmWindowOpened())
        return;

    var confirmHeader = getSettingMessage("SettingResetSpreadsheetHeader");
    var confirmMessage = getSettingMessage("SettingResetSpreadsheetMessage");
    var cancelButtonText = "Cancel";
    var okButtonText = getButtonText("ResetButton", "Reset Spreadsheet");

    getParentWindow(window).createWarningWindow(confirmHeader, confirmMessage, cancelButtonText, okButtonText, function () {
        resetClick();
    });
}

// FormItemID for column header
function validateAddColumn(iFormId, fItemId) {
    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened() || getParentWindow(window).isConfirmWindowOpened())
        return;

    if (!validateActiveSpreadsheet())
        return;

    // error and empty counter
    var counter = checkUnsavedItems();
    if (counter > 0) {
        var confirmHeader = getSettingMessage("SettingAddColumnHeader");
        var confirmMessage = getSettingMessage("SettingAddColumnMessage");
        var cancelButtonText = "Cancel";
        var okButtonText = getButtonText("AddColButton", "Add New Column");

        getParentWindow(window).createConfirmWindow(confirmHeader, confirmMessage, cancelButtonText, okButtonText,
        function () { openAddNewColumnWindow(iFormId, fItemId); });
        return;
    }

    openAddNewColumnWindow(iFormId, fItemId);
}

function validateDeleteColumn(fColumnId, pColumnId) {
    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened() || getParentWindow(window).isConfirmWindowOpened())
        return;

    if (!validateActiveSpreadsheet())
        return;

    var confirmHeader = getSettingMessage("SettingDeleteColumnHeader");
    var confirmMessage = getSettingMessage("SettingDeleteColumnMessage");
    var cancelButtonText = "Cancel";
    var okButtonText = getButtonText("DeleteColButton1", "Delete");
    var confirmNote = getSettingMessage("SettingDeleteColumnNote");

    var counter = checkUnsavedItems(fColumnId, pColumnId);
    if (counter > 0) {
        confirmMessage += "<div class=\"confirmWindowNote\">" + confirmNote + "</div>";
    }

    getParentWindow(window).createWarningWindow(confirmHeader, confirmMessage, cancelButtonText, okButtonText,
        function () {
            deleteColumnClick(fColumnId, pColumnId);
        });
}

function openAddNewColumnWindow(iformId, fitemId) {
    var url = "/PatientAccess/iForms/SpreadsheetNewColumn.aspx?iformId=" + iformId + "&fitemId=" + fitemId;
    getParentWindow(window).openPopup(url, "SpreadsheetNewCol", "windowSmall", null);
}

function addColumnClick() {
    $(".addColumnButton").trigger('click');	        // AX-24898.24919.2 $(".addColumnButton").click();
    disableSpreadsheetButtons();
}

function refreshClick() {
    $(".refreshButton").trigger('click');	        // AX-24898.24919.2 $(".refreshButton").click();
    disableSpreadsheetButtons();
}

function deleteColumnClick(formColumnId, patientColumnId) {
    $("#DeleteFormColumnId").val(formColumnId);
    $("#DeletePatientColumnId").val(patientColumnId);
    $(".deleteColumnButton").trigger('click');	        // AX-24898.24919.2 $(".deleteColumnButton").click();
    disableSpreadsheetButtons();
}

function resetClick() {
    $(".resetSpreadsheetButton").trigger('click');	        // AX-24898.24919.2 $(".resetSpreadsheetButton").click();
    disableSpreadsheetButtons();
}

// function to check if there are any items that are not saved
function checkUnsavedItems(fColumnId, pColumnId) {
    // error and empty counter
    var counter = 0;

    $("input[id^=SpreadsheetItem_]").each(function () {
        var itemId = $(this).attr("id");
        var fId = itemId.split("_")[2];
        var pId = itemId.split("_")[3];

        var originalValue = $(this).parent().find("input[id^=OriginalItem_]").val();
        var currentValue = $(this).val();

        if (fId != fColumnId || pId != pColumnId) {
            if (originalValue != currentValue)
                counter += 1;
        }
    });

    return counter;
}

// validate element with short text rules
function validateShortText(elmt) {
    var value = $(elmt).val();
    var empty = 0;
    var error = 0;

    if (!validateLength(value, 40)) {
        error += 1;
    }

    enableSpreadsheetCellButtons();

    return { error: error, empty: empty };
}

// validate element with number rules
function validateNumber(elmt) {


    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened())
        return { error: 1, empty: 0 };

    var value = $(elmt).val();
    var min = $(elmt).parent().find("input[name$=min]").val();
    var max = $(elmt).parent().find("input[name$=max]").val();
    var increment = $(elmt).parent().find("input[name$=inc]").val();

    var empty = 0;
    var error = 0;
    var invalidRange = 0;
    var invalidNumber = 0;

    if (!validateRequired(value)) {
        empty += 1;
    }
    else if (!validateDecimal(value)) {
        var pattern = /[^\-\.0-9]/g;
        var output = "";

        // get rid of all un-allowed characters
        var str = value.replace(pattern, "");

        if (str == "") {
            value = "";
        } else {
            // get rid of negative symbol if it is not in correct place
            if (str.substr(0, 1) == "-") {
                output += "-";
                str = str.substr(1);
            }
            str = str.replace(/[\-]/g, "");

            // get rid of decimal if it is not in correct place
            if (str.substr(str.length - 1) == ".")
                str = str.substr(0, str.length - 1);

            var tokens = str.split(".");
            for (var i = 0; i < tokens.length; i++) {
                if (i == 0) {
                    var trimmed = tokens[i].replace(/^0+/, "");
                    output += (trimmed == "") ? "0" : trimmed;
                    if (tokens.length > 1)
                        output += ".";
                } else {
                    output += tokens[i];
                }
            }

            value = output;

            //check if value is 0
            var p = /[^\-\.0]/g;
            if (!p.test(value)) {
                value = "0";
            }
        }

        invalidNumber += 1;
        $(elmt).val(value);
    }
    else {
        var isNegative = false;
        var o = "";
        var s = value;

        // save negative symbol
        if (s.substr(0, 1) == "-") {
            isNegative = true;
            s = s.substr(1, s.length - 1);
        }

        // remove last . if not followed by other numbers
        if (s.substr(s.length - 1) == ".")
            s = s.substr(0, s.length - 1);

        // right trim, if if leading with zero
        var t = s.split(".");
        for (var j = 0; j < t.length; j++) {
            if (j == 0) {
                var x = t[j].replace(/^0+/, "");
                o += (x == "") ? "0" : x;
                if (t.length > 1)
                    o += ".";
            } else {
                o += t[j];
            }
        }

        value = (isNegative) ? "-" + o : o;

        //check if value is 0
        var q = /[^\-\.0]/g;
        if (!q.test(value)) {
            value = "0";
        }

        $(elmt).val(value);
    }

    if (!validateRange(value, min, max, increment)) {
        invalidRange += 1;
    }

    enableSpreadsheetCellButtons();

    return { error: invalidNumber + invalidRange, empty: empty, invalidRange: invalidRange, invalidNumber: invalidNumber };
}

//validate schemed answer list
function validateList(elmt) {
    //var value = $(elmt).val();
    var empty = 0;
    var error = 0;

    enableSpreadsheetCellButtons();

    return { error: error, empty: empty };
}

//validate yes no question
function validateYesNo(elmt) {
    //var value = $(elmt).val();
    var empty = 0;
    var error = 0;

    enableSpreadsheetCellButtons();

    return { error: error, empty: empty };
}

//validate date
function validateDate(elmt, ignoreIncomplete) {
    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened())
        return { error: 1, empty: 0 };

    var year = $(elmt).find('.yearControl').val();
    var month = $(elmt).find('.monthControl').val();
    var day = $(elmt).find('.dayControl').val();
    var date = $(elmt).find("input[type=hidden]").val();

    var empty = 0;
    var rangeError = 0;
    var inputError = 0;

    if (!validateInteger(year)) {
        $(elmt).find(".yearControl").val("");
        inputError += 1;
    }
    else if (date == "") {
        if (ignoreIncomplete == false && (year != "" || month != "0" || day != "0")) {
            inputError += 1;
        }
    }

    if (year != "" && (year < 1900 || year > 2100))
        rangeError += 1;

    enableSpreadsheetCellButtons();

    return { error: (rangeError + inputError), empty: empty, invalidYear: rangeError, invalidDate: inputError };
}