//Prepare to show a date picker linked to three select controls
function readLinked(id) {
    var dateHidden = "#" + id;
    var dateYear = "#" + id + "Year";
    var dateMonth = "#" + id + "Month";
    var dateDay = "#" + id + "Day";

    //$(dateHidden).val($(dateMonth).val() + "/" + $(dateDay).val() + "/" + $(dateYear).val());
    // change to a more i18n friendly format
    $(dateHidden).val($(dateYear).val() + "-" + $(dateMonth).val() + "-" + $(dateDay).val());
    
}

// Update three select controls to match a date picker selection
function updateLinked(id, date) {
    var dateYear = "#" + id + "Year";
    var dateMonth = "#" + id + "Month";
    var dateDay = "#" + id + "Day";

    $(dateMonth).val(date.substring(5, 7));
    $(dateYear).val(date.substring(0, 4));

    checkLinkedDays(id);

    $(dateDay).val(date.substring(8, 10));
}

// Prevent selection of invalid dates through the select controls
function checkLinkedDays(id) {
    var dateYear = "#" + id + "Year";
    var dateMonth = "#" + id + "Month";
    var dateDay = "#" + id + "Day";

    var selectedDate = $(dateDay).val();
    var daysInMonth = 32 - new Date($(dateYear).val(),
        $(dateMonth).val() - 1, 32).getDate();
    $(dateDay + " option").remove();

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

    if (selectedDate > daysInMonth) {
        $(dateDay).val(daysInMonth);
    } else {
        $(dateDay).val(selectedDate);
    }
}

function verifyDay(id) {
    var dateDay = "#" + id + "Day";
    if ($(dateDay).val() == "") {
        $(dateDay).val('01');
    }
}

function verifyMonth(id) {
    var dateMonth = "#" + id + "Month";
    if ($(dateMonth).val() == "") {
        $(dateMonth).val('01');
    }
}

function verifyYear(id) {
    var dateYear = "#" + id + "Year";
    var date = new Date();
    var defaultYear = date.getFullYear();
    if ($(dateYear).val() == "") {
        $(dateYear).val(defaultYear);
    }
}

function changeYear(id) {
  


    checkLinkedDays(id);
    verifyDay(id);
    verifyMonth(id);
    readLinked(id);
  }

function alterYear(id) {
	var dateYear = "#" + id + "Year";

	if ($(dateYear).val() != "") {
		var yearValue = new Number($(dateYear).val());
		if (yearValue < 30)
			$(dateYear).val(2000 + yearValue);

		if (yearValue >= 30 && yearValue < 100)
			$(dateYear).val(1900 + yearValue);
	}

	checkLinkedDays(id);
	verifyDay(id);
	verifyMonth(id);
	readLinked(id);

}

function changeMonth(id) {
    checkLinkedDays(id);
    verifyDay(id);
    verifyYear(id);
    readLinked(id);
}

function changeDay(id) {
    verifyMonth(id);
    verifyYear(id);
    readLinked(id);

    checkLinkedDays(id);
}

function clearDate(id) {
    var dateYear = "#" + id + "Year";
    var dateMonth = "#" + id + "Month";
    var dateDay = "#" + id + "Day";

    $(dateYear).val('');
    $(dateMonth).val('');

    checkLinkedDays(id);

    $(dateDay).val('');

    readLinked(id);
}

function updateDateControlForForm(id, isHighlight) {
    //Function copied from iForm Validation-1.0.min.js
    //Imitate operation when it unhighlights the field
    var dateHidden = "#" + id;
    var dateYear = "#" + id + "Year";
    var dateMonth = "#" + id + "Month";
    var dateDay = "#" + id + "Day";
    var popup = "#" + id + "_div";
    var dateLabel = $(dateHidden).parent().prev();
    var errorClass = "error";

    if ($(dateYear).val() == '') {
        $(dateYear).addClass(errorClass);
        isHighlight = true;
    } else {
        var yearValue = new Number($(dateYear).val());
        var min = 1900;
        var max = 2100;

        if (yearValue > max || yearValue < min) {
            $(dateYear).val('');

            $('body').append($('.jqmWindow'));
            $(popup).jqm({ modal: true });
            $(popup).jqmShow();
            $('*:focus').trigger('blur');					// AX-24898.24919.2 .blur();
            $('.jqmClose:visible').focus();

            $(dateYear).addClass(errorClass);
            isHighlight = true;
        } else {
            $(dateYear).removeClass(errorClass);
        }
    }

    if ($(dateMonth).val() == '') {
        $(dateMonth).addClass(errorClass);
        isHighlight = true;
    } else {
        $(dateMonth).removeClass(errorClass);
    }

    if ($(dateDay).val() == '') {
        $(dateDay).addClass(errorClass);
        isHighlight = true;
    } else {
        $(dateDay).removeClass(errorClass);
    }

    if (isHighlight)
        dateLabel.addClass("iFormError").removeClass("valid");
    else
        dateLabel.addClass("valid").removeClass("iFormError");

    var container = $('div.validationError');
    var links = $('.noValidationLinks');
    if (!container.is(':visible'))
        links.hide();
    else {
        var totalCheckError = $(".iFormInvalid").filter(":visible").length; //23857155
        if (totalCheckError == 0) //23857155
            links.show();
    }
}

function updateDateControlForUser(id, errImgId, isHighlight, minDate, maxDate) {
    var dateYear = "#" + id + "Year";
    var dateMonth = "#" + id + "Month";
    var dateDay = "#" + id + "Day";
    var dateImage = "#" + errImgId;

    var isValidEmpty = false;                           // AX-21790 Is Valid empty date (only for Ambulatory summary)
    var checkOtherDate = isHighlight === false;         // AX-21790 The only case when isHighlight come with true is when is called recursive here
    isHighlight = false;                                // AX-21790 All the calls from script in DateNotificationControl come as false, so return to false value

    var otherId;                                        // AX-21790
    var otherDateYear, otherDateMonth, otherDateDay;    // AX-21790
    var isCurrentDateEmpty = false;                     // AX-21790
    
    // AX-21790 Is valid to have Empty From or Empty To date (but not both dates)
    if (id === 'DVALIDEMPTY123' || id === 'DVALIDEMPTY321') {
        isValidEmpty = true;
        otherId = id === 'DVALIDEMPTY123' ? 'DVALIDEMPTY321' : 'DVALIDEMPTY123';
        otherDateYear = "#" + otherId + "Year";
        otherDateMonth = "#" + otherId + "Month";
        otherDateDay = "#" + otherId + "Day";
    }

    // AX-21790
    if (isValidEmpty) {
        if (($(dateYear).val() === '' || $(dateMonth).val() === '' || $(dateDay).val() === '') &&
            ($(otherDateYear).val() === '' || $(otherDateMonth).val() === '' || $(otherDateDay).val() === '')) {
            isHighlight = true;
        } else {
            isCurrentDateEmpty = $(dateYear).val() === '' && $(dateMonth).val() === '' && $(dateDay).val() === '';
        }
    } else {
        // AX-21790 Original validation
        if ($(dateYear).val() === '' || $(dateMonth).val() === '' || $(dateDay).val() === '') {
            isHighlight = true;
        }
    }
    var yearValue = new Number($(dateYear).val());
    var monthValue = new Number($(dateMonth).val()) - 1;
    var dayValue = new Number($(dateDay).val());
    var minYear = minDate.getFullYear();
    var minMonth = minDate.getMonth();
    var minDay = minDate.getDate();
    var maxYear = maxDate.getFullYear();
    var maxMonth = maxDate.getMonth();
    var maxDay = maxDate.getDate();

    if (!isCurrentDateEmpty && (minYear > yearValue || yearValue > maxYear))
        isHighlight = true;

    if (yearValue === maxYear && (monthValue > maxMonth || (monthValue === maxMonth && dayValue > maxDay)))
        isHighlight = true;

    if (yearValue === minYear && (monthValue < minMonth || (monthValue === minMonth && dayValue < minDay)))
        isHighlight = true;

    if (isHighlight)
        $(dateImage).addClass("imgErrorShow").removeClass("imgErrorHide");
    else
        $(dateImage).addClass("imgErrorHide").removeClass("imgErrorShow");

    // AX-21790 Validate date for the other Date when is valid empty
    if (isValidEmpty && checkOtherDate) {
        updateDateControlForUser(otherId, otherId === 'DVALIDEMPTY123' ? "FromDateImgError" : "ToDateImgError", true, minDate, maxDate);    // AX-21790 Call recursive and set isHighlight = true
    }
}