
function setBirthdate() {
    var birthday = document.getElementById('DQ37297').value;                  // DatePicker use 37297 as Id of Calender control // 69492898 Change id to begin with letter than only numbers
    document.getElementById('hdnBirthdate').value = birthday;
}

function onlyNumbers(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

function ResetCity(elemTextBox) {
    // 70551316 This function is used by Zip textbox field and Emergency Contact Zip texbox field
    if (elemTextBox.id == "Zip") {
        if (document.getElementById('hdnZip').value == document.getElementById('Zip').value)
            return false;
        document.getElementById('hdnZip').value = document.getElementById('Zip').value;
        $('#GetInfoBtnImgError').removeClass('imgErrorHide');
        $('#GetInfoBtnImgError').addClass('imgErrorShow');
        document.getElementById('StateDropDown').selectedIndex = 0;
        document.getElementById('CountryDropDown').selectedIndex = 0;
        document.getElementById('hdnCityReseted').value = "1";
        if (document.getElementById('CityTextBoxDiv') != null)
            document.getElementById('City').value = "";
        if (document.getElementById('CityDropDownDiv') != null) {
            document.getElementById('CityDropDown').selectedIndex = 0;
            document.getElementById('CityDropDown').disabled = true;
        }
        return true;
    } else { // 70551316 
        if (document.getElementById('hdnEmergZip').value == document.getElementById('EmergInfoZip').value)
            return false;
        document.getElementById('hdnEmergZip').value = document.getElementById('EmergInfoZip').value;
        $('#EmergInfoZipBtnImgError').removeClass('imgErrorHide');
        $('#EmergInfoZipBtnImgError').addClass('imgErrorShow');
        document.getElementById('EmergInfoState').selectedIndex = 0;
        document.getElementById('hdnEmergCityReseted').value = "1";
        if (document.getElementById('EmergCityDiv') != null)
            document.getElementById('EmergInfoCity').value = "";
        if (document.getElementById('EmergCityDpDiv') != null) {
            document.getElementById('EmergInfoCityDp').selectedIndex = 0;
            document.getElementById('EmergInfoCityDp').disabled = true;
        }
        return true;
    }
}

// 39647133 Only number
// Validate 0-9 digits
function isOnlyNumber(value) {
    var len = value.length;
    var c;
    for (var i = 0; i < len; i++) {
        c = value.charAt(i).charCodeAt(0);
        if (c < 48 || c > 57)
            return false;
    }
    return true;
}

// 52499005
// Decline To Answer checkbox clicked. Select empty Ethnicity item and disable Ethnicity field
function checkedDeclineAnswer() {
    if ($('#DeclineAnswerChkBox').is(':checked')) {

        $('#EthnicityDropDown').hide();
        $('#EthnicityEmptyDropDown').show();
        $('#EthnicityDropDownImgError').removeClass('imgErrorShow').addClass('imgErrorHide');
        $('#hdnEthnicityInactive').val('Y');

        $('#RaceDivEmpty').show();
        $('#RaceDivListDp').hide();
        $('#RaceDivAddMore').hide();
        $('#RaceImgError').removeClass('imgErrorShow').addClass('imgErrorHide');                                    //52498835 Remove Error Class
    } else {
        $('#EthnicityDropDown').show();
        $('#EthnicityEmptyDropDown').hide();

        $('#RaceDivEmpty').hide();
        $('#RaceDivListDp').show();
        ShowHideAddMoreRaces();
    }
    resizeParentIframe('personalInfoEditPage', window);             // Defined in iframe.231520.js    
}

// 52498835 Function to get Cities when click button. Use to be a Server side function
function getCityClick(elemBtn) {
    // 70551316 This function is used by Get City btn and Emergency Get City btn
    var isEmergencyZipBtn = elemBtn.id == "EmergInfoZipBtn";
    var zipVal = JSON.stringify({ "postal": isEmergencyZipBtn ? $('#EmergInfoZip').val() : $('#Zip').val() });
    $.ajax({
        type: "POST",
        url: "/PatientAccess/Services/CityService.asmx/GetCityInfo",
        data: zipVal,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (cities) {
            if (cities.d) {
                var jsonResult = JSON.parse(cities.d);                                                                                      //Convert a JSON string to JSON Object
                if (jsonResult.cityListValues.length > 0) {
                    // 70551316 Set Values, hide Error Img and is separated in other function for Address Get City or Emergency Adrress Get city
                    if (isEmergencyZipBtn) {
                        setValuesEmergAddress(jsonResult);
                    } else {
                        setValuesAddress(jsonResult);
                    }
                }
            }
        }
    });
}

// 70551316  Set Values for regular Address
function setValuesAddress(jsonResult) {
    $('#hdnCityReseted').val("0");
    $('#hdnZip').val($.trim(jsonResult.cityListValues[0].Postal));
    $('#Zip').val($.trim(jsonResult.cityListValues[0].Postal));
    // 58351466 - update the Zip Code to the proper formatted zip from database
    $('#GetInfoBtnImgError').removeClass('imgErrorShow').addClass('imgErrorHide');                                          // Hide Error image 
    $('#CityImgError').removeClass('imgErrorShow').addClass('imgErrorHide');                                                // Hide Error image 
    $('#StateDropDownImageError').removeClass('imgErrorShow').addClass('imgErrorHide');                                     // Hide Error image 
    $('#CountryDropDownImageError').removeClass('imgErrorShow').addClass('imgErrorHide');                                   // Hide Error image 
    $('#ZipImgError').removeClass('imgErrorShow').addClass('imgErrorHide');                                                 // Hide Error image 

    $('#StateDropDown').val(jsonResult.cityListValues[0].Province);                                                         // Select value in Province in dropdown 
    $('#CountryDropDown').val(jsonResult.cityListValues[0].Country);
    if (jsonResult.cityListValues.length > 1) {
        $('#CityTextBoxDiv').hide();
        $('#CityDropDownDiv').show();
        $('#CityDropDown').empty();
        for (var ii = 0; ii < jsonResult.cityListValues.length; ii++) { // cityListValues is defined in CityService
            $('#CityDropDown').append($('<option></option>').val(jsonResult.cityListValues[ii].City).text(jsonResult.cityListValues[ii].City));
        }
        $('#CityDropDown').prop('disabled', false);
        $('#CityDropDown').val($('#City').val());
    } else {
        $('#City').val($.trim(jsonResult.cityListValues[0].City));
        $('#CityTextBoxDiv').show();
        $('#CityDropDownDiv').hide();
        $('#CityDropDown').prop('disabled', true);
    }
}
// 70551316  Set Values for Emergency Address
function setValuesEmergAddress(jsonResult) {
    $('#hdnEmergCityReseted').val("0");
    $('#hdnEmergZip').val($.trim(jsonResult.cityListValues[0].Postal));
    $('#EmergInfoZip').val($.trim(jsonResult.cityListValues[0].Postal));
    // 58351466 - update the Zip Code to the proper formatted zip from database
    $('#EmergInfoZipBtnImgError').removeClass('imgErrorShow').addClass('imgErrorHide');                                     // Hide Error image 
    $('#EmergInfoCityImgError').removeClass('imgErrorShow').addClass('imgErrorHide');                                       // Hide Error image 
    $('#EmergInfoStateImgError').removeClass('imgErrorShow').addClass('imgErrorHide');                                      // Hide Error image 
    $('#EmergInfoZipImgError').removeClass('imgErrorShow').addClass('imgErrorHide');                                        // Hide Error image 

    $('#EmergInfoState').val(jsonResult.cityListValues[0].Province);                                                        // Select value in Province in dropdown 
    if (jsonResult.cityListValues.length > 1) {
        $('#EmergCityDiv').hide();
        $('#EmergCityDpDiv').show();
        $('#EmergInfoCityDp').empty();
        for (var ii = 0; ii < jsonResult.cityListValues.length; ii++) { // cityListValues is defined in CityService
            $('#EmergInfoCityDp').append($('<option></option>').val(jsonResult.cityListValues[ii].City).text(jsonResult.cityListValues[ii].City));
        }
        $('#EmergInfoCityDp').prop('disabled', false);
        $('#EmergInfoCityDp').val($('#EmergInfoCity').val());
    } else {
        $('#EmergInfoCity').val($.trim(jsonResult.cityListValues[0].City));
        $('#EmergCityDiv').show();
        $('#EmergCityDpDiv').hide();
        $('#EmergInfoCityDp').prop('disabled', true);
    }
}

// 52498835 Set City with same value as CityDropDown
function setCityField() {
    $('#hdnCity').val($('#City').val($('#CityDropDown').val()));
}

// 70551316 Set EmergInfoCity with same value as EmergencyInfoCityDp
function setEmergCityField() {
    $('#hdnEmergCity').val($('#EmergInfoCity').val($('#EmergInfoCityDp').val()));
}


// 70551316 Set EmergInfoCity with same value as EmergencyInfoCityDp
function setEmergRelationField() {
    $('#hdnEmergRelation').val($('#EmergInfoRelation').val());          // Set hdnEmergRelation field with changed dropdown value

}

// *******************************************************************
// *****  Race function for edit Personal Informations  52498835 *****
// *******************************************************************
var IniNameRaceDp = "RaceDropDown";
var EndNameRaceDp = "List";
var IniNameRaceRemoveDiv = "RemoveRaceDiv";
var EndNameRaceRemoveDiv = "Remove";
var IniNameRaceRemoveBtn = "RaceBtn";
var EndNameRaceRemoveBtn = "Remove";
var previousRaceValue;                                                                                          // 52498835 Value in dropdown item Used to set the current RaceId in a dropdown
var previousRaceText;                                                                                           // 52498835 Text in dropdown item Used to set the current RaceId in a dropdown


// 52498835 Get Race Info Click function
function addRaceClick() {
    var racesTxt = $('#hdnRacesJson').val();        // Get Races from stored variable
    var jsonResult = JSON.parse(racesTxt);          // Convert a JSON string to JSON Object
    addRaceSetValuesAndAttributes(jsonResult);
}

// 52498835 Get Avaiable Races (doesn't include inactive) in a JSon string variable (use Ajax to get info from database)
function setAvailabelRacesAsJson() {
    if ($('#hdnRacesJson').val() == '') {
        $.ajax({
            type: "POST",
            url: "/PatientAccess/Services/RaceService.asmx/GetRaceInfo",
            data: "{}",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function (races) {
                if (races.d) {
                    $('#hdnRacesJson').val(races.d); // Store JSON string with races to avoid read next time from database
                }
            },
            error: function () {
                $('#hdnRacesJson').val("");         // Error
            }
        });
    }
}

// 52498835 Set values and attributes for adding a race button
function addRaceSetValuesAndAttributes(jsonResult) {
    var dpNumber = getMaxNumberDp();
    var raceDp = document.createElement("select");
    raceDp.setAttribute("id", IniNameRaceDp + dpNumber + EndNameRaceDp);
    raceDp.setAttribute("class", "RaceField");
    raceDp.setAttribute("onfocus", "getCurrentRaceDp(this)");
    raceDp.setAttribute("onchange", "changeRaceDp(this)");
    var totRacesAdded = 0;

    for (var ii = 0; ii < jsonResult.raceList.length; ii++) { // raceList is defined in RaceService
        if (!CheckIsSelectedInOtherRaceDp(jsonResult.raceList[ii].Value)) {
            var op = new Option();
            op.value = jsonResult.raceList[ii].Value;
            op.text = jsonResult.raceList[ii].Text;
            raceDp.options.add(op);
            totRacesAdded++;
        }
    }
    if (totRacesAdded > 0) {
        // If there is only one drop down (default drop down) add add 'X' remove botton and change size
        if ($('[id^="' + IniNameRaceDp + '"]').length == 1) {
            $('[id^="' + IniNameRaceDp + '"]').removeAttr("class", "RaceDefaultField").attr("class", "RaceField");
            var dpDefaultNumber = getNumberId($('[id^="' + IniNameRaceDp + '"]').attr("id"), IniNameRaceDp, EndNameRaceDp);
            createRemoveRaceButton(dpDefaultNumber);    // Create Remove button and append
        }
        $('#RaceDivListDp').append(raceDp);             // Append a new drop down
        createRemoveRaceButton(dpNumber);               // Create Remove button and append
        removeOnOtherRaceDp(raceDp);                    // To remove for other Race Dropdown selected race from new race drop down
        if (totRacesAdded == 1)
            $('#RaceDivAddMore').hide();

        resizeParentIframe('personalInfoEditPage', window);             // Defined in iframe.231520.js
    }

}

// 52498835 Create Remove button and append
function createRemoveRaceButton(dpNumber) {
    var removeDiv = document.createElement("div");
    removeDiv.setAttribute("id", IniNameRaceRemoveDiv + dpNumber + EndNameRaceRemoveDiv);
    removeDiv.setAttribute("class", "RaceRemoveDiv");
    $('#RaceDivListDp').append(removeDiv);

    var removeBtn = document.createElement("input");
    removeBtn.type = "button";
    removeBtn.value = "X";
    removeBtn.setAttribute("id", IniNameRaceRemoveBtn + dpNumber + EndNameRaceRemoveBtn);
    removeBtn.setAttribute("class", "RaceRemoveField");
    removeBtn.setAttribute("onclick", "removeRaceClick(this)");
    $(removeDiv).append(removeBtn); //  $('#RaceDivListDp').append(removeBtn);    
}

// 52498835 Set the current Race selected in a Race drop down, before change the value
function getCurrentRaceDp(elem) {
    previousRaceValue = elem.options[elem.selectedIndex].value;
    previousRaceText = elem.options[elem.selectedIndex].text;
}

// 52498835 Change Race function. Previous selected race need to be added in other Races dp and delete the new selected option
function changeRaceDp(currentDp) {
    var currentRaceValue = currentDp.options[currentDp.selectedIndex].value;

    // Case when previous drop down is Inactive
    if (previousRaceValue != "" && !raceIsActive(previousRaceValue)) {
        var itemInactive = "#" + currentDp.id + " option[value='" + previousRaceValue + "']";
        $(itemInactive).remove();
        var totItems = 0;
        // Remove actual item in other dropdowns
        $('[id^="' + IniNameRaceDp + '"]').each(function () {
            if ($(this).attr("id") != currentDp.id) {
                var itemDp = "#" + $(this).attr("id") + " option[value='" + currentRaceValue + "']";
                $(itemDp).remove();
                totItems = $(this).children('option').length;                                         // All drop down must have same number of options
            }
        });
        // Every drop down contain only one option
        if (totItems <= 1)
            $('#RaceDivAddMore').hide();
        return;
    }
    // Patient had empty race and now is selecting a new one
    if (previousRaceValue == "") {
        var itemEmptyDp = "#" + currentDp.id + " option[value='" + previousRaceValue + "']";
        $(itemEmptyDp).remove();
        $('#RaceDivAddMore').show();
    } else {
        $('[id^="' + IniNameRaceDp + '"]').each(function () {
            if ($(this).attr("id") != currentDp.id) {
                var actValue = $(this).val();                           // Save actual selected value
                $(this).append($('<option></option>').val(previousRaceValue).text(previousRaceText));
                sortListDp($(this).attr("id"));                         // Sort list 
                $(this).val(actValue);                                  // Set actual selected value because in firefox after sort it display last item f the list. 

                var itemDp = "#" + $(this).attr("id") + " option[value='" + currentRaceValue + "']";
                $(itemDp).remove();
            }
        });
    }
}

// 52498835 Check if Race is not Inactive
function raceIsActive(raceValue) {
    var jsonResult = JSON.parse($('#hdnRacesJson').val());          // Convert a JSON string to JSON Object
    if (jsonResult.raceList.length > 0) {
        for (var ii = 0; ii < jsonResult.raceList.length; ii++) {   // raceList is defined in RaceService
            if (raceValue == jsonResult.raceList[ii].Value)
                return true;                                        // Is active
        }
    }
    return false;
}

// 52498835 Remove Race Click function
function removeRaceClick(elemBtn) {
    var btnId = elemBtn.id;
    var numberElem = getNumberId(btnId, IniNameRaceRemoveBtn, EndNameRaceRemoveBtn);

    var currentDp = $('[id^="' + IniNameRaceDp + numberElem + '"]')[0];
    var currentRaceValue = currentDp.options[currentDp.selectedIndex].value;
    var currentRaceText = currentDp.options[currentDp.selectedIndex].text;

    $(currentDp).remove();
    $(elemBtn).remove();
    if (raceIsActive(currentRaceValue)) {
        $('[id^="' + IniNameRaceDp + '"]').each(function () {
            var actValue = $(this).val();                               // Save actual selected value
            $(this).append($('<option></option>').val(currentRaceValue).text(currentRaceText));
            sortListDp($(this).attr("id"));                             // Sort list
            $(this).val(actValue);                                      // Set actual selected value because in firefox after sort it display last item f the list.
        });
        // Total elements is 1 then is default DropDown
        if ($('[id^="' + IniNameRaceDp + '"]').length == 1) {
            $('[id^="' + IniNameRaceDp + '"]').removeAttr("class", "RaceField").attr("class", "RaceDefaultField");
            $('[id^="' + IniNameRaceRemoveDiv + '"]').remove();
            $('[id^="' + IniNameRaceRemoveBtn + '"]').remove();
        }
        $('#RaceDivAddMore').show();
    }
    resizeParentIframe('personalInfoEditPage', window);             // Defined in iframe.231520.js
}

// 52498835 Get Number Id for controld ID (ID for DropDown and RemoveBtn control has Init + Number + End)
function getNumberId(elemId, initialPart, endPart) {
    var posIni = elemId.search(initialPart);
    var posEnd = elemId.search(endPart);
    var indexId = -1;
    if (posIni >= 0 && posEnd > 0)
        indexId = elemId.substring(posIni + initialPart.length, posEnd);
    return indexId;
}


// 52498835 Get the next number for the new Race dropdown and Remove btn
function getMaxNumberDp() {
    var maxNumber = 1;
    $('[id^="' + IniNameRaceDp + '"]').each(function () {
        $(this).attr("id");
        var numberElemId = getNumberId($(this).attr("id"), IniNameRaceDp, EndNameRaceDp);
        var numElem = parseInt(numberElemId);
        if (numElem >= maxNumber)
            maxNumber = numElem + 1;
    });
    return maxNumber;
}

// 52498835 Check if value is already a selected value in others Race dropdowns
function CheckIsSelectedInOtherRaceDp(valueToLock) {
    var selected = false;
    $('[id^="' + IniNameRaceDp + '"]').each(function () {
        var currentDp = $(this)[0];
        var currentRaceValue = currentDp.options[currentDp.selectedIndex].value;
        if (currentRaceValue == valueToLock) {
            selected = true;
        }
    });
    return selected;
}

// 52498835 After add a new dropd down, remove selected new item in other Race dropdowns
function removeOnOtherRaceDp(currentDp) {
    var currentRaceValue = currentDp.options[currentDp.selectedIndex].value;
    $('[id^="' + IniNameRaceDp + '"]').each(function () {
        if ($(this).attr("id") != currentDp.id) {
            var itemDp = "#" + $(this).attr("id") + " option[value='" + currentRaceValue + "']";
            $(itemDp).remove();
        }
    });
}

// 52498835 Show or hide "Add More" division. Used when click in Decline to answer questions about ethnicity and race
function ShowHideAddMoreRaces() {
    var showAddMore = false;
    if ($('[id^="' + IniNameRaceDp + '"]').length == 1) {
        var select = $('[id^="' + IniNameRaceDp + '"]')[0];
        showAddMore = $(select).val() != "";
    } else {
        $('[id^="' + IniNameRaceDp + '"]').each(function () {
            showAddMore = $(this).children('option').length > 1;                                         // All drop down must have same number of options
        });
    }
    if (showAddMore)
        $('#RaceDivAddMore').show();
    else
        $('#RaceDivAddMore').hide();
}

// 52498835 Sort Drop down list values
function sortListDp(selectId) {
    var selectOptions = $('#' + selectId + ' option');

    selectOptions.sort(function (a, b) {
        if (a.text > b.text) {
            return 1;
        }
        else if (a.text < b.text) {
            return -1;
        }
        else {
            return 0;
        }
    });
    $('#' + selectId).empty().append(selectOptions);
}

var _raceSeparator = '[rc]';                                                                                    // 52498835 Race separator

// 52498835  At submit button get all the Selected Races to update user info in server side and the same for City, Country and State
function onSubmitSetValues() {
    if ($('#CityDropDownDiv').is(":visible"))
        $('#hdnCity').val($('#CityDropDown').val());
    else
        $('#hdnCity').val($('#City').val());
    $('#hdnState').val($('#StateDropDown').val());
    $('#hdnCountry').val($('#CountryDropDown').val());

    // 70551316 Set Hidden fields for Emergency City and State
    if ($('#EmergInfoCityDp').is(":visible"))
        $('#hdnEmergCity').val($('#EmergInfoCityDp').val());
    else
        $('#hdnEmergCity').val($('#EmergInfoCity').val());
    $('#hdnEmergState').val($('#EmergInfoState').val());

    // Create a json object with all the selected races values
    var jsonObj = [];
    $('[id^="' + IniNameRaceDp + '"]').each(function () {
        var currentDp = $(this)[0];
        var item = {};
        item["Race"] = currentDp.options[currentDp.selectedIndex].value;
        jsonObj.push(item);
    });
    var temp = JSON.stringify(jsonObj);
    $("#hdnRacesSelectedJson").val(JSON.stringify(jsonObj));                        // Convert json Object to string

    return ($('#FormPat').valid());     // 52498835 This extra validation on submit button is needed, because if GetCity button is clicked (ajax function is called/Asynchronous call) 
    //           then $('#FormPat').validate() is not called again if submit button is pressed. So for this scenario, here call valid() page to validate and show orange imgerror
}


// ***************************************************************
// *********  Validate() plug-in functions  39647133 *************
// ***************************************************************
var phoneCodeLen = 3;
var phone1Len = 3;
var phone2Len = 4;

// *** 39647133 Functions for Validator ***

// 39647133 OnChange Contact At DropDown call Validation of phone numbers
// Call validation for one of the field for Home, Work, Other, Mobile and it validate related fields
function validateContactDp() {
    if (!$("#HomePhone1").is(':disabled'))
        $("#HomePhone1").valid();       //Same way to validate: $('#FormPat').validate().element("#HomePhone1");
    if (!$("#WorkPhone1").is(':disabled'))
        $("#WorkPhone1").valid();
    if (!$("#OtherPhone1").is(':disabled'))
        $("#OtherPhone1").valid();
    if (!$("#MobilePhone1").is(':disabled'))
        $("#MobilePhone1").valid();
}

// 39647133 Custom Validation for phone numbers. 
// At every field to validate it needs also to validate related fields. Example validate HomPhone1 need to check for HomePhoneCode and HomePhone2
// Obtain which kind of phone are to validate: Home, Work, Other, Mobile
// Contact At Dropdown is not related to the phone to validate, then it could be empty in all the fields (Code Area, Phone1, Phone2)
// Contact At Dropdown is related then Code Area must be 3 digits or empty, Phone1 needs to be 3 digits and phone2 4 digits
jQuery.validator.addMethod("validatePhoneNumbers", function (value, element) {
    var contactDropDownValue;
    var phoneCode;
    var phone1;
    var phone2;
    var extEmptyOrNotUsed;              // 73341708

    if (element.id.indexOf('HomePhone') >= 0) {
        contactDropDownValue = "1";
        phoneCode = '#HomePhoneCode';
        phone1 = '#HomePhone1';
        phone2 = '#HomePhone2';
        extEmptyOrNotUsed = true;       // 73341708
    } else if (element.id.indexOf('WorkPhone') >= 0) {
        contactDropDownValue = "2";
        phoneCode = '#WorkPhoneCode';
        phone1 = '#WorkPhone1';
        phone2 = '#WorkPhone2';
        extEmptyOrNotUsed = $('#WorkPhoneExt').val() == '';
    } else if (element.id.indexOf('OtherPhone') >= 0) {
        contactDropDownValue = "3";
        phoneCode = '#OtherPhoneCode';
        phone1 = '#OtherPhone1';
        phone2 = '#OtherPhone2';
        extEmptyOrNotUsed = $('#OtherPhoneExt').val() == '';
    } else {
        contactDropDownValue = "4";
        phoneCode = '#MobilePhoneCode';
        phone1 = '#MobilePhone1';
        phone2 = '#MobilePhone2';
        extEmptyOrNotUsed = true;       // 73341708
    }

    // 73341708 Check also for empty Extension or not used
    if ($('#ContactAtDropDown').val() != contactDropDownValue && $(phoneCode).val().length == 0 && $(phone1).val().length == 0 && $(phone2).val().length == 0 && extEmptyOrNotUsed == true)
        return true;
    var okCode = $(phoneCode).val().length == 0 || ($(phoneCode).val().length == phoneCodeLen && isOnlyNumber($(phoneCode).val()));
    var ok = okCode && ($(phone1).val().length == phone1Len && isOnlyNumber($(phone1).val())) &&
        ($(phone2).val().length == phone2Len && isOnlyNumber($(phone2).val()));
    return ok;
});


// 70551316 Custom Validation for Emergency phone numbers.
jQuery.validator.addMethod("validateEmergPhoneNumbers", function (value, element) {
    var phoneCode;
    var phone1;
    var phone2;
    var extension;                                                      // 73341708

    if (element.id.indexOf('EmergInfoPhone') >= 0) {
        phoneCode = '#EmergInfoPhoneCode';
        phone1 = '#EmergInfoPhone1';
        phone2 = '#EmergInfoPhone2';
        extension = '#EmergInfoPhoneExt';                               // 73341708
    } else {
        phoneCode = '#EmergInfoAlternativePhoneCode';
        phone1 = '#EmergInfoAlternativePhone1';
        phone2 = '#EmergInfoAlternativePhone2';
        extension = '#EmergInfoAlternativePhoneExt';                    // 73341708
    }
    // 73341708 Check also Extension is not empty
    if ($(phoneCode).val().length == 0 && $(phone1).val().length == 0 && $(phone2).val().length == 0 && $(extension).val().length == 0) {
        return (element.id.indexOf('EmergInfoAlternativePhone') >= 0);          // Return true if is EmergInfoAlternativePhone; Return false if is EmergInfoPhone bacause is required field. 
    }

    var okCode = $(phoneCode).val().length == 0 || ($(phoneCode).val().length == phoneCodeLen && isOnlyNumber($(phoneCode).val()));
    var ok = okCode && ($(phone1).val().length == phone1Len && isOnlyNumber($(phone1).val())) &&
        ($(phone2).val().length == phone2Len && isOnlyNumber($(phone2).val()));
    return ok;
});

// 52498835 During Race, found that need to do client side validation of title. Don't allow empty title if parameter allowBlancTitle is not 1
function ValidTitle() {
    if ($('#hdnAllowBlankTitle').val() != '1' && $('#TitleDropDown').val() == "") {
        return false;
    }
    return true;
}

// 52498835 During Race, found that need to do client side validation of title
jQuery.validator.addMethod("validateTitle", function () {
    return ValidTitle();
});


// 52498757
function ValidCustomCode(type) {
    var list = $('#hdnCustomCodes').val().split(",");
    var list2 = $('#hdnCustomCodesValidate').val().split(",");
    if ($.inArray(type.toString(), list2) >= 0 && $.inArray(type.toString(), list) >= 0) {

        if ($.trim($('#CustomCode' + (type + 1).toString()).val()) == "") // 67051480
            return false;
        else {
            return true;
        }
    }
    return true;
}
// 52498757
jQuery.validator.addMethod("validateCustomCode1", function () {
    return ValidCustomCode(0);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode2", function () {
    return ValidCustomCode(1);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode3", function () {
    return ValidCustomCode(2);
});


// 52498757
jQuery.validator.addMethod("validateCustomCode4", function () {
    return ValidCustomCode(3);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode5", function () {
    return ValidCustomCode(4);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode6", function () {
    return ValidCustomCode(5);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode7", function () {
    return ValidCustomCode(6);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode8", function () {
    return ValidCustomCode(7);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode9", function () {
    return ValidCustomCode(8);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode10", function () {
    return ValidCustomCode(9);
});



// 52498757
jQuery.validator.addMethod("validateCustomCode27", function () {
    return ValidCustomCode(26);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode28", function () {
    return ValidCustomCode(27);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode29", function () {
    return ValidCustomCode(28);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode30", function () {
    return ValidCustomCode(29);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode31", function () {
    return ValidCustomCode(30);
});


// 52499051
// Validate Preferred Language drop down
function ValidLanguage() {
    if ($('#hdnPrefLangInactive').val() == 'Y') {
        var selectedIndex = $('#PreferredLanguageDropDown').prop('selectedIndex');
        if (selectedIndex < 0)
            return false;
        if (selectedIndex == 0 && $("#PreferredLanguageDropDown option").eq(0).val() == $('#hdnPrefLangInactiveValue').val())
            return false;
    }
    return true;
}
// 52499051
// Add method to Validator plug-in to validate Preferred Language drop down
jQuery.validator.addMethod("validatePreferredLang", function () {
    return ValidLanguage();
});

// 52499005
// Validate Ethnicity drop down
function ValidEthnicity() {
    if ($('#DeclineAnswerChkBox').is(':checked'))
        return true;
    if ($('#hdnEthnicityInactive').val() == 'Y') {
        var selectedIndex = $('#EthnicityDropDown').prop('selectedIndex');
        if (selectedIndex < 0)
            return false;
        if ($("#EthnicityDropDown option").eq(selectedIndex).val() == '' || $("#EthnicityDropDown option").eq(selectedIndex).val() == $('#hdnEthnicityInactiveValue').val())
            return false;
    }
    return true;
}
// 52499051
// Add method to Validator plug-in to validate Ethnicity drop down
jQuery.validator.addMethod("validateEthnicity", function () {
    return ValidEthnicity();
});

// 52498835 Validate Races; Decline Answer Selected, or are more than one drop down or the only one is not empty
function ValidRaces() {
    // If decline to answer or there are more than one Race Dropdown then is ok
    if ($('#DeclineAnswerChkBox').is(':checked') || $('[id^="' + IniNameRaceDp + '"]').length > 1) {
        return true;
    }
    var valueSelected = "";
    // Only one drop down. Check is not empty selected value
    $('[id^="' + IniNameRaceDp + '"]').each(function () {
        var currentDp = $(this)[0];
        valueSelected = currentDp.options[currentDp.selectedIndex].value;
    });
    return valueSelected != "";
}

// 52498835 
// Add method to Validator for Races validation
jQuery.validator.addMethod("validateRaces", function () {
    return ValidRaces();
});

// 52499051
// Add a Class Rule to say the class "RaceDefaultField" needs to be validated using "validateRaces" method
jQuery.validator.addClassRules("RaceDefaultField", { validateRaces: true });


// 70551316 Ajax Function in synchronous mode (asynchronous: false) to check if selected Relation still in Relation table (updated relation in another PA instance)
// If CheckValid fail set EmergInfoRelation as empty
function CheckValidRelationJson() {
    if ($('#EmergInfoRelation').val() != '') {
        var relationParam = JSON.stringify({ "userIdStr": $('#hdnUserId').val(), "relation": $('#EmergInfoRelation').val() });
        //var relationParam = JSON.stringify({ "userIdStr": $('#hdnUserId').val() });
        $.ajax({
            type: "POST",
            url: "/PatientAccess/Services/RelationService.asmx/CheckValidRelation",
            data: relationParam,
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: false,
            success: function (data) {
                if (!data.d) {
                    RemoveInvalidRelation();
                }
            },
            error: function (error) {
                RemoveInvalidRelation();
            }
        });
    }
}

// 70551316 Clear current selection
function RemoveInvalidRelation() {
    var selectVal = $("#EmergInfoRelation").val();
    $("#EmergInfoRelation option[value='" + selectVal + "']").remove();                         // Remove current selected item
    // if there is not empty first item, add one.
    if ($("#PreferredLanguageDropDown option").eq(0).val() != "")
        $("#EmergInfoRelation").prepend("<option value='' selected='selected'></option>");      // Insert first empty item
    $('#hdnEmergRelation').val("");
}


// 70551316
function ValidEmergRelation() {

    CheckValidRelationJson();       // Ajax function, check Relation exist
    if ($('#EmergInfoRelation').val() == '')
        return false;
    return true;
}

// 70551316
jQuery.validator.addMethod("validateEmergRelation", function () {
    return ValidEmergRelation();
});

// 70551316
function ValidEmergCity() {
    if ($('#hdnValidateEmergAddress').val() == '0')
        return true;

    if ($('#hdnEmergCity').val() == '')
        return false;
    return true;
}
// 70551316
jQuery.validator.addMethod("validateEmergCity", function () {
    return ValidEmergCity();
});

// 70551316
function ValidEmergState() {
    if ($('#hdnValidateEmergAddress').val() == '0')
        return true;
    if ($('#hdnEmergState').val() == '')
        return false;
    return true;
}
// 70551316
jQuery.validator.addMethod("validateEmergState", function () {
    return ValidEmergState();
});


// 66825488
function ValidCity() {
    if ($('#hdnIsEditableZipPostalCode').val() == '0')
        return true;

    if ($('#hdnCity').val() == '')
        return false;

    return true;
}

// 66825488
jQuery.validator.addMethod("validateCity", function () {
    return ValidCity();
});

// 66825488
function ValidCountry() {

    if ($('#hdnIsEditableZipPostalCode').val() == '0')
        return true;

    if ($('#hdnCountry').val() == '')
        return false;

    return true;
}

// 66825488
jQuery.validator.addMethod("validateCountry", function () {
    return ValidCountry();
});

// 66825488
function ValidState() {
    if ($('#hdnIsEditableZipPostalCode').val() == '0')
        return true;

    if ($('#hdnState').val() == '')
        return false;

    return true;
}



// 66825488
jQuery.validator.addMethod("validateState", function () {
    return ValidState();
});

// 42766229
function ValidFirstName() {
    if ($('#hdnIsEditableFirstName').val() == '0')
        return true;
    if ($('#FirstNameTxt').val() == '')
        return false;

    return true;
}
jQuery.validator.addMethod("validateFirstName", function () {
    return ValidFirstName();
});

// 42766229
function ValidLastName() {
    if ($('#hdnIsEditableLastName').val() == '0')
        return true;
    if ($('#LastNameTxt').val() == '')
        return false;

    return true;
}
jQuery.validator.addMethod("validateLastName", function () {
    return ValidLastName();
});



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

// AX-17079 validate if Patient Information change to allow navigate to menu option
function canLeavePatientInfo(redirectUrl, redirectId) {
    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened() || getParentWindow(window).isConfirmWindowOpened())
        return false;

    var formSerialized = $('#FormPat').serialize();
    var different = $('#hdnPatSerial').val() != formSerialized;

    if (different) {
        var confirmHeader = getSettingMessage("hdnSettingLeaveUnsavedPatHeader");
        var confirmMessage = getSettingMessage("hdnSettingLeaveUnsavedPatMessage");
        var cancelButtonText = "No";
        var okButtonText = "Yes";

        getParentWindow(window).createConfirmWindow(confirmHeader, confirmMessage, cancelButtonText, okButtonText,
            function () {
                getParentWindow(window).location.href = redirectId !== '0' ? redirectUrl + redirectId : redirectUrl;    // When in confirm window select Ok continue and lose changes, then redirect
            });

        return false;     // This is trigger first time before even show the confirmWindow, so need to return false.
    }
    return true;      // Nothing to save, then return true

}

// AX-17079 validate if logout is possible (has personal info saved)
function canLeavePatientInfoToLogoutOrAuthor(continueOption) {
    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened() || getParentWindow(window).isConfirmWindowOpened())
        return false;

    var formSerialized = $('#FormPat').serialize();
    var different = $('#hdnPatSerial').val() != formSerialized;

    if (different) {
        var confirmHeader = getSettingMessage("hdnSettingLeaveUnsavedPatHeader");
        var confirmMessage = getSettingMessage("hdnSettingLeaveUnsavedPatMessage");
        var cancelButtonText = "No";
        var okButtonText = "Yes";

        getParentWindow(window).createConfirmWindow(confirmHeader, confirmMessage, cancelButtonText, okButtonText,
            function () {
                var hdnBtn;
                if (continueOption === 1)
                    hdnBtn = jQuery('#logoutIfrmId', window.parent.document).contents().find("#HiddenApplyAuthorBtn");
                else {
                    hdnBtn = jQuery('#logoutIfrmId', window.parent.document).contents().find("#HiddenLogoutBtn");
                }
                hdnBtn.trigger('click');	        // AX-24898.24919.2 hdnBtn.click();
            });

        return false;     // This is trigger first time before even show the confirmWindow, so need to return false.
    }
    return true;      // Nothing to save, then return true

}

// AX-17079.2 Back button, check if pressing browser back button can go back
function checkCanGoBackPatient() {

    var formSerialized = $('#FormPat').serialize();
    var different = $('#hdnPatSerial').val() != formSerialized;

    if (!different) {       // Nothing changed, then go back
        // go back
        if (window.history.length > 0)
            window.history.back();

        return;
    }

    var confirmMessage = getSettingMessage("hdnSettingLeaveUnsavedPatMessage");
    if (confirmMessage) {
        // Use jquery Confirm dialog!
        if (confirm(confirmMessage)) {
            getParentWindow(window).hideSpinner();

            history.back(); // no trigger
            return;
        } else {
            history.pushState(null, null, null);

        }
        return;
    }
}

$(document).ready(function () {
    setAvailabelRacesAsJson();            // 52498835 Set hdnRacesJson variable with all the active races as json

    // 66825488 allows validating hidden fields
    $.validator.setDefaults({
        ignore: []

    });

    if ($('#hdnBirthdateEditable').val() != '1') {
        $('#BirthdayDateControlDiv').find('input,select,button,textarea,a,img').attr('disabled', 'disabled'); //33513979 To disable birthday controls inside div 
        $('#BirthdayDateControlDiv').find('a,img').hide(); //33513979 To disable birthday controls inside div 
    }
    $('input').on('keydown', function (e) {		// AX-24898.24919.2 .keydown(function (e) {
        $('.success').hide(); //33513979 To hide success when user press at input field                                                                              
    });
    $('select').on('change', function () {     	// AX-24898.24919.2 .change(function () {
        $('.success').hide();
    });


    // 52499051
    // Preferred Language first dropdown item
    var preferredLangDropDownFirstItem = $("#PreferredLanguageDropDown option").eq(0);

    // 52499051
    // Define change function and blur function for Preferred Language first dropdown item
    $('#PreferredLanguageDropDown').on('change', function () {     	// AX-24898.24919.2 .change(function () {
        if ($('#hdnPrefLangInactive').val() == 'Y' && $("#PreferredLanguageDropDown option").eq(0).val() == $('#hdnPrefLangInactiveValue').val())
            preferredLangDropDownFirstItem.remove();
    }).on('blur', function () {			// AX-24898.24919.2 .blur(function() {       // At blur function check if invalid was selected and display error
        if (!ValidLanguage())
            $('#PreferredLanguageDropDownImgError').removeClass('imgErrorHide').addClass('imgErrorShow');
    });


    // 52499005
    // Define change function and blur function for Ethnicity first dropdown item
    $('#EthnicityDropDown').on('change', function () {     	// AX-24898.24919.2 .change(function () {
        if ($('#hdnEthnicityInactive').val() == 'Y' && $("#EthnicityDropDown option").eq(0).val() == $('#hdnEthnicityInactiveValue').val())
            $("#EthnicityDropDown option").eq(0).remove();
    }).on('blur', function () {			// AX-24898.24919.2 .blur(function() {       // At blur function check if invalid was selected and display error
        if (!ValidEthnicity())
            $('#EthnicityDropDownImgError').removeClass('imgErrorHide').addClass('imgErrorShow');
    });

    $('#FormPat').validate({
        onkeyup: function () { return false; },      //39647133 Don't validate when type in field 
        onfocusout: function (element) {            // 73341708 OnBlur is not always trigger, having phone1, phone2 fields clear one of then and error is nor raised
            $(element).valid();
        },
        errorPlacement: function () {
            return true;                            // Override error placement to not show error message beside element. Instead use highligth and unhighlight functions
        },
        rules: {    //39647133 Define rules for Phone Numbers setting special validation function
            FirstNameTxt: { validateFirstName: true }, // 42766229
            LastNameTxt: { validateLastName: true }, // 42766229
            HomePhoneCode: { validatePhoneNumbers: true },
            HomePhone1: { validatePhoneNumbers: true },
            HomePhone2: { validatePhoneNumbers: true },
            WorkPhoneCode: { validatePhoneNumbers: true },
            WorkPhone1: { validatePhoneNumbers: true },
            WorkPhone2: { validatePhoneNumbers: true },
            WorkPhoneExt: { validatePhoneNumbers: true }, // 73341708
            OtherPhoneCode: { validatePhoneNumbers: true },
            OtherPhone1: { validatePhoneNumbers: true },
            OtherPhone2: { validatePhoneNumbers: true },
            OtherPhoneExt: { validatePhoneNumbers: true }, // 73341708
            MobilePhoneCode: { validatePhoneNumbers: true },
            MobilePhone1: { validatePhoneNumbers: true },
            MobilePhone2: { validatePhoneNumbers: true },
            TitleDropDown: { validateTitle: true },
            PreferredLanguageDropDown: { validatePreferredLang: true },
            EthnicityDropDown: { validateEthnicity: true },
            CustomCode1: { validateCustomCode1: true },
            CustomCode2: { validateCustomCode2: true },
            CustomCode3: { validateCustomCode3: true },
            CustomCode4: { validateCustomCode4: true },
            CustomCode5: { validateCustomCode5: true },
            CustomCode6: { validateCustomCode6: true },
            CustomCode7: { validateCustomCode7: true },
            CustomCode8: { validateCustomCode8: true },
            CustomCode9: { validateCustomCode9: true },
            CustomCode10: { validateCustomCode10: true },

            CustomCode27: { validateCustomCode27: true },
            CustomCode28: { validateCustomCode28: true },
            CustomCode29: { validateCustomCode29: true },
            CustomCode30: { validateCustomCode30: true },
            CustomCode31: { validateCustomCode31: true },
            hdnCity: { validateCity: true },
            CityDropDown: { validateCity: true },
            hdnState: { validateState: true },
            hdnCountry: { validateCountry: true },
            hdnEmergCity: { validateEmergCity: true }, // 70551316
            EmergCityDpDiv: { validateEmergCity: true }, // 70551316
            hdnEmergState: { validateEmergState: true }, // 70551316
            EmergInfoPhoneCode: { validateEmergPhoneNumbers: true }, // 70551316
            EmergInfoPhone1: { validateEmergPhoneNumbers: true }, // 70551316
            EmergInfoPhone2: { validateEmergPhoneNumbers: true }, // 70551316
            EmergInfoPhoneExt: { validateEmergPhoneNumbers: true }, // 73341708
            EmergInfoAlternativePhoneCode: { validateEmergPhoneNumbers: true }, // 70551316
            EmergInfoAlternativePhone1: { validateEmergPhoneNumbers: true }, // 70551316
            EmergInfoAlternativePhone2: { validateEmergPhoneNumbers: true }, // 70551316
            EmergInfoAlternativePhoneExt: { validateEmergPhoneNumbers: true }, // 73341708
            EmergInfoRelation: { validateEmergRelation: true }
        },
        groups: {   //39647133 Define group fields
            homePhoneGroup: "HomePhoneCode HomePhone1 HomePhone2",
            workPhoneGroup: "WorkPhoneCode WorkPhone1 WorkPhone2 WorkPhoneExt",
            otherPhoneGroup: "OtherPhoneCode OtherPhone1 OtherPhone2 OtherPhoneExt",
            mobilePhoneGroup: "MobilePhoneCode MobilePhone1 MobilePhone2",
            emergPhoneGroup: "EmergInfoPhoneCode EmergInfoPhone1 EmergInfoPhone2 EmergInfoPhoneExt", // 70551316
            emergAltPhoneGroup: "EmergInfoAlternativePhoneCode EmergInfoAlternativePhone1 EmergInfoAlternativePhone2 EmergInfoAlternativePhoneExt" // 70551316
        },
        highlight: function (element) {
            var imgId = element.id + 'ImgError'; // Id of Image error 'must' be same as TextBox field + 'ImgError'
            if (element.id.indexOf('Phone') >= 0) {
                imgId = element.id.substr(0, element.id.indexOf('Phone') + 5) + 'ImgError';
            }

            if (element.id.indexOf(IniNameRaceDp) >= 0) {
                imgId = 'RaceImgError';
            }
            if (element.id.indexOf('DQ37297') >= 0) { // DatePicker use 37297 as Id of Calender control   // 69492898 Change id to begin with letter than only numbers
                imgId = 'BirthdayDateCImgError';
            }

            // 66825488
            if (element.id == 'hdnCity') {
                imgId = 'CityImgError';
            }
            if (element.id == 'hdnState') {
                imgId = 'StateDropDownImageError';
            }
            if (element.id == 'hdnCountry') {
                imgId = 'CountryDropDownImageError';
            }

            // 70551316
            if (element.id == 'hdnEmergCity') {
                imgId = 'EmergInfoCityImgError';
            }
            // 70551316
            if (element.id == 'hdnEmergState') {
                imgId = 'EmergInfoStateImgError';
            }

            var imgCtrl = $(element.form).find('img[id=' + imgId + ']');
            imgCtrl.addClass('imgErrorShow').removeClass('imgErrorHide');
        },
        unhighlight: function (element) {
            var imgId = element.id + 'ImgError'; // Name of Image error 'must' be same as input field + 'ImgError'
            if (element.id.indexOf('Phone') >= 0) {
                imgId = element.id.substr(0, element.id.indexOf('Phone') + 5) + 'ImgError';
            }
            if (element.id.indexOf(IniNameRaceDp) >= 0) {
                imgId = 'RaceImgError';
            }
            if (element.id.indexOf('DQ37297') >= 0) { // DatePicker use 37297 as Id of Calender control  // 69492898 Change id to begin with letter than only numbers
                imgId = 'BirthdayDateCImgError';
            }

            // 66825488
            if (element.id == 'hdnCity') {
                imgId = 'CityImgError';
            }
            if (element.id == 'hdnState') {
                imgId = 'StateDropDownImageError';
            }
            if (element.id == 'hdnCountry') {
                imgId = 'CountryDropDownImageError';
            }

            // 70551316
            if (element.id == 'hdnEmergCity') {
                imgId = 'EmergInfoCityImgError';
            }
            // 70551316
            if (element.id == 'hdnEmergState') {
                imgId = 'EmergInfoStateImgError';
            }

            var imgCtrl = $(element.form).find('img[id=' + imgId + ']');
            imgCtrl.removeClass('imgErrorShow').addClass('imgErrorHide');
        }
    });


    // AX-17079
    var formSerialize = $('#FormPat').serialize();
    $('#hdnPatSerial').val(formSerialize);
});
