$(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);");

        // 66376692
        $(this).attr("onchange", "hideSpreadsheetColumnMessage(); enableButtons();");
        $(this).attr("onkeyup", "hideSpreadsheetColumnMessage(); enableButtons();");
        $(this).attr("onkeydown", "hideSpreadsheetColumnMessage(); enableButtons();");
        $(this).attr("oninput", "hideSpreadsheetColumnMessage(); enableButtons();");

        // Disable enter from submitting the form
        $(this).on('keypress', function (e) {		// AX-24898.24919.2 .keypress(function (e) {
            hideSpreadsheetColumnMessage();
            enableButtons();
            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);
                hideSpreadsheetColumnMessage();
                enableButtons();
            }
        });

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

    $(".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) {
            hideSpreadsheetColumnMessage();
            enableButtons();
            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) {
                hideSpreadsheetColumnMessage();
                enableButtons();
            }
        });
        /*
        // 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 () {
            hideSpreadsheetColumnMessage();
            enableButtons();
        });
    });

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

    $(".dateControl").each(function () {

        var current = this;

        $(current).find('.calendarControl').datepicker({
            minDate: new Date(1900, 0, 1),
            maxDate: new Date(2100, 11, 31),
            altField: ".altField",
            altFormat: "MM dd, yy",
            onSelect: function (dateStr, inst) {
                $(current).find("input[id^=FormItem_]").val(dateStr);
                hideSpreadsheetColumnMessage();
                enableButtons();
            },
            onUpdateDatepicker: function () {
                resizeParentIframe('spreadsheetNewColPage', window);
            },
            dateFormat: 'yy-mm-dd',
            yearRange: '1900, 2100'
        });

        $(current).find('.clearButton').click(function () {
            clearDate(current);
            hideSpreadsheetColumnMessage();
            enableButtons();
        });
    });

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

function clearDate(container) {
    $(container).find(".altField").val("");
    $(container).find("input[type=hidden]").val("");
}

// Enable submit button if value of input field is different from original value
function enableButtons() {
    var value = $(".shortTextControl").val() ||
        $(".numberControl").val() ||
        $(".listControl").val() ||
        $(".dateControl").find("input[id^=FormItem_]").val();

    if (value == "" || value == null)
        $('input[name="SubmitButton"].ok').attr('disabled', 'disabled');
    else {
        $('input[name="SubmitButton"].ok').removeAttr('disabled');
    }
}

// Validate the form if there is any empty fields
function validateSubmit() {
    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened() || getParentWindow(window).isConfirmWindowOpened())
        return false;

    var error = false;
    $(".shortTextControl").each(function () {
        if (!validateShortText(this)) {
            error += 1;
        }
    });

    $(".numberControl").each(function () {
        if (!validateNumber(this)) {
            error += 1;
        }
    });

    $(".listControl").each(function () {
        if (!validateList(this)) {
            error += 1;
        }
    });

    $(".dateControl").each(function () {
        if (!validateDate(this)) {
            error += 1;
        }
    });

    if (error > 0)
        return false;

    //If everything passes, submit form to add new spreadsheet
    return true;
}

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

    closeSpreadsheetColumnWindow();
}

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

    //enable/diable OK button based on availablility of the value
    hideSpreadsheetColumnMessage();
    enableButtons();

    if (!validateRequired(value) || !validateLength(value, 40)) {
        return false;
    }

    return true;
}

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

    var msg1 = $('input[id$="SettingInvalidNumberMessage"]').val();
    if (msg1 == "")
        msg1 = "Please enter a valid number.";

    var msg2 = $('input[id$="SettingInvalidNumberRangeMessage"]').val();
    if (msg2 == "")
        msg2 = "Please enter a number in the specified range.";

    var invalidNumberMessage = msg1;
    var invalidRangeMessage = msg2;

    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened())
        return false;

    // currently input value
    var value = $(elmt).val();

    // enable/diable OK button based on availablility of the value
    hideSpreadsheetColumnMessage();
    enableButtons();

    // number scheme
    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();

    if (!validateRequired(value)) {
        return false;
    }

    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";
            }
        }

        $(elmt).val(value);

        showSpreadsheetColumnMessage(invalidNumberMessage);
        enableButtons();

        return false;
    }
    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)) {
        showSpreadsheetColumnMessage(invalidRangeMessage);
        enableButtons();
        return false;
    }

    return true;
}

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

    hideSpreadsheetColumnMessage();
    enableButtons();

    return validateRequired(value);
}

//validate date
function validateDate(elmt) {
    var value = $(elmt).find("input[type=hidden]").val();

    hideSpreadsheetColumnMessage();
    enableButtons();

    return validateRequired(value);
}