//active page is listed here: meta[name='activeURL']
var whereAreWe = window.location.href;
var stringLoc = whereAreWe;
$("meta[name='url:location']").attr("content", stringLoc);

//this check is to prevent users from pasting values which may contain illegal characters
$('#beneNameFirst, #beneMiddleInitial, #beneNameLast, #beneNameFirst2, #beneMiddleInitial2, #beneNameLast2,#acctName,#repFullName,#careFirstName,#careLastName').on("paste", function (e) {
    var $this = $(this);
    setTimeout(function () {
        var val = $this.val(),
            regex = /^[A-Za-z0-9\s'_.-]+$/;
        //regex = '[\s\da-zA-Z]*$';
        if (regex.test(val)) {
            $this.val(val);
        }
        else {
            $this.val('');
        }
    }, 0);

});

//this check is to prevent users from pasting values which may contain illegal characters
$('#mbiNum,#acctNum').on("paste", function (e) {
    var $this = $(this);
    setTimeout(function () {
        var val = $this.val(),
            regex = /^[A-Za-z0-9]+$/;
        if (regex.test(val)) {
            $this.val(val);
        }
        else {
            $this.val('');
        }
    }, 0);

});

//this check is to prevent users from pasting values which may contain illegal characters
$('#repAddress,#repApt,#address1,#address2,#address3,#address4').on("paste", function (e) {
    var $this = $(this);
    setTimeout(function () {
        var val = $this.val(),
            //AlphaNumeric, "/" , " ", "-"
            regex = /^[A-Za-z0-9\s-]+$/;
        if (regex.test(val)) {
            $this.val(val);
        }
        else {
            $this.val('');
        }
    }, 0);

});

//this check is to prevent users from pasting values which may contain illegal characters
$('#repCity,#city,#city2,#county').on("paste", function (e) {
    var $this = $(this);
    setTimeout(function () {
        var val = $this.val(),
            //Alpha, " "
            regex = /^[A-Za-z\s]+$/;
        if (regex.test(val)) {
            $this.val(val);
        }
        else {
            $this.val('');
        }
    }, 0);

});

//this check is to prevent users from pasting values which may contain illegal characters
$('#Institution,#planName,#RxGroup,#RxID,#planName2,#RxGroup2,#RxID2,#RxBin,#RxPCN,#RxBin2,#RxPCN2').on("paste", function (e) {
    var $this = $(this);
    setTimeout(function () {
        var val = $this.val(),
            //AlphaNumeric, "." , " ", "-"
            regex = /^[A-Za-z0-9\s.-]+$/;
        if (regex.test(val)) {
            $this.val(val);
        }
        else {
            $this.val('');
        }
    }, 0);

});

//this check is to prevent users from pasting values which may contain illegal characters
$('#repEmail,#repConfEmail,#careEmail,#careEmailConf,#email3,#email3Confirm,#eobemail,#eobemailConfirm').on("paste", function (e) {
    var $this = $(this);
    setTimeout(function () {
        var val = $this.val(),
            //AlphaNumeric, ".", "-", "@", "_"
            regex = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        if (regex.test(val)) {
            $this.val(val);
        }
        else {
            $this.val('');
        }
    }, 0);

});


//this check is to prevent users from pasting values which may contain illegal characters
$(document).on("paste", "input[name*='zip'], input[name*='Zip'], input[name*='ZIP'], input[name*='postal']", function (e) {
    var $this = $(this);
    setTimeout(function () {
        var val = $this.val(),
            //AlphaNumeric, ".", "-", "@", "_"
            regex = /^[0-9]+$/;
        if (regex.test(val)) {
            $this.val(val);
        }
        else {
            $this.val('');
        }
    }, 0);

});


///all regEx (except email and phone)
///    Added field "repApt"
///              "0"       "1"             "2"       "3"           "4"          "5"          "6"           "7"         "8"        "9"           "10"        "11"        "12"         "13"      "14"      "15"      "16"     "17"       "18"    "19"         "20"            "21"            "22"        "23"  "24"   "25"     "26"     "27"       "28"      "29"
var ckRegEx = ["city", "middleinitial", "email", "institution", "namefirst", "firstname", "first_name", "namelast", "lastname", "last_name", "medinum", "planname", "repzipcode", "postal", "address", "rxbin", "rxpcn", "rxgroup", "rxid", "address2", "first_name_er", "last_name_er", "fullname", "care", "zip", "postal", "apt", "acctname", "acctnum", "routnum"];


$(document).on("keyup", "input[type='text']", function () {
    //debugger;
    var whichId = $(this).attr("id");
    var whichInput = $(this).attr("name");
    if (whichInput != null && whichInput != 'undefined')
        whichInput = whichInput.toString().toLowerCase();

    var txtInput = $(this).val();
    var maxLength = $(this).attr("maxlength");
    txtInput = txtInput.substring(0, maxLength); //max characters
    var regEx = "";

    var passThrough = true;
    //JT - removing the console logs from the below person
    function runRegEx(i) {

        // if (i == "2" || i == "23" || i == "12" || i == "10" ) {//9
        if (i == "2" || i == "23" || i == "10") { //9       
            passThrough = false;
            return false;
        } //end 2"email"  , 23 "care", 12 "repZipCode"
        //---Removing middleinitial i=1 has same validate as first name
        if (i == "0") { //1          
            regEx = /^[a-zA-Z\s-.]*$/;
        } //end 0"city", 1"middleinitial"
        if (i == "14" || i == "26") { //2           
            regEx = /^[a-zA-Z0-9\s-/ ]+$/;
        } //end 14"address"
        if (i == "19") { //3       
            regEx = /^[a-zA-Z0-9-\/ ]+$/;
        } //end 19"address2"
        if (i == "2" || i == "11") { //4    
            regEx = /^[a-zA-Z0-9.\-\ ]+$/;
        } //end 3"institution", 11 "planname"
        if (i == "4" || i == "5" || i == "6" || i == "20" || i == "22" || i == "1") { //5           
            if (whichInput != 'ctl00$maincontent$carefirstname')
                regEx = /^[A-Za-z0-9\s'"_-]+$/;
        } //end  4"namefirst", 5"firstname", 6"first_name", 20 "first_name_er", 22 "fullname"
        //----removed i=10 b/c medicare number in prod expecting all char
        if (i == "7" || i == "8" || i == "9" || i == "15" || i == "16" || i == "21") { //6            
            regEx = /^[a-zA-Z0-9]+$/;
        } //end 7"namelast", 8"lastname", 9"last_name", 10"medinum",  15 "rxbin", 16 "rxpcn", 21 "last_name_er"
        //  || i == "27" || i == "28" || i == "29"
        // 02/08/2018 reference to the Task- 13380 -Rs removewd i=28 for not allowing alphabets in Account number 
        if (i == "17" || i == "18" || i == "3" || i == "27") { //7              
            regEx = /^[a-zA-Z0-9\s-.]+$/;
        } //end 17 "rxgroup", 18"rxid" // 02/08/2018 reference to the Task- 13380 added i==29 in the below line -Rs
        if (i == "24" || i == "13" || i == "25" || i == "30" || i == "12" || i == "28" || i == "29") { //8          
            regEx = /^[0-9]+$/;
        } //end 24"zip", 13"postal",29 "routnum",28"Accountnum"


        txtLength = txtInput.length;
        txtLength = parseInt(txtLength);

        if (txtInput.match(regEx) != null && passThrough == true) { //validate char allowed
            console.log("char allowed");

        } //end if
        if (txtInput.match(regEx) == null && passThrough == true) { //validate char not allowed
            console.log("CHAR NOT ALLOWED! - " + whichId);

            var newVal = txtInput.substring(0, txtLength - 1); //take out bad characters
            $("#" + whichId).val(newVal);
        } //end else

        return false;
    } //end runRegEx

    $(ckRegEx).each(function (i) { //check to see if this is to be validated here
        if (whichInput != null && whichInput != 'undefined') {
            if (whichInput.indexOf(ckRegEx[i]) != -1) {
                runRegEx(i);
            } //end if
        }
    }); //end each

    return false;

}); //end keyup  


(function ($) {

    $(document).ready(function () {

        if ($('#paymentOptions').length) {
            managePaymentOptions();
        }

        $(".accordion-group").click(function (e) {
            e.preventDefault();
            var button$ = $(this);
            var content$ = $("#" + button$.attr("aria-controls"));
            var groupId = button$.closest('.accordion-group').attr('id');
            var contentExpanded = (button$.attr('aria-expanded') == "true");

            //$("#" + groupId + " .accordion-button").attr("aria-expanded",false);
            //$("#" + groupId + " .accordion-content").attr("aria-hidden",true);

            button$.attr('aria-expanded', !contentExpanded);
            content$.attr('aria-hidden', contentExpanded);
        });

        ///////
        // Hide Stuff
        ///////
        $(".curtainSelect, .overlayWrap, .details > .planCosts, .details > .priceTable, .details > .priceTableforCatastrophic, #rep, #railroad, #password, #dvInstitution, #mailingAddress, .otherCover, .otherCover2, #zips, #contactInfo").hide();

        ///////
        // Increase/Decrease Text Size Functions
        ///////
        function alterLi(textpos) { // the line items need to grow with the text size
            textpos = parseInt(textpos);
            setTimeout(function () {
                if (textpos <= 1) { }

                if (textpos > 1) {

                }

            }, 350);

        } //end alterLi

        var font_size = readCookie('fontSize');

        if (font_size <= 100) {
            textpos = 1;
            alterLi(textpos);
        }

        if (font_size > 100) {
            textpos = 2;
            alterLi(textpos);
        }

        setDefaultFontSize();
        $('#minus').click(function () {
            changeFontsize(-1);
            textpos--
            if (textpos < 1) {
                textpos = 1;
            }
            alterLi(textpos);
        });
        $('#plus').click(function () {
            changeFontsize(1);
            textpos++
            if (textpos > 3) {
                textpos = 3;
            }
            alterLi(textpos);
        });

        ///////
        // Top Nav DropDowns
        ///////
        $('.pharmLocator').hover(
            function () {
                $('#pharmNavTool').show();
            },
            function () {
                $('#pharmNavTool').hide();
            }
        );
        $('.drugSearch').hover(
            function () {
                $('#drugNavTool').show();
            },
            function () {
                $('#drugNavTool').hide();
            }
        );
        $('.enrollRemind').hover(
            function () {
                $('#enrollNavTool').show();
            },
            function () {
                $('#enrollNavTool').hide();
            }
        );

        // start enroll page
        $('#imgAltTagCard').hover(
            function () {
                $('#ulAltTagCard').show();
            },
            function () {
                $('#ulAltTagCard').hide();
            }
        );
        $('#imgAltTagList').hover(
            function () {
                $('#ulAltTagList').show();
            },
            function () {
                $('#ulAltTagList').hide();
            }
        );

        $('#imgAltTagTime').hover(
            function () {
                $('#ulAltTagTime').show();
            },
            function () {
                $('#ulAltTagTime').hide();
            }
        );
        ///////
        // Input Masking
        ///////       
        $("#phoneNum, .phone").mask("(999)-999-9999");
        $("#mobileNum").mask("(999)-999-9999");
        //$("#ddlDOBMonth, #ddlDOBDay").mask("99");
        $("#emailremainddlDOBMonth, #emailremainddlDOBDay").mask("99");
        $('#bdPick, #bdPick2, .datePick, #datePick2, #bdPick3, .personalInfoDatePick, .datePickTermEffective, .datePickEnrollmentOption').mask('99/99/9999');

        // Form Validation (Home Page)

        var zipCodeValue = "";


        $('#zipHome, #zipHomeCompareMenu').attr("placeholder", "").css('color', '#d1d1d1');

        if ($('#zipHomePremiumSummary').val() == "")
            $('#zipHomePremiumSummary').attr("placeholder", "").css('color', '#d1d1d1');

        if ($('#zipHomePremiumSummary').val() != "")
            $('#zipHomePremiumSummary').css('color', '#555555');

        $('#zipHome, #zipHomeCompareMenu').on('focus', function () {
            if (($(this).val() == "") || ($(this).val() == ""))
                $(this).val('').css('color', '#555555');
            else
                $(this).css('color', '#555555');
        });

        $('#zipHome, #zipHomeCompareMenu').on('blur', function () {
            if ($(this).val() != "" && $(this).val() != "")
                zipCodeValue = $(this).val();
            else {
                if ($(this).val() == "")
                    $(this).attr("placeholder", "").css('color', '#d1d1d1'); //$(this).val('ex. 94110').css('color', '#d1d1d1');
                zipCodeValue = "";
            }
        });

        $('#zipHomePremiumSummary').on('blur', function () {
            if ($(this).val() != "" && $(this).val() != "")
                zipCodeValue = $(this).val();
            else {
                if ($(this).val() == "")
                    $(this).attr("placeholder", "").css('color', '#d1d1d1'); // $(this).val('ex. 94110').css('color', '#d1d1d1');
                zipCodeValue = "";
            }
        });

        if ($('#emailremainddlDOBMonth').val() == "")
            $('#emailremainddlDOBMonth').val('mm');

        if ($('#emailremainddlDOBDay').val() == "")
            $('#emailremainddlDOBDay').val('dd');


        $('#emailremainddlDOBMonth').on('blur', function () {
            if ($(this).val() != "" && $(this).val() != "mm") {
                //continue
            }
            else {
                if ($(this).val() == "")
                    $(this).val('mm');
            }
        });

        $('#emailremainddlDOBDay').on('blur', function () {
            if ($(this).val() != "" && $(this).val() != "dd") {
                //continue
            }
            else {
                if ($(this).val() == "")
                    $(this).val('dd');
            }
        });

        //Cancel Click
        $("#lnkCancel").click(function () {
            var confirmation = window.confirm("Do you want to exit the Enrollment process ? ");
            if (confirmation)
                return true;
            else
                return false;
        });

        //Main Master Page Menu Compare Link
        var errorRegion = "",
            formularySearch = false,
            pricingTool = false;

        ///////
        // formularySearch
        ///////   
        $('[data-visit="pricingTool"]').click(function (e) {
            var sessionValue = $('#sessionInput').val();
            formularySearch = false, pricingTool = false;
            if (sessionValue != "") {
                overlay.classList.add("is-hidden");
                if ($(this).attr('id') == 'subPricingTool' || $(this).attr('id') == 'subPricingTool1' || $(this).attr('data-visit') == 'pricingTool')
                    pricingTool = true;
                else
                    formularySearch = true;

                RedirectToJavaTool();
            } else {
                if ($(this).attr('id') == 'subPricingTool' || $(this).attr('id') == 'subPricingTool1' || $(this).attr('data-visit') == 'pricingTool')
                    pricingTool = true;
                else
                    formularySearch = true;
                resetFancyBox("#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#divStatesCompareMenu,#zipErrorCompareMenu,#errorRegionShowPlanCompareMenu");
                overlay.classList.remove("is-hidden");
                $("#zipHomeCompareMenu").focus();
            }
        });

        $('.formularyZipSearch, #subPricingTool, #subPricingTool1').click(function (e) {
            var sessionValue = $('#sessionInput').val();
            formularySearch = false, pricingTool = false;
            if (sessionValue != "") {
                $.fancybox.close();
                if ($(this).attr('id') == 'subPricingTool' || $(this).attr('id') == 'subPricingTool1' || $(this).attr('data-visit') == 'pricingTool')
                    pricingTool = true;
                else
                    formularySearch = true;

                RedirectToJavaTool();
            }
            else {
                if ($(this).attr('id') == 'subPricingTool' || $(this).attr('id') == 'subPricingTool1' || $(this).attr('data-visit') == 'pricingTool')
                    pricingTool = true;
                else
                    formularySearch = true;
                $.fancybox.open(
                    {
                        src: '#zipCompareMenu',
                        type: 'inline',
                        opts:
                        {
                            beforeLoad: function () {
                                resetFancyBox("#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#divStatesCompareMenu,#zipErrorCompareMenu,#errorRegionShowPlanCompareMenu");
                            },
                            afterShow: function () {
                                $(".fancybox-close-small").focus();

                                $('.lastFancyBtn').on('keydown', function (e) {
                                    var keyCode = e.keyCode || e.which;
                                    if (keyCode == 9) {
                                        if (!e.shiftKey) {
                                            e.preventDefault();
                                            $(".fancybox-close-small").focus();
                                        }
                                    }
                                });
                                $('.fancybox-close-small').on('keydown', function (e) {
                                    var keyCode = e.keyCode || e.which;
                                    if (keyCode == 9) {
                                        if (e.shiftKey) {
                                            e.preventDefault();
                                            $(".lastFancyBtn").focus();
                                        }
                                        else {
                                            e.preventDefault();
                                            $('.zip-section input').focus();
                                        }
                                    }
                                    if (keyCode == 13) {
                                        $.fancybox.close();
                                    }
                                });
                                $('#zipHomeCompareMenu').on('keydown', function (e) {
                                    var keyCode = e.keyCode || e.which;
                                    if (keyCode == 9) {
                                        if (e.shiftKey) {
                                            e.preventDefault();
                                            $(".fancybox-close-small").focus();
                                        }
                                    }
                                });

                            }
                        }
                    });
            }
        });

        $('#ZipcodeValidate').click(function (e) {
            e.preventDefault();
            var code = $("#zipHomeCompareMenu").val();
            if (code.length != 5 || isNaN(code) == true) {
                SetLabelTextCss("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid ZIP Code.", '#zipCodeCompareMenu', '#zipHomeCompareMenu', '#zipErrorCompareMenu');

                $(".error[for='zipHomeCompareMenu']").each(function () { //added for pricing tool fancy box.
                    $(this).css("display", "block").html("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid ZIP Code.");
                }); //end each
                overlay.classList.remove("is-hidden");
                $("#zipHomeCompareMenu").focus();
                $('.modal-outer').css("padding-top", "56px");
            }
            else {
                var url = "../handlers/zipcodesearch.ashx";
                //Passing the OnPage=true Parameter to resolve the Issue with radio buttons on the Plans Over view page/fancy Box.
                var querystring = "ZipCode=" + code;
                if (formularySearch || (typeof (pageName) != 'undefined' && pageName == 'formularySearch')) {
                    formularySearch = true, pricingTool = false, pageName = '';
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenu,#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#hdZipCodeCompareMenu,#zipErrorCompareMenu,''");
                }
                else if (pricingTool || (typeof (pageName) != 'undefined' && pageName == 'pricingtool')) {
                    formularySearch = false, pricingTool = true, pageName = '';
                    //DT - 05/26/2017 - ITPR019124 Pricing Tool Zip Code:  Add passing the pageName to the CallAjax function
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenu,#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#hdZipCodeCompareMenu,#zipErrorCompareMenu,''", pageName);
                }
                //DT - 03/02/2018 TFS # 135988 Plan Detail Zip Code:  Keep the user on the plan detail page if already there.
                //Note: typeof(pageName) is required to make this work
                else if (!pricingTool && (typeof (pageName) == 'plandetail')) {
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenu,#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#hdZipCodeCompareMenu,#zipErrorCompareMenu,''", pageName);
                }
                else
                    //DT - 05/26/2017 - ITPR019124 Pricing Tool Zip Code:  Add passing the pageName to the CallAjax function
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenu,#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#hdZipCodeCompareMenu,#zipErrorCompareMenu,''");
            }


        });
        function RedirectToJavaTool(data, ctrls) {

            var controls;
            var innerErrorRegion = errorRegion,
                ctrlDivZipCode, ctrlTxtBxZipHome, ctrlLblErrorZipCode, ctrlLblErrorRegionShowPlan;

            if (typeof (ctrls) != "undefined" && ctrls != null && ctrls.indexOf(',') > -1)
                controls = ctrls.split(',')


            if (controls != null && controls.length > 0) {
                ctrlDivZipCode = controls[0];
                ctrlTxtBxZipHome = controls[1];
                ctrlLblErrorZipCode = controls[2];
                ctrlLblErrorRegionShowPlan = controls[3];
            }

            if (innerErrorRegion == "zipSplit" && data == "No Plan") {
                $(ctrlLblErrorRegionShowPlan.replace('#', '.')).show();
                $(ctrlLblErrorRegionShowPlan).html("No Plan Exists");
                return;
            }
            else if (data == "No Plan") {
                SetLabelTextCss("<br/>No Plan Exists", ctrlDivZipCode, ctrlTxtBxZipHome, ctrlLblErrorZipCode);
                return;
            }
            if (typeof (data) != "undefined" && data != "No Plan")
                // setCookie('selectedPlan', 'none');
                setCookie('selectedPlan', 'none', '', '', '.meddweb.net', '');

            if (pricingTool) {
                pricingTool = false;
                /*CSAT Drug pricing Quote- RS 08/01/2018- Instead of redirecting to the Pricing tool page, 
				  as per the new design and new implmentation we are submiting the form. Using the existing genraic
				  form from the main.master*/
                $("#form1").submit();
                //window.location.href = "../pricing-tool.aspx";
            }
            else if (formularySearch) {
                formularySearch = false;
                window.location.href = "../formulary-search.aspx";
            }

        }


        $('#homeEnrollAEP').on("click", function () {
            window.location.href = "../member";
            return false;
        });

        $('#homeEnrollAfterAEP').on("click", function () {
            window.location.href = "../member";
            return false;
        });

        $('[data-visit="comparefutureSitePlans"]').click(function (e) {
            formularySearch = false, pricingTool = false;
            pageName = 'statefutureplancomparemodule';
            var sessionValue = $('#sessionInput').val();
            if (sessionValue != "") {
                $.fancybox.close();
                RedirectToPlanLanding();
            }
            else {
                $.fancybox.open({
                    src: '#zipCompareMenu',
                    type: 'inline',
                    opts: {
                        beforeLoad: function () {
                            resetFancyBox("#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#divStatesCompareMenu,#zipErrorCompareMenu,#errorRegionShowPlanCompareMenu");
                        },
                        afterShow: function () {
                            $(".fancybox-close-small").focus();
                            $('.lastFancyBtn').on('keydown', function (e) {
                                var keyCode = e.keyCode || e.which;
                                if (keyCode == 9) {
                                    if (!e.shiftKey) {
                                        e.preventDefault();
                                        $(".fancybox-close-small").focus();
                                    }
                                }
                            });
                            $('.fancybox-close-small').on('keydown', function (e) {
                                var keyCode = e.keyCode || e.which;
                                if (keyCode == 9) {
                                    if (e.shiftKey) {
                                        e.preventDefault();
                                        $(".lastFancyBtn").focus();
                                    }
                                    else {
                                        e.preventDefault();
                                        $('.zip-section input').focus();
                                    }
                                }
                                if (keyCode == 13) {
                                    $.fancybox.close();
                                }
                            });
                            $('#zipHomeCompareMenu').on('keydown', function (e) {
                                var keyCode = e.keyCode || e.which;
                                if (keyCode == 9) {
                                    if (e.shiftKey) {
                                        e.preventDefault();
                                        $(".fancybox-close-small").focus();
                                    }
                                }
                            });

                        }
                    }
                });
            }
        });

        $('#compareZipHome').click(function (e) {
            pageName = 'statecomparemodule';
            formularySearch = false, pricingTool = false;
            var sessionValue = $('#sessionInput').val();
            $('.modal-outer').css("padding-top", "20px");
            $("#zipErrorCompareMenu").css("display", "none")
            $.ajax(
                {
                    type: "POST",
                    url: "../plan/compare-module.aspx/getsession",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        if (result.d != "") {
                            overlay.classList.add("is-hidden");
                            RedirectToPlanLanding();
                        }
                        else {
                            resetFancyBox("#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#divStatesCompareMenu,#zipErrorCompareMenu,#errorRegionShowPlanCompareMenu");
                            overlay.classList.remove("is-hidden");
                            $("#zipHomeCompareMenu").focus();
                        }
                    }
                });

        });
        ///////
        // Compare Menu
        ///////
        $('#compareZipMaster, #compareZipIndex, #compareZipEnroll, #compareZipMasterSlide, #compareZipMasterSlide_Enroll, #btnTriptychLB').click(function (e) {

            pageName = 'statecomparemodule';

            if (this.id == 'compareZipMasterSlide_Enroll' && $('#compareZipMasterSlide_Enroll').text() == "Enroll in a 2017 plan") {
                window.location.href = "../learn/enroll.aspx";
                return false;
            }
            else {
                e.preventDefault();
                if ($(this).attr('id') == 'compareZipEnroll')
                    e.preventDefault();

                formularySearch = false, pricingTool = false;
                var sessionValue = $('#sessionInput').val();
                $.ajax(
                    {
                        type: "POST",
                        url: "../plan/compare-module.aspx/getsession",
                        data: "{}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (result) {
                            if (result.d != "") {
                                $.fancybox.close();
                                RedirectToPlanLanding();
                            }
                            else {
                                $.fancybox.open(
                                    {
                                        src: '#zipCompareMenu',
                                        type: 'inline',
                                        opts:
                                        {
                                            beforeLoad: function () {
                                                resetFancyBox("#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#divStatesCompareMenu,#zipErrorCompareMenu,#errorRegionShowPlanCompareMenu");
                                            },
                                            afterShow: function () {
                                                $(".fancybox-close-small").focus();

                                                $('.lastFancyBtn').on('keydown', function (e) {
                                                    var keyCode = e.keyCode || e.which;
                                                    if (keyCode == 9) {
                                                        if (!e.shiftKey) {
                                                            e.preventDefault();
                                                            $(".fancybox-close-small").focus();
                                                        }
                                                    }
                                                });

                                                $('.fancybox-close-small').on('keydown', function (e) {
                                                    var keyCode = e.keyCode || e.which;
                                                    if (keyCode == 9) {
                                                        if (e.shiftKey) {
                                                            e.preventDefault();
                                                            $(".lastFancyBtn").focus();
                                                        }
                                                        else {
                                                            e.preventDefault();
                                                            $('.zip-section input').focus();
                                                        }
                                                    }
                                                    if (keyCode == 13) {
                                                        $.fancybox.close();
                                                    }
                                                });

                                                $('#zipHomeCompareMenu').on('keydown', function (e) {
                                                    var keyCode = e.keyCode || e.which;
                                                    if (keyCode == 9) {
                                                        if (e.shiftKey) {
                                                            e.preventDefault();
                                                            $(".fancybox-close-small").focus();
                                                        }
                                                    }
                                                });
                                            }
                                        }
                                    });
                                //alert(x);
                            }
                        }
                    });
            }
        });

        ///////
        // Site Map - Compare Link
        ///////
        $('#compareZipMaster1, #compareZipIndex').click(function (e) {
            formularySearch = false, pricingTool = false;
            var sessionValue = $('#sessionInput').val();
            $.ajax(
                {
                    type: "POST",
                    url: "../plan/compare-module.aspx/getsession",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {


                        if (result.d != "") {
                            $.fancybox.close();

                            RedirectToPlanLanding();
                        }
                        else {
                            $.fancybox.open(
                                {
                                    src: '#zipCompareMenu',
                                    type: 'inline',
                                    opts:
                                    {
                                        beforeLoad: function () {
                                            resetFancyBox("#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#divStatesCompareMenu,#zipErrorCompareMenu,#errorRegionShowPlanCompareMenu");
                                        },
                                        afterShow: function () {
                                            $(".fancybox-close-small").focus();

                                            $('.lastFancyBtn').on('keydown', function (e) {
                                                var keyCode = e.keyCode || e.which;
                                                if (keyCode == 9) {
                                                    if (!e.shiftKey) {
                                                        e.preventDefault();
                                                        $(".fancybox-close-small").focus();
                                                    }
                                                }
                                            });

                                            $('.fancybox-close-small').on('keydown', function (e) {
                                                var keyCode = e.keyCode || e.which;
                                                if (keyCode == 9) {
                                                    if (e.shiftKey) {
                                                        e.preventDefault();
                                                        $(".lastFancyBtn").focus();
                                                    }
                                                    else {
                                                        e.preventDefault();
                                                        $('.zip-section input').focus();
                                                    }
                                                }
                                                if (keyCode == 13) {
                                                    $.fancybox.close();
                                                }
                                            });

                                            $('#zipHomeCompareMenu').on('keydown', function (e) {
                                                var keyCode = e.keyCode || e.which;
                                                if (keyCode == 9) {
                                                    if (e.shiftKey) {
                                                        e.preventDefault();
                                                        $(".fancybox-close-small").focus();
                                                    }
                                                }
                                            });
                                        }
                                    }
                                });
                        }
                    }
                });
        });

        ///////
        // Site Map - Compare Landing Link
        ///////
        $('#comparePriorSitePlans').click(function (e) {
            formularySearch = false, pricingTool = false;
            pageName = 'statepriorplancomparemodule';
            var sessionValue = $('#sessionInput').val();
            if (sessionValue != "") {
                $.fancybox.close();
                RedirectToPlanLanding();
            }
            else {
                $.fancybox.open({
                    src: '#zipCompareMenu',
                    type: 'inline',
                    opts: {
                        beforeLoad: function () {
                            resetFancyBox("#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#divStatesCompareMenu,#zipErrorCompareMenu,#errorRegionShowPlanCompareMenu");
                        },
                        afterShow: function () {
                            $(".fancybox-close-small").focus();
                            $('.lastFancyBtn').on('keydown', function (e) {
                                var keyCode = e.keyCode || e.which;
                                if (keyCode == 9) {
                                    if (!e.shiftKey) {
                                        e.preventDefault();
                                        $(".fancybox-close-small").focus();
                                    }
                                }
                            });
                            $('.fancybox-close-small').on('keydown', function (e) {
                                var keyCode = e.keyCode || e.which;
                                if (keyCode == 9) {
                                    if (e.shiftKey) {
                                        e.preventDefault();
                                        $(".lastFancyBtn").focus();
                                    }
                                    else {
                                        e.preventDefault();
                                        $('.zip-section input').focus();
                                    }
                                }
                                if (keyCode == 13) {
                                    $.fancybox.close();
                                }
                            });
                            $('#zipHomeCompareMenu').on('keydown', function (e) {
                                var keyCode = e.keyCode || e.which;
                                if (keyCode == 9) {
                                    if (e.shiftKey) {
                                        e.preventDefault();
                                        $(".fancybox-close-small").focus();
                                    }
                                }
                            });

                        }
                    }
                });
            }
        });

        var eobflag;

        //BD: display and hide div based on whether eEOB is yes or No respectively on submit-application.aspx reload 
        if ($('#eEOBYes').is(':checked')) {

            $('#EOBemailField').show();
            $('#EOBemaildisclaimer').show();
            eobflag = 1;
        }

        if ($('#eEOBNo').is(':checked')) {

            $('#EOBemailField').hide();
            $('#EOBemaildisclaimer').hide();
            eobflag = 0;
        }
        //BD: Email Eob-opt in changes
        $('#eEOB input[type="checkbox"]').on('click', function () {
            // $("#lblPreferenceMsg").hide();
            if ($('#eEOBYes').is(':checked')) {

                $('#EOBemailField').show();
                $('#EOBemaildisclaimer').show();
                eobflag = 1;
            }
            else {
                $('#EOBemailField').hide();
                $('#EOBemaildisclaimer').hide();
                eobflag = 0;
            }
        });


        //BD: Email Eob-opt in changes
        //$("#eobemail").bind("keyup", function (event) {
        //    $('#lblEOBemailAddressErrorMSg').hide();
        //    $('#lbleobEmailAddressValid').show();
        //});

        //$('#cbxIAgree').click(function () {

        //    $('#cbxIAgree').removeClass("error");

        //    if ($('#cbxIAgree').is(":checked")) {
        //        $('#lblSummaryMsg').hide();
        //        //$('#cbxIAgree').css('outline', 'none');
        //    }
        //});

        $('.eEOB').on('change', function () {
            var checked = $('input[name="EOB"]:checked').val();
            //console.log(checked);
            if (checked = "yes") {

                $('#eEOBYes').next().attr('class', '');
                //$('#eEOBNo').next().attr('class', '');
                // $('#lblPreferenceMsg').hide();
            }
            //else {
            //    $('#eEOBNo').next().attr('class', 'label-radio-error');
            //    $('#eEOBYes').next().attr('class', 'label-radio-error');
            //    $('#lblPreferenceMsg').html('Please select an option for paperless setting');
            //    $('#lblPreferenceMsg').show();
            //    $('#eEOBYes').focus();
            //}
        });

        function validateSummaryInfo(formId, checkIAgree, sendTealiumData) {
            var errorList = [];
            var isValid = true

            var eEOB = $('input[name="EOB"]:checked').val();

            //if (typeof (eEOB) != "undefined" && (eEOB == "yes" || eEOB == "no")) {
            //    $('#eEOBYes').next().attr('class', '');
            //    $('#eEOBNo').next().attr('class', '');
            //    $('#lblPreferenceMsg').hide();
            //    $('#eEOBYes').focus();
            //} else if (typeof (eEOB) == "undefined") {
            //    $('#eEOBNo').next().attr('class', 'label-radio-error');
            //    $('#eEOBYes').next().attr('class', 'label-radio-error');
            //    $('#lblPreferenceMsg').html('Please select an option for paperless setting');
            //    $('#lblPreferenceMsg').show();
            //    isValid = false;
            //    addValidationError("eEOBYes", "Please select an option for paperless setting", errorList)
            //}

            //if (eEOB == "no") {
            //    $('#eobemail').next().attr('class', '');
            //}

            if (eobflag) {
                if (($('#eEOBYes').val() == "true") && ($('#eobemail').val().length < 1)) {
                    $('#lblEOBemailAddressErrorMSg').html('Enter an email address, for example: address@mail.com');
                    $('#lblEOBemailAddressErrorMSg').show();
                    $('#lblEmailAddressValidConfirm').hide();
                    $('#lbleobEmailAddressValid').hide();
                    $('#eobemail').attr('class', 'error long');
                    //$('#eobemailConfirm').attr('class', 'long');
                    addValidationError("eobemail", "Enter an email address, for example: address@mail.com", errorList)
                    isValid = false;
                }
                else {
                    $('#blah').valid();
                    if (($('#eEOBYes').val() == "true") && ($('#eobemail').val().length > 1)) {
                        var email = $.trim($('#eobemail').val()).toLowerCase();
                        //var confemail = $.trim($('#eobemailConfirm').val()).toLowerCase();
                        var emailRegExp = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
                        if (email && !emailRegExp.test(email)) {

                            $('#eobemail').attr('class', 'error long');
                            $('#lblEOBemailAddressErrorMSg').html('Enter an email address, for example: address@mail.com');
                            $('#lblEOBemailAddressErrorMSg').show();
                            isValid = false;
                            addValidationError("eobemail", "Enter an email address, for example: address@mail.com", errorList)
                        } else {
                            $('#eobemail').attr('class', 'long');
                            $('#lblEOBemailAddressErrorMSg').hide();
                        }
                    }
                }
            }

            if (checkIAgree) {
                if (!$('#cbxIAgree').is(":checked")) {
                    $('#cbxIAgree').addClass("error");
                    $('#lblSummaryMsg').html('Accept the terms and conditions before submitting the application');
                    $('#lblSummaryMsg').show();
                    isValid = false;
                    addValidationError("cbxIAgree", "Accept the terms and conditions before submitting the application", errorList)
                } else {
                    $('#lblSummaryMsg').hide();
                }
            } else {
                $('#cbxIAgree').removeClass("error");
                $('#lblSummaryMsg').hide();
            }

            if (!isValid) {
                ShowValidationSummaryWithTitle(errorList, formId, "", false)
            }

            if (sendTealiumData) {
                //JT-8/21/2018-method added for appending all errors generated on the page for tealium
                var errors = "";
                var elements = document.getElementsByClassName('error');
                for (var i = 0, len = elements.length; i < len; i++) {
                    if (elements[i].style.display === 'block')
                        errors += elements[i].innerText.trim() + '|';
                }
                if (errors != '')
                    TealiumNotifyErrors_OnClick(errors);
                //end of tealium
            }

            return isValid;
        }

        $('#btnSummarySubmitButton').click(function (e) {
            var ret = validateSummaryInfo(this.form.id, true, true);
            if (!ret) {
                e.preventDefault();
            }
        });

        $('#btnSaveSummaryInfo').click(function (e) {
            var ret = validateSummaryInfo(this.form.id, false, false);
            if (!ret) {
                e.preventDefault();
            }
        });


        //RS - 02/20/2018 -Reference to Task 135623, EOB OPT-->Save my Application for later
        function setErrorClasse() {
            $('#lblEOBemailAddressErrorMSg').html('<i class="fa fa-exclamation-triangle"></i> ' + ' Please enter the Email Address');
            $('#lbleobEmailAddressValid').hide();
            $('#eobemail').attr('class', 'error long');
            $('#eobemailConfirm').attr('class', 'long');
            $('#eobemail').focus();
        }


        $('#closeTandC').click(function (e) {
            $.fancybox.close();
        });

        function resetFancyBox(ctrls) {
            if (typeof (ctrls) != "undefined" && ctrls.indexOf(',') > -1) {
                var controls = ctrls.split(',');
                if (controls != null && controls.length > 0) {
                    var control1 = controls[0];
                    var control2 = controls[1];
                    var control3 = controls[2];
                    var control4 = controls[3];
                    var control5 = controls[4];
                    var control6 = controls[5];
                    $(control1).show();
                    $(control2).hide();
                    $(control4).html("");
                    $(control3).attr('class', '');
                    $(control5).html("");
                    $(control6).html("");
                }
            }
        }
        function resetHomeFancyBox(ctrls) {
            if (typeof (ctrls) != "undefined" && ctrls.indexOf(',') > -1) {
                var controls = ctrls.split(',');
                if (controls != null && controls.length > 0) {
                    var control1 = controls[0];
                    var control2 = controls[1];
                    var control3 = controls[2];
                    var control4 = controls[3];
                    var control5 = controls[4];
                    var control6 = controls[5];
                    $(control1).show();
                    $(control2).hide();
                    $(control4).html("");
                    $(control3).attr('class', '');
                    $(control5).html("");
                    $(control6).html("");
                }
            }
        }


        $('#btnShowPlanCompareMenu').click(function (e) {
            e.preventDefault();
            var code = $("#zipHomeCompareMenu").val();

            if (code.length != 5 || isNaN(code) == true) {
                SetLabelTextCss("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid ZIP Code.", '#zipCodeCompareMenu', '#zipHomeCompareMenu', '#zipErrorCompareMenu');

                $(".error[for='zipHomeCompareMenu']").each(function () { //added for pricing tool fancy box.
                    $(this).css("display", "block").html("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid ZIP Code.");
                }); //end each

            }
            else {
                var url = "../handlers/zipcodesearch.ashx";
                if ($("#planYear") != undefined && $("#planYear").val() !== undefined) {
                    var planyear = $("#planYear").val()
                    var url = window.location.pathname
                    if (url.indexOf(planyear) > -1) {
                        url = "../../handlers/zipcodesearch.ashx";
                    }
                }
                //Passing the OnPage=true Parameter to resolve the Issue with radio buttons on the Plans Over view page/fancy Box.
                var querystring = "ZipCode=" + code;
                if (formularySearch || (typeof (pageName) != 'undefined' && pageName == 'formularySearch')) {
                    formularySearch = true, pricingTool = false, pageName = '';
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenu,#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#hdZipCodeCompareMenu,#zipErrorCompareMenu,''");
                }
                else if (pricingTool || (typeof (pageName) != 'undefined' && pageName == 'pricingtool')) {
                    formularySearch = false, pricingTool = true, pageName = '';
                    //DT - 05/26/2017 - ITPR019124 Pricing Tool Zip Code:  Add passing the pageName to the CallAjax function
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenu,#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#hdZipCodeCompareMenu,#zipErrorCompareMenu,''", pageName);
                }
                //DT - 03/02/2018 TFS # 135988 Plan Detail Zip Code:  Keep the user on the plan detail page if already there.
                //Note: typeof(pageName) is required to make this work
                else if (!pricingTool && (typeof (pageName) == 'plandetail')) {
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenu,#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#hdZipCodeCompareMenu,#zipErrorCompareMenu,''", pageName);
                }
                else
                    //DT - 05/26/2017 - ITPR019124 Pricing Tool Zip Code:  Add passing the pageName to the CallAjax function
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenu,#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#hdZipCodeCompareMenu,#zipErrorCompareMenu,''");
            }
        });

        $('#btnShowPlanCompareMenuOnPage').click(function (e) {
            e.preventDefault();
            var code = $("#zipHomeCompareMenuOnPage").val();

            if (code.length != 5 || isNaN(code) == true) {
                SetLabelTextCss("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid ZIP Code.", '#zipCodeCompareMenuOnPage', '#zipHomeCompareMenuOnPage', '#zipErrorCompareMenuOnPage');

                $(".error[for='zipHomeCompareMenuOnPage']").each(function () {
                    $(this).css("display", "block").html("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid ZIP Code.");
                }); //end each

            }
            else {

                var url = "../handlers/zipcodesearch.ashx";
                if ($("#planYear") != undefined && $("#planYear").val() !== undefined) {
                    var planyear = $("#planYear").val()
                    var url = window.location.pathname
                    if (url.indexOf(planyear) > -1) {
                        url = "../../handlers/zipcodesearch.ashx";
                    }
                }
                var querystring = "ZipCode=" + code + "&SelectedFromPage=true";
                zipCodeValue = code;
                if (formularySearch || (typeof (pageName) != 'undefined' && pageName == 'formularySearch')) {
                    formularySearch = true, pricingTool = false, pageName = '';
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenuOnPage,#zipCodeCompareMenuOnPage,#zipSplitCompareMenuOnPage,#zipHomeCompareMenuOnPage,#hdZipCodeCompareMenu,#zipErrorCompareMenuOnPage,''");
                }
                else if (pricingTool || (typeof (pageName) != 'undefined' && pageName == 'pricingtool')) {
                    formularySearch = false, pricingTool = true, pageName = '';
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenuOnPage,#zipCodeCompareMenuOnPage,#zipSplitCompareMenuOnPage,#zipHomeCompareMenuOnPage,#hdZipCodeCompareMenu,#zipErrorCompareMenuOnPage,''", pageName);
                }
                else if (!pricingTool && (typeof (pageName) == 'plandetail')) {
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenuOnPage,#zipCodeCompareMenuOnPage,#zipSplitCompareMenuOnPage,#zipHomeCompareMenuOnPage,#hdZipCodeCompareMenu,#zipErrorCompareMenuOnPage,''", pageName);
                }
                else
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenuOnPage,#zipCodeCompareMenuOnPage,#zipSplitCompareMenuOnPage,#zipHomeCompareMenuOnPage,#hdZipCodeCompareMenu,#zipErrorCompareMenuOnPage,''");
            }
        });

        $("#btnShowPlanCompareMenuOnHomePage").click(function (e) {
            e.preventDefault();
            var code = $("#zipHomeCompareMenuOnHomePage").val();

            if (code.length != 5 || isNaN(code) == true) {
                SetLabelTextCss("Enter a ZIP Code.", '#zipCodeCompareMenuOnHomePage', '#zipHomeCompareMenuOnHomePage', '#zipErrorCompareMenuonHomePage');

                $(".error[for='zipHomeCompareMenuOnHomePage']").each(function () {
                    $(this).css("display", "block").html("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid ZIP Code.");
                }); //end each
                document.getElementById("zipErrorBannerCompareMenuonHomePage").innerHTML = "Enter a ZIP Code."
                document.getElementById("divAEP1").classList.add("error-scenario");
                var errorBanner = document.getElementById("diverror-banner");
                errorBanner.style.display = "block";
                errorBanner.focus();
                errorBanner.classList.add("add-focus");
            }
            else {
                document.getElementById("diverror-banner").style.display = "none";
                document.getElementById("divAEP1").classList.remove("error-scenario");
                var url = "../handlers/zipcodesearch.ashx";
                var querystring = "ZipCode=" + code + "&SelectedFromPage=true&AccessedPage=index";
                zipCodeValue = code;
                if (formularySearch || (typeof (pageName) != 'undefined' && pageName == 'formularySearch')) {
                    formularySearch = true, pricingTool = false, pageName = '';
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenu,#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#hdZipCodeCompareMenu,#zipErrorCompareMenu,''");
                }
                else if (pricingTool || (typeof (pageName) != 'undefined' && pageName == 'pricingtool')) {
                    formularySearch = false, pricingTool = true, pageName = '';
                    //DT - 05/26/2017 - ITPR019124 Pricing Tool Zip Code:  Add passing the pageName to the CallAjax function
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenu,#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#hdZipCodeCompareMenu,#zipErrorCompareMenu,''", pageName);
                }
                //DT - 03/02/2018 TFS # 135988 Plan Detail Zip Code:  Keep the user on the plan detail page if already there.
                //Note: typeof(pageName) is required to make this work
                else if (!pricingTool && (typeof (pageName) == 'plandetail')) {
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenu,#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#hdZipCodeCompareMenu,#zipErrorCompareMenu,''", pageName);
                }
                else if ((typeof (pageName) != 'undefined' && pageName == 'statepriorplancomparemodule')) {
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenu,#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#hdZipCodeCompareMenu,#zipErrorCompareMenu,''", pageName);
                }
                else
                    //DT - 05/26/2017 - ITPR019124 Pricing Tool Zip Code:  Add passing the pageName to the CallAjax function
                    CallAjax(url, querystring, ZipSearchSuccess, "#divStatesCompareMenuOnHomePage,#zipCodeCompareMenuOnHomePage,#zipSplitCompareMenuOnHomePage,#zipHomeCompareMenuOnHomePage,#hdZipCodeCompareMenu,#zipErrorCompareMenuonHomePage,''");

            }
        });

        var zipBackUp = "";
        $("#btnRegionShowPlanCompareMenu").click(function (e) {
            var regionId, stateName, rbtnId, stateCode;
            e.preventDefault();

            //Used in RedirectToPlanLanding method in case of error
            errorRegion = "zipSplit";

            $("#zipSplitCompareMenu input[type='radio']").each(function () {
                var currentRatioButton = this.checked;
                if (currentRatioButton == true) {
                    regionId = $(this).attr('value');
                    rbtnId = $(this).attr('id');
                    //BD-ITPR013986-Obv1-[used the below line to get the text (stateName) associated with label using the div ID]
                    stateName = $("label[for='" + rbtnId + "']").text();
                    if (rbtnId != null && rbtnId.indexOf('_') > -1) {
                        stateCode = rbtnId.split('_')[2];
                    }
                }
            });

            //perform ajax and redirect
            var url = "../handlers/zipcodesearch.ashx";
            var theZip = $('#hdZipCodeCompareMenu').val();

            if (theZip == "" || theZip == null || theZip == "undefined") {

                theZip = zipBackUp;
            } //end if


            var querystring = "SelectedRegionId=" + regionId + "&ZipState=" + theZip + "~" + stateName + "~" + stateCode;

            if (formularySearch || pricingTool)
                CallAjax(url, querystring, RedirectToJavaTool, "#zipCodeCompareMenu,#zipHomeCompareMenu,#zipErrorCompareMenu,#errorRegionShowPlanCompareMenu");
            else
                CallAjax(url, querystring, RedirectToPlanLanding, "#zipCodeCompareMenu,#zipHomeCompareMenu,#zipErrorCompareMenu,#errorRegionShowPlanCompareMenu");
        });


        resetFancyBox("#zipCodeCompareMenuOnPage,#zipSplitCompareMenuOnPage,#zipHomeCompareMenuOnPage,#divStatesCompareMenuOnPage,#zipErrorCompareMenuOnPage,#errorRegionShowPlanCompareMenuOnPage");


        $("#btnRegionShowPlanCompareMenuOnPage").click(function (e) {
            var regionId, stateName, rbtnId, stateCode;
            e.preventDefault();

            //Used in RedirectToPlanLanding method in case of error
            errorRegion = "zipSplit";

            $("#zipSplitCompareMenuOnPage input[type='radio']").each(function () {
                var currentRatioButton = this.checked;
                if (currentRatioButton == true) {
                    regionId = $(this).attr('value');
                    rbtnId = $(this).attr('id');
                    //BD-ITPR013986-Obv1-[used the below line to get the text (stateName) associated with label using the div ID]
                    stateName = $("label[for='" + rbtnId + "']").text();
                    if (rbtnId != null && rbtnId.indexOf('_') > -1) {
                        stateCode = rbtnId.split('_')[3];
                    }
                }
            });
            $("#zipSplitCompareMenuOnHomePage input[type='radio']").each(function () {
                var currentRatioButton = this.checked;
                if (currentRatioButton == true) {
                    regionId = $(this).attr('value');
                    rbtnId = $(this).attr('id');
                    //BD-ITPR013986-Obv1-[used the below line to get the text (stateName) associated with label using the div ID]
                    stateName = $("label[for='" + rbtnId + "']").text();
                    if (rbtnId != null && rbtnId.indexOf('_') > -1) {
                        stateCode = rbtnId.split('_')[3];
                    }
                }
            });
            //perform ajax and redirect
            var url = "../handlers/zipcodesearch.ashx";
            var theZip = $('#hdZipCodeCompareMenu').val();

            if (theZip == "" || theZip == null || theZip == "undefined") {

                theZip = zipBackUp;
            } //end if

            var querystring = "SelectedRegionId=" + regionId + "&ZipState=" + theZip + "~" + stateName + "~" + stateCode;

            if (formularySearch || pricingTool)
                CallAjax(url, querystring, RedirectToJavaTool, "#zipCodeCompareMenuOnHomePage", "#zipCodeCompareMenuOnPage,#zipHomeCompareMenuOnHomePage,#zipHomeCompareMenuOnPage,#zipErrorCompareMenuOnPage,#zipErrorCompareMenuonHomePage,#errorRegionShowPlanCompareMenuOnPage");
            else
                CallAjax(url, querystring, RedirectToPlanLanding, "#zipCodeCompareMenuOnHomePage", "#zipCodeCompareMenuOnPage,#zipHomeCompareMenuOnHomePage,#zipHomeCompareMenuOnPage,#zipErrorCompareMenuOnPage,#zipErrorCompareMenuonHomePage");
        });

        //End

        //Index Page
        resetHomeFancyBox("#zipCodeCompareMenuOnHomePage,#zipSplitCompareMenuOnHomePage,#zipHomeCompareMenuOnHomePage,#divStatesCompareMenuOnHomePage,#zipErrorCompareMenuonHomePage,#errorRegionShowPlanCompareMenuOnPage");
        $("#btnRegionShowPlanCompareMenuOnHomePage").click(function (e) {
            var regionId, stateName, rbtnId, stateCode;
            e.preventDefault();

            //Used in RedirectToPlanLanding method in case of error
            errorRegion = "zipSplit";
            $("#zipSplitCompareMenuOnHomePage input[type='radio']").each(function () {
                var currentRatioButton = this.checked;
                if (currentRatioButton == true) {
                    regionId = $(this).attr('value');
                    rbtnId = $(this).attr('id');
                    //BD-ITPR013986-Obv1-[used the below line to get the text (stateName) associated with label using the div ID]
                    stateName = $("label[for='" + rbtnId + "']").text();
                    if (rbtnId != null && rbtnId.indexOf('_') > -1) {
                        stateCode = rbtnId.split('_')[3];
                    }
                }
            });
            //perform ajax and redirect
            var url = "../handlers/zipcodesearch.ashx";
            var theZip = $('#hdZipCodeCompareMenu').val();

            if (theZip == "" || theZip == null || theZip == "undefined") {

                theZip = zipBackUp;
            } //end if

            var querystring = "SelectedRegionId=" + regionId + "&ZipState=" + theZip + "~" + stateName + "~" + stateCode;

            if (formularySearch || pricingTool)
                CallAjax(url, querystring, RedirectToJavaTool, "#zipCodeCompareMenuOnHomePage,#zipHomeCompareMenuOnHomePage,#zipErrorCompareMenuonHomePage,#errorRegionShowPlanCompareMenuOnPage");
            else
                CallAjax(url, querystring, RedirectToPlanLanding, "#zipCodeCompareMenuOnHomePage,#zipHomeCompareMenuOnHomePage,#zipErrorCompareMenuonHomePage,#errorRegionShowPlanCompareMenuOnPage");
        });

        function isNumeric(zipCodeVal) {
            if (pattern.test(zipCodeVal) && zipCodeVal.length <= 5) {
                return true;
            }
            else
                return false;

        }

        $("#zipHome").bind("keyup", function (event) {

            formularySearch = false, pricingTool = false;
            var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
            if (keycode == 13) {
                zipCodeValue = $("#zipHome").val();
                $('#btnShowPlan').click();
                return false;
            }
            else {
                if (isNumeric(event.target.value)) {
                    zipCodeValue = $(this).val();
                    return true;
                }
                else {
                    event.target.value = event.target.value.replace(/.$/, "");
                    return false;
                }
            }

        });

        $('#btnShowEnrollmentPlanByRegion').click(function (e) {
            var regionId, stateName, rbtnId, stateCode;
            $("#multistates input[type='radio']").each(function () {
                var currentRatioButton = this.checked;
                if (currentRatioButton == true) {
                    regionId = $(this).attr('value');
                    rbtnId = $(this).attr('id');
                    stateName = $("label[for='" + rbtnId + "']").text();
                    if (rbtnId != null && rbtnId.indexOf('_') > -1) {
                        stateCode = rbtnId.split('_')[2];
                    }
                }
            });

            $("#hdPlanId").val(regionId);
            $("#hdStateCode").val(stateCode);
            $("#hdStateName").val(stateName);
        });

        $("#btnShowPlan").click(function (e) {
            formularySearch = false, pricingTool = false;
            e.preventDefault();
            var code = zipCodeValue;

            if (code.length !== 5 || isNaN(code) == true) {

                if ($("#zipCode").length > 0) {
                    SetLabelTextCss("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid ZIP Code.", '#zipCode', '#zipHome', '#zipError2');

                }
                else {
                    var value = "<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid ZIP Code.";
                    $('#zipError').attr('style', 'display:block')
                    $('#zipHome').addClass('error');
                    $('#zipError').html(value);
                    $('#zipHome').focus(); //"<br/>Please enter a valid ZIP Code."
                    zipCodeValue = "";
                }
            }
            else {
                var url = "../handlers/zipcodesearch.ashx";
                var querystring = "ZipCode=" + code;

                //DT - 05/26/2017 - ITPR019124 Pricing Tool Zip Code:  Add passing the pageName to the CallAjax function
                CallAjax(url, querystring, ZipSearchSuccess, "#divStates,#zipCode,#zipSplit,#zipHome,#hdZipCode,#zipError2," + pageName + "");
            }
        });
        function CallfutureZipStateAjax(url) {

            $.ajax(
                {
                    type: "GET",
                    url: url,
                    data: "",
                    dataType: 'text',
                    success: function (data) {
                        window.location.href = "/plan/compare-module.aspx?ZipState=" + data;
                    }
                });

            return false;
        }
        function CallZipStateAjax(url) {

            $.ajax(
                {
                    type: "GET",
                    url: url,
                    data: "",
                    dataType: 'text',
                    success: function (data) {
                        window.location.href = "/2019/plan/compare-module.aspx?ZipState=" + data;
                    }
                });

            return false;
        }
        //DT - 05/26/2017 - ITPR019124 Pricing Tool Zip Code:  Add a new redirectPageName parameter
        function CallAjax(url, querystring, onsuccess, parameter, redirectPageName) {
            if (typeof (parameter) == "undefined")
                parameter = "";

            $.ajax(
                {
                    type: "POST",
                    url: url,
                    data: querystring,
                    dataType: 'text',
                    success: function (data) {
                        //DT - 05/26/2017 - ITPR019124 Pricing Tool Zip Code:  Use the new redirectPageName to determine 
                        //                  which page to land on after the fancy box zip code is submitted
                        if (redirectPageName == 'statecomparemodule')
                            window.location.href = '../plan/compare-module.aspx';
                        if (redirectPageName == 'statepriorplancomparemodule') {
                            var url = "../handlers/retrievezipstatehandler.ashx"
                            CallZipStateAjax(url)
                        }
                        if (redirectPageName == 'statefutureplancomparemodule') {
                            var url = "../handlers/retrievezipstatehandler.ashx"
                            CallfutureZipStateAjax(url)
                        }
                        if (redirectPageName == 'plandetail')
                            //DT - 03/02/2018 TFS # 135988 Plan Detail Zip Code:  Keep the user on the plan detail page if already there
                            window.location.href = '../plan/plan-detail.aspx';
                        else if (redirectPageName != undefined && redirectPageName == null) // when the page is undefined and it is null it should redirect to pricing tool page 
                            window.location.href = '/pricing-tool';
                        else if (typeof (parameter) == "undefined" || parameter == "")
                            onsuccess(data);
                        else
                            onsuccess(data, parameter);
                    }

                });
            return false;
        }


        function ZipSearchSuccess(data, ctrls) {
            var controls;
            var ctrlDivState, ctrlDivZipCode, ctrlDivZipSplit, ctrlTxtBxZipHome, ctrlHd, ctrlLblErrorZipCode, innerPageName;
            if (ctrls.indexOf(',') > -1)
                controls = ctrls.split(',');
            if (controls != null && controls.length > 0) {
                ctrlDivState = controls[0];
                ctrlDivZipCode = controls[1];
                ctrlDivZipSplit = controls[2];
                ctrlTxtBxZipHome = controls[3];
                ctrlHd = controls[4];
                ctrlLblErrorZipCode = controls[5];
                innerPageName = controls[6];
            }

            if (data == "No State")
            //  lims --SetLabelTextCss("<br/>State not found. Try again.", ctrlDivZipCode, ctrlTxtBxZipHome, ctrlLblErrorZipCode);
            {
                SetLabelTextCss("Enter a valid ZIP code.", ctrlDivZipCode, ctrlTxtBxZipHome, ctrlLblErrorZipCode);
                if (ctrlLblErrorZipCode == "#zipError2")
                    SetLabelTextCss("<br/><i class='fa fa-exclamation-triangle'></i> State not found. Try again.", ctrlDivZipCode, ctrlTxtBxZipHome, ctrlLblErrorZipCode);
                document.getElementById("zipErrorBannerCompareMenuonHomePage").innerHTML = "Enter a valid ZIP code."
                document.getElementById("welcome-members").innerHTML = "We're sorry. We could not find a state with that ZIP code."
                document.getElementById("divAEP1").classList.add("error-scenario");
                var errorBanner = document.getElementById("diverror-banner");
                errorBanner.style.display = "block";
                errorBanner.focus();
                errorBanner.classList.add("add-focus");
            }
            else if (data == "No Plan")
            // lims SetLabelTextCss("<br/>No Plan Exists", ctrlDivZipCode, ctrlTxtBxZipHome, ctrlLblErrorZipCode);
            {
                SetLabelTextCss("<br/>No Plan Exists", ctrlDivZipCode, ctrlTxtBxZipHome, ctrlLblErrorZipCode);
                if (ctrlLblErrorZipCode == "#zipError2")
                    SetLabelTextCss("<br/><i class='fa fa-exclamation-triangle'></i> No Plan Exists", ctrlDivZipCode, ctrlTxtBxZipHome, ctrlLblErrorZipCode);
            }
            else if (data == "One State") {
                errorRegion = "";
                if (formularySearch || pricingTool)
                    RedirectToJavaTool(data)
                else
                    RedirectToPlanLanding(data);
            }
            else {
                $(ctrlDivState).html(data);
                $(ctrlDivZipCode).hide();
                var code = zipCodeValue;
                $(ctrlHd).val(code);
                //createCookie('Zip', code);
                createCookie('Zip', code, '', '', '.meddweb.net', '');
                if (innerPageName != "" && innerPageName == "home")
                    $.fancybox.close();
                $(ctrlDivZipSplit).show();
                var elem = $("input[name='SelectedStateFromPage']")[0]
                if (elem !== undefined || elem !== null) {
                    elem.focus();
                }

            }
        }

        function SetLabelTextCss(value, ctrlDivZipCode, ctrlTxtBxZipHome, ctrlLblErrorZipCode) {
            $(ctrlDivZipCode).find('.error').show();
            $(ctrlTxtBxZipHome).addClass('error');
            $(ctrlLblErrorZipCode).html(value);
            $(ctrlTxtBxZipHome).focus();
            zipCodeValue = "";
        }

        $("#btnRegionShowPlan").click(function (e) {
            var regionId, stateName, rbtnId, stateCode;
            e.preventDefault();

            //Used in RedirectToPlanLanding method in case of error
            errorRegion = "zipSplit";

            $("#zipSplit input[type='radio']").each(function () {
                var currentRatioButton = this.checked;
                if (currentRatioButton == true) {
                    regionId = $(this).attr('value');
                    stateName = $(this).context.nextSibling.innerText;
                    rbtnId = $(this).attr('id');
                    if (rbtnId != null && rbtnId.indexOf('_') > -1) {
                        stateCode = rbtnId.split('_')[2];
                    }
                }
            });

            //perform ajax and redirect
            var url = "../handlers/zipcodesearch.ashx";
            var querystring = "SelectedRegionId=" + regionId + "&ZipState=" + $('#hdZipCode').val() + "~" + stateName + "~" + stateCode;
            CallAjax(url, querystring, RedirectToPlanLanding, "#zipCode,#zipHome,#zipError,#errorRegionShowPlan");
        });


        function RedirectToPlanLanding(data, ctrls) {
            var controls;
            var innerErrorRegion = errorRegion,
                ctrlDivZipCode, ctrlTxtBxZipHome, ctrlLblErrorZipCode, ctrlLblErrorRegionShowPlan;

            if (typeof (ctrls) != "undefined" && ctrls != null && ctrls.indexOf(',') > -1)
                controls = ctrls.split(',')


            if (controls != null && controls.length > 0) {
                ctrlDivZipCode = controls[0];
                ctrlTxtBxZipHome = controls[1];
                ctrlLblErrorZipCode = controls[2];
                ctrlLblErrorRegionShowPlan = controls[3];
            }

            if (innerErrorRegion == "zipSplit" && data == "No Plan") {
                $(ctrlLblErrorRegionShowPlan.replace('#', '.')).show();
                $(ctrlLblErrorRegionShowPlan).html("No Plan Exists");
                return;
            }
            else if (data == "No Plan") {
                SetLabelTextCss("<br/>No Plan Exists", ctrlDivZipCode, ctrlTxtBxZipHome, ctrlLblErrorZipCode);
                return;
            }
            if (typeof (data) != "undefined" && data != "No Plan")
                //setCookie('selectedPlan', 'none');
                setCookie('selectedPlan', 'none', '', '', '.meddweb.net', '');

            if (typeof (pageName) != "undefined" && pageName != null) {
                if (pageName == "premiumDeductibleWorksheet") {
                    window.location.href = "../plan/Premium-Deductible-Worksheet.aspx";
                    return;
                }
                if (pageName == "statecompareenroll") {
                    window.location.href = "../learn/enroll.aspx";
                    return;
                }
                //DT - 03/15/2018 - TFS# 135988 - Detect if the current page is the plan-detail.aspx page and keep the user on it
                if (pageName == "plandetail") {
                    window.location.href = "../plan/plan-detail.aspx";
                    return;
                }
                if (pageName == "statecomparemodule") {
                    window.location.href = "../plan/compare-module.aspx";
                    return;
                }
                if (pageName == "statepriorplancomparemodule") {
                    var url = "../handlers/retrievezipstatehandler.ashx"
                    CallZipStateAjax(url)
                    return;
                }
                //  RS - 05/01/2018 - DefectId-4287 - Detect if the current page is the pricing-tool.aspx page and keep the user on it
                if (pageName == "pricingtool") {
                    window.location.href = "/pricing-tool";
                    return;

                }
                if (pageName == "statepriorplancomparemodule") {
                    var url = "../handlers/retrievezipstatehandler.ashx"
                    CallfutureZipStateAjax(url)
                    return;
                }
            }
            window.location.href = "../plan/compare-module.aspx";
        }

        //End


        //Premium Summary 
        //$("#btnPremiumSummaryShowPlan").click(function (e) {
        //    zipCodeValue = $("#zipHomePremiumSummary").val();
        //    var code = zipCodeValue;

        //    if (code.length != 5 || isNaN(code) == true) {
        //        $('#lblError').hide();
        //        SetLabelTextCss("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid ZIP Code.", '#zipCodeSection', '#zipHomePremiumSummary', '#zipError');
        //        return false;
        //    }
        //    else {
        //        return true;
        //    }
        //});

        //Premium Summary 
        $("#btnShowComparePlan").click(function (e) {
            zipCodeValue = $("#zipHome").val();
            var code = zipCodeValue;

            if (code.length != 5 || isNaN(code) == true) {
                $('#zipError2').show();
                SetLabelTextCss("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid ZIP Code.", '#zipCodeSection', '#zipHome', '#zipError2');
                return false;
            }
            else {
                return true;
            }
        });
        ///upon enter trigger submit for zip codes
        $("#zipHomeCompareMenu").keydown(function (e) {

            if ((e.keyCode || e.which) == 13) // enter
            {
                var theZip = $(this).val();

                zipBackUp = theZip;
                $("#btnShowPlanCompareMenu").trigger("click");
            }
        }); //end key down 
        $("#zipHomePremiumSummary").keydown(function (e) {
            if ((e.keyCode || e.which) == 13) // enter
            {
                __doPostBack('ctl00$MainContent$btnPremiumSummaryShowPlan', '')
            }
        }); //end key down 



        function SetLabelTextCssforCompareLanding(value) {
            $("#lblTest").html(value);
            $('.error').show();
        }

        var isFromCompareLanding = false,
            isPlanSelected = false;

        //$('#btnShowPerfectAddress, #btnSaveAddressInfo').click(function (e) {
        //    e.preventDefault();
        //    if ($('#additionalInfo').valid()) {
        //        if (!CheckAdditionalData()) //|| !CheckPassWordValidation())
        //        {
        //            return false;
        //        }
        //        var url = "../handlers/perfectaddressservicecall.ashx";
        //        var zipCode = $('#zip').val();
        //        var addr1 = $('#address1').val();
        //        var addr2 = $('#address2').val();
        //        var city = $('#city').val();
        //        var state = $('#state').val();
        //        var county = $('#county').val();

        //        var zip2 = $('#zip2').val();
        //        var addr3 = $('#address3').val();
        //        var addr4 = $('#address4').val();
        //        var city2 = $('#city2').val();
        //        var state2 = $('#state2').val();

        //        var isMailAdsress = $('#sameAsStreet').is(':checked');

        //        var querystring = "zip=" + zipCode + "&addr1=" + addr1 + "&addr2=" + addr2 + "&city=" + city + "&state=" + state + "&county=" + county;

        //        if (isMailAdsress)
        //            querystring = querystring + "&isMailAdsress=true" + "&zip2=" + zip2 + "&addr3=" + addr3 + "&addr4=" + addr4 + "&city2=" + city2 + "&state2=" + state2;

        //        CallAjax(url, querystring, PerfectAddressChoices);
        //    }
        //});

        function PerfectAddressChoices(data) {
            if (data == "no result") {
                $('#submitAdditionalButton').trigger('click');
                return;
            }
            else {
                $('#spnPerfectAddressOptions').html(data);
                $('.pPerfectAddress').fancybox(
                    {
                        'padding': 30,
                        'showCloseButton': true,
                        'titleShow': false
                    }).trigger('click');
                $('#paImageButton').show();
            }
        }

        $('#btnShowPerfectCancel').click(function (e) {
            $.fancybox.close();
        });

        $('#btnShowPerfectChoose').click(function (e) {
            FillPerferctAddress();
        });

        function FillPerferctAddress() {
            var isMailAdsress = $('#sameAsStreet').is(':checked');
            //            var isLtcAddress = $('#instName').is(':checked');
            var perferctAdress = $('input:radio[name=PerfectPermAddress]:checked').val();
            if (perferctAdress != null && perferctAdress != "0") {
                var zipCode = perferctAdress.substring(perferctAdress.indexOf('Zip=') + 4, perferctAdress.indexOf('County='));
                zipCode = zipCode.substring(0, 5);
                var addr1 = perferctAdress.substring(perferctAdress.indexOf('Add1=') + 5, perferctAdress.indexOf('Add2='));
                var addr2 = perferctAdress.substring(perferctAdress.indexOf('Add2=') + 5, perferctAdress.indexOf('City='));
                var city = perferctAdress.substring(perferctAdress.indexOf('City=') + 5, perferctAdress.indexOf('State='));
                var state = perferctAdress.substring(perferctAdress.indexOf('State=') + 6, perferctAdress.indexOf('Zip='));
                var county = perferctAdress.substring(perferctAdress.indexOf('County=') + 7);
                $('#address1').val(addr1);
                $('#address2').val(addr2);
                $('#city').val(city);
                $('#state').val(state);
                $('#county').val(county);
                $('#zip').val(zipCode);
            }

            if (isMailAdsress) {
                var perferctMailAdress = $('input:radio[name=PerfectMailAddress]:checked').val();
                if (perferctMailAdress != null && perferctMailAdress != "0") {
                    var zipCode2 = perferctMailAdress.substring(perferctMailAdress.indexOf('MailZip=') + 8, perferctMailAdress.indexOf('MailCounty='));
                    zipCode2 = zipCode2.substring(0, 5);
                    var addr3 = perferctMailAdress.substring(perferctMailAdress.indexOf('MailAdd1=') + 9, perferctMailAdress.indexOf('MailAdd2='));
                    var addr4 = perferctMailAdress.substring(perferctMailAdress.indexOf('MailAdd2=') + 9, perferctMailAdress.indexOf('MailCity='));
                    var city2 = perferctMailAdress.substring(perferctMailAdress.indexOf('MailCity=') + 9, perferctMailAdress.indexOf('MailState='));
                    var state2 = perferctMailAdress.substring(perferctMailAdress.indexOf('MailState=') + 10, perferctMailAdress.indexOf('MailZip='));
                    $('#address3').val(addr3);
                    $('#address4').val(addr4);
                    $('#city2').val(city2);
                    $('#state2').val(state2);
                    $('#zip2').val(zipCode2);
                }
            }

            $.fancybox.close();
        }


        $('#planAEffectiveDate').on('blur', function (e) {
            var control = '#planAEffectiveDate';
            if (!validateDateAdditional(control)) {
                $(control).attr('class', 'error');
                $(control).next().show();
            }

        });

        $('#planATermDate').on('blur', function (e) {
            var control = '#planATermDate';
            if (!validateDateAdditional(control)) {
                $(control).attr('class', 'error');
                $(control).next().show();
            }
        });
        $('#planAEffectiveDate2').on('blur', function (e) {
            var control = '#planAEffectiveDate2';
            if (!validateDateAdditional(control)) {
                $(control).attr('class', 'error');
                $(control).next().show();
            }
        });
        $('#planATermDate2').on('blur', function (e) {
            var control = '#planATermDate2';
            if (!validateDateAdditional(control)) {
                $(control).attr('class', 'error');
                $(control).next().show();
            }
        });

        $('#nPassword').on('blur', function (e) {
            if (!CheckPassWordValidation()) {
                $(this).attr('class', 'error');
                $(this).next().show();
            }
        });

        function CheckAdditionalData() {

            var IsCorrectDates = false;
            var IsCorrectDatesAEF = false;
            var IsCorrectDatesATD = false;
            var IsCorrectDatesAEF2 = false;
            var IsCorrectDatesATD2 = false;
            var IsOtherCoverageFieldsValid = true;

            var ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError;
            //---For PlanAEffective date----------------// 
            ctrlDOBDay = '#planAEffectiveDateDay';
            ctrlDOBMonth = '#planAEffectiveDateMonth';
            ctrlDOByear = '#planAEffectiveDateYear';
            ctrlDOBError = '#errorEffectiveDate';

            //DOB 
            if (!validateEffectiveDate1(ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError)) {
                IsCorrectDatesAEF = false;
                //$(ctrlDOBDay).attr('class', 'error');
                //$(ctrlDOBDay).next().show();
                $("#errorEffectiveDate").show();

            }
            else {
                IsCorrectDatesAEF = true;
                $("#errorEffectiveDate").hide();
            }

            //------For PlanATermDate-----------------//
            ctrlDOBDay = '#planATermDateDay';
            ctrlDOBMonth = '#planATermDateMonth';
            ctrlDOByear = '#planATermDateYear';
            ctrlDOBError = '#errorTermDate';

            //DOB 
            if (!validateEffectiveDate1(ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError)) {
                IsCorrectDatesATD = false;
                $("#errorTermDate").show();
            }
            else {
                IsCorrectDatesATD = true;
                $("#errorTermDate").hide();
            }

            ///----
            //------For PlanAEffectiveDate2-----------------//
            ctrlDOBDay = '#planAEffectiveDate2Day';
            ctrlDOBMonth = '#planAEffectiveDate2Month';
            ctrlDOByear = '#planAEffectiveDate2Year';
            ctrlDOBError = '#errorEffectiveDate2';
            if ($("#othercoverage2Yes").is(":checked") && $("#othercoverage2Yes").val() == "yes") {
                if (!validateEffectiveDate1(ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError)) {
                    IsCorrectDatesAEF2 = false;
                    $("#errorEffectiveDate2").show();
                }
                else {
                    IsCorrectDatesAEF2 = true;
                    $("#errorEffectiveDate2").hide();
                }
            }
            else {
                IsCorrectDatesAEF2 = true;
                $("#errorEffectiveDate2").hide();
            }

            ///----
            //------For PlanATermDate2-----------------//
            ctrlDOBDay = '#planATermDate2Day';
            ctrlDOBMonth = '#planATermDate2Month';
            ctrlDOByear = '#planATermDate2Year';
            ctrlDOBError = '#errorTermDate2';
            if ($("#othercoverage2Yes").is(":checked") && $("#othercoverage2Yes").val() == "yes") {
                if (!validateEffectiveDate1(ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError)) {
                    $("#errorTermDate2").show();
                    IsCorrectDatesATD2 = false;
                }
                else {
                    $("#errorTermDate2").hide();
                    IsCorrectDatesATD2 = true;
                }
            }
            else {
                $("#errorTermDate2").hide();
                IsCorrectDatesATD2 = true;
            }

            var planNameValue = $("#planName").val();
            var RxBinValue = $("#RxBin").val();
            var RxPCNValue = $("#RxPCN").val();
            var RxGroupValue = $("#RxGroup").val();
            var RxIDValue = $("#RxID").val();
            var addtnCvrg = $("input[name='otherCoverage2']:checked").length;


            if (planNameValue !== undefined && planNameValue === '') {
                $("#planName").removeClass("valid").addClass("error");
                $("#lblPlanNameValid1").parent().show();
                IsOtherCoverageFieldsValid = false;
            }
            if (RxBinValue === undefined || RxBinValue === '') {
                $("#RxBin").removeClass("valid").addClass("error");
                $("#lblRxBinValid1").parent().show();
                IsOtherCoverageFieldsValid = false;
            }
            if (RxPCNValue === undefined || RxPCNValue === '') {
                $("#RxPCN").removeClass("valid").addClass("error");
                $("#lblRxPCNValid1").parent().show();
                IsOtherCoverageFieldsValid = false;
            }
            if (RxGroupValue === undefined || RxGroupValue === '') {
                $("#RxGroup").removeClass("valid").addClass("error");
                $("#lblRxGroupValid1").parent().show();
                IsOtherCoverageFieldsValid = false;
            }
            if (RxIDValue === undefined || RxIDValue === '') {
                $("#RxID").removeClass("valid").addClass("error");
                $("#lblRxIDValid1").parent().show();
                IsOtherCoverageFieldsValid = false;
            }


            var planName2Value = $("#planName2").val();
            var RxBin2Value = $("#RxBin2").val();
            var RxPCN2Value = $("#RxPCN2").val();
            var RxGroup2Value = $("#RxGroup2").val();
            var RxID2Value = $("#RxID2").val();

            if (addtnCvrg == 0) {
                $('[name="otherCoverage2"]').next().addClass("label-radio-error");
                $("#lblAdditionalValid2").parent().show();
                IsOtherCoverageFieldsValid = false;
            }
            if ($("#othercoverage2Yes").is(":checked") && $("#othercoverage2Yes").val() == "yes") {
                if (planName2Value !== undefined && planName2Value === '') {
                    $("#planName2").removeClass("valid").addClass("error");
                    $("#lblPlanNameValid2").parent().show();
                    IsOtherCoverageFieldsValid = false;
                }
                if (RxBin2Value === undefined || RxBin2Value === '') {
                    $("#RxBin2").removeClass("valid").addClass("error");
                    $("#lblRxBinValid2").parent().show();
                    IsOtherCoverageFieldsValid = false;
                }
                if (RxPCN2Value === undefined || RxPCN2Value === '') {
                    $("#RxPCN2").removeClass("valid").addClass("error");
                    $("#lblRxPCNValid2").parent().show();
                    IsOtherCoverageFieldsValid = false;
                }
                if (RxGroup2Value === undefined || RxGroup2Value === '') {
                    $("#RxGroup2").removeClass("valid").addClass("error");
                    $("#lblRxGroupValid2").parent().show();
                    IsOtherCoverageFieldsValid = false;
                }
                if (RxID2Value === undefined || RxID2Value === '') {
                    $("#RxID2").removeClass("valid").addClass("error");
                    $("#lblRxIDValid2").parent().show();
                    IsOtherCoverageFieldsValid = false;
                }
            }
            ///----
            if (!IsCorrectDatesAEF || !IsCorrectDatesATD || !IsCorrectDatesAEF2 || !IsCorrectDatesATD2 || !IsOtherCoverageFieldsValid) {
                alert('Required information has not been supplied or is invalid.  Please review the form.');
                IsCorrectDates = false;
            }
            else {
                IsCorrectDates = true;
            }

            return IsCorrectDates;

        }




        ///////
        // Reminder popup 
        ///////
        $('#repAddress,#repApt1').bind("keypress", function (event) {
            var keyCode = event.keyCode || event.which;
            if (keyCode != 13) {
                return Address(event);
            }
        });



        //AlphaNumeric, "/" , " ", "-"
        function Address(e) {

            var regex = new RegExp("^[A-Za-z0-9 \s -/]+");
            var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
            if (!regex.test(key)) {
                event.preventDefault();
                return false;
            }
        }

        //AlphaNumeric, "." , " ", "-"
        function AddressWithDot(e) {

            var regex = new RegExp("^[A-Za-z0-9.]+");
            var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
            if (!regex.test(key)) {
                event.preventDefault();
                return false;
            }
        }

        //Alpha, "." , " ", "-" "@"
        function EmailValidation(e, control) {
            var keynum;
            var keychar;
            var charcheck;
            if (window.event)
                keynum = e.keyCode;
            else if (e.which)
                keynum = e.which;

            keychar = String.fromCharCode(keynum);

            if (e.shiftKey && (keychar == "%" || keychar == "#" || keychar == "$"))
                return false;
            if (keynum == 8 || keynum == 46) {
                return true;
            }

            else if (keynum == 9 || keynum == 35 || keynum == 36 || keynum == 37 || keynum == 39 ||
                keynum == 45 || keynum == 46 || keynum == 32 || keynum == 64 || keynum == 190 || keynum == 189)
                return true;

            charcheck = /[a-zA-Z0-9]/;
            return charcheck.test(keychar);
        }

        //Alpha, " "
        function AddressWithSpace(e) {
            var regex = new RegExp("^[ A-Za-z0-9]+");
            var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
            if (!regex.test(key)) {
                event.preventDefault();
                return false;
            }
        }

        ////check for only alpha with space
        //$('#repCity,#city,#city2,#county').bind("keypress", function (event) {
        //    return AddressWithSpace(event);
        //});

        //Alphanumeric Check For First name and Last Name
        //$('#acctNum,#first_name, #last_name, #RxBin,#RxPCN,#RxBin2,#RxPCN2, #rMediNum, #rMediNumConf').bind("keypress", function (event) {
        $('#acctNum,#first_name, #last_name, #RxBin,#RxPCN,#RxBin2,#RxPCN2').bind("keypress", function (event) {
            return isAlphaNumeric(event, $(this));
        });

        function isAlphaNumeric(e, control) {
            var regex = new RegExp("^[A-Za-z0-9]+");
            var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);

            if (!regex.test(key)) {
                if ($(control).attr('id') == "rMediNum" || $(control).attr('id') == "rMediNumConf") {
                    if (($(control).val().length - 1) < 1) {
                        $(control).next().next().html("");
                        $(control).next().next().hide();
                    }
                    event.preventDefault();
                    return false;
                }
            }
        }


        //AlphaNumric With " "
        function isAlphaNumericWithSpace(e) {

            var regex = new RegExp("^[ A-Za-z0-9]+");
            var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
            if (!regex.test(key)) {
                event.preventDefault();
                return false;
            }
        }

        $('.enrollRemind a, .emailRemind').each(function () {
            var reminder = $(this),
                reminderType = reminder.attr('title'),
                reminderTypeId = reminder.attr('id');
            $('#para1AEP, #para1Turn65, #dobHide, #dtrHide, #chkRemindHide,#rdoRemindHide').hide();

            if (reminderTypeId == 'lbtnAge65Reminder') {
                $('#para1Turn65').show();
                $('#dobHide').show();
                $('#rdoTurning65').attr('checked', 'checked');
                $('#rdoRemindHide').show();
            }
            else if (reminderTypeId == 'lbtnAEPReminder' || reminderTypeId == 'lnkMainReminder' || reminderTypeId == "indexEmailReminder") {
                $('#para1AEP').show();
                $('#chkRemind').attr('checked', false);
                $('#chkRemindHide').show();
            }
        });


        $("#chkRemind").click(function (e) {
            var value = $('#chkRemind').attr('checked');
            if (value == "checked") {
                $('#dtrHide').show();
            }
            else {
                $('#datePick2').attr('class', '');
                $('#error_datePick2').hide();
                $('#dtrHide').hide();
            }

        });

        $('#rdoRemindHide input[type="radio"]').click(function (e) {
            var value = $('#rdoTurning65').attr('checked');
            if (value == "checked") {
                $('#datePick2').attr('class', '');
                $('#error_datePick2').hide();
                $('#dtrHide').hide();
                $('#dobHide').show();
            }
            else {
                $('#dtrHide').show();
                $('#error_bdPick3').hide();

                $('#dobHide').hide();
            }

        });

        // Email Reminder Click - from stand-alone page
        $("#btnRemindMe").click(function (e) {

            //if (!validateEmailReminder())
            //    return false;

            ctrlDOBDay = '#emailremainddlDOBDay';
            ctrlDOBMonth = '#emailremainddlDOBMonth';
            ctrlDOByear = '#emailremainddlDOBYear';
            ctrlDOBError = '#emailremainerrorDOB';
            if (!validateEmailReminder()) {
                validateEmailRemainDOB(ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError);
            }
            else {
                var dobDay = $(ctrlDOBDay).val()
                var dobMonth = $(ctrlDOBMonth).val()
                var dobyear = $(ctrlDOByear).val()
                if (dobDay === "" || dobDay === "dd" || dobDay == "__" || dobMonth === "" || dobMonth === "mm" || dobMonth == "__" || dobyear === "") {
                    if ($("#dobErrorMsg").is(":visible")) {
                        $("#dobErrorMsg").hide();
                        validateEmailRemainDOB(ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError);
                        return false;
                    } else {
                        validateEmailRemainDOB(ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError);
                    }
                }
                else if (!validateEmailRemainDOB(ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError)) {
                    return false;
                }
            }

        });

        function validateEmailReminder() {
            var IsValid = true;
            var zipCode = $('#zip_code_er').val();
            var focusField = ''
            $('.emailReminderError').hide();
            //first name
            if ($('#first_name_er').val() == "") {
                $('#first_name_er').attr('class', 'error');
                $('#error_first_name').show();
                focusField = '#first_name_er'
                IsValid = false;
            }
            else {
                $('#first_name_er').attr('class', 'textfield-white');
                $('#error_first_name').hide();
            }

            //last name
            if ($('#last_name_er').val() == "") {
                $('#last_name_er').attr('class', 'error');
                $('#error_last_name').show();
                if (focusField == "")
                    focusField = '#last_name_er'
                IsValid = false;
            }
            else {
                $('#last_name_er').attr('class', 'textfield-white');
                $('#error_last_name').hide();
            }

            //Zip Code
            if (zipCode.length !== 5 || isNaN(zipCode) == true) {
                $('#zip_code_er').attr('class', 'error');
                $('#zipcode_error').show();
                if (focusField == "")
                    focusField = '#zip_code_er'
                IsValid = false;
            }
            else {
                $('#zip_code_er').attr('class', 'textfield-white');
                $('#zipcode_error').hide();
            }


            //DOB
            //ctrlDOBDay = '#emailremainddlDOBDay';
            //ctrlDOBMonth = '#emailremainddlDOBMonth';
            //ctrlDOByear = '#emailremainddlDOBYear';
            //ctrlDOBError = '#emailremainerrorDOB';
            //if (IsValid) {
            //    IsValid = validateEmailRemainDOB(ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError);
            //    if (focusField == "" && !IsValid)
            //        focusField = '#emailremainddlDOBMonth'
            //}
            //else {
            //    IsValid = validateEmailRemainDOB(ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError);

            //}

            //emaill
            var emailRegExp = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

            var email = $('#email_er').val();
            if (email == "" || !emailRegExp.test(email)) {
                $('#email_er').attr('class', 'error');
                $('#error_email').show();
                if (focusField == "")
                    focusField = '#email_er'
                IsValid = false;
            }
            else {
                $('#email_er').attr('class', 'textfield-white');
                $('#error_email').hide();
            }
            if (focusField != "")
                $(focusField).focus();

            return IsValid;
        }


        //Saved Enrollment

        //$('#SavedEnrollment').click(function (e) {
        //    e.preventDefault();
        //    $.fancybox({
        //        'href': '#saveEnrollForm',
        //        'padding': 0,
        //        'scrolling': 'no',
        //        'showCloseButton': true,
        //        'titleShow': false,
        //        'onStart': function () {
        //            $('#trackingNumber').val("");
        //            $('#beneNameLast').val("");
        //            $('#lblRetrieveEnrollMsg').text("");
        //        }
        //    })
        //});

        /* accordion for learn/enroll */
        $('#idcard-accordion').click(function (e) {
            e.preventDefault();
            $('#idcard-accordion').toggleClass("activeAccord");
            var panel = this.nextElementSibling;
            if (this.getAttributeNode("aria-expanded").value == "true") {

                this.setAttribute("aria-expanded", "false");
                panel.setAttribute("aria-hidden", "true");
            }
            else {
                this.setAttribute("aria-expanded", "true");
                panel.setAttribute("aria-hidden", "false");
            }
            return false;
        });

        $('#btnRetrieveEnrollment').click(function (e) {
            var errorList = [];
            var formId = this.form.id
            var isFormInvalid = false;

            var ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError;
            ctrlDOBDay = '#ddlDOBDay';
            ctrlDOBMonth = '#ddlDOBMonth';
            ctrlDOByear = '#ddlDOBYear';
            ctrlDOBError = '#errorDOB';
            ctrlDOB = '#ddlDOBYear';
            ctrlDOBError = '#errorDOB';

            var isValid = true;

            $('#secondLine').remove();
            if ($('#trackingNumber').val() == "") {
                $('#trackingNumber').attr('class', 'error');
                $('#error_trackingNumber').show();
                $('#trackingNumber').focus();
                addValidationError("trackingNumber", "Enter a valid tracking number", errorList);
                isValid = false;
            }
            else {
                $('#trackingNumber').attr('class', 'textfield textfieldW240 ');
                $('#error_trackingNumber').hide();
            }

            if ($('#beneNameLast').val() == "") {
                $('#beneNameLast').attr('class', 'error');
                $('#error_beneNameLast').show();
                addValidationError("beneNameLast", "Enter your last name", errorList);
                isValid = false;
            }
            else {
                $('#beneNameLast').attr('class', 'textfield textfieldW240');
                $('#error_beneNameLast').hide();
            }

            //DOB Check  
            var monthPartDOB = $.trim($("#ddlDOBMonth").val());
            var datePartDOB = $.trim($("#ddlDOBDay").val());
            var yearPartDOB = $.trim($("#ddlDOBYear").val());

            $("#dobMonthError").removeClass("dobMonthError");
            $("#dobDayError").removeClass("dobDayError");
            $("#dobYearError").removeClass("dobYearError");

            $('#ddlDOBMonth').removeClass("select-ddl-error");
            $('#ddlDOBDay').removeClass("select-ddl-error");
            $('#ddlDOBYear').removeClass("select-ddl-error");
            $("#dobMonthError").hide();
            $("#dobDayError").hide();
            $("#dobYearError").hide();

            var dobMonthErrMsg = "Select a valid birth month";
            var dobDayErrMsg = "Select a valid birth day";
            var dobYearErrMsg = "Select a valid birth year";

            if ((datePartDOB != "") && (monthPartDOB != "") && (yearPartDOB != "") && (datePartDOB != "00") && (monthPartDOB != "00")) //&& DOB.indexOf('/') != -1) 
            {
                var isDOBValid = true;
                var userDate = new Date();
                userDate.setFullYear(yearPartDOB, monthPartDOB - 1, datePartDOB - 1);
                var currDate = new Date();
                currDate.setFullYear(currDate.getFullYear() - 65);

                var currentYear = new Date().getFullYear();

                //DOB
                if (((datePartDOB >= 01) & (datePartDOB <= 31)) & ((monthPartDOB >= 01) & (monthPartDOB <= 12)) & ((yearPartDOB >= 1887) & (yearPartDOB <= currentYear))) {
                    var dobDate = Date.parse(monthPartDOB + '/' + datePartDOB + '/' + yearPartDOB);
                    var fullDate = new Date();
                    var twoDigitMonth = ((fullDate.getMonth().length + 1) === 1) ? (fullDate.getMonth() + 1) : '0' + (fullDate.getMonth() + 1);
                    var formatedDate = twoDigitMonth + "/" + fullDate.getDate() + "/" + fullDate.getFullYear();
                    var currentDate = Date.parse(formatedDate);

                    if (!validDate(datePartDOB, monthPartDOB, yearPartDOB)) {
                        isDOBValid = false;
                    }


                    if (isDOBValid) {
                        if (dobDate >= currentDate) {
                            isDOBValid = false;
                        }
                        //else if (new Date() <= new Date(DOB)) {
                        //    isDOBValid = false;
                        //}
                    }
                }
                else {
                    isDOBValid = false;
                }

                if (!isDOBValid) {
                    $('#ddlDOBMonth').attr('class', 'select-ddl-error');
                    $("#dobMonthError").addClass("dobMonthError");
                    $("#dobMonthError").html(dobMonthErrMsg);
                    $("#dobMonthError").attr("aria-label", " (Error) " + dobMonthErrMsg).attr("role", "text");
                    $("#dobMonthError").show();
                    addValidationError("ddlDOBMonth", dobMonthErrMsg, errorList);

                    $('#ddlDOBDay').attr('class', 'select-ddl-error');
                    $("#dobDayError").addClass("dobDayError");
                    $("#dobDayError").html(dobDayErrMsg);
                    $("#dobDayError").attr("aria-label", " (Error) " + dobDayErrMsg).attr("role", "text");
                    $("#dobDayError").show();
                    addValidationError("ddlDOBDay", dobDayErrMsg, errorList);

                    $('#ddlDOBYear').attr('class', 'select-ddl-error width105');
                    $("#dobYearError").addClass("dobYearError");
                    $("#dobYearError").html(dobYearErrMsg);
                    $("#dobYearError").attr("aria-label", " (Error) " + dobYearErrMsg).attr("role", "text");
                    $("#dobYearError").show();
                    addValidationError("ddlDOBYear", dobYearErrMsg, errorList);

                    isValid = false;
                }
            }
            else {
                $('#ddlDOBMonth').attr('class', 'select-ddl-error');
                $("#dobMonthError").addClass("dobMonthError");
                $("#dobMonthError").html(dobMonthErrMsg);
                $("#dobMonthError").attr("aria-label", " (Error) " + dobMonthErrMsg).attr("role", "text");
                $("#dobMonthError").show();
                addValidationError("ddlDOBMonth", dobMonthErrMsg, errorList);

                $('#ddlDOBDay').attr('class', 'select-ddl-error');
                $("#dobDayError").addClass("dobDayError");
                $("#dobDayError").html(dobDayErrMsg);
                $("#dobDayError").attr("aria-label", " (Error) " + dobDayErrMsg).attr("role", "text");
                $("#dobDayError").show();
                addValidationError("ddlDOBDay", dobDayErrMsg, errorList);

                $('#ddlDOBYear').attr('class', 'select-ddl-error width105');
                $("#dobYearError").addClass("dobYearError");
                $("#dobYearError").html(dobYearErrMsg);
                $("#dobYearError").attr("aria-label", " (Error) " + dobYearErrMsg).attr("role", "text");
                $("#dobYearError").show();
                addValidationError("ddlDOBYear", dobYearErrMsg, errorList);

                isValid = false;
            }

            if (!isValid) {
                ShowValidationSummaryWithTitle(errorList, formId, "", false);
                return false;
            }

        });


        function RetrieveEnrollmentSuccess(data) {

            if (data == "Saved Enrollment not found, please try again.") {
                $('#trackingNumber').attr('class', 'error');
                $('#lblRetrieveEnrollMsg').html('<i class="fa fa-exclamation-triangle"></i> ' + data);
                $('#lblRetrieveEnrollMsg').show();


            }
            // else if (data.indexOf('not found for plan year') > -1) {
            else if (data.indexOf('application number is not found') > -1) {
                $('#trackingNumber').attr('class', 'error');
                $('#lblRetrieveEnrollMsg').html('<i class="fa fa-exclamation-triangle"></i> ' + data);
                $('#lblRetrieveEnrollMsg').show();
            }
            else if (data.indexOf('Tracking number') > -1) {
                $.fancybox.close();
                return confirm(data);
            }
            else if (data == "Enrollment has expired.  Please create a new enrollment.") {
                $.fancybox.close();
                return confirm(data);
            }
            else {
                $.fancybox.close();
                window.location.href = data;
            }
        }


        $('#first_name').on('blur', function () {
            if ($('#first_name').val() == "") {
                $('#first_name').attr('class', 'error');
                $('#error_first_name').show();
                IsValid = false;
            }
            else {
                $('#first_name').attr('class', 'textfield textfieldW240');
                $('#error_first_name').hide();
            }
        });


        $('#last_name').on('blur', function () {
            if ($('#last_name').val() == "") {
                $('#last_name').attr('class', 'error');
                $('#error_last_name').show();
                IsValid = false;
            }
            else {
                $('#last_name').attr('class', 'textfield textfieldW240');
                $('#error_last_name').hide();
            }
        });


        $('#zip_code').on('blur', function () {
            var zipCode = $('#zip_code').val();
            if (zipCode.length !== 5 || isNaN(zipCode) == true) {
                $('#zip_code').attr('class', 'error');
                $('#zipcode_error').show();
                IsValid = false;
            }
            else {
                $('#zip_code').attr('class', 'textfield textfieldW225');
                $('#zipcode_error').hide();
            }
        });

        $('#email').on('blur', function () {

            //emaill
            var emailRegExp = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

            var email = $('#email').val();
            if (email == "" || !emailRegExp.test(email)) {
                $('#email').attr('class', 'error');
                $('#error_email').show();
                IsValid = false;
            }
            else {
                $('#email').attr('class', 'textfield textfieldW225');
                $('#error_email').hide();
            }
        });

        function TealiumNotifyEmailRemainder_OnBlur() {
            utag.link(
                {
                    form_start: "event10",
                    form_name: "Email Reminder",
                    link_name: "Custom: email reminder form start"
                });
        }
        var tagfire;

        $('#first_name_er').on('blur', function () {
            if ($('#first_name_er').val() == "") {
                $('#first_name_er').attr('class', 'error');
                $('#error_first_name').show();
                IsValid = false;
            }
            else {
                $('#first_name_er').attr('class', 'textfield-white');
                $('#error_first_name').hide();
            }

            //DP-12/20/2017-On Focus of any field on the email reminder page fire a utag.link with form_start, form_name and link_name.
            if (tagfire != true) {
                TealiumNotifyEmailRemainder_OnBlur();
                tagfire = true;
            }
        });

        $('#last_name_er').on('blur', function () {
            if ($('#last_name_er').val() == "") {
                $('#last_name_er').attr('class', 'error');
                $('#error_last_name').show();
                IsValid = false;
            }
            else {
                $('#last_name_er').attr('class', 'textfield-white');
                $('#error_last_name').hide();
            }

            //DP-12/20/2017-On Focus of any field on the email reminder page fire a utag.link with form_start, form_name and link_name.
            if (tagfire != true) {
                TealiumNotifyEmailRemainder_OnBlur();
                tagfire = true;
            }
        });

        $('#zip_code_er').on('blur', function () {
            if ($('#zip_code_er').val() == "") {
                $('#zip_code_er').attr('class', 'error');
                $('#zipcode_error').show();
                IsValid = false;
            }
            else {
                $('#zip_code_er').attr('class', 'textfield-white');
                $('#zipcode_error').hide();
            }

            //DP-12/20/2017-On Focus of any field on the email reminder page fire a utag.link with form_start, form_name and link_name.
            if (tagfire != true) {
                TealiumNotifyEmailRemainder_OnBlur();
                tagfire = true;
            }
        });

        $('#email_er').on('blur', function () {

            var emailRegExp = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

            var email = $('#email_er').val();
            if (email == "" || !emailRegExp.test(email)) {
                $('#email_er').attr('class', 'error');
                $('#error_email').show();
                IsValid = false;
            }
            else {
                $('#email_er').attr('class', 'textfield-white');
                $('#error_email').hide();
            }

            //DP-12/20/2017-On Focus of any field on the email reminder page fire a utag.link with form_start, form_name and link_name.
            if (tagfire != true) {
                TealiumNotifyEmailRemainder_OnBlur();
                tagfire = true;
            }
        });

        $('#emailremainddlDOBDay').change(function () {
            ctrlDOBDay = '#emailremainddlDOBDay';
            ctrlDOBMonth = '#emailremainddlDOBMonth';
            ctrlDOByear = '#emailremainddlDOBYear';
            ctrlDOBError = '#emailremainerrorDOB';
            setEmailRemainFocus();

            //DP-12/20/2017-On Focus of any field on the email reminder page fire a utag.link with form_start, form_name and link_name.
            if (tagfire != true) {
                TealiumNotifyEmailRemainder_OnBlur();
                tagfire = true;
            }
        });


        $('#emailremainddlDOBMonth').change(function () {
            ctrlDOBDay = '#emailremainddlDOBDay';
            ctrlDOBMonth = '#emailremainddlDOBMonth';
            ctrlDOByear = '#emailremainddlDOBYear';
            ctrlDOBError = '#emailremainerrorDOB';
            if ($(ctrlDOBDay).val() !== "" && $(ctrlDOBMonth).val() !== "" && $(ctrlDOBDay).val() !== "dd" && $(ctrlDOBMonth).val() !== "mm") {
                setEmailRemainFocus();
            }
            else if (($(ctrlDOBDay).val() === "" && $(ctrlDOBMonth).val() === "") || ($(ctrlDOBDay).val() === "dd" && $(ctrlDOBMonth).val() === "mm") || ($(ctrlDOBDay).val() === "" && $(ctrlDOBMonth).val() === "mm") || ($(ctrlDOBDay).val() === "dd" && $(ctrlDOBMonth).val() === "")) {
                setEmailRemainFocus();
            } else if ($(ctrlDOBDay).val() !== "" && $(ctrlDOBDay).val() !== "dd") {
                setEmailRemainFocus();
            }
            //DP-12/20/2017-On Focus of any field on the email reminder page fire a utag.link with form_start, form_name and link_name.
            if (tagfire != true) {
                TealiumNotifyEmailRemainder_OnBlur();
                tagfire = true;
            }
        });

        $('#emailremainddlDOBYear').change(function () {
            ctrlDOBDay = '#emailremainddlDOBDay';
            ctrlDOBMonth = '#emailremainddlDOBMonth';
            ctrlDOByear = '#emailremainddlDOBYear';
            ctrlDOBError = '#emailremainerrorDOB';
            setEmailRemainFocus();

            //DP-12/20/2017-On Focus of any field on the email reminder page fire a utag.link with form_start, form_name and link_name.
            if (tagfire != true) {
                TealiumNotifyEmailRemainder_OnBlur();
                tagfire = true;
            }
        });

        function setEmailRemainFocus() {
            var isValid = validateEmailRemainDOB(ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError);

            if (!isValid) {
                setTimeout(function () {
                    $('#emailremainddlDOBMonth').focus();
                }, 10);
            }
        }

        //$('#trackingNumber').on('blur', function () {
        //    if ($('#trackingNumber').val() == "") {
        //        $('#trackingNumber').attr('class', 'error');
        //        $('#error_trackingNumber').show();
        //        IsValid = false;
        //    }
        //    else {
        //        $('#trackingNumber').attr('class', 'textfield textfieldW240');
        //        $('#error_trackingNumber').hide();
        //    }
        //});



        $('#trackingNumber,#beneNameLast').bind("keypress", function (event) {
            return isAlphaNumeric(event, $(this));
        });

        function isValidDateFormat(txtDate) {
            var currVal = txtDate;
            if (currVal == '')
                return false;

            var rxDatePattern = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/;
            var dtArray = currVal.match(rxDatePattern);

            if (dtArray == null)
                return false;

            dtMonth = dtArray[1];
            dtDay = dtArray[3];
            dtYear = dtArray[5];

            if (dtMonth < 1 || dtMonth > 12)
                return false;

            else if (dtDay < 1 || dtDay > 31)
                return false;

            else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31)
                return false;

            else if (dtMonth == 2) {
                var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
                if (dtDay > 29 || (dtDay == 29 && !isleap))
                    return false;
            }
            return true;
        }

        //End       

        $(".personalInfoDatePick").datepicker(
            { //DatePicker Call
                changeMonth: true, //Shows | Hides Month Drop-Down
                changeYear: true, //Shows | Hides Year Drop-Down
                dateFormat: 'mm/dd/yy', //formats date
                //minDate: '01/01/2000',
                minDate: '-100Y', //sets Minimum Date user can pick
                maxDate: '+1Y' //sets Maximum Date user can pick
                ,
                defaultDate: '01/01/2000'
                //,yearRange: '2000:' + new Date().getFullYear() //sets Year Dropdown Range
                ,
                yearRange: '-100:+1' //sets Year Dropdown Range
                ,
                onSelect: function () {
                    var selectedDate = $(this).val();
                    if (selectedDate.indexOf('/') != -1) {
                        var selectedMonth = selectedDate.split('/')[0];
                        var selectedDay = selectedDate.split('/')[1];
                        var selectedYear = selectedDate.split('/')[2];
                        var newDate = selectedMonth + "/" + "01/" + selectedYear;
                        $(this).val(newDate);

                        var control = '#' + $(this).attr('id');
                        var errorLabel = '#' + $(this).next().next().attr('id');
                        validatePersonalInfoHospitalDates(control, errorLabel);
                    }
                }
            });

        $(".datePickEnrollmentOption").datepicker(
            { //DatePicker Call
                changeMonth: true, //Shows | Hides Month Drop-Down
                changeYear: true, //Shows | Hides Year Drop-Down
                dateFormat: 'mm/dd/yy', //formats date
                minDate: '-100Y', //sets Minimum Date user can pick
                maxDate: '+1Y', //sets Maximum Date user can pick
                yearRange: '-100:+1' //sets Year Dropdown Range
                //Added For AdditionalInfo
                ,
                onSelect: function () {
                    var id = $(this).attr('id');
                    var control = '#' + id;

                    if (id == 'planAEffectiveDate' || id == 'planATermDate' || id == 'planAEffectiveDate2' || id == 'planATermDate2') {
                        if (validateDateAdditional(control)) {
                            $(control).attr('class', '');
                            $(control).next().hide();
                        }
                    }
                    else if (id.indexOf("txtdate") > -1) {
                        var controlErr = '#' + id + "error";

                        if (validateDateAdditional(control)) {
                            $(control).attr('class', 'datePickEnrollmentOption SEPSub');
                            $(controlErr).hide();
                        }
                    }
                }
            });

        $(".datePickEnrollmentOption").on('blur', function (e) {
            var id = $(this).attr('id');
            var control = '#' + id;
            var controlErr = '#' + id + "error";

            if (id.indexOf("txtdate") > -1) {
                if (validateDateAdditional(control)) {
                    $(control).attr('class', 'datePickEnrollmentOption SEPSub');
                    $(controlErr).hide();
                    $('#lblSEPSelectedError').hide();
                }
                else {
                    $(control).attr('class', 'datePickEnrollmentOption SEPSubError');
                    $(controlErr).show();
                }
            }

        });

        $(".datePick").datepicker(
            { //DatePicker Call
                changeMonth: true, //Shows | Hides Month Drop-Down
                changeYear: true, //Shows | Hides Year Drop-Down
                dateFormat: 'mm/dd/yy', //formats date
                minDate: '-100Y', //sets Minimum Date user can pick
                maxDate: '-1d', //sets Maximum Date user can pick
                yearRange: '-100' //sets Year Dropdown Range
                //Added For AdditionalInfo
                ,
                onSelect: function () {
                    var id = $(this).attr('id');
                    var control = '#' + id;

                    if (id == 'planAEffectiveDate' || id == 'planATermDate' || id == 'planAEffectiveDate2' || id == 'planATermDate2') {
                        if (validateDateAdditional(control)) {
                            $(control).attr('class', '');
                            $(control).next().hide();
                        }
                    }
                }
            });

        //Modified for Term Date and Effective Date
        $(".datePickTermEffective").datepicker(
            { //DatePicker Call
                changeMonth: true, //Shows | Hides Month Drop-Down
                changeYear: true, //Shows | Hides Year Drop-Down
                dateFormat: 'mm/dd/yy', //formats date
                minDate: '01/01/1890' //sets Minimum Date user can pick
                //,maxDate: '-1d'  //sets Maximum Date user can pick
                ,
                yearRange: '1890:9999' //sets Year Dropdown Range
                //Added For AdditionalInfo
                ,
                onSelect: function () {
                    var id = $(this).attr('id');
                    var control = '#' + id;

                    if (id == 'planAEffectiveDate' || id == 'planATermDate' || id == 'planAEffectiveDate2' || id == 'planATermDate2') {
                        if (validateDateAdditional(control)) {
                            $(control).attr('class', '');
                            $(control).next().hide();
                        }
                    }
                }
            });

        $(".datePick2").datepicker(
            { //DatePicker Call
                changeMonth: true, //Shows | Hides Month Drop-Down
                changeYear: true, //Shows | Hides Year Drop-Down
                dateFormat: 'mm/dd/yy', //formats date
                minDate: '1', //sets Minimum Date user can pick
                //maxDate: '-1d',  //sets Maximum Date user can pick
                yearRange: '2012:2014' //sets Year Dropdown Range
            });

        /**
		 *
		 * Form Validations Section
		 *
		 */
        //////
        // Form Validation Enroll Page 1
        //////
        $('#startInfoA').validate(
            {
                rules:
                {
                    planCheck: 'required'
                }
            });


        //////
        // Form Validation (Enroll Page 2)
        //////

        //var representative = $('input[name="ctl00$MainContent$group1"]:checked').val();
        //if (representative == "representative")
        //    $('#rep').show();

        //var representative = $('input[name="repChecked"]:checked').val();
        //if (representative !== undefined && representative.toString().toLowerCase() == "true")
        //    $('#rep').show();

        ///*caregiver section - mohana*/
        //var assist = $('input[name="ctl00$MainContent$assistance"]:checked').val();
        //if (typeof (assist) != "undefined") {
        //    if (assist == "caregiver") {
        //        $('#dvcaregiver').attr('style', 'display:block');
        //        $('#dvPOA').attr('style', 'display:none');
        //    }
        //    else if (assist == "POA") {
        //        $('#dvPOA').attr('style', 'display:block');
        //        $('#dvcaregiver').attr('style', 'display:none');
        //    }
        //}
        //else {
        //    $('#dvcaregiver').attr('style', 'display:none');
        //    $('#dvPOA').attr('style', 'display:none');

        //    //for Medicare Info page converted to MVC
        //    var poa = $('input[name="POAAssist"]:checked').val();
        //    if (typeof (poa) != "undefined" && poa.toString().toLowerCase() === "true") {
        //        $('#dvPOA').attr('style', 'display:block');
        //    }
        //    else {
        //        $('#dvPOA').attr('style', 'display:none');
        //    }
        //}


        //End Change
        $('#personalInfo input[type="radio"]').on('change', function () {
            var group1 = $('input[name="ctl00$MainContent$group1"]:checked').val();
            if (group1 == undefined) {
                group1 = $('input[name="repChecked"]:checked').val();
            }
            var group2 = $('input[name="ctl00$MainContent$group2"]:checked').val();
            if (group2 == undefined) {
                group2 = $('input[name="group2"]:checked').val();
            }
            // Show Hide Group 1
            if (group1 == "representative" || (group1 !== undefined && group1.toString().toLowerCase() == "true")) {
                $('#rep').show();
            }
            else {
                $('#rep').hide();
                $('#POAAssistError').hide();
            }

            /*Caregiver & POA sections - Mohana*/
            var assist = $('input[name="ctl00$MainContent$assistance"]:checked').val();
            if (typeof (assist) != "undefined") {
                if (assist == "caregiver") {
                    $('#dvPOA').attr('style', 'display:none');
                    $('#dvcaregiver').attr('style', 'display:block');
                }
                else if (assist == "POA") {
                    $('#dvPOA').attr('style', 'display:block');
                    $('#dvcaregiver').attr('style', 'display:none');
                }
            }
            else {
                $('#dvcaregiver').attr('style', 'display:none');
                $('#dvPOA').attr('style', 'display:none');

                //for Medicare Info page converted to MVC
                var poa = $('input[name="POAAssist"]:checked').val();
                if (typeof (poa) != "undefined" && poa.toString().toLowerCase() === "true") {
                    $('#dvPOA').attr('style', 'display:block');
                }
                else {
                    $('#dvPOA').attr('style', 'display:none');
                }
            }
        });

        /*Email Check validation on confirm field on continue - p2*/
        $.validator.addMethod("EqualsTocaregiverEmail", function (value, element) {

            var ConfEmail = value;
            return $.trim(ConfEmail).toLowerCase() == $.trim($('#careEmail').val()).toLowerCase() ? true : false;
        });

        /*Email Check validation on confirm field on continue - p2*/
        $.validator.addMethod("EqualsToRepEmail", function (value, element) {

            var ConfEmail = value;
            return $.trim(ConfEmail).toLowerCase() == $.trim($('#repEmail').val()).toLowerCase() ? true : false;
        });
        /*Email Check validation on confirm field on continue - p3*/
        $.validator.addMethod("EqualsToEmail3", function (value, element) {

            var ConfEmail = value;
            return $.trim(ConfEmail).toLowerCase() == $.trim($('#email3').val()).toLowerCase() ? true : false;

        });

        //$.validator.addMethod("EqualsToHIC", function (value, element) {
        //    var MediNumConfTrimmed = value.replace(/_/g, '');
        //    return $.trim(MediNumConfTrimmed).toLowerCase() == $.trim($('#mediNum').val()).toLowerCase() ? true : false;
        //});

        //$.validator.addMethod("EqualsToRR", function (value, element) {
        //    var rMediNumConfTrimmed = value.replace(/_/g, '');
        //    if (rMediNumConfTrimmed.length > 0)
        //        return $.trim(rMediNumConfTrimmed).toLowerCase() == $.trim($('#rMediNum').val()).toLowerCase() ? true : false;
        //    else
        //        return $.trim(value).toLowerCase() == $.trim($('#rMediNum').val()).toLowerCase() ? true : false;
        //});

        $.validator.addMethod("CheckDateOfBirth", function (value, element) {

            var ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError;
            ctrlDOBDay = '#ddlDOBDay';
            ctrlDOBMonth = '#ddlDOBMonth';
            ctrlDOByear = '#ddlDOBYear';
            ctrlDOBError = '#errorDOB';
            validateDateOfBirth(ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError);
        });

        //BD: Email Eob-opt in changes
        $.validator.addMethod("EqualsToeobemail", function (value, element) {
            var ConfEmail = value;
            return $.trim(ConfEmail).toLowerCase() == $.trim($('#eobemail').val()).toLowerCase() ? true : false;

        });

        //$(function () {
        //    $('input, select, textarea').each(function () {
        //        if ($(this).hasClass('input-validation-error'))
        //            $(this).focus();
        //    });
        //});

        //Validate  Personal Info page Email address 

        $('#email3Confirm').on('blur', function (e) {

            var email3 = $.trim($('#email3').val()).toLowerCase();
            var confemail = $.trim($('#email3Confirm').val()).toLowerCase();

            if (email3 != "" && confemail == "" && email3 != confemail) {
                $('#email3Confirm').attr('class', 'error long'); // email3 Confirm confirm input box
                $('#lblEmailAddressValidConfirm').show(); //confirm error message lable lblEmailAddressValidConfirm
                $('#lblEmailAddressValidConfirm').attr('class', 'error');
            }
            else if (email3 != "" && confemail != "" && email3 != confemail) {
                $('#email3Confirm').attr('class', 'error long'); // email3 Confirm confirm input box
                // $('#lblEmailAddressValidConfirm')
                $('#lblEmailAddressValidConfirm').show(); //confirm error message lable lblEmailAddressValidConfirm
                $('#lblEmailAddressValidConfirm').attr('class', 'error');
            }

            else if (email3 != "" && confemail != "" && email3 == confemail) {
                $('#email3').attr('class', 'long'); // email3 Confirm confirm input box
                $('#email3Confirm').attr('class', 'long'); //email input texbox email3
                $('#email3').next().hide();
                //$('#lblEmailAddressValid').hide();
                $('#lblEmailAddressValidConfirm').hide(); //email doesn't match box lblEmailAddressValidConfirm
            }

        });


        //BD: Email Eob-opt in changes
        //validate submit-application page confirm Email address
        //$('#eobemail').on('blur', function (e) {

        //    var email = $.trim($('#eobemail').val()).toLowerCase();
        //    var emailRegExp = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        //    if (email && !emailRegExp.test(email)) {

        //        $('#eobemail').attr('class', 'error long');
        //        $('#email3ErrLbl').show();
        //    }

        //    else {
        //        $('#eobemail').attr('class', 'long');
        //        $('#email3ErrLbl').hide();

        //    }
        //});

        //$('#eobemailConfirm').on('blur', function (e) {

        //    var email = $.trim($('#eobemail').val()).toLowerCase();
        //    var confemail = $.trim($('#eobemailConfirm').val()).toLowerCase();
        //    if (email != "" && confemail == "" && email != confemail) {
        //        $('#eobemailConfirm').attr('class', 'error long'); // email3 Confirm confirm input box
        //        $('#lblEmailAddressValidConfirm').show(); //confirm error message lable lblEmailAddressValidConfirm
        //        $('#lblEmailAddressValidConfirm').attr('class', 'error');
        //    }
        //    else if (email != "" && confemail != "" && email != confemail) {
        //        $('#eobemailConfirm').attr('class', 'error long'); // email3 Confirm confirm input box
        //        // $('#lblEmailAddressValidConfirm')
        //        $('#lblEmailAddressValidConfirm').show(); //confirm error message lable lblEmailAddressValidConfirm
        //        $('#lblEmailAddressValidConfirm').attr('class', 'error');
        //    }
        //    else if (email != "" && confemail != "" && email == confemail) {
        //        $('#eobemail').attr('class', 'long'); // email3 Confirm confirm input box
        //        $('#eobemailConfirm').attr('class', 'long'); //email input texbox email3
        //        $('#eobemail').next().hide();
        //        //$('#lblEmailAddressValid').hide();
        //        $('#lblEmailAddressValidConfirm').hide(); //email doesn't match box lblEmailAddressValidConfirm
        //    }
        //    else if (email == "" && confemail != "" && email != confemail) {
        //        //$('#lblEmailAddressValid').hide();
        //        $('#lblEOBemailAddressErrorMSg').hide(); //email doesn't match box lblEmailAddressValidConfirm
        //    }


        //});



        //Validate POA Email address
        $('#repConfEmail').on('blur', function (e) {

            var email = $.trim($('#repEmail').val()).toLowerCase();
            var confemail = $.trim($('#repConfEmail').val()).toLowerCase();

            if (email != "" && confemail != "" && email != confemail) {
                $('#repConfEmail').attr('class', 'error long');
                $('#repConfEmailErrLbl').show();
                $('#repConfEmailErrLbl').attr('class', 'error');
            }

            else if (email != "" && confemail != "" && email == confemail) {
                $('#repConfEmail').attr('class', 'long'); //Mohana
                $('#repEmail').attr('class', 'long'); //Mohana
                $('#repEmail').next().hide();
                $('#repConfEmailErrLbl').hide();

            }

            //Added this condition to fix Defect #2032
            else if (email == "" && confemail != "") {
                $('#repConfEmail').attr('class', 'error long');
                $('#repConfEmailErrLbl').show();
                $('#repConfEmailErrLbl').attr('class', 'error');
            }

        });

        //Validate Caregiver Email address
        $('#careEmailConf').on('blur', function (e) {

            var email = $.trim($('#careEmail').val()).toLowerCase();
            var confemail = $.trim($('#careEmailConf').val()).toLowerCase();

            if (email != "" && confemail != "" && email != confemail) {
                $('#careEmailConf').attr('class', 'error long');
                $('#lblcarePhoneErr').show();
                $('#lblcarePhoneErr').attr('class', 'error');
            }

            else if (email != "" && confemail != "" && email == confemail) {
                $('#careEmailConf').attr('class', 'long'); //Mohana
                $('#careEmail').attr('class', 'long'); //Mohana
                $('#careEmail').next().hide();
                $('#lblcarePhoneErr').hide();

            }
            else if (email == "" && confemail != "") {
                $('#careEmailConf').attr('class', 'error long');
                $('#lblcarePhoneErr').show();
                $('#lblcarePhoneErr').attr('class', 'error');
            }

        });


        function IsValidateMBINumber(control, showError) {
            //debugger;
            var MedicareValue = $(control).val();
            var dashCheck = MedicareValue;
            MedicareValue = dashCheck.replace(/[- ]/g, '').toUpperCase();
            var isValidMBI = false,
                isRegxMatched = false,
                MBIRegx;
            if (MedicareValue != "") {
                MBIRegx = /^[1-9][^(a-z)+SLOIBZsloibz\d\(s~`)!@#$%\^&*\(\)\(-)\(_)\+=\{\}\[\]\|:;""'<,>.?/][^(a-z)+SLOIBZsloibz\(s~`)!@#$%\^&*\(\)\(-)\(_)\+=\{\}\[\]\|:;""'<,>.?/][0-9][^(a-z)+SLOIBZsloibz\d\(s~`)!@#$%\^&*\(\)\(-)\(_)\+=\{\}\[\]\|:;""'<,>.?/][^(a-z)+SLOIBZsloibz\(s~`)!@#$%\^&*\(\)\(-)\(_)\+=\{\}\[\]\|:;""'<,>.?/][0-9][^(a-z)+SLOIBZsloibz\d\(s~`)!@#$%\^&*\(\)\(-)\(_)\+=\{\}\[\]\|:;""'<,>.?/][^(a-z)+SLOIBZsloibz\d\(s~`)!@#$%\^&*\(\)\(-)\(_)\+=\{\}\[\]\|:;""'<,>.?/][0-9][0-9]$/;

                isRegxMatched = MBIRegx.test(MedicareValue);
                if (!isRegxMatched)
                    isValidMBI = false;
                else
                    isValidMBI = true;
            }
            $(control).val(MedicareValue);
            return isValidMBI;
        }


        $('#mbiNum').on('blur', function (e) {
            //debugger;
            document.getElementById('mbiNum').value = $.trim($('#mbiNum').val()).toUpperCase();
            var mbiNum = $.trim($('#mbiNum').val()).toUpperCase().replace(/[- ]/g, '');
            $('#mbiNum').val(mbiNum);
            var errors = "";
            var elements = document.getElementsByClassName('error');
            for (var i = 0, len = elements.length; i < len; i++) {
                if (elements[i].style.display === 'block' && elements[i].innerText != '' && elements[i].className !== 'error hide')
                    errors += elements[i].innerText.trim() + '|';
            }
            if (errors != '')
                TealiumNotifyMbiErrors_OnClick(errors);
        });



        function isOnlyLetter(checkString) {
            var isOnlyLetter = true;
            for (var i = 0; i < checkString.length; i++) {
                keychar = checkString.charAt(i);
                charcheck = /[a-zA-Z]/;
                isOnlyLetter = charcheck.test(keychar);
                if (!isOnlyLetter)
                    break;
            }
            return isOnlyLetter;
        }

        function isOnlyDigit(checkString) {
            var isOnlyDigit = true;
            for (var i = 0; i < checkString.length; i++) {
                keychar = checkString.charAt(i);
                charcheck = /[0-9]/;
                isOnlyDigit = charcheck.test(keychar);
                if (!isOnlyDigit)
                    break;
            }
            return isOnlyDigit;
        }

        /*medicare page*/

        //Gendercheck to remove the error highlight


        //POA check to remove the error highlight
        $('[name="ctl00$MainContent$group1"]:radio').on('change', function () {
            var poacheck = $('input[name="ctl00$MainContent$group1"]:checked').val();
            if (typeof (poacheck) != "undefined" && (poacheck == "myself" || poacheck == "representative")) {

                $('#group1').next().attr('class', '');
                $('#repChecked').next().attr('class', '');
            }
            else if (typeof (poacheck) == "undefined") {
                $('#group1').next().attr('class', 'label-radio-error');
                $('#repChecked').next().attr('class', 'label-radio-error');
            }
        });

        //POA check to remove the error highlight
        //$('[name="repChecked"]:radio').on('change', function () {
        //    var poacheck = $('input[name="repChecked"]:checked').val().toString().toLowerCase();
        //    if (typeof (poacheck) != "undefined" && (poacheck == "true" || poacheck == "false")) {

        //        $("#repCheckedError").attr("style", "display:none");
        //        $('#group1').next().attr('class', '');
        //        $('#repChecked').next().attr('class', '');
        //    }
        //    else if (typeof (poacheck) == "undefined") {
        //        $('#group1').next().attr('class', 'label-radio-error');
        //        $('#repChecked').next().attr('class', 'label-radio-error');
        //        $("#repCheckedError").attr("style", "display:block");
        //    }
        //});

        //Assistance check to remove the error highlight - Mohana
        $('[name="ctl00$MainContent$assistance"]:radio').on('change', function () {

            var assistcheck = $('input[name="ctl00$MainContent$assistance"]:checked').val();
            if (typeof (assistcheck) != "undefined" && (assistcheck == "caregiver" || assistcheck == "POA")) {

                $('#caregiver').next().attr('class', '');
                $('#POA').next().attr('class', '');
            }
            else if (typeof (poacheck) == "undefined") {
                $('#caregiver').next().attr('class', 'label-radio-error');
                $('#POA').next().attr('class', 'label-radio-error');
            }
        });


        //Assistance check to remove the error highlight - Mohana
        //$('[name="POAAssist"]:radio').on('change', function () {

        //    var assistcheck = $('input[name="POAAssist"]:checked').val();
        //    if (typeof (assistcheck) != "undefined" && (assistcheck.toLowerCase() == "true")) {

        //        $('#caregiver').next().attr('class', '');
        //        $('#POA').next().attr('class', '');
        //        $("#POAAssistError").hide();
        //    }
        //    else if (typeof (poacheck) == "undefined") {
        //        $('#caregiver').next().attr('class', 'label-radio-error');
        //        $('#POA').next().attr('class', 'label-radio-error');
        //        $("#POAAssistError").show();
        //    }
        //});

        //othercoverage check to remove the error highlight
        $('[name="ctl00$MainContent$otherCoverage"]:radio').on('change', function () {
            var othercovcheck = $('input[name="ctl00$MainContent$otherCoverage"]:checked').val();
            if (typeof (othercovcheck) != "undefined" && (othercovcheck == "yes" || othercovcheck == "no")) {

                $('#otherCoverageYes').next().attr('class', '');
                $('#otherCoverageNo').next().attr('class', '');
            }
            else if (typeof (othercovcheck) == "undefined") {
                $('#otherCoverageYes').next().attr('class', 'label-radio-error');
                $('#otherCoverageNo').next().attr('class', 'label-radio-error');
            }
        });

        $('[name="otherCoverage"]:radio').on('change', function () {
            //$("#errorEffectiveDate").hide()
            //$("#errorTermDate").hide()

            //$('#planAEffectiveDateDay').attr('class', 'textfield');
            //$('#planAEffectiveDateMonth').attr('class', 'textfield');
            //$('#planAEffectiveDateYear').attr('class', 'textfield');

            //$('#planATermDateMonth').attr('class', 'textfield');
            //$('#planATermDateDay').attr('class', 'textfield');
            //$('#planATermDateYear').attr('class', 'textfield');

            var othercovcheck = $('input[name="otherCoverage"]:checked').val();
            if (typeof (othercovcheck) != "undefined" && (othercovcheck == "yes" || othercovcheck == "no")) {

                $('#otherCoverageYes').next().attr('class', '');
                $('#otherCoverageNo').next().attr('class', '');
            }
            else if (typeof (othercovcheck) == "undefined") {
                $('#otherCoverageYes').next().attr('class', 'label-radio-error');
                $('#otherCoverageNo').next().attr('class', 'label-radio-error');
            }
        });

        ////othercoverage2 check to remove the error highlight
        //$('[name="ctl00$MainContent$otherCoverage2"]:radio').on('change', function () {
        //    var othercovcheck = $('input[name="ctl00$MainContent$otherCoverage2"]:checked').val();
        //    if (typeof (othercovcheck) != "undefined" && (othercovcheck == "yes" || othercovcheck == "no")) {

        //        $('#othercoverage2Yes').next().attr('class', '');
        //        $('#othercoverage2No').next().attr('class', '');
        //    }
        //    else if (typeof (othercovcheck) == "undefined") {
        //        $('#othercoverage2Yes').next().attr('class', 'label-radio-error');
        //        $('#othercoverage2No').next().attr('class', 'label-radio-error');
        //    }
        //});

        //$('[name="otherCoverage2"]:radio').on('change', function () {
        //   // $('[name="otherCoverage2"]').next().removeClass("label-radio-error");
        //   // $("#lblAdditionalValid2").parent().hide();

        //    //$("#errorEffectiveDate2").hide()
        //    //$("#errorTermDate2").hide()

        //    //$('#planAEffectiveDate2Month').attr('class', 'textfield');
        //    //$('#planAEffectiveDate2Day').attr('class', 'textfield');
        //    //$('#planAEffectiveDate2Year').attr('class', 'textfield');
        //    //$('#planATermDate2Month').attr('class', 'textfield');
        //    //$('#planATermDate2Day').attr('class', 'textfield');
        //    //$('#planATermDate2Year').attr('class', 'textfield');

        //    var othercovcheck = $('input[name="otherCoverage2"]:checked').val();
        //    if (typeof (othercovcheck) != "undefined" && (othercovcheck == "yes" || othercovcheck == "no")) {

        //        $('#othercoverage2Yes').next().attr('class', '');
        //        $('#othercoverage2No').next().attr('class', '');
        //    }
        //    else if (typeof (othercovcheck) == "undefined") {
        //        $('#othercoverage2Yes').next().attr('class', 'label-radio-error');
        //        $('#othercoverage2No').next().attr('class', 'label-radio-error');
        //    }
        //});

        ////sep check to remove the error highlight
        //$('[name="ctl00$MainContent$grpInner"]:radio').on('change', function () {
        //    var sepcovcheck = $('input[name="ctl00$MainContent$grpInner"]:checked').val();
        //    if (typeof (sepcovcheck) != "undefined" && sepcovcheck != "") {
        //        removeIEPSEPRedRadios()
        //    }
        //});

        ////iep check to remove the error highlight
        //$('[name="ctl00$MainContent$grpInner1"]:radio').on('change', function () {
        //    var iepcovcheck = $('input[name="ctl00$MainContent$grpInner1"]:checked').val();
        //    if (typeof (iepcovcheck) != "undefined" && iepcovcheck != "") {
        //        removeIEPSEPRedRadios()
        //    }
        //});

        //$('[name="SEPREASONCD"]:radio').on('change', function () {
        //    var iepcovcheck = $('input[name="SEPREASONCD"]:checked').val();
        //    if (typeof (iepcovcheck) != "undefined" && iepcovcheck != "") {
        //        removeIEPSEPRedRadios()
        //    }
        //});



        function removeIEPSEPRedRadios() {

            $('#enrollSubSEP :radio').each(function () {
                $(this).next().attr('class', '');
            });
            $('#enrollSubIEP  :radio').each(function () {
                $(this).next().attr('class', '');
            });
            $('label[for="ctl00$MainContent$grpInner1"]').hide();
            $('label[for="ctl00$MainContent$grpInner"]').hide();
            $('#iepRadioError').hide();
            $('#sepRadioError').hide();
        }

        function makeIEPSEPRedRadios() {

            $('#enrollSubSEP  :radio').each(function () {
                $(this).attr('class', 'error');
                $(this).next().attr('class', 'label-radio-error');
            });
            $('#enrollSubIEP  :radio').each(function () {
                $(this).attr('class', 'error');
                $(this).next().attr('class', 'label-radio-error');
            });
            $('#iepRadioError').show();
            $('#sepRadioError').show();
        }

        function validateDDL(selectedValue, ddlname) {

            if (selectedValue == "S") {
                $(ddlname).attr('class', 'select-ddl-error');
                $(ddlname).next().show();
                return false;
            }
            else {

                $(ddlname).attr('class', 'textfield ');
                return true;
            }
        }

        /*medicare info page validation*/
        $('#btnSubmitPersonalInfo, #oKButtonPersonalInfo, #btnSavePersonalnfo').click(function (e) {

            var errorList = [];
            var formId = this.form.id
            var isFormInvalid = false;
            var showPartABError = false;

            var result1 = true,
                result2 = true;
            var radioButton = $('input[name="IsRailRoadRetiree"]:checked').val();

            var control1, control2, errorLabel1, errorLabel2;
            var ctrlDOBDay, ctrlDOBMonth, ctrlDOByear, ctrlDOBError;
            var ctrlPartAMonth, ctrlPartAYear, ctrlPartBMonth, ctrlPartBYear;


            var repstate = $("#repState option:selected").val(); /*medicare page*/
            var selectedValue = $("#ddlRelationshipToYou option:selected").val();
            var representative = $('input[name="repChecked"]:checked').val();
            var assist = $('input[name="POAAssist"]:checked').val();




            ctrlPartAMonth = '#ddlPartAMonth';
            ctrlPartAYear = '#ddlPartAYear';
            ctrlPartBMonth = '#ddlPartBMonth';
            ctrlPartBYear = '#ddlPartBYear';

            control1 = '#haPick';
            control2 = '#hbPick';
            errorLabel1 = '#errorhaPick';
            errorLabel2 = '#errorhbPick';

            // Valdiation Check for "Are you applying for yourself or someone else"
            if (typeof (representative) == "undefined") {
                var errorMessage = "Select an applicant";
                $('#group1').next().attr('aria-required', 'true');
                $('#group1').next().attr('aria-labelledby', 'lblPlsSelectOne');
                $('#group1').next().attr('class', 'label-radio-error');
                $('#repChecked').next().attr('class', 'label-radio-error');
                isFormInvalid = true;
                $("#repCheckedError").attr("style", "display:block");
                $("#lblPlsSelectOne").html(errorMessage);
                $("#lblPlsSelectOne").attr("aria-label", " (Error) " + errorMessage).attr("role", "text");
                $(".repSelect").addClass("radioErrorEnroll");
                addValidationError("group1", errorMessage, errorList);
            }
            else if (representative == "representative" || representative.toLowerCase() == "true") {

                $("#repCheckedError").attr("style", "display:none");
                $(".repSelect").removeClass("radioErrorEnroll");
                if (typeof (assist) != "undefined") {
                    $("#rdio-3-med").removeClass("radioErrorEnroll");
                    $('#POA').next().removeClass('label-radio-error');
                    $("#POAAssistError").attr("style", "display:none");

                    if (assist == "POA" || assist.toLowerCase() == "true") {

                        var repFullName = $("#repFullName").val()

                        if (repFullName == "") {
                            var error = "Enter your full name";
                            $('#repFullName').removeClass("valid").addClass("error");
                            $('#repFullName').next().show();
                            $("#lblPlsEnterYourName").html(error)
                            $("#lblPlsEnterYourName").attr("aria-label", " (Error) " + error).attr("role", "text");
                            isFormInvalid = true;

                            addValidationError("repFullName", error, errorList);
                        } else {
                            $('#repFullName').removeClass("error").addClass("valid");
                            $('#repFullName').next().hide();
                        }

                        var selectedValue = $("#ddlRelationshipToYou option:selected").val();

                        if (selectedValue == "S") {
                            var error = "Select relationship";
                            $('#ddlRelationshipToYou').attr('class', 'select-ddl-error'); /*medicare page*/
                            $("#ddlRelationshipToYou").next().show();
                            $("#lblPlsSelectRelationShip").html(error);
                            $("#lblPlsSelectRelationShip").attr("aria-label", " (Error) " + error).attr("role", "text");
                            isFormInvalid = true;
                            addValidationError("ddlRelationshipToYou", error, errorList);
                        }
                        else {
                            $('#ddlRelationshipToYou').attr('class', 'textfield'); /*medicare page*/
                            $("#ddlRelationshipToYou").next().hide();
                        }

                        var repAddress = $("#repAddress").val()

                        if (repAddress == "") {
                            var error = "Enter your address";

                            $('#repAddress').removeClass("valid").addClass("error");
                            $('#repAddress').next().show();
                            $("#lblPlsEnterYourAddress").html(error);
                            $("#lblPlsEnterYourAddress").attr("aria-label", " (Error) " + error).attr("role", "text");
                            isFormInvalid = true;
                            addValidationError("repAddress", error, errorList);
                        } else {
                            $('#repAddress').removeClass("error").addClass("valid");
                            $('#repAddress').next().hide();
                        }

                        var repCity = $("#repCity").val()

                        if (repCity == "") {
                            var error = "Enter your city";

                            $('#repCity').removeClass("valid").addClass("error");
                            $('#repCity').next().show();
                            $("#lblPlsEnterYourCity").html(error);
                            $("#lblPlsEnterYourCity").attr("aria-label", " (Error) " + error).attr("role", "text");
                            isFormInvalid = true;
                            addValidationError("repCity", error, errorList);
                        } else {
                            $('#repCity').removeClass("error").addClass("valid");
                            $('#repCity').next().hide();
                        }

                        var repState = $("#repState").val()

                        if (repState == undefined || repState == "") {
                            var error = "Enter your state";
                            $('#repState').removeClass("valid").addClass("select-ddl-error");
                            $('#repState').next().show();
                            $("#lblPlsSelectState").html(error);
                            $("#lblPlsSelectState").attr("aria-label", " (Error) " + error).attr("role", "text");
                            isFormInvalid = true;
                            addValidationError("repState", error, errorList);
                        } else {
                            $('#repState').removeClass("select-ddl-error").addClass("valid");
                            $('#repState').next().hide();
                        }


                        var repZipCode = $("#repZipCode").val()

                        if (repZipCode == "") {
                            var error = "Enter your ZIP Code";
                            $('#repZipCode').removeClass("valid").addClass("error");
                            $('#repZipCode').next().show();
                            $("#lblplsenterzipcode").html(error);
                            $("#lblplsenterzipcode").attr("aria-label", " (Error) " + error).attr("role", "text");
                            isFormInvalid = true;
                            addValidationError("repZipCode", error, errorList);
                        } else {
                            $('#repZipCode').removeClass("error").addClass("valid");
                            $('#repZipCode').next().hide();
                        }

                        var repPhoneNum = $("#repPhoneNum").val()

                        if (repPhoneNum == "") {
                            var error = "Enter a valid 10 digit phone number";
                            $('#repPhoneNum').removeClass("valid").addClass("error");
                            $('#repPhoneNum').next().show();
                            $("#lblPlsEnterPhoneNumber").html(error);
                            $("#lblPlsEnterPhoneNumber").attr("aria-label", " (Error) " + error).attr("role", "text");
                            isFormInvalid = true;
                            addValidationError("repPhoneNum", error, errorList);
                        } else {
                            var repPhoneNumCheck = repPhoneNum.replace(/[^0-9]/g, "");
                            if (repPhoneNumCheck.length != 10) {
                                var error = "Enter a valid 10 digit phone number";
                                $('#repPhoneNum').removeClass("valid").addClass("error");
                                $('#repPhoneNum').next().show();
                                $("#lblPlsEnterPhoneNumber").html(error);
                                $("#lblPlsEnterPhoneNumber").attr("aria-label", " (Error) " + error).attr("role", "text");
                                isFormInvalid = true;
                                addValidationError("repPhoneNum", error, errorList);
                            } else {
                                $('#repPhoneNum').removeClass("error").addClass("valid");
                                $('#repPhoneNum').next().hide();
                            }
                        }

                        var email = $.trim($('#repEmail').val()).toLowerCase();
                        var emailRegExp = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

                        if (email && !emailRegExp.test(email)) {
                            var error = "Enter an email address, for example address@mail.com";
                            $('#repEmail').attr('class', 'error long');
                            $('#repEmailErrLbl').show();
                            $("#lblInValidEmailAddress").html(error);
                            $("#lblInValidEmailAddress").attr("aria-label", " (Error) " + error).attr("role", "text");
                            isFormInvalid = true;
                            addValidationError("repEmail", error, errorList);
                        }
                        else {
                            $('#repEmail').attr('class', 'long');
                            $('#repEmailErrLbl').hide();
                        }
                    }
                }
                else {
                    var error = "Select an option to continue"
                    $('#caregiver').next().attr('class', 'label-radio-error');
                    $('#POA').next().attr('class', 'label-radio-error');
                    $("#POAAssistError").attr("style", "display:block");
                    $("#rdio-3-med").addClass("radioErrorEnroll");
                    $("#lblAssistance").html(error)
                    $("#lblAssistance").attr("aria-label", " (Error) " + error).attr("role", "text");
                    isFormInvalid = true;

                    addValidationError("POA", error, errorList);

                }
            }
            else {
                $("#repCheckedError").attr("style", "display:none");
                $(".repSelect").removeClass("radioErrorEnroll");
            }

            //Validation for First Name
            var firstName = $('#beneNameFirst').val();
            if (firstName === undefined || firstName == '') {
                var error = "Enter your first name";
                $("#beneNameFirst").addClass("error");
                $("#firstNameErr").attr("style", "display:block");
                $("#lblfirstNameErr").html(error);
                $("#lblfirstNameErr").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
                addValidationError("beneNameFirst", error, errorList);
            }
            else {
                $("#firstNameErr").attr("style", "display:none");
                $("#beneNameFirst").removeClass("error");
            }

            //Validation for Last Name
            var lastName = $('#beneNameLast').val();
            if (lastName === undefined || lastName == '') {
                var error = "Enter your last name";
                $("#beneNameLast").addClass("error");
                $("#lastNameErr").attr("style", "display:block");
                $("#lblLastNameErr").html(error);
                $("#lblLastNameErr").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
                addValidationError("beneNameLast", error, errorList);
            }
            else {
                $("#lastNameErr").attr("style", "display:none");
                $("#beneNameLast").removeClass("error");
            }

            //validate RRL No
            if (radioButton == "rMediCard" || radioButton.toLocaleLowerCase() == "true") {
                if (!IsValidateMBINumber('#mbiNum', true)) {
                    $("#mbiNum").addClass("error");
                    $('#lblInvalidMBINumber').html("Invalid Medicare Number format. Enter the numbers and letters exactly as they appear on your Medicare card.");
                    $('#lblInvalidMBINumber').attr("aria-label", " (Error) " +
                        "Invalid Medicare Number format. Enter the numbers and letters exactly as they appear on your Medicare card.").attr("role", "text");
                    $('#lblInvalidMBINumber').attr('style', 'display:block');
                    isFormInvalid = true;

                    addValidationError("mbiNum", "Enter a valid Medicare Number", errorList);
                }
                else {
                    $("#mbiNum").removeClass("error");
                    $("#lblInvalidMBINumber").attr("style", "display:none");
                }
            }

            //validate Medicare No
            if (radioButton == "mediCard" || radioButton.toLowerCase() == "false") {

                if (!IsValidateMBINumber('#mbiNum', true)) {
                    $("#mbiNum").addClass("error");
                    $('#lblInvalidMBINumber').html("Invalid Medicare Number format. Enter the numbers and letters exactly as they appear on your Medicare card.");
                    $('#lblInvalidMBINumber').attr("aria-label", " (Error) " +
                        "Invalid Medicare Number format. Enter the numbers and letters exactly as they appear on your Medicare card.").attr("role", "text");
                    $('#lblInvalidMBINumber').attr('style', 'display:block');

                    isFormInvalid = true;
                    addValidationError("mbiNum", "Enter a valid Medicare Number", errorList);
                }
                else {
                    $("#mbiNum").removeClass("error");
                    $('#mbiNum').attr('class', '');
                    $('#lblInvalidMBINumber').attr('style', 'display:none');
                }
            }


            //Validate Part A/B Dates
            if (!validatePersonalInfoOptionalDates(ctrlPartAMonth, ctrlPartAYear, ctrlPartBMonth, ctrlPartBYear, errorList)) {
                isFormInvalid = true;
            }
            //Validate Gender is selected.
            var gender = $('input[name="Sex"]:checked').val();

            //GenderCheck
            if (typeof (gender) == "undefined") {
                $('#rbMedicareMale').next().attr('class', 'label-radio-error');
                $('#group4').next().attr('class', 'label-radio-error');

                var error = "Select a sex";
                $("#lblPlsEnterYourGender").html(error);
                $("#lblPlsEnterYourGender").attr("aria-label", " (Error) " + error).attr("role", "text");
                $("#lblPlsEnterYourGender").show();
                $("#lblPlsEnterYourGender").attr("style", "display:block");
                $("#rdio-4-med").addClass("radioErrorEnroll");
                $("#rdio-5-med").addClass("radioErrorEnroll");

                addValidationError("rbMedicareMale", error, errorList);
                isFormInvalid = true;
            } else {
                $('#rbMedicareMale').next().removeClass('label-radio-error');
                $("#group4").next().removeClass('label-radio-error');

                $("#rdio-4-med").removeClass("radioErrorEnroll");
                $("#rdio-5-med").removeClass("radioErrorEnroll");
                $("#lblPlsEnterYourGender").attr("style", "display:none");
                $("#lblPlsEnterYourGender").hide();
            }


            //DOB Check  
            var monthPartDOB = $.trim($("#ddlDOBMonth").val());
            var datePartDOB = $.trim($("#ddlDOBDay").val());
            var yearPartDOB = $.trim($("#ddlDOBYear").val());

            $("#dobMonthError").removeClass("dobMonthError");
            $("#dobDayError").removeClass("dobDayError");
            $("#dobYearError").removeClass("dobYearError");

            $('#ddlDOBMonth').removeClass("select-ddl-error");
            $('#ddlDOBDay').removeClass("select-ddl-error");
            $('#ddlDOBYear').removeClass("select-ddl-error");
            $("#dobMonthError").hide();
            $("#dobDayError").hide();
            $("#dobYearError").hide();

            if ((datePartDOB != "") && (monthPartDOB != "") && (yearPartDOB != "") && (datePartDOB != "00") && (monthPartDOB != "00")) //&& DOB.indexOf('/') != -1) 
            {
                var isDOBValid = true;
                var userDate = new Date();
                userDate.setFullYear(yearPartDOB, monthPartDOB - 1, datePartDOB - 1);
                var currDate = new Date();
                currDate.setFullYear(currDate.getFullYear() - 65);

                var currentYear = new Date().getFullYear();

                //DOB
                if (((datePartDOB >= 01) & (datePartDOB <= 31)) & ((monthPartDOB >= 01) & (monthPartDOB <= 12)) & ((yearPartDOB >= 1887) & (yearPartDOB <= currentYear))) {
                    var dobDate = Date.parse(monthPartDOB + '/' + datePartDOB + '/' + yearPartDOB);
                    var fullDate = new Date();
                    var twoDigitMonth = ((fullDate.getMonth().length + 1) === 1) ? (fullDate.getMonth() + 1) : '0' + (fullDate.getMonth() + 1);
                    var formatedDate = twoDigitMonth + "/" + fullDate.getDate() + "/" + fullDate.getFullYear();
                    var currentDate = Date.parse(formatedDate);

                    if (!validDate(datePartDOB, monthPartDOB, yearPartDOB)) {
                        isDOBValid = false;
                    }


                    if (isDOBValid) {
                        if (dobDate >= currentDate) {
                            isDOBValid = false;
                        }
                        //else if (new Date() <= new Date(DOB)) {
                        //    isDOBValid = false;
                        //}
                    }
                }
                else {
                    isDOBValid = false;
                }

                if (!isDOBValid) {
                    $('#ddlDOBMonth').attr('class', 'select-ddl-error');
                    $("#dobMonthError").addClass("dobMonthError");
                    var dobMonthErrMsg = "Select a valid birth month";
                    $("#dobMonthError").html(dobMonthErrMsg);
                    $("#dobMonthError").attr("aria-label", " (Error) " + dobMonthErrMsg).attr("role", "text");
                    $("#dobMonthError").show();
                    addValidationError("ddlDOBMonth", dobMonthErrMsg, errorList);

                    $('#ddlDOBDay').attr('class', 'select-ddl-error');
                    $("#dobDayError").addClass("dobDayError");
                    var dobDayErrMsg = "Select a valid birth day";
                    $("#dobDayError").html(dobDayErrMsg);
                    $("#dobDayError").attr("aria-label", " (Error) " + dobDayErrMsg).attr("role", "text");
                    $("#dobDayError").show();

                    addValidationError("ddlDOBDay", dobDayErrMsg, errorList);

                    $('#ddlDOBYear').attr('class', 'select-ddl-error width105');

                    $("#dobYearError").addClass("dobYearError");
                    var dobYearErrMsg = "Select a valid birth year";
                    $("#dobYearError").html(dobYearErrMsg);
                    $("#dobYearError").attr("aria-label", " (Error) " + dobYearErrMsg).attr("role", "text");
                    $("#dobYearError").show();

                    addValidationError("ddlDOBYear", dobYearErrMsg, errorList);

                    isFormInvalid = true;
                }
            }
            else {
                $('#ddlDOBMonth').attr('class', 'select-ddl-error');
                $("#dobMonthError").addClass("dobMonthError");
                var dobMonthErrMsg = "Select a valid birth month";
                $("#dobMonthError").html(dobMonthErrMsg);
                $("#dobMonthError").attr("aria-label", " (Error) " + dobMonthErrMsg).attr("role", "text");
                $("#dobMonthError").show();
                addValidationError("ddlDOBMonth", dobMonthErrMsg, errorList);

                $('#ddlDOBDay').attr('class', 'select-ddl-error');
                $("#dobDayError").addClass("dobDayError");
                var dobDayErrMsg = "Select a valid birth day";
                $("#dobDayError").html(dobDayErrMsg);
                $("#dobDayError").attr("aria-label", " (Error) " + dobDayErrMsg).attr("role", "text");
                $("#dobDayError").show();

                addValidationError("ddlDOBDay", dobDayErrMsg, errorList);

                $('#ddlDOBYear').attr('class', 'select-ddl-error width105');

                $("#dobYearError").addClass("dobYearError");
                var dobYearErrMsg = "Select a valid birth year";
                $("#dobYearError").html(dobYearErrMsg);
                $("#dobYearError").attr("aria-label", " (Error) " + dobYearErrMsg).attr("role", "text");
                $("#dobYearError").show();

                addValidationError("ddlDOBYear", dobYearErrMsg, errorList);
                isFormInvalid = true;
            }



            if (isFormInvalid) {

                $("#ValidationTitle").show();
                //Show the error banner
                ShowValidationSummaryWithTitle(errorList, formId, "Information is missing or is not valid", showPartABError);

                //Tealium Errors
                var errors = "";
                var elements = document.getElementsByClassName('error');
                for (var i = 0, len = elements.length; i < len; i++) {
                    if (elements[i].style.display === 'block' && elements[i].innerText != '' && elements[i].className !== 'error hide')
                        errors += elements[i].innerText.trim() + '|';
                }
                if (errors != '')
                    TealiumNotifyErrors_OnClick(errors);
                return false;
            }
        });


        function validatePersonalInfoOptionalDates(ctrlPartAMonth, ctrlPartAYear, ctrlPartBMonth, ctrlPartBYear, errorList) {
            //Reset validation state for Part A/B dropdowns
            $("#partAMonthErr").hide();
            $("#partADayErr").hide();
            $("#partAYearErr").hide();

            $("#partBMonthErr").hide();
            $("#partBDayErr").hide();
            $("#partBYearErr").hide();

            $("#ddlPartAMonth").removeClass("select-ddl-error");
            $("#ddlPartADay").removeClass("select-ddl-error");
            $("#ddlPartAYear").removeClass("select-ddl-error");

            $("#ddlPartBMonth").removeClass("select-ddl-error");
            $("#ddlPartBDay").removeClass("select-ddl-error");
            $("#ddlPartBYear").removeClass("select-ddl-error");

            //Validation check for Part A/B Dates
            var dayPartA = "1";
            var monthPartA = $.trim($(ctrlPartAMonth).val());
            var yearPartA = $.trim($(ctrlPartAYear).val());

            var dayPartB = "1";
            var monthPartB = $.trim($(ctrlPartBMonth).val());
            var yearPartB = $.trim($(ctrlPartBYear).val());

            if ((monthPartB == "" && yearPartB == "" && monthPartA == "" && yearPartA == "")) {
                /*medicare page*/
                $(ctrlPartAMonth).attr('class', 'select-ddl-error');
                $(ctrlPartAYear).attr('class', 'select-ddl-error');
                $(ctrlPartBMonth).attr('class', 'select-ddl-error');
                $(ctrlPartBYear).attr('class', 'select-ddl-error');

                var partAMonthError = "Select valid Part A month";
                $("#partAMonthErr").show()
                $("#partAMonthErr").html("<span>" + partAMonthError + "</span>");
                $("#partAMonthErr").attr("aria-label", " (Error) " + partAMonthError).attr("role", "text");

                addValidationError("ddlPartAMonth", partAMonthError, errorList);

                var partAYearError = "Select valid Part A year";
                $("#partAYearErr").show()
                $("#partAYearErr").html("<span>" + partAYearError + "</span>");
                $("#partAYearErr").attr("aria-label", " (Error) " + partAYearError).attr("role", "text");

                addValidationError("ddlPartAYear", partAYearError, errorList);



                var partBMonthError = "Select valid Part B month";
                $("#partBMonthErr").show()
                $("#partBMonthErr").html("<span>" + partBMonthError + "</span>");
                $("#partBMonthErr").attr("aria-label", " (Error) " + partBMonthError).attr("role", "text");

                addValidationError("ddlPartBMonth", partBMonthError, errorList);

                var partBYearError = "Select valid Part B year";
                $("#partBYearErr").show()
                $("#partBYearErr").html("<span>" + partBYearError + "</span>");
                $("#partBYearErr").attr("aria-label", " (Error) " + partBYearError).attr("role", "text");

                addValidationError("ddlPartBYear", partBYearError, errorList);

                return false;
            }
            else {
                var isPArtABDateInvalid = false;
                if (monthPartA != "" || yearPartA != "") {
                    if (monthPartA == "") {
                        $(ctrlPartAMonth).attr('class', 'select-ddl-error');

                        //$("#partAYearErr").show()

                        var partAMonthError = "Select valid Part A month";
                        $("#partAMonthErr").show()
                        $("#partAMonthErr").html("<span>" + partAMonthError + "</span>");
                        $("#partAMonthErr").attr("aria-label", " (Error) " + partAMonthError).attr("role", "text");

                        addValidationError("ddlPartAMonth", partAMonthError, errorList);
                        isPArtABDateInvalid = true;
                    }
                    if (yearPartA == "") {
                        $(ctrlPartAYear).attr('class', 'select-ddl-error');

                        // $("#partAMonthErr").show()
                        if ($("#partAMonthErr").is(":hidden")) {
                            $("#partAMonthErr").show();
                            $("#partAMonthErr").html();
                        }
                        var partAYearError = "Select valid Part A year";
                        $("#partAYearErr").show()
                        $("#partAYearErr").html("<span>" + partAYearError + "</span>");
                        $("#partAYearErr").attr("aria-label", " (Error) " + partAYearError).attr("role", "text");

                        addValidationError("ddlPartAYear", partAYearError, errorList);
                        isPArtABDateInvalid = true;
                    }

                    if (monthPartA != "" && yearPartA != "") {
                        if (!validDate(dayPartA, monthPartA, yearPartA)) {
                            /*medicare page*/

                            $(ctrlPartAMonth).attr('class', 'select-ddl-error');

                            $("#partAYearErr").show()

                            var partAMonthError = "Select valid Part A month";
                            $("#partAMonthErr").show()
                            $("#partAMonthErr").html("<span>" + partAMonthError + "</span>");
                            $("#partAMonthErr").attr("aria-label", " (Error) " + partAMonthError).attr("role", "text");

                            addValidationError("ddlPartAMonth", partAMonthError, errorList);

                            $(ctrlPartAYear).attr('class', 'select-ddl-error');

                            $("#partAMonthErr").show()

                            var partAYearError = "Select valid Part A year";
                            $("#partAYearErr").show()
                            $("#partAYearErr").html("<span>" + partAYearError + "</span>");
                            $("#partAYearErr").attr("aria-label", " (Error) " + partAYearError).attr("role", "text");

                            addValidationError("ddlPartAYear", partAYearError, errorList);

                            isPArtABDateInvalid = true;
                        }
                    }
                }

                if (monthPartB != "" || yearPartB != "") //&& ((monthPartA == "" && yearPartA == ""))) 
                {
                    if (monthPartB == "") {
                        $(ctrlPartBMonth).attr('class', 'select-ddl-error');

                        var partBMonthError = "Select valid Part B month";
                        $("#partBMonthErr").show()
                        $("#partBMonthErr").html("<span>" + partBMonthError + "</span>");
                        $("#partBMonthErr").attr("aria-label", " (Error) " + partBMonthError).attr("role", "text");

                        addValidationError("ddlPartBMonth", partBMonthError, errorList);
                        isPArtABDateInvalid = true;
                    }
                    if (yearPartB == "") {
                        $(ctrlPartBYear).attr('class', 'select-ddl-error');

                        if ($("#partBMonthErr").is(":hidden")) {
                            $("#partBMonthErr").show();
                            $("#partBMonthErr").html();
                        }


                        var partBYearError = "Select valid Part B year";
                        $("#partBYearErr").show()
                        $("#partBYearErr").html("<span>" + partBYearError + "</span>");
                        $("#partBYearErr").attr("aria-label", " (Error) " + partBYearError).attr("role", "text");

                        addValidationError("ddlPartBYear", partBYearError, errorList);
                        isPArtABDateInvalid = true;

                    }
                    if ((monthPartB != "" && yearPartB != "")) {
                        if (!validDate(dayPartB, monthPartB, yearPartB)) {
                            /*medicare page*/
                            $(ctrlPartBMonth).attr('class', 'select-ddl-error');

                            $("#partBYearErr").show()

                            var partBMonthError = "Select valid Part B month";
                            $("#partBMonthErr").show()
                            $("#partBMonthErr").html("<span>" + partBMonthError + "</span>");
                            $("#partBMonthErr").attr("aria-label", " (Error) " + partBMonthError).attr("role", "text");

                            addValidationError("ddlPartBMonth", partBMonthError, errorList);

                            $(ctrlPartBYear).attr('class', 'select-ddl-error');

                            $("#partBMonthErr").show()

                            var partBYearError = "Select valid Part B year";
                            $("#partBYearErr").show()
                            $("#partBYearErr").html("<span>" + partBYearError + "</span>");
                            $("#partBYearErr").attr("aria-label", " (Error) " + partBYearError).attr("role", "text");

                            addValidationError("ddlPartBYear", partBYearError, errorList);
                            isPArtABDateInvalid = true;
                        }
                    }
                }

                if (isPArtABDateInvalid) {
                    return false;
                }
            }

            return true;
        }

        function validatePersonalInfoDates(ctrl, errorControl, commonErrorMsg, commonErrorMsgId) {
            var txtValue = $(ctrl).val();
            if (txtValue != "" && txtValue.indexOf('/') != -1) {
                var datePart = txtValue.split('/')[1];
                if (datePart != "01") {
                    $(ctrl).attr('class', 'error');
                    $(errorControl).html("<br/>Invalid Date (Valid Format is MM/01/YYYY).");
                    $(errorControl).show();
                    return false;
                }
            }
            else {
                $(ctrl).attr('class', '');
                var errorMsg = $(errorControl).html().toLowerCase();

                if ((commonErrorMsg == "<br>please enter valid date either in hospital (part a) or (part b)." && errorMsg == "<br>please enter valid date either in hospital (part a) or (part b).") || (commonErrorMsg == "<br>please enter valid date either in hospital (part a) or (part b)." && $('#' + commonErrorMsgId).attr('style') == "display: inline")) { }
                else {
                    $(errorControl).html("");
                    $(errorControl).hide();
                }

            }
            return true;
        }

        var checkDOB;
        $('#bdPick').on('keypress keydown', function (e) {
            checkDOB = true;
        });

        /*Pinfo new change */

        $('#bdPick').on('blur', function (e) {
            var control = '#' + $(this).attr('id');
            var errorLabel = '#' + $(this).next().next().attr('id');
            validateDateOfBirth(control, errorLabel);
        });

        /*Pinfo new change */
        $('#haPick, #hbPick').on('blur', function (e) {
            var control = '#' + $(this).attr('id');
            var errorLabel = '#' + $(this).next().next().attr('id');
            var errorMsg, errorMsgId;
            var hostA, hostB;
            if (control == "#haPick" || control == "#hbPick") {
                hostA = $('#haPick').val();
                hostB = $('#hbPick').val();
                errorMsg = $('#hbPick').next().next().html();
                errorMsgId = $('#hbPick').next().next().attr('id');

                if (errorMsg.toLowerCase() == "<br><i class='fa fa-exclamation-triangle'></i> <span style='color:#cc0000'> Please enter valid date either in hospital (part a) or (part b).</span>") {
                    if (hostA == "" && hostB == "") { }
                    else
                        $('#hbPick').next().next().html("");
                }

                if (validatePersonalInfoHospitalDates(control, errorLabel)) {
                    if (validatePersonalInfoDates(control, errorLabel, errorMsg.toLowerCase(), errorMsgId))
                        validateDateOfBirth(control, errorLabel);
                }
            }
        });

        function validatePersonalInfoHospitalDates(control, errorLabel) {
            var hospitalDate = $(control).val();
            var isValid = true;
            if (hospitalDate != "" && hospitalDate.indexOf('/') != -1) {
                var datePartDOB = hospitalDate.split('/')[1];
                var monthPartDOB = hospitalDate.split('/')[0];
                var yearPartDOB = hospitalDate.split('/')[2];
                var newHospitalDate = monthPartDOB + "/01/" + yearPartDOB;
                $(control).val(newHospitalDate);
                $(control).attr('class', '');
                $(errorLabel).hide();
            }
            return isValid;
        }

        function validateDOB(controlDay, controlMonth, controlYear, errorLabel) {

            var isValidDOB = false;
            var datePartDOB = $.trim($(controlDay).val());
            var monthPartDOB = $.trim($(controlMonth).val());
            var yearPartDOB = $.trim($(controlYear).val());

            if ((datePartDOB != "") && (monthPartDOB != "") && (yearPartDOB != "")) //&& DOB.indexOf('/') != -1) 
            {
                var userDate = new Date();
                userDate.setFullYear(yearPartDOB, monthPartDOB - 1, datePartDOB - 1);
                var currDate = new Date();
                currDate.setFullYear(currDate.getFullYear() - 65);

                var currentYear = new Date().getFullYear();

                //DOB
                if (controlDay == '#ddlDOBDay' && controlMonth == '#ddlDOBMonth' && controlYear == '#ddlDOBYear') {
                    if (((datePartDOB >= 01) & (datePartDOB <= 31)) & ((monthPartDOB >= 01) & (monthPartDOB <= 12)) & ((yearPartDOB >= 1887) & (yearPartDOB <= currentYear))) {
                        var dobDate = Date.parse(monthPartDOB + '/' + datePartDOB + '/' + yearPartDOB);
                        var fullDate = new Date();
                        var twoDigitMonth = ((fullDate.getMonth().length + 1) === 1) ? (fullDate.getMonth() + 1) : '0' + (fullDate.getMonth() + 1);
                        var formatedDate = twoDigitMonth + "/" + fullDate.getDate() + "/" + fullDate.getFullYear();
                        var currentDate = Date.parse(formatedDate);

                        var threeMonthBefore = new Date();
                        threeMonthBefore.setFullYear(yearPartDOB, monthPartDOB - 1, datePartDOB);
                        threeMonthBefore.setDate(1); //first day of the birth month
                        threeMonthBefore.setMonth(threeMonthBefore.getMonth() - 3); //three months prior to birth month

                        var threeMonthAfter = new Date();
                        threeMonthAfter.setFullYear(yearPartDOB, monthPartDOB - 1, datePartDOB);
                        threeMonthAfter.setDate(1);
                        threeMonthAfter.setMonth(threeMonthAfter.getMonth() + 4);
                        threeMonthAfter.setDate(0); //roles it back to the last day of the 3rd month ahead of the birth month


                        if (dobDate >= currentDate) {
                            //$(control).attr('class', 'error');
                            $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Date of birth cannot be greater than or equal the current date.");
                            $(errorLabel).show();
                            isValidDOB = false;
                            return isValidDOB;
                        }
                        else if (!validDate(datePartDOB, monthPartDOB, yearPartDOB)) {
                            $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid date."); /*medicare page*/
                            $(errorLabel).show();
                            isValidDOB = false;
                            return isValidDOB;
                        }
                        else {
                            $('#ddlDOBDay').attr('class', 'textfield');
                            $('#ddlDOBMonth').attr('class', 'textfield');
                            $('#ddlDOBYear').attr('class', 'textfield');
                            $(errorLabel).hide();
                            isValidDOB = true;
                            return isValidDOB;
                        }
                    }
                    else {
                        //$(controlYear).attr('class', 'error');
                        $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date."); /*medicare page*/
                        $(errorLabel).show();
                        isValidDOB = false;
                        return isValidDOB;
                    }
                    checkDOB = false;
                }
                //FOR PART-A, B
                else {
                    if (((datePartDOB >= 01) & (datePartDOB <= 31)) & ((monthPartDOB >= 01) & (monthPartDOB <= 12)) & ((yearPartDOB >= 1890) & (yearPartDOB <= currentYear))) {
                        $(errorLabel).hide();
                        var dobDate = Date.parse(DOB);
                        var fullDate = new Date();
                        var twoDigitMonth = ((fullDate.getMonth().length + 1) === 1) ? (fullDate.getMonth() + 1) : '0' + (fullDate.getMonth() + 1);
                        var formatedDate = twoDigitMonth + "/" + fullDate.getDate() + "/" + fullDate.getFullYear();
                        var currentDate = Date.parse(formatedDate);

                        if (dobDate >= currentDate) {
                            $(control).attr('class', 'error');
                            $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date."); /*medicare page*/
                            $(errorLabel).show();
                            isValidDOB = false;
                            return isValidDOB;
                        }
                        else {
                            $(control).attr('class', '');
                            $('#ddlDOBDay').attr('class', 'textfield');
                            $('#ddlDOBMonth').attr('class', 'textfield');
                            $('#ddlDOBYear').attr('class', 'textfield');
                            $(errorLabel).hide();
                            isValidDOB = true;
                            return isValidDOB;
                        }
                    }
                    else {
                        $(control).attr('class', 'error');
                        $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date."); /*medicare page*/
                        $(errorLabel).show();
                        isValidDOB = false;
                        return isValidDOB;
                    }
                }

                if (new Date() <= new Date(DOB)) {
                    $(control).attr('class', 'error');
                    $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date."); /*medicare page*/
                    $(errorLabel).show();
                    isValidDOB = false;
                    return isValidDOB;
                }
                else {
                    $(control).attr('class', '');
                    $('#ddlDOBDay').attr('class', 'textfield');
                    $('#ddlDOBMonth').attr('class', 'textfield');
                    $('#ddlDOBYear').attr('class', 'textfield');
                    $(errorLabel).hide();
                    isValidDOB = true;
                    return isValidDOB;
                }
            }
            else {
                if (controlDay != '#ddlDOBDay' && controlMonth != '#ddlDOBMonth' && controlYear != '#ddlDOBYear') { }
                else {
                    //if (checkDOB) 
                    if (controlDay == '#ddlDOBDay' && controlMonth == '#ddlDOBMonth' && controlYear == '#ddlDOBYear') {
                        /*medicare page*/
                        $('#ddlDOBDay').attr('class', 'input-error');
                        $('#ddlDOBMonth').attr('class', 'input-error');
                        $('#ddlDOBYear').attr('class', 'select-ddl-error width105');
                        $(errorLabel).html("<i class='fa fa-exclamation-triangle'></i> Please enter a valid date of birth."); /*medicare page*/
                        $(errorLabel).show();
                        return isValidDOB;
                    }
                }
            }
            return isValidDOB;
        }

        function validateEmailRemainDOB(controlDay, controlMonth, controlYear, errorLabel) {
            var isValidDOB = false;
            var datePartDOB = $.trim($(controlDay).val());
            var monthPartDOB = $.trim($(controlMonth).val());
            var yearPartDOB = $.trim($(controlYear).val());

            if ((datePartDOB != "") && (monthPartDOB != "") && (yearPartDOB != "") && (datePartDOB != "dd") && (monthPartDOB != "mm")) //&& DOB.indexOf('/') != -1) 
            {
                var userDate = new Date();
                userDate.setFullYear(yearPartDOB, monthPartDOB - 1, datePartDOB - 1);
                var currDate = new Date();
                currDate.setFullYear(currDate.getFullYear());
                var currentYear = new Date().getFullYear();

                //DOB
                if (controlDay == '#emailremainddlDOBDay' && controlMonth == '#emailremainddlDOBMonth' && controlYear == '#emailremainddlDOBYear') {
                    if (((datePartDOB >= 01) & (datePartDOB <= 31)) & ((monthPartDOB >= 01) & (monthPartDOB <= 12)) & ((yearPartDOB >= 1887))) {
                        var dobDate = Date.parse(monthPartDOB + '/' + datePartDOB + '/' + yearPartDOB);
                        var fullDate = new Date();
                        var twoDigitMonth = ((fullDate.getMonth().length + 1) === 1) ? (fullDate.getMonth() + 1) : '0' + (fullDate.getMonth() + 1);
                        var formatedDate = twoDigitMonth + "/" + fullDate.getDate() + "/" + fullDate.getFullYear();
                        var currentDate = Date.parse(formatedDate);

                        var threeMonthBefore = new Date();
                        threeMonthBefore.setFullYear(yearPartDOB, monthPartDOB - 1, datePartDOB);
                        threeMonthBefore.setDate(1); //first day of the birth month
                        threeMonthBefore.setMonth(threeMonthBefore.getMonth() - 3); //three months prior to birth month

                        var threeMonthAfter = new Date();
                        threeMonthAfter.setFullYear(yearPartDOB, monthPartDOB - 1, datePartDOB);
                        threeMonthAfter.setDate(1);
                        threeMonthAfter.setMonth(threeMonthAfter.getMonth() + 4);
                        threeMonthAfter.setDate(0); //roles it back to the last day of the 3rd month ahead of the birth month

                        if (dobDate >= currentDate) {
                            $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Date of birth cannot be greater than <br/>or equal the current date."); /*medicare page*/
                            $(errorLabel).show();
                            $('#emailremainddlDOBMonth').attr('class', 'error');
                            $('#emailremainddlDOBDay').attr('class', 'error');
                            $('#emailremainddlDOBYear').attr('class', 'select-ddl-error width105');

                            isValidDOB = false;
                            return isValidDOB;
                        }
                        else if (!validDate(datePartDOB, monthPartDOB, yearPartDOB)) {
                            $(errorLabel).html("<i class='fa fa-exclamation-triangle'></i> Invalid date.");
                            $(errorLabel).show();
                            $('#emailremainddlDOBMonth').attr('class', 'error');
                            $('#emailremainddlDOBDay').attr('class', 'error');
                            $('#emailremainddlDOBYear').attr('class', 'select-ddl-error width105');

                            isValidDOB = false;
                            return isValidDOB;
                        }
                        else {
                            $('#emailremainddlDOBMonth').attr('class', 'textfield modal-small');
                            $('#emailremainddlDOBDay').attr('class', 'textfield modal-small');
                            $('#emailremainddlDOBYear').attr('class', 'textfield width105');

                            $(errorLabel).hide();
                            isValidDOB = true;
                            return isValidDOB;
                        }
                    }
                    else {
                        $(errorLabel).html("<i class='fa fa-exclamation-triangle'></i> Invalid Date.");
                        $(errorLabel).show();
                        $('#emailremainddlDOBMonth').attr('class', 'error');
                        $('#emailremainddlDOBDay').attr('class', 'error');
                        $('#emailremainddlDOBYear').attr('class', 'select-ddl-error width105');

                        isValidDOB = false;
                        return isValidDOB;
                    }
                    checkDOB = false;
                }
                //FOR PART-A, B
                else {
                    if (((datePartDOB >= 01) & (datePartDOB <= 31)) & ((monthPartDOB >= 01) & (monthPartDOB <= 12)) & ((yearPartDOB >= 1890) & (yearPartDOB <= currentYear))) {
                        $(errorLabel).hide();
                        var dobDate = Date.parse(DOB);
                        var fullDate = new Date();
                        var twoDigitMonth = ((fullDate.getMonth().length + 1) === 1) ? (fullDate.getMonth() + 1) : '0' + (fullDate.getMonth() + 1);
                        var formatedDate = twoDigitMonth + "/" + fullDate.getDate() + "/" + fullDate.getFullYear();
                        var currentDate = Date.parse(formatedDate);

                        if (dobDate >= currentDate) {
                            $(control).attr('class', 'error');
                            $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date.");
                            $(errorLabel).show();
                            isValidDOB = false;
                            return isValidDOB;
                        }
                        else {
                            $(control).attr('class', '');
                            $('#emailremainddlDOBMonth').attr('class', 'textfield modal-small');
                            $('#emailremainddlDOBDay').attr('class', 'textfield modal-small');
                            $('#emailremainddlDOBYear').attr('class', 'textfield width105');
                            $(errorLabel).hide();
                            isValidDOB = true;
                            return isValidDOB;
                        }
                    }
                    else {
                        $(control).attr('class', 'error');
                        $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date.");
                        $(errorLabel).show();
                        isValidDOB = false;
                        return isValidDOB;
                    }
                }

                if (new Date() <= new Date(DOB)) {
                    $(control).attr('class', 'error');
                    $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date.");
                    $(errorLabel).show();
                    isValidDOB = false;
                    return isValidDOB;
                }
                else {
                    $(control).attr('class', '');
                    $(errorLabel).hide();
                    isValidDOB = true;
                    return isValidDOB;
                }
            }
            else {
                if (controlDay != '#emailremainddlDOBDay' && controlMonth != '#emailremainddlDOBMonth' && controlYear != '#emailremainddlDOBYear') { }
                else {
                    //if (checkDOB) 
                    if (controlDay == '#emailremainddlDOBDay' && controlMonth == '#emailremainddlDOBMonth' && controlYear == '#emailremainddlDOBYear') {

                        $('#emailremainddlDOBMonth').attr('class', 'error');
                        $('#emailremainddlDOBDay').attr('class', 'error');
                        $('#emailremainddlDOBYear').attr('class', 'select-ddl-error width105');
                        if ($("#dobErrorMsg").is(":hidden")) {
                            $(errorLabel).html("<i class='fa fa-exclamation-triangle'></i> Please enter your DOB.");
                            $(errorLabel).show();
                        }

                        return isValidDOB;
                    }
                }
            }
            return isValidDOB;
        }

        //------Function will validate Effective date ,term date, effective date 2 and term date2------//
        //-----Using on Personal Information Page----------//

        function validateEffectiveDate1(controlDay, controlMonth, controlYear, errorLabel) {

            var isValidDOB = false;
            var datePartDOB = $.trim($(controlDay).val());
            var monthPartDOB = $.trim($(controlMonth).val());
            var yearPartDOB = $.trim($(controlYear).val());

            if ((datePartDOB != "") && (monthPartDOB != "") && (yearPartDOB != "")) //&& DOB.indexOf('/') != -1) 
            {


                //PlanAEffectiveDAte
                if (controlDay == '#planAEffectiveDateDay' && controlMonth == '#planAEffectiveDateMonth' && controlYear == '#planAEffectiveDateYear') {
                    return GetValidationResult(controlDay, controlMonth, controlYear, errorLabel);
                }
                //--
                if (controlDay == '#planATermDateDay' && controlMonth == '#planATermDateMonth' && controlYear == '#planATermDateYear') {
                    return GetValidationResult(controlDay, controlMonth, controlYear, errorLabel);
                }
                ///---
                if (controlDay == '#planAEffectiveDate2Day' && controlMonth == '#planAEffectiveDate2Month' && controlYear == '#planAEffectiveDate2Year') {
                    return GetValidationResult(controlDay, controlMonth, controlYear, errorLabel);
                }
                //---
                if (controlDay == '#planATermDate2Day' && controlMonth == '#planATermDate2Month' && controlYear == '#planATermDate2Year') {
                    return GetValidationResult(controlDay, controlMonth, controlYear, errorLabel);
                }
            }
            else {

                if (controlDay == '#planAEffectiveDateDay' && controlMonth == '#planAEffectiveDateMonth' && controlYear == '#planAEffectiveDateYear') {
                    /*PersonalInfo page*/
                    $('#planAEffectiveDateDay').attr('class', 'select-ddl-error width105');
                    $('#planAEffectiveDateMonth').attr('class', 'select-ddl-error width105');
                    $('#planAEffectiveDateYear').attr('class', 'select-ddl-error width105');
                    $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid Effective Date."); /*Personal Info*/
                    $(errorLabel).show();
                    return isValidDOB;
                }


                //-----PlanATermDate
                if (controlDay == '#planATermDateDay' && controlMonth == '#planATermDateMonth' && controlYear == '#planATermDateYear') {
                    /*PersonalInfo page*/
                    $('#planATermDateDay').attr('class', 'select-ddl-error width105');
                    $('#planATermDateMonth').attr('class', 'select-ddl-error width105');
                    $('#planATermDateYear').attr('class', 'select-ddl-error width105');
                    $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid Term Date."); /*Personal Info*/
                    $(errorLabel).show();
                    return isValidDOB;
                }
                //---PlanAEffectivedate2
                if (controlDay == '#planAEffectiveDate2Day' && controlMonth == '#planAEffectiveDate2Month' && controlYear == '#planAEffectiveDate2Year') {
                    /*PersonalInfo page*/
                    $('#planAEffectiveDate2Day').attr('class', 'select-ddl-error width105');
                    $('#planAEffectiveDate2Month').attr('class', 'select-ddl-error width105');
                    $('#planAEffectiveDate2Year').attr('class', 'select-ddl-error width105');
                    $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid Effective Date."); /*Personal Info*/
                    $(errorLabel).show();
                    return isValidDOB;
                }
                //----PlanATermDate2
                if (controlDay == '#planATermDate2Day' && controlMonth == '#planATermDate2Month' && controlYear == '#planATermDate2Year') {
                    /*PersonalInfo page*/
                    $('#planATermDate2Day').attr('class', 'select-ddl-error width105');
                    $('#planATermDate2Month').attr('class', 'select-ddl-error width105');
                    $('#planATermDate2Year').attr('class', 'select-ddl-error width105');
                    $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Please enter a valid Term Date."); /*Personal Info*/
                    $(errorLabel).show();
                    return isValidDOB;
                }

            }

            return isValidDOB;


        }

        //------For Personal Info By- TP------//
        function GetValidationResult(controlDay, controlMonth, controlYear, errorLabel) {

            var datePartDOB = $.trim($(controlDay).val());
            var monthPartDOB = $.trim($(controlMonth).val());
            var yearPartDOB = $.trim($(controlYear).val());
            var userDate = new Date();
            userDate.setFullYear(yearPartDOB, monthPartDOB - 1, datePartDOB - 1);
            var currDate = new Date();
            currDate.setFullYear(currDate.getFullYear() - 65);

            var currentYear = new Date().getFullYear();
            if (((datePartDOB >= 01) & (datePartDOB <= 31)) & ((monthPartDOB >= 01) & (monthPartDOB <= 12)) & ((yearPartDOB >= 1887))) {
                var dobDate = Date.parse(monthPartDOB + '/' + datePartDOB + '/' + yearPartDOB);
                var fullDate = new Date();
                var twoDigitMonth = ((fullDate.getMonth().length + 1) === 1) ? (fullDate.getMonth() + 1) : '0' + (fullDate.getMonth() + 1);
                var formatedDate = twoDigitMonth + "/" + fullDate.getDate() + "/" + fullDate.getFullYear();
                var currentDate = Date.parse(formatedDate);

                var threeMonthBefore = new Date();
                threeMonthBefore.setFullYear(yearPartDOB, monthPartDOB - 1, datePartDOB);
                threeMonthBefore.setDate(1); //first day of the birth month
                threeMonthBefore.setMonth(threeMonthBefore.getMonth() - 3); //three months prior to birth month

                var threeMonthAfter = new Date();
                threeMonthAfter.setFullYear(yearPartDOB, monthPartDOB - 1, datePartDOB);
                threeMonthAfter.setDate(1);
                threeMonthAfter.setMonth(threeMonthAfter.getMonth() + 4);
                threeMonthAfter.setDate(0); //roles it back to the last day of the 3rd month ahead of the birth month


                if (!validDate(datePartDOB, monthPartDOB, yearPartDOB)) {
                    $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid date."); /*medicare page*/
                    $(errorLabel).show();
                    isValidDOB = false;
                    return isValidDOB;
                }
                else {
                    $(controlDay).attr('class', 'textfield');
                    $(controlMonth).attr('class', 'textfield');
                    $(controlYear).attr('class', 'textfield');
                    $(errorLabel).hide();
                    isValidDOB = true;
                    return isValidDOB;
                }
            }
            else {
                $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date."); /*medicare page*/
                $(errorLabel).show();
                isValidDOB = false;
                return isValidDOB;
            }
            checkDOB = false;


            if (new Date() <= new Date(DOB)) {
                $(control).attr('class', 'error');
                $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date."); /*medicare page*/
                $(errorLabel).show();
                isValidDOB = false;
                return isValidDOB;
            }
            else {
                $(controlDay).attr('class', 'textfield');
                $(controlMonth).attr('class', 'textfield');
                $(controlYear).attr('class', 'textfield');
                $(errorLabel).hide();
                isValidDOB = true;
                return isValidDOB;
            }
        }
        //$('#planAEffectiveDateDay,#planAEffectiveDateMonth,planAEffectiveDateYear').change(function () {
        //    $('#planAEffectiveDateDay').attr('class', 'textfield');
        //    $('#planAEffectiveDateMonth').attr('class', 'textfield');
        //    $('#planAEffectiveDateYear').attr('class', 'textfield');
        //    $('#errorEffectiveDate').hide();
        //});
        //$('#planATermDateMonth,#planATermDateDay,#planATermDateYear').change(function () {
        //    $('#planATermDateMonth').attr('class', 'textfield');
        //    $('#planATermDateDay').attr('class', 'textfield');
        //    $('#planATermDateYear').attr('class', 'textfield');
        //    $('#errorTermDate').hide();
        //});
        //$('#planAEffectiveDate2Month,#planAEffectiveDate2Day,#planAEffectiveDate2Year').change(function () {
        //    $('#planAEffectiveDate2Month').attr('class', 'textfield');
        //    $('#planAEffectiveDate2Day').attr('class', 'textfield');
        //    $('#planAEffectiveDate2Year').attr('class', 'textfield');
        //    $('#errorEffectiveDate2').hide();
        //});
        //$('#planATermDate2Month,#planATermDate2Day,#planATermDate2Year').change(function () {
        //    $('#planATermDate2Month').attr('class', 'textfield');
        //    $('#planATermDate2Day').attr('class', 'textfield');
        //    $('#planATermDate2Year').attr('class', 'textfield');
        //    $('#errorTermDate2').hide();
        //});

        //-----------End of Personal information page validation----------//


        function validDate(day, month, year) {

            var isValidDate = false;

            if (day == "" || month == "" || year == "")
                return false;

            if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
                if (day <= 31) {
                    isValidDate = true;
                    return isValidDate;
                }
            }
            else if (month == 4 || month == 6 || month == 9 || month == 11) {
                if (day <= 30) {
                    isValidDate = true;
                    return isValidDate;
                }
            }
            else if (month == 2) {

                var LeapYear = (((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0));
                if (LeapYear) {
                    if (day <= 29) {
                        isValidDate = true;
                        return isValidDate;
                    }
                }
                else {

                    if (day <= 28) {
                        isValidDate = true;
                        return isValidDate;
                    }
                }
            }
            return isValidDate;
        }

        function validateDateOfBirth(control, errorLabel) {
            var isValidDOB = false;
            var DOB = $(control).val();
            if (DOB != "" && DOB.indexOf('/') != -1) {
                var datePartDOB = DOB.split('/')[1];
                var monthPartDOB = DOB.split('/')[0];
                var yearPartDOB = DOB.split('/')[2];

                var currentYear = new Date().getFullYear();
                //DOB
                if (control == '#bdPick') {
                    if (((datePartDOB >= 01) & (datePartDOB <= 31)) & ((monthPartDOB >= 01) & (monthPartDOB <= 12)) & ((yearPartDOB >= 1887) & (yearPartDOB <= currentYear))) {
                        var dobDate = Date.parse(DOB);

                        var fullDate = new Date();
                        var twoDigitMonth = ((fullDate.getMonth().length + 1) === 1) ? (fullDate.getMonth() + 1) : '0' + (fullDate.getMonth() + 1);
                        var formatedDate = twoDigitMonth + "/" + fullDate.getDate() + "/" + fullDate.getFullYear();
                        var currentDate = Date.parse(formatedDate);

                        if (dobDate >= currentDate) {
                            $(control).attr('class', 'error');
                            $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date.");
                            $(errorLabel).show();
                            isValidDOB = false;
                            return isValidDOB;
                        }
                        else {
                            $(control).attr('class', '');
                            $(errorLabel).hide();
                            isValidDOB = true;
                            return isValidDOB;
                        }
                    }
                    else {
                        $(control).attr('class', 'error');
                        $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date.");
                        $(errorLabel).show();
                        isValidDOB = false;
                        return isValidDOB;
                    }
                    checkDOB = false;
                }
                //FOR PART-A, B
                else {
                    if (((datePartDOB >= 01) & (datePartDOB <= 31)) & ((monthPartDOB >= 01) & (monthPartDOB <= 12)) & ((yearPartDOB >= 1890) & (yearPartDOB <= currentYear))) {
                        $(errorLabel).hide();
                        var dobDate = Date.parse(DOB);
                        var fullDate = new Date();
                        var twoDigitMonth = ((fullDate.getMonth().length + 1) === 1) ? (fullDate.getMonth() + 1) : '0' + (fullDate.getMonth() + 1);
                        var formatedDate = twoDigitMonth + "/" + fullDate.getDate() + "/" + fullDate.getFullYear();
                        var currentDate = Date.parse(formatedDate);

                        if (dobDate >= currentDate) {
                            $(control).attr('class', 'error');
                            $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date.");
                            $(errorLabel).show();
                            isValidDOB = false;
                            return isValidDOB;
                        }
                        else {
                            $(control).attr('class', '');
                            $(errorLabel).hide();
                            isValidDOB = true;
                            return isValidDOB;
                        }
                    }
                    else {
                        $(control).attr('class', 'error');
                        $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date.");
                        $(errorLabel).show();
                        isValidDOB = false;
                        return isValidDOB;
                    }
                }

                if (new Date() <= new Date(DOB)) {
                    $(control).attr('class', 'error');
                    $(errorLabel).html("<br/><i class='fa fa-exclamation-triangle'></i> Invalid Date.");
                    $(errorLabel).show();
                    isValidDOB = false;
                    return isValidDOB;
                }
                else {
                    $(control).attr('class', '');
                    $(errorLabel).hide();
                    isValidDOB = true;
                    return isValidDOB;
                }
            }
            else {
                if (control == "#hbPick" || control == "#haPick") { }
                else {
                    if (checkDOB) {
                        $(control).attr('class', 'error');
                        $(control).next().show();
                    }
                    checkDOB = false;
                    $(errorLabel).hide();
                }
            }
            return isValidDOB;
        }

        function validateDateAdditional(control) {
            var isValidDOB = false;
            var DOB = $(control).val();
            if (DOB != "" && DOB.indexOf('/') != -1) {
                var datePartDOB = DOB.split('/')[1];
                var monthPartDOB = DOB.split('/')[0];
                var yearPartDOB = DOB.split('/')[2];
                var currentYear = new Date().getFullYear();

                if (((datePartDOB >= 01) & (datePartDOB <= 31)) & ((monthPartDOB >= 01) & (monthPartDOB <= 12)) & ((yearPartDOB >= 1890)) && (yearPartDOB < currentYear + 1)) {
                    isValidDOB = true;
                }
                else {
                    isValidDOB = false;
                    return isValidDOB;
                }
            }
            else
                isValidDOB = true;
            return isValidDOB;
        }
        //////
        // Form Validation (Enroll Page 5)
        //////
        $('[name="ctl00$MainContent$group5"]:radio:checked').next().show();

        $('[name="ctl00$MainContent$enP1"]:radio').on('change', function () {
            $('[name="ctl00$MainContent$grpInner"]:radio').removeAttr("checked");
        });

        $('[name="ctl00$MainContent$grpInner"]:radio').on('change', function () {
            //            $('#enrollOptions input').attr('value', '')
            $("#enrollSubContent").find("input:text").val('');
        });
        $('[name="ctl00$MainContent$enP1"]:radio').on('change', function () {
            //            $('#enrollOptions input').attr('value', '')
            $("#enrollSubContent").find("input:text").val('');
        });
        $('[name="ELECTION"]:radio').on('change', function () {
            $('#pnlSEPExtended').css('display', 'none');
            //$('[name="SEPREASONCD"]:radio').prop('checked', false);
            $("#enrollSubContent").find("input:text").val('');
            var selElemID = $("#selSep").val();

            if (selElemID === undefined || selElemID === '') {
                selElemID = $("input[name='SEPREASONCD']:checked").val();
            }

            if (selElemID !== undefined && selElemID !== '' && $(this).prop('id') === 'rbtSep') {

                var isVisible = $("#" + selElemID).is(":visible");
                var showExtendedSep = $("#" + "pnlSEPExtended #pnlSEPEffDate" + selElemID).length > 0
                if (!isVisible && showExtendedSep) {
                    ShowSEPExtension();
                }
                if (!$("#" + selElemID).is(":checked")) {
                    $("#" + selElemID).click();
                } else {
                    $("#pnlSEPEffDate" + selElemID).show();
                }
            }

            if ($(".error-banner-new ").is(":visible") && ($("#iepRadioError").is(":visible") || $("#sepRadioError").is(":visible"))) {
                var errorList = [];
                var formId = this.form.id

                var isFormInvalid = false;

                isFormInvalid = ValidateOnTabChange(errorList);

                if (isFormInvalid) {

                    ShowValidationSummaryWithTitle([], 'enrollOptions');

                    ShowValidationSummaryWithTitle(errorList, formId);

                    $(this).focus();
                }
            }
        });

        function ValidateOnTabChange(errorList) {
            var isFormInvalid = false;
            var aepChecked = $("#rbtAnnual").is(':checked');
            var iepChecked = $("#rbtInitial").is(':checked');
            var sepChecked = $("#rbtSep").is(':checked');

            if (iepChecked) {
                var iepRadioChecked = $('#pnlIEP input:radio:checked').val();
                if (iepRadioChecked == undefined || !iepRadioChecked) {
                    var error = 'Select an option to continue';
                    $("#iepRadioError").html(error);
                    $("#sepRadioError").html(error);
                    var firstElementId = $("#pnlIEP input").first().prop('id');
                    addValidationError(firstElementId, error, errorList);
                    makeIEPSEPRedRadios();
                    isFormInvalid = true;
                    return isFormInvalid;
                }
                else if ($("#iepRadioError").is(":visible") || $("#sepRadioError").is(":visible")) {
                    var error = 'Select an option to continue';
                    $("#iepRadioError").html(error);
                    $("#sepRadioError").html(error);
                    var firstElementId = $("#pnlIEP input").first().prop('id');
                    addValidationError(firstElementId, error, errorList);
                    makeIEPSEPRedRadios();
                    isFormInvalid = true;
                    return isFormInvalid;
                }
            }
            else if (sepChecked) {
                var sepRadioCheckedID = $('#pnlSEP input:radio:checked').val();
                var sepExtendedRadioCheckedID = $('#pnlSEPExtended input:radio:checked').val();

                if ((sepRadioCheckedID == undefined || !sepRadioCheckedID) && (sepExtendedRadioCheckedID == undefined || !sepExtendedRadioCheckedID)) {

                    var error = 'Select an option to continue';
                    $("#sepRadioError").html(error);
                    var firstElementId = $("#pnlSEP input").first().prop('id');
                    addValidationError(firstElementId, error, errorList);

                    makeIEPSEPRedRadios();
                    isFormInvalid = true;
                    return isFormInvalid;
                }
                else {
                    if ($("#iepRadioError").is(":visible") || $("#sepRadioError").is(":visible")) {
                        var error = 'Select an option to continue';
                        $("#sepRadioError").html(error);
                        var firstElementId = $("#pnlSEP input").first().prop('id');
                        addValidationError(firstElementId, error, errorList);

                        makeIEPSEPRedRadios();
                        isFormInvalid = true;
                        return isFormInvalid;
                    }

                    if (sepRadioCheckedID == undefined) {
                        sepRadioCheckedID = sepExtendedRadioCheckedID
                    }
                    var isDateField = $("#" + sepRadioCheckedID + "IsDateField");
                    var monthValue = $("#ddlMonth" + sepRadioCheckedID).val();;
                    var dayValue = $("#ddlDay" + sepRadioCheckedID).val();
                    var yearValue = $("#ddlYear" + sepRadioCheckedID).val();

                    if (monthValue == undefined) {
                        monthValue = $("#ddlMonth" + sepRadioCheckedID + "Selected").val();
                    }
                    if (dayValue == undefined) {
                        dayValue = $("#ddlDay" + sepRadioCheckedID + "Selected").val();
                    }
                    if (yearValue == undefined) {
                        yearValue = $("#ddlYear" + sepRadioCheckedID + "Selected").val();
                    }

                    if (isDateField != undefined && isDateField.val().toLowerCase() == "true") {

                        if (monthValue == undefined || monthValue == "" || dayValue == undefined || dayValue == "" || yearValue == undefined || yearValue == "") {
                            var isSEPPanelVisible = $("#pnlSEPEffDate" + sepRadioCheckedID).is(":visible");
                            if (!isSEPPanelVisible) {
                                $("#" + sepRadioCheckedID).click();
                            }
                            var monthField = $("#ddlMonth" + sepRadioCheckedID);
                            if (monthField.val() == undefined) {
                                monthField = $("#ddlMonth" + sepRadioCheckedID + "Selected");
                            }
                            //monthField.addClass("error_h");

                            var dayField = $("#ddlDay" + sepRadioCheckedID);
                            if (dayField.val() == undefined) {
                                dayField = $("#ddlDay" + sepRadioCheckedID + "Selected");
                            }
                            //dayField.addClass("error_h");

                            var yearField = $("#ddlYear" + sepRadioCheckedID);
                            if (yearField.val() == undefined) {
                                yearField = $("#ddlYear" + sepRadioCheckedID + "Selected");
                            }
                            //yearField.addClass("error_h");

                            $(".SEPDateSelect").addClass("error_h");

                            var error = 'Select a valid month';
                            var monthFieldId = monthField.prop('id');
                            var MonthErrorField = "ddlMonth" + sepRadioCheckedID + "Error";
                            $("#" + MonthErrorField).html(error);
                            addValidationError(monthFieldId, error, errorList);

                            var error = 'Select a valid day';
                            var dayFieldId = dayField.prop('id');
                            var DayErrorField = "ddlDay" + sepRadioCheckedID + "Error";
                            $("#" + DayErrorField).html(error);
                            addValidationError(dayFieldId, error, errorList);

                            var error = 'Select a valid year';
                            var yearFieldId = yearField.prop('id');
                            var YearErrorField = "ddlYear" + sepRadioCheckedID + "Error";
                            $("#" + YearErrorField).html(error);
                            addValidationError(yearFieldId, error, errorList);

                            isFormInvalid = true;
                            return isFormInvalid;
                        } else {
                            var isDateValid = true;
                            if ((monthValue == 4 || monthValue == 6 || monthValue == 9 || monthValue == 11) && dayValue == 31) {
                                isDateValid = false;
                            }
                            else if (monthValue == 2) {
                                var isleap = (yearValue % 4 == 0 && (yearValue % 100 != 0 || yearValue % 400 == 0));

                                if (dayValue > 29 || (dayValue == 29 && !isleap)) {
                                    isDateValid = false;
                                }
                            }
                            if (!isDateValid) {
                                if (!isSEPPanelVisible) {
                                    $("#" + sepRadioCheckedID).click();
                                }
                                var monthField = $("#ddlMonth" + sepRadioCheckedID);
                                if (monthField.val() == undefined) {
                                    monthField = $("#ddlMonth" + sepRadioCheckedID + "Selected");
                                }
                                //monthField.addClass("error_h");

                                var dayField = $("#ddlDay" + sepRadioCheckedID);
                                if (dayField.val() == undefined) {
                                    dayField = $("#ddlDay" + sepRadioCheckedID + "Selected");
                                }
                                //dayField.addClass("error_h");

                                var yearField = $("#ddlYear" + sepRadioCheckedID);
                                if (yearField.val() == undefined) {
                                    yearField = $("#ddlYear" + sepRadioCheckedID + "Selected");
                                }
                                //yearField.addClass("error_h");

                                $(".SEPDateSelect").addClass("error_h");

                                var error = 'Select a valid month';
                                var monthFieldId = monthField.prop('id');
                                var MonthErrorField = "ddlMonth" + sepRadioCheckedID + "Error";
                                $("#" + MonthErrorField).html(error);
                                addValidationError(monthFieldId, error, errorList);

                                var error = 'Select a valid day';
                                var dayFieldId = dayField.prop('id');
                                var DayErrorField = "ddlDay" + sepRadioCheckedID + "Error";
                                $("#" + DayErrorField).html(error);
                                addValidationError(dayFieldId, error, errorList);

                                var error = 'Select a valid year';
                                var yearFieldId = yearField.prop('id');
                                var YearErrorField = "ddlYear" + sepRadioCheckedID + "Error";
                                $("#" + YearErrorField).html(error);
                                addValidationError(yearFieldId, error, errorList);

                                isFormInvalid = true;
                                return isFormInvalid;
                            }
                        }

                    }

                }

            }
        }


        //////
        // Form Validation (Enroll Page 3)
        //////

        var mailchecked = $('input[name="ctl00$MainContent$sameAsStreet"]:checked').val();
        if (mailchecked == undefined) {
            mailchecked = $('input[Id="sameAsStreet"]:checked').val();
        }
        if (mailchecked == "yes")
            $('#mailingAddress').show();
        var passwordchecked = $('#newPassword');
        if (passwordchecked.is(':checked'))
            $('#password').show();
        var instchecked = $('#instName');
        if (instchecked.is(':checked'))
            $('#dvInstitution').show();
        var sameStreetChecked = $('#sameAsStreet');
        if (sameStreetChecked.is(':checked')) //mohana
            $('#mailingAddress').show();
        var otherCoverage = $('input[id="otherCoverageYes"]:checked').val();
        if (otherCoverage == "yes") {
            $('.otherCover').show();
            var otherCoverage2 = $('input[id="othercoverage2Yes"]:checked').val();
            if (otherCoverage2 == "yes")
                $('.otherCover2').show();
        }
        //End Change  

        $('#nPassword, #confirm_password').on('blur', function () {
            var password = $.trim($('#nPassword').val());
            var cPassword = $.trim($('#confirm_password').val());
            if (password == "" && cPassword == "") {
                $('#confirm_password').attr('class', '');
                $('#confirm_password').next().hide();
            }
        });

        $('#newPassword').on('change', function () {
            var passwordCheckBox = $('#newPassword');
            if (!passwordCheckBox.is(':checked')) {
                $('#nPassword, #confirm_password').val('');
                $('#nPassword, #confirm_password').attr('class', '');
                $('#nPassword, #confirm_password').next().hide();
            }
            $('#password').toggle();
        });
        $('#instName').on('change', function () {
            $('#dvInstitution').toggle();
        });
        $('#sameAsStreet').on('change', function () {
            $('#mailingAddress').toggle();
        });

        $('.otherCoverage').on('change', function () {
            var checked = $('input[name="ctl00$MainContent$otherCoverage"]:checked').val();
            if (checked == undefined) {
                checked = $('input[name="otherCoverage"]:checked').val();
            }
            if (checked == "yes") {
                $('.otherCover').show();
            }
            else {
                $('.otherCover').hide();
            }
        });

        $('.otherCoverage2').on('change', function () {
            var checked = $('input[name="ctl00$MainContent$otherCoverage2"]:checked').val();
            if (checked == undefined) {
                checked = $('input[name="otherCoverage2"]:checked').val();
            }
            if (checked == "yes") {
                $('.otherCover2').show();
            }
            else {
                $('.otherCover2').hide();
            }
        });

        $("#btnSaveAdditionalInfo, #btnSaveAdditionalInfo2, #submitAdditionalButton, #btnShowPerfectAddress, #oKButtonAdditionalInfo").click(function (e) {
            return ValidateAdditionalInfo(this.form.id);
        });

        function ValidateAdditionalInfo(formId) {
            /*personal info page*/
            var errorList = [];
            //var formId = this.form.id
            var isFormInvalid = false;

            //Reset Multi State zip code
            if ($("#selectedRegionID").val() !== '' && $("#selectedStateCode").val() !== '' && $("#selectedStateName").val() !== '') {
                $("#lblStateChangeErr").addClass('hide');
            }

            var instNameChecked = $("#instName").is(":checked");

            if (instNameChecked !== undefined && instNameChecked) {
                var instituteName = $("#Institution").val();
                if (instituteName === undefined || instituteName === '') {
                    var error = "Enter institution's name";
                    $('#Institution').addClass('error');
                    $("#Institution").next().show();
                    $("#lblInstNameValid").html(error);
                    $("#lblInstNameValid").attr("aria-label", " (Error) " + error).attr("role", "text");
                    isFormInvalid = true;
                    addValidationError("Institution", error, errorList);
                }
                else {
                    $('#Institution').removeClass("error");
                    $("#Institution").next().hide();
                }
            }
            else {
                $('#Institution').removeClass("error");
                $("#Institution").next().hide();
            }

            var appAddr = $("#APPADD1").val();

            if (appAddr === undefined || appAddr === '') {
                var error = "Enter your address";
                $('#APPADD1').addClass("error");
                $("#permAddressError").show();
                addValidationError("APPADD1", error, errorList);
                $("#lblAddressResValid").html(error);
                $("#lblAddressResValid").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#permAddressError").hide();
                $('#APPADD1').removeClass("error");

            }

            var appCity = $("#city").val();

            if (appCity === undefined || appCity === '') {
                var error = "Enter your city";
                $('#city').addClass("error");
                $("#city").next().show();
                addValidationError("city", error, errorList);
                $("#lblCityValid").html(error);
                $("#lblCityValid").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#city").next().hide();
                $('#city').removeClass("error");
            }

            var appZip = $("#zip").val();

            if (appZip === undefined || appZip === '') {
                var error = "Enter your ZIP Code";
                $('#zip').addClass("error");
                addValidationError("zip", error, errorList);

                $("#zip").next().show();
                $("#lblZipCodeValid").html(error);
                $("#lblZipCodeValid").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                if (appZip.length == 5) {
                    $("#zip").next().hide();
                    $('#zip').removeClass("error");
                } else {
                    var error = "Enter a valid 5-digit ZIP Code for the state";
                    $('#zip').addClass("error");
                    addValidationError("zip", error, errorList);

                    $("#zip").next().show();
                    $("#lblZipCodeValid").html(error);
                    $("#lblZipCodeValid").attr("aria-label", " (Error) " + error).attr("role", "text");
                    isFormInvalid = true;
                }
            }
            var sameAsStreet = $("#sameAsStreet").is(":checked");

            if (sameAsStreet !== undefined && sameAsStreet) {
                var address3 = $("#address3").val();

                if (address3 === undefined || address3 === '') {
                    var error = "Enter your mailing address's street address";
                    $('#address3').addClass("error");
                    addValidationError("address3", error, errorList);

                    $("#address3").next().show();
                    $("#lblAddressResValid3").html(error);
                    $("#lblAddressResValid3").attr("aria-label", " (Error) " + error).attr("role", "text");
                    isFormInvalid = true;
                } else {
                    $("#address3").next().hide();
                    $('#address3').removeClass("error");
                }

                var city2 = $("#city2").val();

                if (city2 === undefined || city2 === '') {
                    var error = "Enter your mailing address's city";
                    $('#city2').addClass("error");
                    addValidationError("city2", error, errorList);

                    $("#city2").next().show();
                    $("#lblCityValid2").html(error);
                    $("#lblCityValid2").attr("aria-label", " (Error) " + error).attr("role", "text");
                    isFormInvalid = true;
                } else {
                    $("#city2").next().hide();
                    $('#city2').removeClass("error");
                }

                var state2 = $("#state2").val();

                if (state2 === undefined || state2 === '') {
                    var error = "Enter your mailing address's state";
                    $('#state2').addClass("select-ddl-error");
                    addValidationError("state2", error, errorList);

                    $("#state2").next().show();
                    $("#lblStateValid2").html(error);
                    $("#lblStateValid2").attr("aria-label", " (Error) " + error).attr("role", "text");
                    isFormInvalid = true;
                } else {
                    $("#state2").next().hide();
                    $('#state2').removeClass("select-ddl-error");
                }

                var zip2 = $("#zip2").val();

                if (zip2 === undefined || zip2 === '') {
                    var error = "Enter your mailing address's ZIP Code";
                    $('#zip2').addClass("error");
                    addValidationError("zip2", error, errorList);

                    $("#zip2").next().show();
                    $("#lblZipCodeValid2").html(error);
                    $("#lblZipCodeValid2").attr("aria-label", " (Error) " + error).attr("role", "text");
                    isFormInvalid = true;
                } else {
                    if (zip2.length < 5) {
                        var error = "Enter a valid 5-digit mailing address ZIP Code for the state";
                        $('#zip2').addClass("error");
                        addValidationError("zip2", error, errorList);

                        $("#zip2").next().show();
                        $("#lblZipCodeValid2").html(error);
                        $("#lblZipCodeValid2").attr("aria-label", " (Error) " + error).attr("role", "text");
                        isFormInvalid = true;
                    } else {
                        $("#zip2").next().hide();
                        $('#zip2').removeClass("error");
                    }
                }
            } else {

            }


            var primaryPhone = $("#appphone").val();

            if (primaryPhone === undefined || primaryPhone === '') {
                var error = "Enter a valid 10-digit primary phone number";
                $('#appphone').addClass("error");
                addValidationError("appphone", error, errorList);

                $("#appphone").next().show();
                $("#lblPhoneNumberValid").html(error);
                $("#lblPhoneNumberValid").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                if (primaryPhone.length !== 14) {
                    var error = "Enter a valid 10-digit primary phone number";
                    $('#appphone').addClass("error");
                    addValidationError("appphone", error, errorList);

                    $("#appphone").next().show();
                    $("#lblPhoneNumberValid").html(error);
                    $("#lblPhoneNumberValid").attr("aria-label", " (Error) " + error).attr("role", "text");
                    isFormInvalid = true;

                } else {
                    $("#appphone").next().hide();
                    $('#appphone').removeClass("error");
                }
            }


            var secondaryPhone = $("#cellphone").val();

            if (secondaryPhone !== undefined && secondaryPhone !== '' && secondaryPhone.length !== 14) {
                var error = "Enter a valid 10-digit secondary phone number";
                $('#cellphone').addClass("error");
                addValidationError("appphone", error, errorList);

                $("#cellphone").next().show();
                $("#lblMobileNumberValid").html(error);
                $("#lblMobileNumberValid").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#cellphone").next().hide();
                $('#cellphone').removeClass("error");
            }

            var email = $.trim($('#email3').val()).toLowerCase();
            if (email !== undefined && email !== '') {
                var emailRegExp = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
                if (email && !emailRegExp.test(email)) {
                    var error = "Enter an email address, for example: address@mail.com";
                    $('#email3').addClass("error");
                    addValidationError("email3", error, errorList);

                    $("#email3").next().show();
                    $("#email3ErrLbl").html(error);
                    $("#email3ErrLbl").attr("aria-label", " (Error) " + error).attr("role", "text");
                    isFormInvalid = true;
                } else {
                    $("#email3").next().hide();
                    $('#email3').removeClass("error");
                }
            } else {
                $("#email3").next().hide();
                $('#email3').removeClass("error");
            }

            var otherCoverageChecked = $("input[name='otherCoverage']").is(":checked");
            if (otherCoverageChecked === undefined || !otherCoverageChecked) {
                var error = "Select if you have prescription drug coverage";
                $("#rYes span").first().addClass("radioErrorEnroll");
                $("#rNo span").first().addClass("radioErrorEnroll");
                addValidationError("otherCoverageYes", error, errorList);

                $("#otherCoverageError").show();
                $("#lblAdditionalValid1").html(error);
                $("#lblAdditionalValid1").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#otherCoverageError").hide();
                $("#rYes span").first().removeClass("radioErrorEnroll");
                $("#rNo span").first().removeClass("radioErrorEnroll");

                var isYesChecked = $("#otherCoverageYes").is(":checked");

                if (isYesChecked) {
                    if (ValidateOtherCoverage(errorList)) {
                        isFormInvalid = true;
                    }

                    var otherCoverage2Checked = $("input[name='otherCoverage2']").is(":checked");
                    if (otherCoverage2Checked === undefined || !otherCoverage2Checked) {
                        var error = "Select if you have additional prescription drug coverage";
                        $('#othercoverage2yesspan').addClass("radioErrorEnroll");
                        $('#othercoverage2nospan').addClass("radioErrorEnroll");
                        addValidationError("othercoverage2Yes", error, errorList);

                        $("#lblAdditionalValid2Error").show();
                        $("#lblAdditionalValid2").html(error);
                        $("#lblAdditionalValid2").attr("aria-label", " (Error) " + error).attr("role", "text");
                        isFormInvalid = true;
                    } else {
                        $("#lblAdditionalValid2Error").hide();
                        $('#othercoverage2yesspan').removeClass("radioErrorEnroll");
                        $('#othercoverage2nospan').removeClass("radioErrorEnroll");

                        var othrCvgr2YesChecked = $("#othercoverage2Yes").is(":checked");

                        if (othrCvgr2YesChecked !== undefined && othrCvgr2YesChecked) {
                            if (ValidateAdditionalCoverage(errorList)) {
                                isFormInvalid = true;
                            }
                        }

                    }
                }

            }
            if (isFormInvalid) {

                $("#ValidationTitle").show();
                //Show the error banner
                ShowValidationSummaryWithTitle(errorList, formId);

                //Tealium Errors
                var errors = "";
                var elements = document.getElementsByClassName('error');
                for (var i = 0, len = elements.length; i < len; i++) {
                    if (elements[i].style.display === 'block' && elements[i].innerText != '' && elements[i].className !== 'error hide')
                        errors += elements[i].innerText.trim() + '|';
                }
                if (errors != '')
                    TealiumNotifyErrors_OnClick(errors);
            }
            return !isFormInvalid;
        }

        function ValidateOtherCoverage(errorList) {
            var isFormInvalid = false;
            var planName = $("#planName").val();

            if (planName === undefined || planName === '') {
                var error = "Enter a plan name";
                $('#planName').addClass("error");
                addValidationError("planName", error, errorList);

                $("#planName").next().show();
                $("#lblPlanNameValid1").html(error);
                $("#lblPlanNameValid1").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#planName").next().hide();
                $('#planName').removeClass("error");
            }
            //Other Prescription Coverage -Effective Date Validation
            var planAEffectiveDateMonth = $("#planAEffectiveDateMonth").val();
            var planAEffectiveDateDay = $("#planAEffectiveDateDay").val();
            var planAEffectiveDateYear = $("#planAEffectiveDateYear").val();

            if ((planAEffectiveDateMonth === undefined || planAEffectiveDateMonth === '') || (planAEffectiveDateDay === undefined || planAEffectiveDateDay === '') || (planAEffectiveDateYear === undefined || planAEffectiveDateYear === '')) {
                var error = "Select a valid Effective Date month";
                $('#planAEffectiveDateMonth').addClass("select-ddl-error");
                addValidationError("planAEffectiveDateMonth", error, errorList);

                $("#planAEffectiveDateMonth").next().show();
                $("#othCvrgMth1Error").html(error);
                $("#othCvrgMth1Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                var error = "Select a valid Effective Date day";
                $('#planAEffectiveDateDay').addClass("select-ddl-error");
                addValidationError("planAEffectiveDateDay", error, errorList);

                $("#planAEffectiveDateDay").next().show();
                $("#othCvrgDay1Error").html(error);
                $("#othCvrgDay1Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                var error = "Select a valid Effective Date year";
                $('#planAEffectiveDateYear').addClass("select-ddl-error");
                addValidationError("planAEffectiveDateYear", error, errorList);

                $("#planAEffectiveDateYear").next().show();
                $("#othCvrgYear1Error").html(error);
                $("#othCvrgYear1Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                isFormInvalid = true;
            } else {
                $("#planAEffectiveDateMonth").next().hide();
                $("#planAEffectiveDateDay").next().hide();
                $("#planAEffectiveDateYear").next().hide();

                $('#planAEffectiveDateMonth').removeClass("select-ddl-error");
                $('#planAEffectiveDateDay').removeClass("select-ddl-error");
                $('#planAEffectiveDateYear').removeClass("select-ddl-error");

                if (!validDate(planAEffectiveDateDay, planAEffectiveDateMonth, planAEffectiveDateYear)) {
                    var error = "Select a valid Effective Date month";
                    $('#planAEffectiveDateMonth').addClass("select-ddl-error");
                    addValidationError("planAEffectiveDateMonth", error, errorList);

                    $("#planAEffectiveDateMonth").next().show();
                    $("#othCvrgMth1Error").html(error);
                    $("#othCvrgMth1Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                    var error = "Select a valid Effective Date day";
                    $('#planAEffectiveDateDay').addClass("select-ddl-error");
                    addValidationError("planAEffectiveDateDay", error, errorList);

                    $("#planAEffectiveDateDay").next().show();
                    $("#othCvrgDay1Error").html(error);
                    $("#othCvrgDay1Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                    var error = "Select a valid Effective Date year";
                    $('#planAEffectiveDateYear').addClass("select-ddl-error");
                    addValidationError("planAEffectiveDateYear", error, errorList);

                    $("#planAEffectiveDateYear").next().show();
                    $("#othCvrgYear1Error").html(error);
                    $("#othCvrgYear1Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                    isFormInvalid = true;
                }
            }

            //Other Prescription Coverage -Term Date Validation
            var planATermDateMonth = $("#planATermDateMonth").val();
            var planATermDateDay = $("#planATermDateDay").val();
            var planATermDateYear = $("#planATermDateYear").val();

            if ((planATermDateMonth === undefined || planATermDateMonth === '') || (planATermDateDay === undefined || planATermDateDay === '') || (planATermDateYear === undefined || planATermDateYear === '')) {
                var error = "Select a valid Term Date month";
                $('#planATermDateMonth').addClass("select-ddl-error");
                addValidationError("planATermDateMonth", error, errorList);

                $("#planATermDateMonth").next().show();
                $("#othCvrgTermMth1Error").html(error);
                $("#othCvrgTermMth1Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                var error = "Select a valid Term Date day";
                $('#planATermDateDay').addClass("select-ddl-error");
                addValidationError("planATermDateDay", error, errorList);

                $("#planATermDateDay").next().show();
                $("#othCvrgTermDay1Error").html(error);
                $("#othCvrgTermDay1Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                var error = "Select a valid Term Date year";
                $('#planATermDateYear').addClass("select-ddl-error");
                addValidationError("planATermDateYear", error, errorList);

                $("#planATermDateYear").next().show();
                $("#othCvrgTermYear1Error").html(error);
                $("#othCvrgTermYear1Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                isFormInvalid = true;
            } else {
                $("#planATermDateMonth").next().hide();
                $("#planATermDateDay").next().hide();
                $("#planATermDateYear").next().hide();

                $('#planATermDateMonth').removeClass("select-ddl-error");
                $('#planATermDateDay').removeClass("select-ddl-error");
                $('#planATermDateYear').removeClass("select-ddl-error");

                if (!validDate(planATermDateDay, planATermDateMonth, planATermDateYear)) {
                    var error = "Select a valid Term Date month";
                    $('#planATermDateMonth').addClass("select-ddl-error");
                    addValidationError("planATermDateMonth", error, errorList);

                    $("#planATermDateMonth").next().show();
                    $("#othCvrgTermMth1Error").html(error);
                    $("#othCvrgTermMth1Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                    var error = "Select a valid Term Date day";
                    $('#planATermDateDay').addClass("select-ddl-error");
                    addValidationError("planATermDateDay", error, errorList);

                    $("#planATermDateDay").next().show();
                    $("#othCvrgTermDay1Error").html(error);
                    $("#othCvrgTermDay1Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                    var error = "Select a valid Term Date year";
                    $('#planATermDateYear').addClass("select-ddl-error");
                    addValidationError("planATermDateYear", error, errorList);

                    $("#planATermDateYear").next().show();
                    $("#othCvrgTermYear1Error").html(error);
                    $("#othCvrgTermYear1Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                    isFormInvalid = true;
                }

            }

            var RxBin = $("#RxBin").val();
            if (RxBin === undefined || RxBin === '') {
                var error = "Enter the RxBin";
                $('#RxBin').addClass("error");
                addValidationError("RxBin", error, errorList);

                $("#RxBin").next().show();
                $("#lblRxBinValid1").html(error);
                $("#lblRxBinValid1").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#RxBin").next().hide();
                $('#RxBin').removeClass("error");
            }

            var RxPCN = $("#RxPCN").val();
            if (RxPCN === undefined || RxPCN === '') {
                var error = "Enter the RxPCN";
                $('#RxPCN').addClass("error");
                addValidationError("RxPCN", error, errorList);

                $("#RxPCN").next().show();
                $("#lblRxPCNValid1").html(error);
                $("#lblRxPCNValid1").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#RxPCN").next().hide();
                $('#RxPCN').removeClass("error");
            }

            var RxGroup = $("#RxGroup").val();
            if (RxGroup === undefined || RxGroup === '') {
                var error = "Enter the RxGroup";
                $('#RxGroup').addClass("error");
                addValidationError("RxGroup", error, errorList);

                $("#RxGroup").next().show();
                $("#lblRxGroupValid1").html(error);
                $("#lblRxGroupValid1").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#RxGroup").next().hide();
                $('#RxGroup').removeClass("error");
            }

            var RxID = $("#RxID").val();
            if (RxID === undefined || RxID === '') {
                var error = "Enter the RxID";
                $('#RxID').addClass("error");
                addValidationError("RxID", error, errorList);

                $("#RxID").next().show();
                $("#lblRxIDValid1").html(error);
                $("#lblRxIDValid1").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#RxID").next().hide();
                $('#RxID').removeClass("error");
            }

            return isFormInvalid;
        }


        function ValidateAdditionalCoverage(errorList) {
            var isFormInvalid = false;
            var planName2 = $("#planName2").val();

            if (planName2 === undefined || planName2 === '') {
                var error = "Enter additional plan name";
                $('#planName2').addClass("error");
                addValidationError("planName2", error, errorList);

                $("#planName2").next().show();
                $("#lblPlanNameValid2").html(error);
                $("#lblPlanNameValid2").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#planName2").next().hide();
                $('#planName2').removeClass("error");
            }
            //Additional Prescription Coverage -Effective Date Validation
            var planAEffectiveDate2Month = $("#planAEffectiveDate2Month").val();
            var planAEffectiveDate2Day = $("#planAEffectiveDate2Day").val();
            var planAEffectiveDate2Year = $("#planAEffectiveDate2Year").val();

            if ((planAEffectiveDate2Month === undefined || planAEffectiveDate2Month === '') || (planAEffectiveDate2Day === undefined || planAEffectiveDate2Day === '') || (planAEffectiveDate2Year === undefined || planAEffectiveDate2Year === '')) {
                var error = "Select a valid Effective Date month for additional plan";
                $('#planAEffectiveDate2Month').addClass("select-ddl-error");
                addValidationError("planAEffectiveDate2Month", error, errorList);

                $("#planAEffectiveDate2Month").next().show();
                $("#othCvrgMth2Error").html(error);
                $("#othCvrgMth2Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                var error = "Select a valid Effective Date day for additional plan";
                $('#planAEffectiveDate2Day').addClass("select-ddl-error");
                addValidationError("planAEffectiveDate2Day", error, errorList);

                $("#planAEffectiveDate2Day").next().show();
                $("#othCvrgDay2Error").html(error);
                $("#othCvrgDay2Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                var error = "Select a valid Effective Date year for additional plan";
                $('#planAEffectiveDate2Year').addClass("select-ddl-error");
                addValidationError("planAEffectiveDate2Year", error, errorList);

                $("#planAEffectiveDate2Year").next().show();
                $("#othCvrgYear2Error").html(error);
                $("#othCvrgYear2Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                isFormInvalid = true;
            } else {
                $("#planAEffectiveDate2Month").next().hide();
                $("#planAEffectiveDate2Day").next().hide();
                $("#planAEffectiveDate2Year").next().hide();

                $('#planAEffectiveDate2Month').removeClass("select-ddl-error");
                $('#planAEffectiveDate2Day').removeClass("select-ddl-error");
                $('#planAEffectiveDate2Year').removeClass("select-ddl-error");

                if (!validDate(planAEffectiveDate2Day, planAEffectiveDate2Month, planAEffectiveDate2Year)) {
                    var error = "Select a valid Effective Date month for additional plan";
                    $('#planAEffectiveDate2Month').addClass("select-ddl-error");
                    addValidationError("planAEffectiveDate2Month", error, errorList);

                    $("#planAEffectiveDate2Month").next().show();
                    $("#othCvrgMth2Error").html(error);
                    $("#othCvrgMth2Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                    var error = "Select a valid Effective Date day for additional plan";
                    $('#planAEffectiveDate2Day').addClass("select-ddl-error");
                    addValidationError("planAEffectiveDate2Day", error, errorList);

                    $("#planAEffectiveDate2Day").next().show();
                    $("#othCvrgDay2Error").html(error);
                    $("#othCvrgDay2Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                    var error = "Select a valid Effective Date year for additional plan";
                    $('#planAEffectiveDate2Year').addClass("select-ddl-error");
                    addValidationError("planAEffectiveDate2Year", error, errorList);

                    $("#planAEffectiveDate2Year").next().show();
                    $("#othCvrgYear2Error").html(error);
                    $("#othCvrgYear2Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                    isFormInvalid = true;
                }
            }

            //Other Prescription Coverage -Term Date Validation
            var planATermDate2Month = $("#planATermDate2Month").val();
            var planATermDate2Day = $("#planATermDate2Day").val();
            var planATermDate2Year = $("#planATermDate2Year").val();

            if ((planATermDate2Month === undefined || planATermDate2Month === '') || (planATermDate2Day === undefined || planATermDate2Day === '') || (planATermDate2Year === undefined || planATermDate2Year === '')) {
                var error = "Select a valid Term Date month for additional plan";
                $('#planATermDate2Month').addClass("select-ddl-error");
                addValidationError("planATermDate2Month", error, errorList);

                $("#planATermDate2Month").next().show();
                $("#othCvrgTermMth2Error").html(error);
                $("#othCvrgTermMth2Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                var error = "Select a valid Term Date day for additional plan";
                $('#planATermDate2Day').addClass("select-ddl-error");
                addValidationError("planATermDate2Day", error, errorList);

                $("#planATermDate2Day").next().show();
                $("#othCvrgTermDay2Error").html(error);
                $("#othCvrgTermDay2Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                var error = "Select a valid Term Date year for additional plan";
                $('#planATermDate2Year').addClass("select-ddl-error");
                addValidationError("planATermDate2Year", error, errorList);

                $("#planATermDate2Year").next().show();
                $("#othCvrgTermYear2Error").html(error);
                $("#othCvrgTermYear2Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                isFormInvalid = true;
            } else {
                $("#planATermDate2Month").next().hide();
                $("#planATermDate2Day").next().hide();
                $("#planATermDate2Year").next().hide();

                $('#planATermDate2Month').removeClass("select-ddl-error");
                $('#planATermDate2Day').removeClass("select-ddl-error");
                $('#planATermDate2Year').removeClass("select-ddl-error");

                if (!validDate(planATermDate2Day, planATermDate2Month, planATermDate2Year)) {
                    var error = "Select a valid Term Date month for additional plan";
                    $('#planATermDate2Month').addClass("select-ddl-error");
                    addValidationError("planATermDate2Month", error, errorList);

                    $("#planATermDate2Month").next().show();
                    $("#othCvrgTermMth2Error").html(error);
                    $("#othCvrgTermMth2Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                    var error = "Select a valid Term Date day for additional plan";
                    $('#planATermDate2Day').addClass("select-ddl-error");
                    addValidationError("planATermDate2Day", error, errorList);

                    $("#planATermDate2Day").next().show();
                    $("#othCvrgTermDay2Error").html(error);
                    $("#othCvrgTermDay2Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                    var error = "Select a valid Term Date year for additional plan";
                    $('#planATermDate2Year').addClass("select-ddl-error");
                    addValidationError("planATermDate2Year", error, errorList);

                    $("#planATermDate2Year").next().show();
                    $("#othCvrgTermYear2Error").html(error);
                    $("#othCvrgTermYear2Error").attr("aria-label", " (Error) " + error).attr("role", "text");

                    isFormInvalid = true;
                }

            }

            var RxBin2 = $("#RxBin2").val();
            if (RxBin2 === undefined || RxBin2 === '') {
                var error = "Enter the RxBin for additional plan";
                $('#RxBin2').addClass("error");
                addValidationError("RxBin2", error, errorList);

                $("#RxBin2").next().show();
                $("#lblRxBinValid2").html(error);
                $("#lblRxBinValid2").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#RxBin2").next().hide();
                $('#RxBin2').removeClass("error");
            }

            var RxPCN2 = $("#RxPCN2").val();
            if (RxPCN2 === undefined || RxPCN2 === '') {
                var error = "Enter the RxPCN for additional plan";
                $('#RxPCN2').addClass("error");
                addValidationError("RxPCN2", error, errorList);

                $("#RxPCN2").next().show();
                $("#lblRxPCNValid2").html(error);
                $("#lblRxPCNValid2").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#RxPCN2").next().hide();
                $('#RxPCN2').removeClass("error");
            }

            var RxGroup2 = $("#RxGroup2").val();
            if (RxGroup2 === undefined || RxGroup2 === '') {
                var error = "Enter the RxGroup for additional plan";
                $('#RxGroup2').addClass("error");
                addValidationError("RxGroup2", error, errorList);

                $("#RxGroup2").next().show();
                $("#lblRxGroupValid2").html(error);
                $("#lblRxGroupValid2").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#RxGroup2").next().hide();
                $('#RxGroup2').removeClass("error");
            }

            var RxID2 = $("#RxID2").val();
            if (RxID2 === undefined || RxID2 === '') {
                var error = "Enter the RxID for additional plan";
                $('#RxID2').addClass("error");
                addValidationError("RxID2", error, errorList);

                $("#RxID2").next().show();
                $("#lblRxIDValid2").html(error);
                $("#lblRxIDValid2").attr("aria-label", " (Error) " + error).attr("role", "text");
                isFormInvalid = true;
            } else {
                $("#RxID2").next().hide();
                $('#RxID2').removeClass("error");
            }

            return isFormInvalid;
        }

        function oldPersonalInfoValidation() {

            var returnStatus = false;
            var othercoverage = $('input[name="ctl00$MainContent$otherCoverage"]:checked').val();
            if (othercoverage == undefined) {
                checked = $('input[name="otherCoverage"]:checked').val();
            }
            if ($('#additionalInfo').valid()) {
                returnStatus = true;
                return returnStatus;
            }
            else {
                if (othercoverage != "yes" && othercoverage != "no") {
                    $('#otherCoverageYes').next().attr('class', 'label-radio-error');
                    $('#otherCoverageNo').next().attr('class', 'label-radio-error');
                    returnStatus = false;
                    return returnStatus;
                }
                else if (othercoverage == "yes") {
                    if (document.getElementById("coverage1") != null) {

                        var othercoverage2 = $('input[name="ctl00$MainContent$otherCoverage2"]:checked').val();
                        if (otherCoverage2 == undefined) {
                            othercoverage2 = $('input[name="otherCoverage2"]:checked').val();
                        }
                        if (othercoverage2 != "yes" && othercoverage2 != "no") {
                            $('#othercoverage2Yes').next().attr('class', 'label-radio-error');
                            $('#othercoverage2No').next().attr('class', 'label-radio-error');
                            returnStatus = false;
                            return returnStatus;
                        }
                    }
                }
                return returnStatus;
            }
        }

        function managePaymentOptions() {
            var radiobutton = $("input[name='PWO']:checked").attr('id');
            if (radiobutton == 'bankDraft') {
                $('.choose-answers.sscheck').hide();
                $('.choose-answers.rrcheck').hide();
                $('.choose-answers.bankaccount').show();
            }
            else if (radiobutton == 'ssCheck') {
                $('.choose-answers.bankaccount').hide();
                $('.choose-answers.sscheck').show();
            }
            else if (radiobutton == 'rrCheck') {
                $('.choose-answers.bankaccount').hide();
                $(this).parent().find('#divRCheckDiv').show();
            }
            else if (radiobutton == 'monthly') {
                $('.choose-answers.bankaccount').hide();
                $('.choose-answers.sscheck').hide();
                $('.choose-answers.rrcheck').hide();
            }
        }

        //////
        // Form Validation (Enroll Page 5) Payment Options
        //////
        $('[name="ctl00$MainContent$enP1"]:radio:checked').parent().next().next().show();
        $('#paymentOptions input[type="radio"]').on('click', function () {
            managePaymentOptions();
        });

        //add custom validation methods to Jquery validation
        // Rs 02/08/2018 reference to the Task- 13380 validate the Routing number 
        $.validator.addMethod("validateRoutingNumber", function () {
            var isValidNum = isValidRoutingNumber();
            return isValidNum;
        });
        $.validator.addMethod("Validaccountnum", function () {
            var isValidNum = isValidAccountNumber();
            return isValidNum;
        });

        $("#paymentOptions").validate(
            {
                rules:
                {
                    acctNum:
                    {
                        required: true,
                        Validaccountnum: true
                    },
                    acctType: "required",
                    acctName: "required",
                    "routNum":
                    {
                        required: true,
                        validateRoutingNumber: true // Rs 02/08/2018 reference to the Task- 13380 -Validating the Routing number
                    }
                }
            });

        function validatePaymentOptions(formId) {
            var errorList = [];

            var PWOSelected = $("input[name='PWO']:checked")

            if (PWOSelected !== undefined && PWOSelected[0] !== undefined && PWOSelected[0].id == 'bankDraft') {
                var isValid = true
                if ($("#acctName").val() == '') {
                    isValid = false;
                    $('#erroracctName').show();
                    $("#acctName").removeClass("valid").addClass("error")
                    addValidationError("acctName", "Enter your account name", errorList)
                }
                else {
                    $('#erroracctName').hide();
                    $("#acctName").removeClass("error").addClass("valid")
                }
                if ($("#acctType").val() == '') {
                    isValid = false;
                    $('#errorAccttype').show();
                    $("#acctType").removeClass("valid").addClass("error")
                    addValidationError("acctType", "Select your account type", errorList)
                }
                else {
                    $('#errorAccttype').hide();
                    $("#acctType").removeClass("error").addClass("valid")
                }
                if ($("#routNum").val() == '') {
                    isValid = false;
                    $('#msgReqRoutingNum').show();
                    $("#routNum").removeClass("valid").addClass("error");
                    addValidationError("routNum", "Enter your valid 9-digit routing number", errorList)
                }
                else {
                    if (isValidRoutingNumber()) {
                        $("#routNum").removeClass("error").addClass("valid");
                    } else {
                        isValid = false;
                        $("#routNum").removeClass("valid").addClass("error");
                        addValidationError("routNum", "Enter your valid 9-digit routing number", errorList)
                    }
                }
                if ($("#acctNum").val() == '') {
                    isValid = false;
                    $('#msgAccountNum').show();
                    $("#acctNum").removeClass("valid").addClass("error");
                    addValidationError("acctNum", "Enter your valid account number", errorList)
                }
                else {
                    if (isValidAccountNumber()) {
                        $("#acctNum").removeClass("error").addClass("valid");
                    } else {
                        isValid = false;
                        $("#acctNum").removeClass("valid").addClass("error");
                        addValidationError("acctNum", "Enter your valid account number", errorList)
                    }
                }

                if (!isValid) {
                    ShowValidationSummaryWithTitle(errorList, formId, "", false)
                    // $(".error").first().focus();
                    var errors = "";
                    var elements = document.getElementsByClassName('error');
                    for (var i = 0, len = elements.length; i < len; i++) {
                        if (elements[i].style.display === 'block')
                            errors += elements[i].innerText.trim() + '|';
                    }
                    if (errors != '')
                        TealiumNotifyErrors_OnClick(errors);
                    //end of tealium
                    return false;
                }
            }

            return true;
        }

        $('#oKButtonPaymentInfo, #btnSavePaymentInfo, #cancelButtonPaymentInfo').click(function (e) {
            if (!$('#paymentOptions').valid()) {
                alert('Required information has not been supplied or is invalid.  Please review the form.');
                if ($(":input.error:first").length > 0) {
                    $(":input.error:first").focus();
                } else {
                    $(":input.input-validation-error:first").focus();
                }
                return false;
            } else {
                return validatePaymentOptions(this.form.id);
            }
        });

        $('#submitPaymentInfo').click(function (e) {
            if (!$('#paymentOptions').valid()) {
                $(":input.error:first").focus();

                //JT-8/21/2018-method added for appending all errors generated on the page for tealium
                var errors = "";
                var elements = document.getElementsByClassName('error');
                for (var i = 0, len = elements.length; i < len; i++) {
                    if (elements[i].style.display === 'block' && document.getElementById('divBankDraft').style.display === 'block' && elements[i].innerText != '')
                        errors += elements[i].innerText.trim() + '|';
                }
                if (errors != '')
                    TealiumNotifyErrors_OnClick(errors);
                //end of tealium

                return false;
            } else {
                return validatePaymentOptions(this.form.id);
            }
        });

        //$('#address3, #city2, #zip2').keyup(function () {
        //    if ($(this).val() == '') {
        //        $(this).next().show();
        //        $(this).removeClass("valid").addClass("error");
        //    } else {
        //        $(this).next().hide();
        //        $(this).removeClass("error").addClass("valid");
        //    }
        //});


        //$("#state2").change(function () {
        //    if ($("#state2").val() == '') {
        //        $('#state2').next().show();
        //        $("#state2").removeClass("valid").addClass("error")
        //    } else {
        //        $('#state2').next().hide();
        //        $("#state2").removeClass("error").addClass("valid")
        //    }
        //});

        //////
        // Form Validation (Enroll Page 4) Enrollment Options
        //////

        $('#enrollOptions h2 input[type="radio"]').on('click', function () {
            $('.hide').hide();
            var elm = $(this).parent();
            elm.next().next().show();
            $('#lblIEPSelectedError').html('');
            $('#lblAEPSelectedError').html('');
            $('#lblSEPSelectedError').html('');
        });

        $('#enrollOptions').validate(
            {
                rules:
                {
                    'ctl00$MainContent$enP1': 'required',
                    'ctl00$MainContent$grpInner': 'required',
                    'ctl00$MainContent$grpInner1': 'required',
                    'ctl00$MainContent$grpInner3': 'required'
                }
            });

        $('#btnEnrollInfoContinue, #oKButtonEnrollInfo, #btnSaveEnrolllnfo').click(function (e) {
            if ($('input[name="SEPREASONCD"]').is(':checked')) {
                $("#titledisc1").addClass("hide");
                $("#dvMainCall").addClass("hide");
            }
            if ($("#rbtInitial").is(":checked")) {
                $("#selSep").val('');
                $("select").each(function () {
                    if ($(this).prop('id').indexOf('ddlSEPEffDate') < 0) {
                        $(this).val('');
                        $(this).removeClass("error_h");
                        $(this).next().html('');
                    }
                });
            }
            var errorList = [];
            var formId = this.form.id
            var isFormInvalid = false;

            isFormInvalid = CheckEligibilityValidations(errorList);

            if (isFormInvalid) {

                $("#ValidationTitle").show();
                //Show the error banner 
                ShowValidationSummaryWithTitle(errorList, formId);
                var errors = '';
                //Tealium Errors
                for (var i = 0, len = errorList.length; i < len; i++) {
                    errors += errorList[i].message + '|';
                }
                if (errors != '')
                    TealiumNotifyErrors_OnClick(errors);

                return false;
            }
        });


        function CheckEligibilityValidations(errorList) {
            var isFormInvalid = false;
            var aepChecked = $("#rbtAnnual").is(':checked')
            var iepChecked = $("#rbtInitial").is(':checked')
            var sepChecked = $("#rbtSep").is(':checked')

            if (!aepChecked && !iepChecked && !sepChecked) {
                isFormInvalid = true;
                $("#rbtAnnual").addClass("error");
                $("#rbtInitial").addClass("error");
                $("#rbtSep").addClass("error");
                $(".radio-choice-box").addClass("radio-error");

                var error = 'Select an option to continue';
                var focusField = '';
                var ua = window.navigator.userAgent;
                if (ua !== undefined || ua !== '') {
                    var msie = ua.indexOf("MSIE ");

                    if ((msie !== undefined && msie !== '') && (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)))  // If Internet Explorer, return version number
                    {
                        if ($("#rbtAnnual").is(":visible")) {
                            focusField = 'rbtAnnual';
                        } else {
                            focusField = 'rbtInitial';
                        }
                    }
                }
                if (focusField == '') {
                    if ($("#rbtAnnual").is(":visible")) {
                        focusField = 'rbtAnnual';
                    } else {
                        focusField = 'rbtInitial';
                    }
                }

                addValidationError(focusField, error, errorList);
                $('#lblErrorElectionPeriod').html(error);
                $('#lblErrorElectionPeriod').attr("aria-label", " (Error) " + error).attr("role", "text");
                $('#lblErrorElectionPeriod').show();

                var error = $('#lblErrorElectionPeriod').text();
                if (error != '') {
                    TealiumNotifyErrors_OnClick(error);
                }
                //makeIEPSEPRedRadios(); 
                return isFormInvalid;
            } else {

                $(".radio-choice-box").removeClass("radio-error");
                $('#lblErrorElectionPeriod').hide();
                if (iepChecked) {
                    var iepRadioChecked = $('#pnlIEP input:radio:checked').val();
                    if (iepRadioChecked == undefined || !iepRadioChecked) {
                        isFormInvalid = true;
                        var error = 'Select an option to continue';
                        $("#iepRadioError").html(error);
                        $("#sepRadioError").attr("aria-label", " (Error) " + error).attr("role", "text");
                        var firstElementId = $("#pnlIEP input").first().prop('id');
                        addValidationError(firstElementId, error, errorList);
                        makeIEPSEPRedRadios();
                        isFormInvalid = true;
                        return isFormInvalid;
                    }

                }
                else if (sepChecked) {
                    var sepRadioCheckedID = $('#pnlSEP input:radio:checked').val();
                    var sepExtendedRadioCheckedID = $('#pnlSEPExtended input:radio:checked').val();

                    if ((sepRadioCheckedID == undefined || !sepRadioCheckedID) && (sepExtendedRadioCheckedID == undefined || !sepExtendedRadioCheckedID)) {

                        var error = 'Select an option to continue';
                        $("#sepRadioError").html(error);
                        $("#sepRadioError").attr("aria-label", " (Error) " + error).attr("role", "text");
                        var firstElementId = $("#pnlSEP input").first().prop('id');
                        addValidationError(firstElementId, error, errorList);

                        makeIEPSEPRedRadios();
                        isFormInvalid = true;
                        return isFormInvalid;
                    }
                    else {
                        removeIEPSEPRedRadios();
                        if (sepRadioCheckedID == undefined) {
                            sepRadioCheckedID = sepExtendedRadioCheckedID
                        }
                        var isDateField = $("#" + sepRadioCheckedID + "IsDateField");
                        var monthValue = $("#ddlMonth" + sepRadioCheckedID).val();;
                        var dayValue = $("#ddlDay" + sepRadioCheckedID).val();
                        var yearValue = $("#ddlYear" + sepRadioCheckedID).val();

                        if (monthValue == undefined) {
                            monthValue = $("#ddlMonth" + sepRadioCheckedID + "Selected").val();
                        }
                        if (dayValue == undefined) {
                            dayValue = $("#ddlDay" + sepRadioCheckedID + "Selected").val();
                        }
                        if (yearValue == undefined) {
                            yearValue = $("#ddlYear" + sepRadioCheckedID + "Selected").val();
                        }

                        if (isDateField != undefined && isDateField.val().toLowerCase() == "true") {

                            if (monthValue == undefined || monthValue == "" || dayValue == undefined || dayValue == "" || yearValue == undefined || yearValue == "") {
                                var isSEPPanelVisible = $("#pnlSEPEffDate" + sepRadioCheckedID).is(":visible");
                                if (!isSEPPanelVisible) {
                                    $("#" + sepRadioCheckedID).click();
                                }
                                var monthField = $("#ddlMonth" + sepRadioCheckedID);
                                if (monthField.val() == undefined) {
                                    monthField = $("#ddlMonth" + sepRadioCheckedID + "Selected");
                                }
                                //monthField.addClass("error_h");

                                var dayField = $("#ddlDay" + sepRadioCheckedID);
                                if (dayField.val() == undefined) {
                                    dayField = $("#ddlDay" + sepRadioCheckedID + "Selected");
                                }
                                //dayField.addClass("error_h");

                                var yearField = $("#ddlYear" + sepRadioCheckedID);
                                if (yearField.val() == undefined) {
                                    yearField = $("#ddlYear" + sepRadioCheckedID + "Selected");
                                }
                                //yearField.addClass("error_h");

                                $(".SEPDateSelect").addClass("error_h");

                                var error = 'Select a valid month';
                                var monthFieldId = monthField.prop('id');
                                var MonthErrorField = "ddlMonth" + sepRadioCheckedID + "Error";
                                $("#" + MonthErrorField).html(error);
                                $("#" + MonthErrorField).attr("aria-label", " (Error) " + error).attr("role", "text");
                                addValidationError(monthFieldId, error, errorList);

                                var error = 'Select a valid day';
                                var dayFieldId = dayField.prop('id');
                                var DayErrorField = "ddlDay" + sepRadioCheckedID + "Error";
                                $("#" + DayErrorField).html(error);
                                $("#" + DayErrorField).attr("aria-label", " (Error) " + error).attr("role", "text");
                                addValidationError(dayFieldId, error, errorList);

                                var error = 'Select a valid year';
                                var yearFieldId = yearField.prop('id');
                                var YearErrorField = "ddlYear" + sepRadioCheckedID + "Error";
                                $("#" + YearErrorField).html(error);
                                $("#" + YearErrorField).attr("aria-label", " (Error) " + error).attr("role", "text");
                                addValidationError(yearFieldId, error, errorList);

                                isFormInvalid = true;
                                return isFormInvalid;
                            } else {
                                var isDateValid = true;
                                if ((monthValue == 4 || monthValue == 6 || monthValue == 9 || monthValue == 11) && dayValue == 31) {
                                    isDateValid = false;
                                }
                                else if (monthValue == 2) {
                                    var isleap = (yearValue % 4 == 0 && (yearValue % 100 != 0 || yearValue % 400 == 0));

                                    if (dayValue > 29 || (dayValue == 29 && !isleap)) {
                                        isDateValid = false;
                                    }
                                }
                                if (!isDateValid) {
                                    if (!isSEPPanelVisible) {
                                        $("#" + sepRadioCheckedID).click();
                                    }
                                    var monthField = $("#ddlMonth" + sepRadioCheckedID);
                                    if (monthField.val() == undefined) {
                                        monthField = $("#ddlMonth" + sepRadioCheckedID + "Selected");
                                    }
                                    //monthField.addClass("error_h");

                                    var dayField = $("#ddlDay" + sepRadioCheckedID);
                                    if (dayField.val() == undefined) {
                                        dayField = $("#ddlDay" + sepRadioCheckedID + "Selected");
                                    }
                                    //dayField.addClass("error_h");

                                    var yearField = $("#ddlYear" + sepRadioCheckedID);
                                    if (yearField.val() == undefined) {
                                        yearField = $("#ddlYear" + sepRadioCheckedID + "Selected");
                                    }
                                    //yearField.addClass("error_h");

                                    $(".SEPDateSelect").addClass("error_h");

                                    var error = 'Select a valid month';
                                    var monthFieldId = monthField.prop('id');
                                    var MonthErrorField = "ddlMonth" + sepRadioCheckedID + "Error";
                                    $("#" + MonthErrorField).html(error);
                                    $("#" + MonthErrorField).attr("aria-label", " (Error) " + error).attr("role", "text");
                                    addValidationError(monthFieldId, error, errorList);

                                    var error = 'Select a valid day';
                                    var dayFieldId = dayField.prop('id');
                                    var DayErrorField = "ddlDay" + sepRadioCheckedID + "Error";
                                    $("#" + DayErrorField).html(error);
                                    $("#" + DayErrorField).attr("aria-label", " (Error) " + error).attr("role", "text");
                                    addValidationError(dayFieldId, error, errorList);

                                    var error = 'Select a valid year';
                                    var yearFieldId = yearField.prop('id');
                                    var YearErrorField = "ddlYear" + sepRadioCheckedID + "Error";
                                    $("#" + YearErrorField).html(error);
                                    $("#" + YearErrorField).attr("aria-label", " (Error) " + error).attr("role", "text");
                                    addValidationError(yearFieldId, error, errorList);

                                    isFormInvalid = true;
                                    return isFormInvalid;
                                }
                            }

                        }

                    }

                }
            }
        }

        //$('.close a').live('click', function (e) {
        $('.close').on('click', 'a', function (e) {
            if (isFromCompareLanding) {
                isFromCompareLanding = false;
                return isPlanSelected;
            }
            e.preventDefault();
            $('label.error').hide();
            $('input').removeClass('error');
            $.fancybox.close();
        });

        ////////////////
        // Summary page Validation
        ///////////////
        $('#summary').validate(
            {
                rules:
                {
                    repFullName: 'required',
                    repAddress: 'required',
                    repCity: 'required',
                    repState: 'required',
                    repZipCode: 'required',
                    repPhoneNum: 'required',
                    bdPick: 'required',
                    group2: 'required',
                    repEmail:
                    {
                        required: true,
                        email: true
                    },
                    group1: "required",
                    haPick: "required",
                    hbPick: "required",
                    group3: "required",
                    group4: "required",
                    group5: "required",
                    beneNameFirst:
                    {
                        required: true
                    },
                    beneNameLast:
                    {
                        required: true
                    },
                    beneNameFirst2:
                    {
                        required: true
                    },
                    beneNameLast2:
                    {
                        required: true
                    },
                    bdPick2: 'required',
                    haPick2: "required",
                    hbPick2: "required",
                    address1: "required",
                    county: "required",
                    city: "required",
                    state: "required",
                    zip: "required",
                    phoneNum: "required",
                    password:
                    {
                        required: true,
                        minlength: 5
                    },
                    confirm_password:
                    {
                        required: true,
                        minlength: 5,
                        equalTo: "#nPassword"
                    },
                    address3: "required",
                    county2: "required",
                    city2: "required",
                    state2: "required",
                    zip2: "required",
                    planName: "required",
                    planId: "required",
                    groupNumber: "required",
                    planName2: "required",
                    planId2: "required",
                    groupNumber2: "required",
                    acctNum: "required",
                    acctType: "required",
                    acctName: "required",
                    routNum: "required",
                    first_name: 'required',
                    last_name: 'required',
                    bdPick3: 'required',
                    email:
                    {
                        required: true,
                        email: true
                    },
                    email2:
                    {
                        required: true,
                        email: true,
                        equalTo: "#email"
                    },
                    datePick2: 'required',
                    email3:
                    {
                        email: true
                    },
                    Institution: 'required',
                    InstAddress: 'required',
                    InstCity: 'required',
                    InstState: 'required',
                    InstZip: 'required',

                    "ctl00$MainContent$eobemail":
                    {
                        email: true
                    }
                }
            });
        //BD: Email Eob-opt in changes
        $('#blah').validate(
            {
                rules:
                {
                    "EOB": "required",
                    "eobemail":
                    {

                        email: true
                    }
                }
            });

        $('#pharmLocator').on('submit', function (e) {
            var zip = $('.zip').val(),
                city = $('.city').val(),
                state = $('#state').val();

            if (zip == '' && city == '') {
                $('.error').show();
                e.preventDefault();
            }
            else if (city !== '' && state == '') {
                $('.error').show().html('Please select a state');
                e.preventDefault();
            }
        });

        /**
         *
         * End Form Validations Section
         *
         */
        ///////
        //  Hide plan
        ///////
        $('.hideMe').on('click', function (e) {
            e.preventDefault();
            $(this).parent().parent().hide();
        });

        ///////
        // Plan details box toggle
        ///////
        $('.open').next().toggle();
        $('.head').on('click', function () {
            $(this).toggleClass('open').next().toggle();
        });

        ///////
        // Plan details box toggle
        ///////
        $('.selectPlanTop .last').on('click', function () {
            if ($(this).parent().hasClass('open'))
                $(this).parent().removeClass('open').addClass('close').next().toggle();
            else if ($(this).parent().hasClass('close'))
                $(this).parent().removeClass('close').addClass('open').next().toggle();
        });

        /////// 
        // Drug Exception Popup
        ///////
        //$('#drugExceptions').on('click', function (e) {
        //    e.preventDefault();
        //    window.open('./drug_coverage_exceptions.php', 'Drug Coverage Exceptions', 'width=700, height=600');
        //});

        ///////
        // Print function for printer button
        ///////
        //$('.printLink').live('click', function (e) {
        $('body').on('click', '.printLink', function (e) {
            e.preventDefault();
            print();
        });

        $('.sideNav > li:last').css('border-bottom', '0px');

        ///////
        // Table Stripes
        ///////
        $('.stripe > li:odd').addClass('odd');
        $('.stripe > li:last, .total > li:last').css('border-bottom', '0');

        ///////
        // Change Location
        ///////
        $('.changeLocation').fancybox(
            {
                type: 'inline',
                beforeLoad: function () {
                    resetFancyBox("#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#divStatesCompareMenu,#zipErrorCompareMenu,#errorRegionShowPlanCompareMenu");
                },
                afterShow: function () {
                    $("#zipHomeCompareMenu").focus();

                    $('.lastFancyBtn').on('keydown', function (e) {
                        var keyCode = e.keyCode || e.which;
                        if (keyCode == 9) {
                            if (!e.shiftKey) {
                                e.preventDefault();
                                $(".fancybox-close-small").focus();
                            }
                        }
                    });
                    $('.fancybox-close-small').on('keydown', function (e) {
                        var keyCode = e.keyCode || e.which;
                        if (keyCode == 9) {
                            if (e.shiftKey) {
                                e.preventDefault();
                                $(".lastFancyBtn").focus();
                            }
                            else {
                                e.preventDefault();
                                $('.zip-section input').focus();
                            }
                        }
                        if (keyCode == 13) {
                            $.fancybox.close();
                        }
                    });
                    $('#zipHomeCompareMenu').on('keydown', function (e) {
                        var keyCode = e.keyCode || e.which;
                        if (keyCode == 9) {
                            if (e.shiftKey) {
                                e.preventDefault();
                                $(".fancybox-close-small").focus();
                            }
                        }
                    });
                }


            });

        $('.changeLocationBlue').fancybox(
            {
                type: 'inline',
                beforeLoad: function () {
                    resetFancyBox("#zipCode,#zipSplit,#zipHome,#divStates,,#zipError,#errorRegionShowPlan");
                },
                afterShow: function () {
                    $(".fancybox-close-small").focus();

                    $('.lastFancyBtn').on('keydown', function (e) {
                        var keyCode = e.keyCode || e.which;
                        if (keyCode == 9) {
                            if (!e.shiftKey) {
                                e.preventDefault();
                                $(".fancybox-close-small").focus();
                            }
                        }
                    });
                    $('.fancybox-close-small').on('keydown', function (e) {
                        var keyCode = e.keyCode || e.which;
                        if (keyCode == 9) {
                            if (e.shiftKey) {
                                e.preventDefault();
                                $(".lastFancyBtn").focus();
                            }
                            else {
                                e.preventDefault();
                                $('.zip-section input').focus();
                            }
                        }
                        if (keyCode == 13) {
                            $.fancybox.close();
                        }
                    });
                    $('#zipHomeCompareMenu').on('keydown', function (e) {
                        var keyCode = e.keyCode || e.which;
                        if (keyCode == 9) {
                            if (e.shiftKey) {
                                e.preventDefault();
                                $(".fancybox-close-small").focus();
                            }
                        }
                    });
                }
            });

        ////////
        // Plan Advisor
        ////////
        $('.pAdvisor').each(function () {
            $(this).fancybox(
                {
                    'padding': 30,
                    'showCloseButton': true,
                    'titleShow': false,
                    'onStart': function () {
                        $('input[name="selectPlan"]:checked').removeAttr('checked');
                    }
                });
        });

        if (!getCookie('selectedPlan')) {
            var plan = createCookie('selectedPlan', 'none', '', '', '.meddweb.net', '');
        }
        else {
            var plan = getCookie('selectedPlan').replace(/^\/\/|\/\/$/g, '');
        }

        //$('#ShowPlanArea').click(function (e) {
        //    e.preventDefault();
        //    plan = $('input[name="selectPlan"]:checked').val();
        //    setCookie('selectedPlan', plan, '', '', '.meddweb.net', '');
        //    changeButton(plan);
        //    $('.confirm').fancybox({
        //        'padding': 30,
        //        'showCloseButton': true,
        //        'titleShow': false
        //    }).trigger('click');

        //    updatePage(plan);
        //    changeHighligth(plan);
        //    return false;
        //});

        $('.closeButton, .seePlan').on('click', function (e) {
            e.preventDefault();
            $.fancybox.close()
        });

        var changeButton = function (plan) {
            var button = $('.buttonImage'),
                goToPlan = $('.selectedPlan');
            if (plan == 'choice') {
                button.attr('src', '../images/btn_enroll-plan1.gif');
                goToPlan.attr('href', 'plan_detail.html')
            }
            else if (plan == 'basic') {
                button.attr('src', '../images/btn_enroll-plan2.gif');
                goToPlan.attr('href', 'plan_detail.html')
            }
            else if (plan == 'plus') {
                button.attr('src', '../images/btn_enroll-plan3.gif');
                goToPlan.attr('href', 'plan_detail.html')
            }
        };

        //update open plan on compare landing
        var updatePage = function (plan) {
            if (typeof (plan) != "undefined" && plan.replace(/\//g, '') != "none") {
                $('.comparePlanWrap').find('.selectPlanTop').addClass('open');
                $('.comparePlanWrap').find('.open').removeClass('open').next().toggle(false);
                $('.comparePlanWrap').find('.selectPlanTop').addClass('close');
                $('.' + plan).removeClass('close').addClass('open').next().toggle(true);
            }
            else {
                $('.comparePlanWrap').find('.selectPlanTop').removeClass('open');
                $('.comparePlanWrap').find('.selectPlanTop').removeClass('close');
                $('.comparePlanWrap').find('.selectPlanTop').addClass('open');
            }
        };
        updatePage(plan);


        // PriceTable Hilight		
        var highlight = function (num) {
            var plan = parseInt(num);
            var plan2 = plan - 1;
            var planHilight = $('.priceTable ul:nth-child(' + plan + ')');
            var planCatastrophicHilight = $('.priceTableforCatastrophic ul:nth-child(' + plan + ')');
            var planTopHilight = $('.planTop ul:nth-child(' + plan2 + ')');
            var planBottomHilight = $('.planBottom ul:nth-child(' + plan2 + ')');
            var planTopHilightState = $('.planTopState ul:nth-child(' + plan + ')');
            var planBottomHilightState = $('.planBottomState ul:nth-child(' + plan2 + ')');
            $('#detailsContainer').find('.hilight').removeClass('hilight');
            return planHilight.addClass('hilight'),
                planCatastrophicHilight.addClass('hilight'),
                planTopHilight.addClass('hilight'),
                planBottomHilight.addClass('hilight'),
                planTopHilightState.addClass('hilight'),
                planBottomHilightState.addClass('hilight');
        };

        //change the highlight on compare module
        var changeHighligth = function (plan) {
            var itemsarray = [];
            var planIndex = 0;
            $("#pAdvisorForm input[type='radio']").each(function () {
                var radioButtonVal = $(this).val();
                itemsarray.push(radioButtonVal);
            });

            planIndex = jQuery.inArray(plan, itemsarray)

            if (planIndex >= 0) {
                highlight(planIndex + 2);
            }
        };
        changeHighligth(plan);

        var getUrlParams = function () {
            var params = {};
            window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (str, key, value) {
                params[key] = value;
            });

            return params;
        };

        // Dynamic column change
        var cols = getUrlParams();
        if (cols.columns == "three_col") {
            $('.two, .three').remove();
        }
        else if (cols.columns == "four_col") {
            $(' .three').remove();
        }
        //		$('#detailsContainer').removeClass().addClass(cols.columns);


        ///////
        // Learn Side Nav arrow collor change on hover
        ///////
        $('.sideNav li a').on('hover', function () {
            $(this).find('span').toggleClass('dingArrowBlack dingArrowBlue');
        });

        ///////
        // Drug Search 
        ///////
        $('.letterSelect label').on('click', function () {
            $('.letterSelect').find('label').removeClass('selected'),
                $(this).addClass('selected');
            var letter = $(this).prev().val();
            $('#drug_name').val(letter);
            callDrugSearch();
        });

        $('#drug_name').bind('keyup', function (e) {
            callDrugSearch();
        });

        function callDrugSearch() {
            var searchValue = $('#drug_name').val(),
                url = '../handlers/drugsearchhandler.ashx',
                querystring = "searchValue=" + searchValue;
            if (searchValue != null && searchValue.length > 0) {
                CallAjax(url, querystring, fillDrugSearchRepeater, '');
            }
            else {
                $('#nothing').hide();
                $('#dvDrugSearchResult').html('');
                $('#dvDrugSearchResult').hide();
            }
        }

        function fillDrugSearchRepeater(data) {
            if (typeof (data) != 'undefined' && data != null && data != '') {
                $('#dvDrugSearchResult').html('');
                $('#nothing').hide();
                $('#dvDrugSearchResult').show();
                $('#dvDrugSearchResult').html(data);
            }
            else {
                $('#nothing').show();
                $('#dvDrugSearchResult').html('');
                $('#dvDrugSearchResult').hide();
            }
        }

        //$('.showDrugToggle').live('click', function () {
        $('body').on('click', '.showDrugToggle', function () {
            var display = $(this)[0].parentElement.parentElement.children[1].style['display'];
            if (display == "")
                $(this)[0].parentElement.parentElement.children[1].style['display'] = "none";
            else
                $(this)[0].parentElement.parentElement.children[1].style['display'] = "";
        });

        /////NDC Drug Pop Up
        var pa_type;
        $('body').on('click', '.ndcDrugPopUp', function () {
            var lnkId = $(this).attr('id'),
                drugName = lnkId.split('_')[1],
                lnkType = lnkId.split('_')[2];
            pa_type = lnkId.split('_')[3];

            if (pa_type == 'service')
                callExternalWebService(drugName, lnkType)

            else {
                var url = '../handlers/ndcdrugsearchhandler.ashx',
                    querystring = "DrugName=" + drugName;
                if (drugName != null && drugName != "") {
                    CallAjax(url, querystring, NdcDrugSearchResult, '');
                }
            }
        });

        function callExternalWebService(drugName, lnkType) {
            url = '../call-pa-st-drug-service?DrugName=' + drugName + "&type=" + lnkType,
                windowName = 'callWebService';
            window.open(url, windowName, 'menubar=0, toolbar=0, location=0, directories=0, status=0, scrollbars=1, resizable=1, dependent=0, width=700, height=640, left=0, top=0');
        }

        function NdcDrugSearchResult(data) {
            if (typeof (data != null) && data.indexOf("One Drug") >= 0) {
                var ndcDrug = data.split('~')[1];
                var confirmation = window.confirm('You are now leaving SilverScript.com, a Medicare-approved website and will be directed to www.covermymeds.com.');
                if (confirmation) {
                    ReDirectToExternalNdcLink(ndcDrug);
                }
            }
            else if (typeof (data != null) && data != "") {
                $.fancybox(
                    {
                        'href': '#dvNdcDrugSearch',
                        'padding': 30,
                        'showCloseButton': true,
                        'titleShow': false,
                        'scrolling': 'no',
                        'onStart': function () {
                            $('#dvNdcDrugResult').html(data);
                        }
                    })
            }
            else
                alert("No NDC Drug Exists");
        }

        function ReDirectToExternalNdcLink(drug_NDC) {
            ndcDrugRedirect(drug_NDC);
        }

        function ndcDrugRedirect(drug_NDC) {
            var redirectNdcUrl;
            if (drug_NDC != null && drug_NDC != '' && pa_type != null && pa_type != '') {
                if (pa_type == 'step')
                    redirectNdcUrl = 'https://www.covermymeds.com/request/quickstart/?drug_NDC=' + drug_NDC + '&form_id=&no_eula=1&ref=ssi&pa_type=' + pa_type + '&format=pdf';
                else
                    redirectNdcUrl = 'https://www.covermymeds.com/request/quickstart/?drug_NDC=' + drug_NDC + '&form_id=&no_eula=1&ref=ssi&pa_type=' + pa_type;

                if (redirectNdcUrl != null)
                    window.open(redirectNdcUrl, "Cover My Meds", 'menubar=0, toolbar=0, location=0, directories=0, status=0, scrollbars=1, resizable=1, dependent=0, width=1000, height=800, left=0, top=0');

            }
        }

        $('body').on('click', '#btnRediectExternalNdcDrug', function (e) {
            e.preventDefault();
            var confirmation = confirm('You are now leaving SilverScript.com, a Medicare-approved website and will be directed to www.covermymeds.com.');
            if (confirmation) {
                var drug_NDC = $("#dvNdcDrugResult input[type='radio']:checked").val();
                ndcDrugRedirect(drug_NDC);
                $.fancybox.close();
            }
        });

        //////////
        //  Show contact info Faq page
        //////////
        $('.contactExp').on('click', function (e) {
            e.preventDefault();
            var showThis = $(this).attr('href');
            $(showThis).show();

        });

        ////////
        // Back to top scroll
        ////////
        $('.alignLeft').on('click', function (e) {
            e.preventDefault();
            $('html, body').animate(
                {
                    scrollTop: 0
                }, 'slow');
        });

        /////////
        // Search Boxes
        /////////

        function runSearch() {
            var search = "";
            $('input[name="searchSite"]').each(function () {
                search = $("input[name='searchSite']").val();
                if (search != "") {
                    $('input[name="searchSite"]').val(search);
                    var searchUrl = "../search-results?searchtext=" + search;
                    //Search Path for Prior Year
                    if ($("#planYear") != undefined && $("#planYear").val() !== undefined) {
                        var planyear = $("#planYear").val()
                        var url = window.location.pathname
                        if (url.indexOf(planyear) > -1) {
                            searchUrl = "../" + searchUrl;
                        }
                    }
                    window.location.href = searchUrl;
                } //end if
            }); //end each
            if (search == "" || search == null) {
                var searchUrl = "../search-results?searchtext=";
                window.location.href = searchUrl;
            } //end if 
        } //end runSearch()

        $('#searchTop').on('click', function () {
            var windowWidth = $(window).width();
            if (windowWidth >= 767) { /*needed for mobile */
                var searchShow = $(".search-box").css("display");
                if (searchShow != "block") {
                    $(this).attr("aria-expanded", "false");
                    $('#searchTop').hide();
                    $('.search-box').show();
                    $("input[name='searchSite']").focus();
                } //end if
            } //end if
        });

        // clear the input search box
        $('.close-button').on('click', function (e) {
            e.preventDefault();
            $("input[name='searchSite']").val("");
            $('.close-button').hide();
            $("input[name='searchSite']").focus();
        });

        $('#languageAnchor').on('focus', function () {
            $(".search").hide();
        });

        $("input[name='searchSite']").keyup(function (e) {
            if ($("input[name='searchSite']").val()) {
                $('.close-button').show();
            }
            else {
                $('.close-button').hide();
            }
            if ((e.keyCode || e.which) == 13) // if focus on search and "enter/return" is selected
            {
                e.preventDefault();
                runSearch();
            } //end if
        }); //end keydown

        $('#search-button').on("click", function (e) {
            if (!$("#btnPremiumShowPlan").is(":visible") && !$("#btnShowEnrollmentPlanByRegion").is(":visible") && !$("#btnRegionShowPlanCompareMenuOnHomePage").is(":visible")) {
                e.preventDefault();
                runSearch();
            }
            else {
                if ($("#btnRegionShowPlanCompareMenuOnHomePage").is(":visible") && $(document.activeElement) !== undefined && $(document.activeElement).prop('name') == "SelectedStateFromPage") {
                    e.preventDefault();
                    $("#btnRegionShowPlanCompareMenuOnHomePage").click();
                }
            }


        }); //end keydown

        var search = getUrlParams();
        if (search.searchSite !== '') {
            $('.searchQuery').text(search.searchSite);
        }

        /////////
        // Tooltips
        /////////
        $('.tooltip').hover(
            function () {
                var offset = $(this).offset();
                var tip = $(this).attr('alt');
                var bubble = $('<div class="bubble"></div>').html(tip);
                $(this).attr('title', '');
                bubble.appendTo('body').css(
                    {
                        position: 'absolute',
                        left: offset.left + 80,
                        top: offset.top - 40,
                        padding: '10px',
                        background: '#fff',
                        width: '300px',
                        border: '1px solid #e6e6e6'
                    });
            },
            function () {
                $('body').find('.bubble').remove();

            }
        );
        $('.tooltipCaremarkMail').hover(
            function () {
                var offset = $(this).offset();
                var tip = $(this).attr('alt');
                var bubble = $('<div class="bubble"></div>').html(tip);
                $(this).attr('title', '');
                bubble.appendTo('body').css(
                    {
                        position: 'absolute',
                        left: offset.left + 20,
                        top: offset.top - 20,
                        padding: '10px',
                        background: '#fff',
                        width: '150px',
                        border: '1px solid #e6e6e6'
                    });
            },
            function () {
                $('body').find('.bubble').remove();

            }
        );
        ////////
        // Countdown on home page
        ///////
        var today = new Date();
        var first = new Date('01/01/2012');
        var lastDay = new Date('12/7/2012'); //December 7th
        var theStartDay = Math.round(((today - first) / 1000 / 60 / 60 / 24) + .5, 0);
        var theEndDay = Math.round(((lastDay - first) / 1000 / 60 / 60 / 24) + .5, 0);
        var end = theEndDay - theStartDay;
        $('.daysLeft, .emailNodeText > strong').html(end + ' days');

        /////////
        // Leaving site confirmation
        /////////
        var site = window.location.hostname;
        $('.ext').on('click', function (e) {
            e.preventDefault();
            var url = $(this).attr('href');
            if (url !== site) {
                r = confirm("You are now leaving SilverScript.com.");
                if (r == true) {
                    window.open(url, '_blank');
                }
                else {
                    return false;
                }

            }
            else {
                return false;
            }

        });

        $(document).ready(function () {
            $('#Popup').click(function () {

                var NWin = window.open($(this).prop('href'), '', 'height=800,width=800');

                if (window.focus) {

                    NWin.focus();

                }

                return false;

            });

            $('#NewTab').click(function () {

                $(this).target = "_blank";

                window.open($(this).prop('href'));

                return false;

            });

            /*
            document.addEventListener('keyup', function (event) {
                if (event.keyCode === 9 || event.keyCode === 38 || event.keyCode === 40) {
                    var currentElement = document.activeElement;
                    currentElement.classList.add('add-focus');
                    if (!currentElement.classList.contains("modal-trigger")) {
                        currentElement.addEventListener('blur', function () {
                            currentElement.classList.remove('add-focus');
                        });
                    }
                }
            }); */
        });

        $("#txtOtherPlan1MonthlyPlanPremium,#txtOtherPlan1Deductible,#txtOtherPlan2MonthlyPlanPremium,#txtOtherPlan2Deductible").bind("keydown", function (event) {
            var keyCode;
            keyCode = event.keyCode;
            if (this.value.length == 0 && (keyCode == 48 || keyCode == 96)) {
                event.preventDefault();
            }
            else if (keyCode == 190 || keyCode == 110) {
                if ($(this).val().indexOf('.') != -1) {
                    event.preventDefault();
                    return false;
                }
                else {
                    return true;
                }
            }
            else {

                var isnum = isNumeric(event);

                if (isnum == true) {
                    var keyCode;
                    if (window.event)
                        keyCode = event.keyCode;
                    else if (event.which)
                        keyCode = event.which;

                    if (keyCode == 46 || keyCode == 8 || keyCode == 9 || keyCode == 27 || keyCode == 13 || (keyCode == 65 && event.ctrlKey === true) || (keyCode >= 35 && keyCode <= 39)) {

                        return true;
                    }
                    else {

                        indexOfPoint = $(this).val().indexOf('.');
                        var number = ($(this).val().split('.'));

                        if (indexOfPoint != -1) {

                            if (number[1].length > 1) {
                                return false;
                            }
                        }
                        else {
                            if (number[0].length > 2) {
                                return false;
                            }
                        }
                    }
                }
                else {
                    return false;
                }
            }

        });

        $("#txtOtherPlan1MonthlyPlanPremium,#txtOtherPlan1Deductible,#txtOtherPlan2MonthlyPlanPremium,#txtOtherPlan2Deductible").bind("keyup", function () {
            CalculatePlan1();
            CalculatePlan2();
            return this; //for chaining
        });

        $('#txtOtherPlan1MonthlyPlanPremium, #txtOtherPlan1Deductible').on('change', function () {
            CalculatePlan1();
        });

        $('#txtOtherPlan2MonthlyPlanPremium, #txtOtherPlan2Deductible').on('change', function () {
            CalculatePlan2();
        });

        $('#txtOtherPlan1MonthlyPlanPremium, #txtOtherPlan1Deductible').click(function () {
            CalculatePlan1();
        });

        $('#txtOtherPlan2MonthlyPlanPremium, #txtOtherPlan2Deductible').click(function () {
            CalculatePlan2();
        });

        $('#txtOtherPlan1MonthlyPlanPremium, #txtOtherPlan1Deductible').on('blur', function () {
            CalculatePlan1();
        });

        $('#txtOtherPlan2MonthlyPlanPremium, #txtOtherPlan2Deductible').on('blur', function () {
            CalculatePlan2();
        });

        function CalculatePlan1() {
            var monthlyPlan = $("#txtOtherPlan1MonthlyPlanPremium").val() * 1;
            if (monthlyPlan == 0 || isNaN(monthlyPlan)) {
                $("#lblMonthlyPlanPremiumPlusDeductibleCost1").text("$X.XX");
                $("#lblAnnualPay1").text("$X.XX");
            }
            else {
                var deduction = $("#txtOtherPlan1Deductible").val() * 1;
                if (isNaN(deduction)) {
                    deduction = 0;
                }
                $("#lblMonthlyPlanPremiumPlusDeductibleCost1").text("$" + (monthlyPlan + (deduction / 12)).toFixed(2));
                $("#lblAnnualPay1").text("$" + ((monthlyPlan * 12) + deduction).toFixed(2));
            }
        }

        function CalculatePlan2() {
            var monthlyPlan = $("#txtOtherPlan2MonthlyPlanPremium").val() * 1;
            if (monthlyPlan == 0 || isNaN(monthlyPlan)) {
                $("#lblMonthlyPlanPremiumPlusDeductibleCost2").text("$X.XX");
                $("#lblAnnualPay2").text("$X.XX");
            }
            else {
                var deduction = $("#txtOtherPlan2Deductible").val() * 1;
                if (isNaN(deduction)) {
                    deduction = 0;
                }
                $("#lblMonthlyPlanPremiumPlusDeductibleCost2").text("$" + (monthlyPlan + (deduction / 12)).toFixed(2));
                $("#lblAnnualPay2").text("$" + ((monthlyPlan * 12) + deduction).toFixed(2));
            }
        }

        //$('#imgbtnSendMailConfirm').click(function (e) {
        //    var IsValid = true;
        //    var emailRegExp = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

        //    var email = $('#txtEmailaddress').val();
        //    if (email == "" || !emailRegExp.test(email)) {
        //        $('#txtEmailaddress').attr('class', 'error');
        //        $('#error_Emailaddress').show();
        //        IsValid = false;
        //    }
        //    else {
        //        $('#txtEmailaddress').attr('class', 'textfield modal-large');
        //        $('#error_Emailaddress').hide();
        //        IsValid = true;
        //    }

        //    var renteremail = $('#txtReenterEmailaddress').val();
        //    if (renteremail == "" || !emailRegExp.test(renteremail)) {
        //        $('#txtReenterEmailaddress').attr('class', 'error');
        //        $('#error_RenterEmailaddress').show();
        //        IsValid = false;
        //    }
        //    else {
        //        $('#txtReenterEmailaddress').attr('class', 'textfield modal-large');
        //        $('#error_RenterEmailaddress').hide();
        //        IsValid = true;
        //    }

        //    if (IsValid == true && email != renteremail) {
        //        $('#error_EmailDonorMatch').show();
        //        IsValid = false;
        //    } else if (IsValid == true) {

        //        $('#error_EmailDonorMatch').hide();
        //        IsValid = true;
        //    }


        //    return IsValid;
        //});


        //* Hidden flickring of send mail Popups when page loads*//
        //Start
        function pageLoad(sender, args) {
            var modalPopups = ['modPopUpSaveAddInfo', 'modPopUpSaveSummaryInfo', 'modPopUpSaveEnrollInfo', 'modPopUpSavePerInfo', 'modPopUpSavePaymentInfo', 'modPopUpSaveRulesInfo'];
            AddHiddenEventToPopups(modalPopups);
        }

        function AddHiddenEventToPopups(modalPopups) {
            for (var i = 0; i < modalPopups.length; i++) {
                var popUp = $find(modalPopups[i]);
                if (popUp) {
                    popUp.add_hidden(HidePopupPanel);
                }
            }
        }

        function HidePopupPanel(source, args) {
            objPanel = document.getElementById(source._PopupControlID);
            if (objPanel) {
                objPanel.style.display = 'none';
            }
        }
        //End

        //CTC 
        // check where the Need help div is 

        //var offset = $('#divChat').offset();
        //if (offset != 'undefined' || offset != null) {
        //    $(window).scroll(function () {
        //        var scrollTop = $(window).scrollTop(); // check the visible top of the browser 
        //        if (offset == null || offset.top < scrollTop)
        //            $('#divChat').addClass('fixed');
        //        else $('#divChat').removeClass('fixed');
        //    });

        //}

    }); //END Document Ready

})(jQuery);

function setPlanPick(planPick) {
    $.ajax(
        {
            type: "POST",
            url: "../handlers/savestateplan.ashx",
            data: "planPick=" + planPick,
            dataType: "text",
            success: function (msg) { },
            error: function (err) { }
        });
}

function resetFancyBoxStatePage(ctrls) {
    if (typeof (ctrls) != "undefined" && ctrls.indexOf(',') > -1) {
        var controls = ctrls.split(',');
        if (controls != null && controls.length > 0) {
            var control1 = controls[0];
            var control2 = controls[1];
            var control3 = controls[2];
            var control4 = controls[3];
            var control5 = controls[4];
            var control6 = controls[5];
            $(control1).show();
            $(control2).hide();
            $(control3).attr("placeholder", "ex. 94110").css('color', '#d1d1d1'); // $(control3).val('ex. 94110').css('color', '#d1d1d1');
            $(control4).html("");
            $(control3).attr('class', '');
            $(control5).html("");
            $(control6).html("");
        }
    }
}
// submit-application.html jquery

$(document).ready(function () {
    var selPlan = $('#lblSelPlanName').html();
    if (selPlan == 'SilverScript Choice (PDP)') {
        $('#planBorderDiv').css("border-top", "8px solid #6D4061");
        //        $('#lblSelPlanName').css("color", "#6D4061");
    }
    else if (selPlan == 'SilverScript Plus (PDP)') {
        $('#planBorderDiv').css("border-top", "8px solid #5482AB");
        //        $('#lblSelPlanName').css("color", "#5482AB");
    }
    else {
        $('#planBorderDiv').css('border-top', 'none');
    }


    ////////////////////////////////////////////////////start global modal
    var info = [
        {
            whichMessage: "leavingSiteComplaintForm",
            link: "https://www.medicare.gov/medicarecomplaintform/home.aspx",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.medicare.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        // SEO update start
        {
            whichMessage: "leavingSiteehealthmedicate",
            link: "https://www.ehealthmedicare.com/medicare-part-c-advantage",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to https://www.ehealthmedicare.com/medicare-part-c-advantage/ </div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        // SEO update end
        {
            whichMessage: "emailConfirmation",
            link: "#",
            message: "<h3 class='msgHead' id='msgHead'><h3>Email Enrollment Confirmation</h3></div><br/> <ul class='noStyle'> <li> <input type='text' class='modal firstEmail' placeholder='email address' aria-label='Email address' aria-required='true' aria-describedby='matchEmails' maxlength='100' id='txtEmailaddress' runat='server'/> <p id='matchEmails'></p></li><li> <input class='modal secondEmail' placeholder='Re-enter email address' type='text' aria-label='Re-enter email address' aria-describredby='matchEmails' aria-readonly='false' id='txtReenterEmailaddress' runat='server' disabled='disabled'/> </li><li> <p class='confirmation disclaimer'> <div id='msgBody' class='msgBody'> If you provide your email address, we will send more information about the SilverScript (PDP) plan. You may opt out at any time.</p></li></ul></diV>",
            button1: "Send",
            target: "_self",
            button2: "Close"
        },
        {
            whichMessage: "leavingSiteMedicare",
            link: "https://www.medicare.gov",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.medicare.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteMedicareSavingProgram",
            link: "https://www.medicare.gov/your-medicare-costs/help-paying-costs/medicare-savings-program/medicare-savings-programs.html",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.medicare.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteMedicareOverallStarRating",
            link: "https://www.medicare.gov/find-a-plan/staticpages/rating/planrating-help.aspx",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.medicare.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteCVSHealth",
            link: "https://www.cvshealth.com",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.cvshealth.com.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteBeltone",
            link: "https://about.beltone.com/silverscript/",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to about.beltone.com.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteSSA",
            link: "https://www.ssa.gov",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.ssa.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteSSAExtraHelp",
            link: "https://www.socialsecurity.gov/extrahelp",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.socialsecurity.gov/extrahelp.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteSSAPrescriptionHelp",
            link: "https://socialsecurity.gov/medicare/prescriptionhelp/",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.socialsecurity.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteSSAPrescription",
            link: "https://www.ssa.gov/medicare/prescriptionhelp/",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.socialsecurity.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSitei1020",
            link: "https://secure.ssa.gov/i1020/start",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to https://secure.ssa.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteCMSBAE",
            link: "https://www.cms.gov/Medicare/Prescription-Drug-Coverage/PrescriptionDrugCovContra/Best_Available_Evidence_Policy.html",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.cms.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteGoldStd",
            link: "https://www.goldstandard.com",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.goldstandard.com.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteELSEVIER",
            link: "https://www.elsevier.com",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.elsevier.com.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteCVS",
            link: "https://www.cvs.com",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.cvs.com.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteCVSECHC",
            link: "https://www.cvs.com/extracare/extracare-health-card.jsp",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.cvs.com.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteCMS1696",
            link: "https://www.cms.gov/Medicare/CMS-Forms/CMS-Forms/downloads/cms1696.pdf",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.cms.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteCMSCovDet",
            link: "http://www.cms.gov/Medicare/Appeals-and-Grievances/MedPrescriptDrugApplGriev/downloads/ModelCoverageDeterminationRequestForm.pdf",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.cms.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteNHCAA",
            link: "https://www.nhcaa.org/",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.nhcaa.org.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteOMO",
            link: "https://www.medicare.gov/claims-and-appeals/medicare-rights/get-help/ombudsman.html",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.medicare.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteBenefitsCheckup",
            link: "https://BenefitsCheckup.org",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to BenefitsCheckup.org.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteCMMPA",
            link: "https://www.covermymeds.com/request/quickstart/?drug_NDC=&form_id=&no_eula=1&ref=ssi&pa_type=nf",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.covermymeds.com.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteCMMRedeter",
            link: "https://www.covermymeds.com/request/quickstart/?drug_NDC=&form_id=&no_eula=1&ref=ssi&pa_type=redeterm",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.covermymeds.com.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteCMK",
            link: "https://www.caremark.com/wps/portal?icid=ssmemberpg",
            message: "<h3 class='msgHead' id='msgHead'>You are now leaving SilverScript.com for Caremark.com</h3> <div id='msgBody' class='msgBody'> SilverScript has selected Caremark as the prescription management and mail delivery service for our members.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteMonthlyEnrollment",
            link: "https://go.cms.gov/mapddata",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.cms.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteAdobe",
            link: "https://get.adobe.com/reader/",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to Adobe.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSite2018Plan",
            link: "http://www.silverscript/2018/learn/enroll.aspx",
            message: "<h3 class='msgHead' id='msgHead'>You're Leaving <#CurrentPlanYear#> Plan Information</h3><div id='msgBody' class='msgBody'>To learn more about or enroll in <#PriorPlanYear#> plans you need to continue to <#PriorPlanYear#> SilverScript plan information. <br/><br/> Only continue if you want your plan to start in <#PriorPlanYear#>.</div>",
            button1: "Go to 2017 site",
            target: "_self",
            button2: "Stay on 2018 site"
        },
        {
            whichMessage: "leavingSite2020Plan",
            link: "https://www.aetnamedicare.com/",
            message: "<h3 class='msgHead' id='msgHead'>You're leaving 2020 Plan Information</h3><div id='msgBody' class='msgBody'>2021 SilverScript is part of the Aetna Medicare Solutions family for 2021 plan information and enrollment, visit aetnamedicare.com.</div>",
            button1: "Go to 2021 Plan Information",
            button2: "Stay on 2020 Plan Information",
            target: "_blank",
            button2: ""
        },
        {
            whichMessage: "leavingSiteModalPopUp",
            link: "https://www.covermymeds.com/request/quickstart/?drug_NDC=&form_id=&no_eula=1&ref=ssi&pa_type=redeterm",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.covermymeds.com.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteCMSYouTube",
            link: "https://www.youtube.com/watch?v=iByQfda5PMo&feature=youtu.be",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to the CMS YouTube page.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "makePayment",
            link: "makePayment",
            message: "<h3 class='msgHead' id='msgHead'>You are leaving SilverScript.com for InstaMed.com </h3> <div id='msgBody' class='msgBody'> SilverScript handles premium payments through InstaMed, a trusted payment service.</div>",
            button1: "Go to InstaMed",
            target: "_blank",
            button2: "Cancel"
        },

        {
            whichMessage: "leavingSiteCMKEOB",
            link: "#",
            message: "<h3 class='msgHead' id='msgHead'>You are leaving SilverScript.com for Caremark.com</h3> <div id='msgBody' class='msgBody'> SilverScript has selected Caremark as the prescription management and mail delivery service for our members.</p><br/></li><li id='CMKEOB_load'><img src='../images/loading-circle-.gif' /><small class='error nudgeUp'>Verifying site status...</small></li></ul><div class='ckSite'><a href='#' target='_blank' id='EOB_ok'>OK</a> <a href='#' class='closeModal'>Cancel</a></div><br/></br/></diV>",
            button1: "",
            target: "_blank",
            button2: ""
        },
        {
            whichMessage: "leavingSiteCMKEOBPDF",
            link: "leavingSiteCMKEOBPDF",
            message: "<h3 class='msgHead' id='msgHead'>You are leaving SilverScript.com for Caremark.com</h3> <div id='msgBody' class='msgBody'> SilverScript has selected Caremark as the prescription management and mail delivery service for our members.</div>",
            button1: "Go to Caremark",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteCMKEOBError",
            link: "https://www.caremark.com",
            message: "<h3 class='msgHead' id='msgHead'><p>We're Sorry, But We Are Unable To Access The Explanation of Benefits Statements At This Time.</h3> <div id='msgBody' class='msgBody'>  Please try again later, or sign in at: </p></div>",
            button1: "Caremark.com",
            target: "_blank",
            button2: "Close"
        },
        {
            whichMessage: "leavingSiteCMSite",
            link: "https://www.caremark.com/wps/portal?icid=ssmemberpg",
            message: "<h3 class='msgHead' id='msgHead'>You are leaving SilverScript.com for Caremark.com </h3> <div id='msgBody' class='msgBody'> SilverScript has selected Caremark as the prescription management and mail delivery service for our members.</div>",
            button1: "Go to Caremark",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "termsAndCondtions",
            link: "#",
            message: "",
            button1: "",
            target: "",
            button2: "Close"
        },
        {
            whichMessage: "learnMoreConfirm",
            link: "#",
            message: "",
            button1: "",
            target: "",
            button2: "Close"
        },
        {
            whichMessage: "logoClick",
            link: "../index",
            message: "<h3 class='msgHead' id='msgHead'>You Are Leaving the SilverScript Enrollment Form</h3> <div id='msgBody' class='msgBody'> You will be routed to the home page of our site. Are you sure you want to leave the Enrollment Process?</div>",
            button1: "Go Home",
            target: "",
            button2: "Stay"
        },
        {
            whichMessage: "leavingSiteCMShhs",
            link: "https://ocrportal.hhs.gov/ocr/portal/lobby.jsf",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to the Department of Health and Human Services.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteCMShhsHippaComplaints",
            link: "https://www.hhs.gov/ocr/privacy/hipaa/complaints/",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to the Department of Health and Human Services.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteCMShhsgov",
            link: "https://www.hhs.gov/ocr/office/file/index.html",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.hhs.gov.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteFlashPlayerSettingsManager07",
            link: "https://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager07.html",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.macromedia.com.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteFlashPlayerSettingsManager03",
            link: "https://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager03.html",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.macromedia.com.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        //{
        //    whichMessage: "leavingSiteAdrOrg",
        //    link: " https://www.adr.org/aaa/faces/rules/searchrules/rulesdetail?doc=ADRSTAGE2021424",
        //    message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to www.adr.org.</div>",
        //    button1: "Leave Site",
        //    target: "_blank",
        //    button2: "Cancel"
        //},
        {
            whichMessage: "signUp4OnlineEOBs",
            link: "https://www.caremark.com/wps/portal?source=silverScriptEOB&ictd%5bmaster%5d=vid~52f4f5bd-6d2a-49c5-b158-63537fd3f7e8&ictd%5bil1247%5d=rlt~1501082613~land~2_8314_direct_654988c78de91c5582a260ad98920da6",
            message: "<h3 class='msgHead' id='msgHead'>You are leaving SilverScript.com for Caremark.com </h3> <div id='msgBody' class='msgBody'> SilverScript has selected Caremark as the prescription management and mail delivery service for our members.</div>",
            button1: "Go to Caremark",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteIrsPublications",
            link: "https://www.irs.gov/forms-pubs/about-publication-502",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to irs.gov</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leavingSiteIrs",
            link: "https://www.irs.gov/",
            message: "<h3 class='msgHead' id='msgHead'>You Are Now Leaving SilverScript.com, a Medicare-Approved Website </h3> <div id='msgBody' class='msgBody'> You will be directed to irs.gov</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        },
        {
            whichMessage: "leaveSiteCoronaVirus",
            link: "https://www.caremark.com/covid19",
            message: "<h3 class='msgHead' id='msgHead'>You are now leaving SilverScript.com for info.Caremark.com</h3> <div id='msgBody' class='msgBody'> What you need to know about the new coronavirus (COVID-19) outbreak.</div>",
            button1: "Leave Site",
            target: "_blank",
            button2: "Cancel"
        }
    ];


    //$(document).on("keyup", ".secondEmail, .firstEmail", function () { //run validate()
    //    validate();
    //});

    //$(document).on("click", ".modalSubmit", "#imgbtnSendMail", function () { //run validate()

    //    validate();
    //});


    $(".popUpLink[data-type='leavingSiteCMKEOB']").click(function () {
        $("#CMKEOB_load").css("display", "block");


        $.ajax(
            {
                type: "POST",
                url: '../member/members/EOBCheck',
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg, textStatus, xhr) {

                    if (msg.d != null) {
                        if (xhr.status == 200) {
                            $("#EOB_ok").attr("href", encodeURIComponent(msg.d));

                            $("#CMKEOB_load").css("display", "none");
                            $(".ckSite").css("display", "block");
                            return false;
                        }
                        else {
                            runModal('leavingSiteCMKEOBError');
                            $("#modalBack").fadeIn(200);
                            $("#popUp").fadeIn(500);
                        }
                    }
                    else {
                        runModal('leavingSiteCMKEOBError');
                        $("#modalBack").fadeIn(200);
                        $("#popUp").fadeIn(500);
                    }
                },
                error: function (e) {
                    runModal('leavingSiteCMKEOBError');
                    $("#modalBack").fadeIn(200);
                    $("#popUp").fadeIn(500);
                }
            });
        $("#modalBack, #popUp").fadeOut();
    });


    //DT - 06/18/2018 - ALM 5284 - Resolved
    //RS -06/26/2018 -ALM 5378 - Resolved.
    $(document).on("click", "#modalOK", function () {
        var isConfirmEmail = $(this).hasClass("confirmEmail");
        if (isConfirmEmail) {
            validate();
            var anyErrors = $(".firstEmail.errorBorder, .secondEmail.errorBorder").length;

            if (anyErrors == 0) {
                SendMail('/enrollment', 'sendemailconf', OnSuccess, OnFailure)
                $("#modalBack, #popUp").removeClass("d-block").addClass("d-none");
 		$('body').css('overflow', 'scroll');
            }
        }
        else {

            $("#modalBack, #popUp").removeClass("d-block").addClass("d-none");
 	    $('body').css('overflow', 'scroll');
        }
    }); //end click


    //$(document).on("click", "#imgbtnSendMail", function (event) {
    //    validate();
    //    var anyErrors = $(".firstEmail.errorBorder, .secondEmail.errorBorder").length;
    //    if (anyErrors != 0) {
    //        event.preventDefault();
    //        return false;
    //    } //end if

    //}); //end click


    function runLinkCk() {
        var linkCheck = $("#modalOK").attr("href");
        $(".dynamicLink").each(function () {
            var linkName = $(this).attr("data-link");
            var dynamicLink = $(this).val();
            if (linkCheck == linkName) {
                $("#modalOK").attr("href", dynamicLink);
            } //end if
        }); //end each
    }; //end runLinkCk

    function runModal(whichLink, forceRedirectUrl, Message, cancelButtonLabel, okButtonLabel) {

        $(info).each(function () {

            var whichMessage = this.whichMessage;
            var message;
            var link = this.link;
            var messageRegEx = getModalTextValidationRegEx();

            if (Message != undefined && Message.match(messageRegEx) != null)
                var messageSent = Message;
            //var messageSent = Message != null && Message.match(getModalTextValidationRegEx()) != null && Message.match(getModalTextValidationRegEx()) != null ? Message.match(getModalTextValidationRegEx())[0] : "";
            var messageRead = this.message != null && this.message.match(getModalTextValidationRegEx()) != null && this.message.match(getModalTextValidationRegEx())[0] != null ? this.message.match(getModalTextValidationRegEx())[0] : "";

            if (Message == null || Message == undefined || Message == "")
                message = messageRead;
            else
                message = messageSent;

            var button1 = this.button1;
            var button2 = this.button2;
            var target = this.target;

            if (forceRedirectUrl)
                link = forceRedirectUrl;

            if (whichLink == whichMessage) {

                if (whichMessage == 'leavingSite2020Plan') {
                    button2 = 'Close';
                }
                if (whichMessage == 'leavingSiteModalPopUp') {
                    button1 = okButtonLabel;
                    button2 = cancelButtonLabel;
                    message = message.toString();
                }
                $("#message").html(message);
                $("#modalOK").attr("href", link).attr("target", target).text(button1);
                $("#closeModal").text(button2);
                if (button1 == "" || button1 == null) {
                    $("#modalOK").hide().addClass("hide");
                }
                //DT - 06/18/2018 - ALM 5284 Resolved
                if (button1 != "" || button1 != null) {
                    $("#modalOK").show().removeClass("hide");
                    if (whichLink == "emailConfirmation") {
                        $("#modalOK").addClass('confirmEmail');
                    }
                }
                if (button2 == "" || button2 == null) {
                    $("#closeModal").hide().addClass("hide");
                }
                if (button2 != "" || button2 != null) {
                    $("#modalOK").show().removeClass("hide");
                }
                if (button1 == "" && button2 == "") {
                    $(".popBts").hide();
                }
                else {
                    $('#popUp, #modalBack').removeClass("d-none").addClass("d-block");
                    $(".popBts").show();
                }
                //$("#popUp").focus();

                // $("#message").attr("aria-labelledby", "msgHead msgBody");
                //$(".popBts").children("input, button, a[href]").attr("role", "button");
                //$("#message").attr("role", "dialog");
                //$("#message").attr("aria-live", "polite");
            } //end if

        }); //end each

        $(".button-close").focus();
    } //end runModal

    $(document).on("click", ".closeModal,.button-close,#EOB_ok", function () {

        $("#modalBack, #popUp").removeClass("d-block").addClass("d-none"); //fadeOut();
        if ($("#timeOutWarning").is(":visible")) {
            $("#sessionWarning").click();
        }
        if ($("#timedOutMessage").is(":visible")) {
            $("#sessionTimedOut").click();
        }
        $('body').css('overflow', 'scroll');
        if ($('#previousElement').val()) {
            $('#' + $('#previousElement').val())[0].focus();
        }
    });

    /*in case your message text has buttons you would like to fix at the bottom of the #popUp, wrap them in the class name .optionalBts and write nothing where the default buttons go. This will let them take their defaults fixed place. It is also important to add the class ".tempBts" to each element within th ".optionalBts" wrapper.  
	    Aaron 6-3-2016 */
    var optionalBtTxt = "";

    function popUpHeight() {
        var winWidth = $(window).width();
        var winHeight = $(window).height();
        if (winWidth < 767) { //only needed for small devices (under iPad and iPad mini)
            $("#popUp").css("max-height", winHeight - 100); //finds height of device and grows if needed.
            $("#message").css("max-height", winHeight - 220);
        } //end if
        if (winHeight < 361) { //only needed for small devices (under iPad and iPad mini)
            $("#popUp").css("max-height", window.screen.height - 100); //finds height of device and grows if needed.
            $("#message").css("max-height", window.screen.height - 220);
        } //end if      
        var optionalBts = $(".optionalBts").length;
        if (optionalBtTxt == "" || optionalBtTxt == null) { //needed in case user switches screen size
            optionalBtTxt = $(".optionalBts").html();
        } //end if
        if (optionalBts == 0) { //reset fixed position buttons
            $(".tempBts").each(function () {
                $(this).remove();
            }); //end each
            var bt1Txt = $("#modalOK").text();
            if (bt1Txt != "" || bt1Txt != null) {
                $("#modalOK").removeClass("hide").attr("style", "");
            } //end if
            var bt2Txt = $("#closeModal").text();
            if (bt2Txt != "" || bt2Txt != null) {
                $("#closeModal").removeClass("hide").attr("style", "");
            } //end if
            if (bt1Txt == "" || bt1Txt == null) {
                $("#modalOK").addClass("hide");
            } //end if
            var bt2Txt = $("#closeModal").text();
            if (bt2Txt == "" || bt2Txt == null) {
                $("#closeModal").addClass("hide");
            } //end if
        } //end if
        if (optionalBts > 0) {
            $(".popBts").children("input, button, a[href]").addClass("hide");
            $(".popBts").append(optionalBtTxt).css("display", "block");
            $(".optionalBts").html(""); //to make sure ID's aren't duplicated  
        } //end if
    } //end popUpHeight()


    //responsive Modal 
    $(window).on("load resize", function (e) {
        var parentWidth = $("#popUp").parent().width();
        var PopUpWidth = $('#popUp').width();
        var midWidth = (parentWidth / 2 - (parentWidth * .45));
        var midWidth2 = (parentWidth / 2 - 360);

        $("#popUp").parent().width();

        if (parentWidth <= 567) {

            $("#popUp").css("margin", "1");
        }
        if (parentWidth > 567) {

            $("#popUp").css("marginLeft", midWidth2);
        }
        //end if 

        popUpHeight();

    }); //end load resize


    $(document).keyup(function (e) {
        if (e.keyCode == 27) {
            $("#modalBack, #popUp").removeClass("d-block").addClass("d-none"); //fadeOut();
            $('body').css('overflow', 'scroll');
        }
    }); //end keyup

    $(".popUpLink").click(function (e) {
        e.preventDefault(); //don't let body scroll to top
        var whichLink = $(this).attr("data-type");
        var forceRedirectUrl = $(this).attr("data-redirect-url");
        var cancelButtonLabel = $(this).attr("data-cancel-label");
        var okButtonLabel = $(this).attr("data-ok-label");
        if (e.target.id) {
            $('#previousElement').val(e.target.id.toString());
        }

        var Message = "";
        var messageRegEx = getModalTextValidationRegEx();

        if ($(this).attr("data-message") != undefined && $(this).attr("data-message").match(messageRegEx)[0].length > 0)
            Message = $(this).attr("data-message");

        runModal(whichLink, forceRedirectUrl, Message, cancelButtonLabel, okButtonLabel);
        $("#modalBack").fadeIn(200);
        //$("#popUp").show();
        $("#popUp").fadeIn(500);
        runLinkCk();
        ////Inorder to Disable bacground of modalPopup
        $(".button-close").focus();
        keepFocusInsideModal(e);
        $('body').css('overflow', 'hidden');
        //Comment ends here
        popUpHeight();
    }); //end click
    ///////end global modal

    //keeping focus inside modal
    function keepFocusInsideModal(e) {
        if ($('.pop-up').is(':visible')) {
            $('.lastPopEl:last').bind('keydown', function (e) {
                var keyCode = e.keyCode || e.which;
                if (keyCode == 9) {
                    if (!e.shiftKey) {
                        e.preventDefault();
                        $(".pop-up .button-close").focus();
                    }
                }
            });
            $('.firstPopEl').on('keydown', function (e) {
                var keyCode = e.keyCode || e.which;
                if (keyCode == 9) {
                    if (e.shiftKey) {
                        e.preventDefault();
                        $(".pop-up .button-close").focus();
                    }
                }
            });
        }

    }

    ///check check-eligibility.html

    $("label[for='rbtSep'], label[for='rbtInitial'], label[for='rbtAnnual']").addClass("buttonTxt");
    $("#rbtSep").addClass("ce-radio");
    $("#rbtInitial").addClass("ce-radio");
    $("#rbtAnnual").addClass("ce-radio");

    $(".ce-radio").focusin(function (event) {
        $(this).parent().addClass("active");
    });
    $(".ce-radio").focusout(function (event) {
        $(this).parent().removeClass("active");
    });

    $(".radio-choice-box").click(function () {
        $(".radio-choice-box").removeClass("radio-choice-boxselected");
        $(this).addClass("radio-choice-boxselected");
    });


    //end ///check check-eligibility.html
    //end radio button selection

    //if AEP is selected, don't display option on the check-eligibilty page
    $("#selectAEP").click(function () {
        $("#enrollSubSEP, #enrollSubIEP").css("display", "none");
    }); //end click
});


function SendMail(page, fn, successFn, errorFn) {
    var emailId = $("#txtEmailaddress").val();
    var confirmationNumber = $("#lblConfirmationNumber").text();
    var firstName = $("#lblFirstName").text();
    var lastName = $("#lblLastName").text();
    var applicationdate = $("#lblDate").text();
    //var applicationDate = 
    $.ajax(
        {
            type: "POST",
            url: page + "/" + fn,
            data: "{'emailId': '" + emailId + "', 'confirmationNumber': '" + confirmationNumber + "', 'firstName': '" + firstName + "', 'lastName': '" + lastName + "', 'applicationdate': '" + applicationdate + "'}",
            dataType: 'text',
            contentType: "application/json; charset=utf-8",
            success: successFn,
            error: errorFn
        });
} //end SendMail

function OnSuccess(result) {
    // Add your code to run after successful .Net code execution
} // end OnSuccess

function OnFailure(result) {
    // Add your code to run after successful .Net code failure
} //end 


//redirect to index page when use click logo
function goHome() {
    var whereAreWe = window.location.href;
    var https = whereAreWe.replace("https://", "");
    var http = whereAreWe.replace("http://", "");
    var firstSlash = whereAreWe.indexOf("/");
    var locCut = whereAreWe.substring(0, firstSlash + 1);

    window.location.href = encodeURIComponent(locCut);

}; //end goHome()

var fileNameCut = stringLoc.lastIndexOf("/");
var fileName = stringLoc.substring(fileNameCut + 1);
$(".side-nav ul li a").each(function () {
    var linkHref = $(this).attr("href");
    if (fileName == linkHref) {
        $(this).addClass("active");
    } //end if
}); //end each

var planFileCk = stringLoc.indexOf("/learn/");
var enrollFileCk = stringLoc.indexOf("/learn/enroll.aspx")
var membersFileCk = stringLoc.indexOf("/member/");
var AboutUsFileCk = stringLoc.indexOf("/about-us");
var planDetails = stringLoc.indexOf("/plan-detail");
//var DocumentsLibrary = stringLoc.indexOf("/documents-library");
if (planFileCk != -1) { //activatelearn link on "learn section"
    if (enrollFileCk == -1) {
        $("#navLearn").addClass("activenavLearn");
    }
} //end if
if (AboutUsFileCk != -1) { //activate member link on "memebers section"
    $("#navLearn").addClass("activenavLearn");
}
if (membersFileCk != -1) { //activate member link on "memebers section"
    $("#navMembers").addClass("activenavMembers");
} //end if
if (planDetails != -1) { //activate member link on "plan details section"
    $("#navCompare").addClass("activenavCompare");
} //end if
//if (DocumentsLibrary != -1) { //activate member link on "plan details section"
//    $("#navDocuments").addClass("activenavDocuments");
//}

/////////////////turn off chat option
var chatCk = [];
var waitTime = 30000; //standard wait time for pop up



//start listeners for user activity
var activeTimer;
$(window).on('click keydown scroll', function () {
    $("#userActive").attr("data-activity", "active");
    clearTimeout(activeTimer);
    activeTimer = setTimeout(function () {
        $("#userActive").attr("data-activity", "");
        waitTime = 10;
        //chatBoxPopUp(waitTime);
    }, 45000);
}); //end listeners for user activity


//Click event to scroll to top
$('.user-locale').click(function () {
    $('html, body').animate(
        {
            scrollTop: 0
        }, 20);
    return false;
}); //end click

$("a[title='Switch Language']").click(function () { //hiding mobile enroll button for a sec due to IE "blur bug"
    $(".enroll-mobile").addClass("hide");
    setTimeout(function () {
        $(".enroll-mobile").removeClass("hide");
    }, 10);
}); //end click

/*START TOGGLING TOOL TIPS*/
var winWidth = $(window).width();
$(window).scroll(function () {
    if (winWidth <= 800) {
        $(".toolTipLink").each(function () {
            $(this).removeClass("tipOpen").addClass("tipClose").blur();
            console.log(winWidth);
        }); //end each
    } //end if
}); //end scroll


$(document).on("click", ".toolTipLink", function () { //for mobile toolTip toggle
    $(".toolTipLink").each(function (i) {
        var whichTip = $(this).attr("data-tipnum", i);
    }); //end each
    var closed = "";
    var winWidth = $(window).width();
    if (winWidth < 1025) { /*iPad landscape goes to 1024px in width therefore no hovers*/
        var thisTipNum = $(this).attr("data-tipnum");
        var opened = $(this).hasClass("tipOpen");
        $(".toolTipLink").each(function () {
            var whichTip = $(this).attr("data-tipnum");
            if (whichTip != thisTipNum) {
                $(this).removeClass("tipOpen").addClass("tipClose").blur();
            } //end if
            if (whichTip == thisTipNum && opened == true) {
                $(this).removeClass("tipOpen").addClass("tipClose").blur();
                closed = "closed";
            } //end if
            if (whichTip == thisTipNum && opened != true && closed != "closed") {
                $(this).removeClass("tipClose").addClass("tipOpen");
            } //end if
        }); //end each
    } //end if window width
}); //end click

/*RESET THE TOOL TIP ON RESIZE*/
$(window).on("resize", function (e) {
    $(".toolTipLink").each(function () {
        $(this).removeClass("tipClose").removeClass("tipOpen");
    }); //end each 
}); //end load resize


var activeElement = []; //take down tool tip on blur
$("*").on("click", function () {
    activeElement = []; //reset array
    var thisTipNum = $(this).attr("class");
    activeElement.push(thisTipNum);
    $(activeElement).each(function () {
        if (activeElement == "toolTipLink") {
            var activeTip = "";
            return false;
        } //end if
        $(".toolTipLink").each(function () {
            $(this).removeClass("tipOpen").addClass("tipClose");
        }); //end each  
    }); //end each
}); //end click

/*END TOGGLING TOOL TIPS*/

/*start responsive toolTip data*/
/*start responsive toolTip data*/
$(document).ready(function () {
    setTimeout(function () {
        $(".toolTipLink[role='button']").each(function () {
            var contentRegEx = /[<|>]+/
            var tipDescribedby = contentRegEx.test($(this).attr("aria-describedby")) ? $(this).attr("aria-describedby") : "";
            var tipText = contentRegEx.test($(this).attr("data-tooltip")) ? $(this).attr("data-tooltip") : "";
            if (tipDescribedby !== undefined && tipDescribedby !== '') {
                $("#" + tipDescribedby).html(tipText);
                console.log("#" + tipDescribedby + "-" + tipText);
            }
        }); //end each
    }, 500);

}); //end ready


/*start UX request. Upon submit user is navigated to the first error instead of the last*/
$("input[type='submit']").click(function () {
    setTimeout(function () {
        $(".error").each(function () {
            var isError = $(this).css("display");
            if (isError == "block") {
                //$(this).focus();
                return false;
            }
        }); //end each
    }, 200);

});

/////issue #3827

//fill all tooltipInfo
$("[aria-describedby]").each(function () {
    var whichTip = $(this).attr("aria-describedby");
    var tipInfo = $(this).attr("data-tooltip");
    if (tipInfo != "") {
        $("[aria-describedby='" + whichTip + "']").attr("data-tooltip", tipInfo);
    } //end if
    $("a:has(i)").css("border", "0px"); //info icon has no border-bottom

}); //end each

$("#dvPlanChoiceLink > div label").each(function () {
    var planOn = $(this).hasClass("on");
    var thisPlan = $(this).text();
    if (planOn == true) {
        $(".planChosen").html(thisPlan);
    } //end if
}); //end each

///start #dvChoiceTable data plan-detail.aspx
var lblSupplyPlus2_text = $("#lblSupplyPlus2").html();
var planChosen = ""; //find out which plan is being viewed
var plusLength = $("#dvPlusTable").length;
var choiceLength = $("#dvChoiceTable").length;
var allureLength = $("#dvAllureTable").length;
var contentRegEx = /[<|>]+/
if (plusLength == 1) {
    planChosen = "dvPlusTable";
} //end if
if (choiceLength == 1) {
    planChosen = "dvChoiceTable";
} //end if

var choiceData = []; //build JSON
var avoidDupId = ["lblToolTipPlusTier1", "lblToolTipPlusTier2", "lblToolTipPlusTier3", "lblToolTipPlusTier4", "lblToolTipPlusTier5", "lblToolTipChoiceTier1", "lblToolTipChoiceTier2", "lblToolTipChoiceTier3", "lblToolTipChoiceTier4", "lblToolTipChoiceTier5"]; /*/these are potential duplicat IDs created when copied to mobile*/
var pharmType = "";

function getData(planChosen) {
    $("#" + planChosen + "  table[data-table='table-original'] tr td").each(function () {
        var whatRow = $(this).parent("tr").attr("data-row");
        var whatCol = $(this).attr("data-column");
        var whatContent = $(this).html();
        $(avoidDupId).each(function () { //this takes out potential duplicate IDs for mobile
            whatContent = whatContent.replace(this, "");
        }); //end each
        if ($(this)[0].firstElementChild !== null) {
            whatContent = whatContent.replace($(this)[0].firstElementChild.id, $(this)[0].firstElementChild.id + "1");
        }
        var colType = "";
        if (whatRow == 2 && whatCol != 0) {
            colType = $(this).attr("data-column");
            $("td[data-column='" + colType + "']").attr("data-pharmType", "standard");
        } //end if
        if (whatContent.indexOf("Mail") != -1) {
            if (whatRow == 2 && whatCol != 0) {
                colType = $(this).attr("data-column");
                $("td[data-column='" + colType + "']").attr("data-pharmType", "mailService");
            } //end if
        } //end if
        if (whatContent.indexOf("Pref") != -1) {
            if (whatRow == 2 && whatCol != 0) {
                colType = $(this).attr("data-column");
                $("td[data-column='" + colType + "']").attr("data-pharmType", "preferred");
            } //end if
        } //end if
        pharmType = $(this).attr("data-pharmType");

        var days = "30";
        $("#" + planChosen + "  table tr[data-row='1'] td").each(function () {
            var whatContent = $(this).html();
            if (whatContent.indexOf("90") != -1) {
                if ($(this).attr("data-column") == whatCol) {
                    days = "90";
                }; //end if
            } //end if
        });

        choiceData.push(
            {
                "whatRow": whatRow,
                "whatCol": whatCol,
                "whatContent": whatContent,
                "pharmType": pharmType,
                "days": days
            });
    }); //end each
} //end getData()

function runGap() {
    var preFill = $("div[data-plan='dvPlusGap'] ul[data-pharmType]").html(); //clear
    if (preFill != "") {
        return false;
    } //end if
    var gapLastTiers = $("#dvPlusGap table tr[data-row='4'] td[data-column='1']").html();
    choiceData = [];
    planChosen = "dvPlusGap";
    getData(planChosen);

    $(choiceData).each(function (i) {
        var whatRow = this.whatRow;
        var whatCol = this.whatCol;
        var whatContent = this.whatContent;
        var pharmType = this.pharmType;
        var days = this.days;

        if (whatCol == 0 && whatRow > 1) {
            $("div[data-plan='" + planChosen + "'] ul[data-pharmType]").append("<li class='tierSection'>" + whatContent + "</li>");
        } //end if
        for (i = 1; i < $("#" + planChosen + " table tr[data-row='1'] td").length; i++) {
            if (whatCol == i && whatRow > 1 && whatRow < 4) {
                $("div[data-plan='" + planChosen + "']  ul[data-pharmType='" + pharmType + "']").append("<li>" + days + " day supply: " + whatContent + "</li>");
            } //end if           
        } //end for
    }); //end each      
    $("div[data-plan='dvPlusGap'] ul[data-pharmtype] > li:last-child").append("<li>" + gapLastTiers + "</li>"); //makes up for the td "colspans"
} //end runGap()

function runAllureGap() {
    var preFill = $("div[data-plan='dvAllureGap'] ul[data-pharmType]").html(); //clear
    if (preFill != "") {
        return false;
    } //end if
    var gapLastTiers = $("#dvAllureGap table tr[data-row='4'] td[data-column='1']").html();
    choiceData = [];
    planChosen = "dvAllureGap";
    getData(planChosen);

    $(choiceData).each(function (i) {
        var whatRow = this.whatRow;
        var whatCol = this.whatCol;
        var whatContent = this.whatContent;
        var pharmType = this.pharmType;
        var days = this.days;

        if (whatCol == 0 && whatRow > 1) {
            $("div[data-plan='" + planChosen + "'] ul[data-pharmType]").append("<li class='tierSection'>" + whatContent + "</li>");
        } //end if
        for (i = 1; i < $("#" + planChosen + " table tr[data-row='1'] td").length; i++) {
            if (whatCol == i && whatRow > 1 && whatRow < 4) {
                $("div[data-plan='" + planChosen + "']  ul[data-pharmType='" + pharmType + "']").append("<li>" + days + " day supply: " + whatContent + "</li>");
            } //end if           
        } //end for
    }); //end each      
    $("div[data-plan='dvAllureGap'] ul[data-pharmtype] > li:last-child").append("<li>" + gapLastTiers + "</li>"); //makes up for the td "colspans"
}

function runMobile(planChosen) {
    $("ul[data-pharmType]").html(""); //clear
    $(".table-mobile").addClass("hide"); //show only mobile being requested
    if (planChosen == "dvChoiceTable") {
        $(".table-mobile[data-plan='dvChoiceTable']").removeClass("hide");
    } //end if
    if (planChosen == "dvPlusTable") {
        $(".table-mobile[data-plan='dvPlusTable'], .table-mobile[data-plan='dvPlusGap']").removeClass("hide");
    } //end if
    if (planChosen == "dvAllureTable") {
        $(".table-mobile[data-plan='dvAllureTable'], .table-mobile[data-plan='dvAllureGap']").removeClass("hide");
    }
    if (planChosen != "" && planChosen != 'undefined') {
        getData(planChosen);
    }
    $(choiceData).each(function () {
        var whatRow = this.whatRow;
        var whatCol = this.whatCol;
        var whatContent = this.whatContent;
        var pharmType = this.pharmType;
        var days = this.days;

        if (whatCol == 0 && whatRow > 1) {
            $("div[data-plan='" + planChosen + "'] ul[data-pharmType]").append("<li class='tierSection'>" + whatContent + "</li>");
        } //end if

        for (i = 1; i < $("#" + planChosen + " table tr[data-row='1'] td").length; i++) {
            if (whatCol == i && whatRow > 1) {
                $("[data-plan='" + planChosen + "'] ul[data-pharmType='" + pharmType + "']").append("<li>" + days + " day supply: " + whatContent + "</li>");
            } //end if
        } //end for

        runGap();

    }); //end each
    choiceData = []; //clear JSON
} //end runMobile()
runMobile(planChosen);
//  Rs DT -02/06/2018 reference to the Task- 13380 -Rs Function added to Validate the routing Number(Numeric or not & Valid 9 digit routing number)
function isValidRoutingNumber() {
    var routingNumber = $.trim($('#routNum').val());
    var num0, num1, num2, num3, num4, num5, num6, num7, num8, value;
    var regex = /(?=[\d]{1,9})*$/gm;
    $('#msgInvRoutingNum').hide();
    $('#msgReqRoutingNum').hide();
    if (routingNumber != '') {
        if (routingNumber.length <= 9 && regex.test(routingNumber)) {
            num0 = parseInt(routingNumber.substring(0, 1)) * 3;
            num1 = parseInt(routingNumber.substring(1, 2)) * 7;
            num2 = parseInt(routingNumber.substring(2, 3));
            num3 = parseInt(routingNumber.substring(3, 4)) * 3;
            num4 = parseInt(routingNumber.substring(4, 5)) * 7;
            num5 = parseInt(routingNumber.substring(5, 6));
            num6 = parseInt(routingNumber.substring(6, 7)) * 3;
            num7 = parseInt(routingNumber.substring(7, 8)) * 7;
            num8 = parseInt(routingNumber.substring(8, 9));
            value = ((num0 + num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8) % 10);

            if (value == 0) {
                return true;
            }
            else {
                $('#msgReqRoutingNum').show();
                return false;
            }
        }
        else if (routingNumber == '') {
            $('#msgReqRoutingNum').show();
            return false;
        }
    }
    return false;
}
//02/21/2018  -Rs for not allowing alphabets in Account number, Defect #2229 fixing in Samsung Devise to Restrict the Max Length.

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}
//02/20/2018 reference to the Task- 13380 -Rs for not allowing alphabets in Account number 
function isValidAccountNumber() {
    //alert("Test");

    var val = $('#acctNum').val();
    //var regex = /^(?=[\d]{1,17})/;
    var regex = /^[0-9]*$/gm;
    if (regex.test(val)) {
        $('#msgAccountNum').hide();
        return true;
    }
    else {
        $('#msgAccountNum').show();
        return false;
    }
}

function maxLengthCheck(object) {
    if (object === undefined || object === null) {
        return;
    }
    else {
        if (object.value.length > object.maxLength)
            object.value = object.value.slice(0, object.maxLength)
    }
}


function openFancyBoxStatePage() {
    $.fancybox.open(
        {
            src: '#zipCompareMenu',
            type: 'inline',
            opts:
            {
                beforeLoad: function () {
                    resetFancyBoxStatePage("#zipCodeCompareMenu,#zipSplitCompareMenu,#zipHomeCompareMenu,#divStatesCompareMenu,#zipErrorCompareMenu,#errorRegionShowPlanCompareMenu");
                },
                afterShow: function () {
                    $(".fancybox-close-small").focus();

                    $('.lastFancyBtn').on('keydown', function (e) {
                        var keyCode = e.keyCode || e.which;
                        if (keyCode == 9) {
                            if (!e.shiftKey) {
                                e.preventDefault();
                                $(".fancybox-close-small").focus();
                            }
                        }
                    });

                    $('.fancybox-close-small').on('keydown', function (e) {
                        var keyCode = e.keyCode || e.which;
                        if (keyCode == 9) {
                            if (e.shiftKey) {
                                e.preventDefault();
                                $(".lastFancyBtn").focus();
                            }
                            else {
                                e.preventDefault();
                                $('.zip-section input').focus();
                            }
                        }
                        if (keyCode == 13) {
                            $.fancybox.close();
                        }
                    });

                    $('#zipHomeCompareMenu').on('keydown', function (e) {
                        var keyCode = e.keyCode || e.which;
                        if (keyCode == 9) {
                            if (e.shiftKey) {
                                e.preventDefault();
                                $(".fancybox-close-small").focus();
                            }
                        }
                    });
                }
            }
        });
}

function getModalTextValidationRegEx() {
    return /[\w< ()_!@^&*=>\,-\/\'\\#]+/;
}

function openPdfInNewTab(url) {
    var win = window.open(url, '_blank');
    win.focus();
}

//$.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options) {
//    options.rules['requiredif'] = options.params;
//    options.messages['requiredif'] = options.message;
//});

//$.validator.addMethod('requiredif', function (value, element, parameters) {
//    var desiredvalue = parameters.desiredvalue;
//    desiredvalue = (desiredvalue == null ? '' : desiredvalue).toString();
//    var controlType = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
//    var actualvalue = {}
//    if (controlType == "checkbox" || controlType == "radio") {
//        var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
//        actualvalue = control.val();
//    } else {
//        actualvalue = $("#" + parameters.dependentproperty).val();
//    }
//    if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
//        var isValid = $.validator.methods.required.call(this, value, element, parameters);
//        return isValid;
//    }
//    return true;
//});

function addValidationError(target, message, errorList) {
    var error = {};
    error.target = target;
    error.message = message;
    errorList.push(error);

}

function ShowValidationSummaryWithTitle(errorList, formId) {

    ShowValidationSummaryWithTitle(errorList, formId, "", false);

}

function ShowValidationSummaryWithTitle(errorList, formId, title, showPartABErrorBanner) {
    $("#showValidationTitle").show();
    if (showPartABErrorBanner !== undefined) {
        showPartABErrorBanner = false;
    }

    if (title !== undefined && title !== '') {
        $("#ValidationTitle").html(title);
    }
    //Remove first empty element created by default.
    if (errorList != undefined && errorList.length > 0 && errorList[0].target == undefined) {
        errorList.splice(0, 1);
    }

    var errorListPartAB = [];


    var formValidator,
        $form = $("#" + formId);

    // find summary div
    var $summary = $form.find("[data-valmsg-summary=true]");

    if (errorList.length == 0) {
        $summary.hide();
    } else {
        $summary.show();
    }


    // find the unordered list
    var $ul = $summary.find("ul");

    // Clear existing errors from DOM by removing all element from the list
    $ul.empty();
    $ul.addClass("noStyle")

    if (showPartABErrorBanner) {

        for (var i = 0; i < errorList.length; i++) {
            if (errorList[i].target == "ddlPartAMonth" || errorList[i].target == "ddlPartAYear" || errorList[i].target == "ddlPartBMonth" || errorList[i].target == "ddlPartBYear") {
                errorListPartAB.push(errorList[i])
                errorList.splice(i, 1);
                i--;
            }

        }
    }

    for (var i = 0; i < errorList.length; i++) {
        $("<li />").html('<a href="javascript:void(0);" onclick="ErrorClick(' + "'" + errorList[i].target.toString().trim() + "'" + ')"' + ' class="errorSummaryText">' + errorList[i].message + '<a/>').appendTo($ul);
    }

    if (showPartABErrorBanner) {
        if (errorListPartAB.length > 0) {
            $("<li />").html('<br /><h2>Your Medicare Part A and/or Part B dates are invalid</h2> <p> You can enroll in Part D benefits during the three months prior to your Medicare Part A and/or Part B month of your 65th birthday unless you have qualified for Social Security benefits prior to that date. SilverScript will determine the effective date based on your enrollment period. </p><br />').appendTo($ul);
        }

        for (var i = 0; i < errorListPartAB.length; i++) {
            $("<li />").html('<a href="javascript:void(0);" onclick="ErrorClick(' + "'" + errorListPartAB[i].target.toString().trim() + "'" + ')"' + ' class="errorSummaryText">' + errorListPartAB[i].message + '<a/>').appendTo($ul);
        }
    }

    // Add the appropriate class to the summary div
    $summary.removeClass("validation-summary-valid")
        .addClass("validation-summary-error");

    $(".error-banner-new").addClass("validation-summary-errors").focus();

}


$("#defaultSubmitBtn").click(function (e) {

    if ($('#mbiNum').is(":visible")) {
        $('#mbiNum').blur();
    }

    $("input[default-button]").click();

    e.preventDefault();
});
