//Module added to restrict the user input. It is initialized in app.js 
angular.module('icisPatternRestrict', [])
    .value('icisPatternRestrictConfig', {
        showDebugInfo: true,
    })
    .directive('icisPatternRestrict', ['icisPatternRestrictConfig', function (patternRestrictConfig) {
        // Uncomment it for enabling debug  
        //function showDebugInfo(message) {
        //    if (patternRestrictConfig.showDebugInfo) {
        //        console.log("[icisPatternRestrict] " + message);
        //    }
        //}

        return {
            restrict: 'A',
            require: "?ngModel",
            compile: function uiPatternRestrictCompile() {
                // var options = patternRestrictConfig;


                return function icisPatternRestrictLinking(scope, iElement, iAttrs, ngModelController) {
                    var originalPattern;
                    var eventsBound = false; // have we bound our events yet?
                    var regex; // validation regex object
                    var oldValue; // keeping track of the previous value of the element
                    var initialized = false; // have we initialized our directive yet?
                    var caretPosition; // keeping track of where the caret is at to avoid jumpiness


                    // initialization
                    function initialize() {
                        if (initialized) {
                            return;
                        }

                        readPattern();
                        oldValue = iElement.val();

                        if (!oldValue) {
                            oldValue = "";
                        }


                        bindListeners();

                        initialized = true;
                    }

                    function readPattern() {
                        originalPattern = iAttrs.pattern;

                        var entryRegex = !!iAttrs.icisPatternRestrict ? iAttrs.icisPatternRestrict : originalPattern;

                        tryParseRegex(entryRegex);
                    }

                    function uninitialize() {

                        unbindListeners();
                    }


                    // setup events
                    function bindListeners() {
                        if (eventsBound) { return; }
                        iElement.bind('input keyup click', genericEventHandler);
                    }

                    function unbindListeners() {
                        if (!eventsBound) { return; }

                        iElement.unbind('input', genericEventHandler);
                        iElement.unbind('keyup', genericEventHandler);

                        iElement.unbind('click', genericEventHandler);
                        eventsBound = false;
                    }

                    // setup based on attributes
                    function tryParseRegex(regexString) {
                        try {
                            regex = new RegExp(regexString);
                        } catch (e) {
                            throw "Invalid RegEx string parsed for icisPatternRestrict: " + regexString;
                        }
                    }
                    // event handlers
                    function genericEventHandler(evt) {
                        var newValue = iElement.val();
                        var stopFurtherExecution = false;
                       
                        if (newValue.length > iElement.attr("maxlength") ) {
                            evt.preventDefault();
                            setElementValue();
                            stopFurtherExecution = true;
                        }

                        if (!stopFurtherExecution) {
                            var inputValidity = iElement.prop("validity");
                            if (newValue === "" && iElement.attr("type") === "number" && inputValidity && inputValidity.badInput) {

                                evt.preventDefault();
                                setElementValue();

                            } else if (regex.test(newValue)) {

                                updateCurrentValue(newValue);
                                setElementValue();
                            } else {
                                var pattern = iElement.attr("data-icis-pattern-restrict");
                                var manufacturedRegExp;
                                if (!angular.isUndefined(iElement.attr("class"))) {
                                    if (iElement.attr("class").includes("decimal-text")) {
                                        pattern = pattern.substr(1, pattern.length - 2);
                                    } else {
                                        pattern = pattern.substr(1, pattern.lastIndexOf("*") - 1);
                                    }
                                }
                                else {
                                    pattern = pattern.substr(1, pattern.lastIndexOf("*") - 1);
                                }
                                manufacturedRegExp = new RegExp(pattern, "g");
                                var invalidCharacters = newValue.replace(manufacturedRegExp, '');
                                if (invalidCharacters === "") {
                                    evt.preventDefault();
                                }
                                else {
                                    var regExpToReplace = "";
                                    for (var i = 0; i < invalidCharacters.length; i++) {
                                        if (regExpToReplace.indexOf(invalidCharacters[i]) === -1)
                                            regExpToReplace += invalidCharacters[i];
                                    }
                                    if (regExpToReplace.indexOf("\\") >= 0) {
                                        regExpToReplace = regExpToReplace.replace("\\", "\\\\");
                                    }
                                    oldValue = newValue.replace(new RegExp("[" + regExpToReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "]", "g"), "");
                                }                                
                                setElementValue();                              
                            }
                        }
                    }

                    function setElementValue() {

                        if (ngModelController) {
                            scope.$apply(function () {
                                ngModelController.$setViewValue(oldValue);
                            });
                        }
                        iElement.val(oldValue);

                        if (!angular.isUndefined(caretPosition) && iElement.attr("type") !== "number") {
                            setCaretPosition(caretPosition);
                        }
                    }

                    function updateCurrentValue(newValue) {
                        oldValue = newValue;
                        caretPosition = getCaretPosition();
                    }


                    // caret position
                    // logic from http://stackoverflow.com/a/9370239/147507

                    function getCaretPosition() {
                        var input = iElement[0]; // we need to go under jqlite

                        // IE support
                        if (document.selection) {
                            var range = document.selection.createRange();
                            range.moveStart('character', -iElement.val().length);
                            return range.text.length;
                        } else {
                            return input.selectionStart;
                        }
                    }

                    // logic from http://stackoverflow.com/q/5755826/147507
                    function setCaretPosition(position) {
                        var input = iElement[0]; // we need to go under jqlite
                        if (input.createTextRange) {
                            var textRange = input.createTextRange();
                            textRange.collapse(true);
                            textRange.moveEnd('character', position);
                            textRange.moveStart('character', position);
                            textRange.select();
                        } else {
                            input.setSelectionRange(position, position);
                        }
                    }


                    iAttrs.$observe("icisPatternRestrict", readPattern);
                    iAttrs.$observe("pattern", readPattern);
                    scope.$on("$destroy", uninitialize);
                    initialize();
                };
            }
        };
    }]);
;
////////////////////////////////////////////////////////////////////////////////////////////////////////
//@Directive: assist-date-picker
//@Description:It attaches JQuery datepicker with the element. Also accepts standard datepicker options
//@Warning:############# Please reach out to Architect Team before modification :######################
////////////////////////////////////////////////////////////////////////////////////////////////////////

( function ()
{
    "use strict";
    angular.module("icisDatepicker", [])
    .directive("icisDatepicker", function () {
        return {
            restrict: "A",
            scope: {},
            link: function (scope, element, attrs) {
                var validateRule = attrs.icisDatepicker;
                var parentScope = scope.$parent;
                var elem = element[0];
                element[0].id = attrs.id;
                var placeholder = attrs.placeholder;
                var minDateRange, maxDateRange;

                //Additional Attributes for Calendar control. Check with Arch Team to add additional attributes for calendar.
                var yearRangeVal = "", changeYearVal = false, changeMonthVal = false, showOtherMonthsVal = false, showButtonPanelVal = false;
                var showWeekVal = false, firstDayVal = 0, selectOtherMonthsVal = false, numberOfMonthsVal = 1;
                if (!angular.isUndefined(validateRule) && validateRule !== "") {
                    var rulesCollection = validateRule.split(",");
                    for (var i = 0; i < rulesCollection.length; i++) {
                        generateDateRange(rulesCollection[i]);
                    }
                }

                function generateDateRange(validateRule) {
                    
                    switch (validateRule.trim()) {
                        
                        case "validateDateInFuture": 
                        case "validateDateNotInFuture":
                        case "validateDateNotBeforeStartDate":
                        case "validateHouseholdDateNotInFuture":
                        case "validateRecentPayDateNotInFutureAndAfterStartDate":
                        case "validatePastEmploymentStartDateNotInFuture":
                        case "validateDateInFutureLessThan18Months":
                        case "validateEndDateForNusringTab":
                        case "validateDateInFutureLessThan3Months":
                        case "validateDateNotBeforeStartDate":
                        case "validateJobInPastOrWithin30Days":
                        case "validateDateFieldInStartAndLastPayCheque":
                        case "validateDateInFutureforOneYear":
                        case "validateDateInPast60DaysOrFuture15Days":
                            changeYearVal = true;
                            yearRangeVal = "1875:2100";          
                            break;
                        case "changeYear":
                            changeYearVal = true;
                            yearRangeVal = "1875:2100";
                            break;
                        case "changeMonth":
                            changeMonthVal = true;
                            break;
                        case "showOtherMonths":
                            showOtherMonthsVal = true;
                            break;
                        case "selectOtherMonths":
                            selectOtherMonthsVal = true;
                            break;
                        case "showButtonPanel":
                            showButtonPanelVal = true;
                            break;
                        case "showWeek":
                            showWeekVal = true;
                            firstDayVal = 1;
                            break;
                        case "displayMultipleMonths":
                            numberOfMonthsVal = 3;
                            showButtonPanelVal = true;
                            break;
                        case "validateDate":
                            break;
                        default:
                            changeYearVal = true;
                            yearRangeVal = "1875:2100";
                            
                    }
                }

                element.datepicker({
                    inline: true,
                    dateFormat: 'mm/dd/yy',
                    minDate: minDateRange,
                    maxDate: maxDateRange,
                    changeYear: changeYearVal,
                    yearRange: yearRangeVal,
                    changeMonth: changeMonthVal,
                    showOtherMonths: showOtherMonthsVal,
                    selectOtherMonths: selectOtherMonthsVal,
                    showButtonPanel: showButtonPanelVal,
                    showWeek: showWeekVal,
                    firstDay: firstDayVal,
                    numberOfMonths: numberOfMonthsVal,
                    placeholder: placeholder
                });

                element.bind('change', function () {
                    if ((parentScope.mode === "CompletionChecker" || parentScope.mode === "Limbo") && $("#" + elem.id).val()!=="") {
                        $("#" + elem.id).closest('div.form-group').closest('div.ui-show').removeClass("completion-check");
                        
                    }
                    if ($(this).hasClass("input-validation-error")) {
                        $(this).removeClass("input-validation-error");
                    }
                });

                //element.bind('paste', function () {
                //    return false;
                //});
            }
        };
    });
}());;
/* eslint eqeqeq: 0 */
/* eslint no-extra-parens: 0 */
(function () {
    
    "use strict";
    var app = angular.module("CustomFilters", []);
        
    appRoot.filter("PeopleHCApplicants", function () {
        return function (input, scope) {
            return input.filter(function (x) {
                return x; 
            });
        };
    });
    appRoot.filter("peopleExceptMe", function () {
        return function (input, scope) {
            return input.filter(function (x) {
                if (scope.individual === null || scope.individual.individualNumber === null) {
                    return input;
                }
                else {
                    return x.individualNumber !== scope.individual.individualNumber;
                }
            });
        };
    });
    appRoot.filter("peopleExceptMeAndMySpouse", function () {
        return function (input, scope) {
            var indivi;
            var keepGoing = true;
            return input.filter(function (x) {
                if (scope.individual === null || scope.individual.individualNumber === null) {
                    return input;
                }
                else {
                    angular.forEach(scope.individual.relationships, function (relation) {
                        if (keepGoing === true) {
                            if (relation.code === "H" || relation.code === "W") {
                                indivi = relation.individualNumber;
                            }
                        }
                    });
                    if (x.individualNumber != indivi) {
                        return x.individualNumber != scope.individual.individualNumber;
                    }
                }
            });
        };
    });
    //Filter has to be implemented : Added sample code for demo
    appRoot.filter("endDateOtherIncome", function () {
        return function (input, scope) {
            if (!angular.isUndefined(input) && input != null && !angular.isUndefined(input.filter) && input.filter != null) {
                return input.filter(function (x) {
                    if (angular.isUndefined(x.lastPaidDate)) {
                        return true;
                    }
                    else {
                        return x.lastPaidDate.length <= 0;
                    }
                });
            }
            else {
                return true;

            }
        };
    });

    //Filter has to be implemented : Added sample code for demo
    appRoot.filter("endDateCurrentIncome", function () {
        return function (input, scope) {
     
            if (!angular.isUndefined(input) && input != null && !angular.isUndefined(input.filter) && input.filter != null) {
                return input.filter(function (x) {
                    if (angular.isUndefined(x.lastPayDate)) {
                        return true;
                    }
                    else {
                        return x.lastPayDate.length <= 0;
                    }
                });
            }
            else {
                return true;
            }
        };
    });

    appRoot.filter("filterPersonBasedOnRelationship", function () {
        return function (input, scope) {
            return input.filter(function (x) {
                if (scope !== undefined && scope === null) {
                    return input;
                }
                if (scope !== undefined && scope !== null && scope.individualNumber !== null) {
                    return x.individualNumber === scope.individualNumber;
                }
                else {
                    return input;
                }
            });
        };
    });


    app.filter("peopleWithCurrentRentalSelfEmploymentJobsOnly", function () {
        return function (input, scope) {
            return input.filter(function (x) {
                if (scope.sectionData.household.income.currentEmployment.individualNumbers !== null && scope.sectionData.household.income.currentEmployment.individualNumbers !== undefined) {

                    var individualCount = scope.sectionData.household.income.currentEmployment.individualNumbers.length;
                    if (scope.sectionData.household.income != null && scope.sectionData.household.income.currentEmployment != null && scope.sectionData.household.income.currentEmployment.individualNumbers != null && individualCount > 0) {
                        for (var i = 0; i < scope.sectionData.household.income.currentEmployment.individualNumbers.length; i++) {

                            if (x.individualNumber == scope.sectionData.household.income.currentEmployment.individualNumbers[i]) {
                                return true;
                            }
                        }
                    }
                }
                if (scope.sectionData.household.income != null && scope.sectionData.household.income.otherIncome != null && scope.sectionData.household.income.otherIncome.individualNumbers != null) {
                    for (var j = 0; j < scope.sectionData.household.income.otherIncome.individualNumbers.length; j++) {
                        if (scope.sectionData.household.income.otherIncome.individualNumbers[j] == x.individualNumber) {
                            for (var k = 0; k < x.income.otherIncomeSources.length; k++) {
                                if (x.income.otherIncomeSources[k].incomeType.code == "SE" || x.income.otherIncomeSources[k].incomeType.code == "SF" || x.income.otherIncomeSources[k].incomeType.code == "RI") {
                                    return true;

                                }
                            }
                        }
                    }
                }

                return false;

            });
        }
    }),

   app.filter("peopleWhoAreNotGivingCareOnly", function () {
       return function (input, scope) {
           return input.filter(function (x) {
               if (scope.individual === null || scope.individual.individualNumber === null)
                   return input;
               else
                   return x.individualNumber != scope.individual.individualNumber;
           });
       }
   }),

    app.filter("schoolDistrictFilter", function () {
        return function (input, scope) { return input; }
    }),

    appRoot.filter("peopleExceptMeAndWhoAlreadyBeenClaimed", function () {
        return function (input, scope) {
            var individualSpouse;
            return input.filter(function (x) {
                if (scope.individual === null || scope.individual.individualNumber === null)
                    return input;
                else {
                    angular.forEach(scope.individual.relationships, function (relation) {
                        if (relation.code === "H" || relation.code === "W") {
                            individualSpouse = relation.individualNumber;
                        }
                    });
                    if (x.individualNumber === individualSpouse) {
                        return false;
                    }
                    else if (x.isIndividualBeingClaimedAsTaxDependent !== null) {
                        return ((x.individualNumber != scope.individual.individualNumber && x.individualNumber != individualSpouse) && (x.isIndividualBeingClaimedAsTaxDependent.code == "N" || angular.isUndefined(x.isIndividualBeingClaimedAsTaxDependent.code)));
                    } else {
                        return true;
                    }
                }
            });
        }
    }),

    app.filter("filterCoverages", function () {
        return function (input, scope) { return input; }
    }),

        app.filter("peopleWithJobsOnly", function () {
       
        return function (input, scope) { return input; }
    }),

    app.filter("currentJob", function () {
        return function (input, scope) {
            return input.filter(function (x) {
                if (x.income != null && x.income.employment != null) {
                    if (x.income.employment.length >= 1) {
                        for (var i = 0; i < x.income.employment.length; i++) {
                            if (x.income.employment[i].employerName != null) {
                                return x;
                            }
                        }
                    }
                }
                if (x.income != null && x.income.otherIncomeSources != null) {
                    if (x.income.otherIncomeSources.length >= 1) {
                        for (var j = 0; j < x.income.otherIncomeSources.length; j++) {
                            if (x.income.otherIncomeSources[j].incomeType.code == "SE" || x.income.otherIncomeSources[j].incomeType.code == "SF") {
                                return x;
                            }
                        }
                    }
                }

            });
        };

    }),

   app.filter("currentIndividualEmployers", function () {
       return function (input, scope, indiv) {
           var dataSource = [];
           for (var i = 0; i < input.length; i++) {

               if (indiv === input[i].individualNumber) {
                   dataSource.push({ keyValue: input[i].keyValue, displayValue: input[i].displayValue });
               }

           }
           dataSource.push({ keyValue: 1000, displayValue: "Other" });
           return dataSource;
       };
   }),
    app.filter("peopleFileTax", function () {
        return function (input, scope) { return input; }
    }),

   app.filter("insuranceCoverageOptions", function () {
            return function (input, scope) {
                return input.filter(function (x) {
                   
                for (var i = 0; i < scope.sectionData.applicationInformation.appliedPrograms.length; i++) {
                    if (scope.sectionData.applicationInformation.appliedPrograms[i].code == "CA" || scope.sectionData.applicationInformation.appliedPrograms[i].code == "CAR") {

                        if (x.keyValue == "1" || x.keyValue == "2" || x.keyValue == "3" || x.keyValue == "4" || x.keyValue == "5" || x.keyValue == "6" || x.keyValue == "7") {
                            isCoverageShown = true;
                            break;
                        }

                    }
                }
                });
            }
        }),

   app.filter("pastInsuranceCoverageOptions", function () {
       var dataSource = [];
       return function (input, scope) {
           return input.filter(function (x) {

               var isCoverageShown = false;
               for (var i = 0; i < scope.sectionData.applicationInformation.appliedPrograms.length; i++) {
                   if (scope.sectionData.applicationInformation.appliedPrograms[i].code == "HC" || scope.sectionData.applicationInformation.appliedPrograms[i].code == "HA" ||
                       scope.sectionData.applicationInformation.appliedPrograms[i].code == "MCR" || scope.sectionData.applicationInformation.appliedPrograms[i].code == "MAR" ||
                       scope.sectionData.applicationInformation.appliedPrograms[i].code == "ABR" || scope.sectionData.applicationInformation.appliedPrograms[i].code == "AB" ||
                       scope.sectionData.applicationInformation.appliedPrograms[i].code == "CHR" || scope.sectionData.applicationInformation.appliedPrograms[i].code == "CH") {

                       if (x.keyValue == "1" || x.keyValue == "2" || x.keyValue == "3" || x.keyValue == "4" || x.keyValue == "5" || x.keyValue == "6" || x.keyValue == "7") {
                           isCoverageShown = true;
                           break;
                       }

                   }
               }




               return isCoverageShown == true ? x : null;
           });
       }
   }),


   app.filter("overFourteen", function () {
       return function (input, scope) {
           return input.filter(function (x) {
               var dob = new Date(x.dateOfBirth);
               var now = new Date();

               var years = now.getFullYear() - dob.getFullYear();
               var curMonth = now.getMonth();
               var curDay = now.getDate();
               var birthMonth = dob.getMonth();
               var birthDay = dob.getDate();
               if (curMonth < birthMonth || (curMonth == birthMonth && curDay < birthDay)) {
                   years--;

               }
               var age = years;
               //  TODO: Please check exact age
               var childCare;
               if (scope.sectionData.people.individuals.length > 0) {
                   for (var i = 0; i < scope.sectionData.people.individuals.length; i++) {
                       if (scope.sectionData.people.individuals[i].appliedBenefits != null) {
                           for (var j = 0; j < scope.sectionData.people.individuals[i].appliedBenefits.length; j++) {
                               if ((scope.sectionData.people.individuals[i].appliedBenefits[j].benefitName.code == "CI") || (scope.sectionData.people.individuals[i].appliedBenefits[j].benefitName.code == "CIR")) {
                                   childCare = true;
                               }
                           }
                       }
                   }
               }
               if (childCare) {
                   if (age >= 14) {
                       return x;
                   }
                   else {
                       return null;
                   }
               }
               if (!childCare) {
                   return x;
               }
           });
       }
   }),
   app.filter("personSelector", function () {
       return function (input, scope) {
           return input.filter(function (x) {

               return (x.useCISIncome.code == "Y") || (x.income.employment.iscisData.code == "Y") || (x.income.otherIncomeSources.iscisData.code == "Y") ? null : x;
           });
       }
   }),
                app.filter("childrenOnly", ['UtilService', function (utilService) {
                    return function (input, scope) {
                        return input.filter(function (x) {
                            var age = utilService.getAge(x.dateOfBirth);
                            
                            return age <18? true : false;
                        });
                    };
                }]),


   app.filter("heatingSourceFilter", function () {
       return function (input, scope) { return input; }
   }),

        app.filter("nslpOnly", ['UtilService', function (utilService) {
                return function (input, scope) {
                    return input.filter(function (x) {
                        var age = utilService.getAge(x.dateOfBirth);

                        return age <21 ? true : false;
                    });
                };
            }]),

                     app.filter("overSixtyOrDisableOnly", ['UtilService', function (utilService) {
                    return function (input, scope) {
                        return input.filter(function (x) {
                            var isdisable = false;
                            if (scope.sectionData.people.individuals.length > 0) {
                                for (var i = 0; i < scope.sectionData.people.individuals.length; i++) {

                                    if (utilService.getAge(scope.sectionData.people.individuals[i].dateOfBirth) >= 60 || scope.sectionData.household.anyOneDisabled.individualNumbers.indexOf(scope.sectionData.people.individuals[i].individualNumber) > -1) {

                                        isdisable = true;
                                    }

                                }
                            }
                         
                            return isdisable;
                        });
                    };
                }]),

   app.filter("removeUnknownCode", function () {
        return function (input, scope) {
            if (input.keyValue === 8) {
                return false;
            }
            else {
                return input;
            }

        };
   }),

   app.filter("guardiansOnlyOne", function () {
       return function (input, scope) { return input; }
   }),

   app.filter("guardiansOnlyTwo", function () {
       return function (input, scope) { return input; }
   }),

   

app.filter("AdultsOnly", ['UtilService', function (utilService) {
        return function (input, scope) {
            return input.filter(function (x) {
                var age = utilService.getAge(x.dateOfBirth);

                return age >= 18 ? x : null;
            });
        };
        }]),


   app.filter("AdultsFromTargetSystemOnly", function () {
       return function (input, scope) { return input; }
   }),

    app.filter("getUtilFunctionByName", function () {
        return function (input, scope) { return input; }
    }),

                app.filter("overSixty", ['UtilService', function (utilService) {
                    return function (input, scope) {
                        return input.filter(function (x) {
                            var age = utilService.getAge(x.dateOfBirth);

                            return age > 59 ? true : false;
                        });
                    };
                }]),
    app.filter("filterPersonEmployer", function () {
        return function (input, scope) { return input; }
    }),

    app.filter("filterTransportationEmployer", function () {
        return function (input, scope) { return input; }
    }),

    app.filter("guardiansWithoutPresentIndividual", function () {
        return function (input, scope) {
            if (input === undefined || scope.individual === null || scope.individual.individualNumber === null) {
                return input;
            }
            else {
                return input.filter(function (x) {
                    return x.keyValue != scope.individual.individualNumber;
                });
            }            
        }
    }),

       app.filter("isCACIApplicant", function () {
           return function (input, scope) {
               return input.filter(function (x) {

                   var isCACIHCHAApplicant = false;
       
                   if (x != null && x.appliedBenefits != null) {
                       for (var i = 0; i < x.appliedBenefits.length; i++) {
                           if (x.appliedBenefits[i].benefitName.code == "CA" || x.appliedBenefits[i].benefitName.code == "CAR" || x.appliedBenefits[i].benefitName.code == "CI" ||
                               x.appliedBenefits[i].benefitName.code == "CIR" || x.appliedBenefits[i].benefitName.code == "FS" || x.appliedBenefits[i].benefitName.code == "FSR" ||
                               x.appliedBenefits[i].benefitName.code == "HC" || x.appliedBenefits[i].benefitName.code == "HA" || x.appliedBenefits[i].benefitName.code == "MAR" ||
                               x.appliedBenefits[i].benefitName.code == "MCR" || x.appliedBenefits[i].benefitName.code == "CHR" || x.appliedBenefits[i].benefitName.code == "MI" ||
                               x.appliedBenefits[i].benefitName.code == "ES" || x.appliedBenefits[i].benefitName.code == "ESR") {
                               isCACIHCHAApplicant = true;
                               break;
                           }

                       }
                   }
                   return isCACIHCHAApplicant == true ? x : null;


               });
           }
       }),

    app.filter("isCACIApplicantDisability", function () {
        return function (input, scope) {
            return input.filter(function (x) {

                var childCareFoodStampOnly = true;
                var isCIFS = ['CI', 'CIR', 'FS', 'FSR'];
                if (scope.sectionData.people.individuals.length > 0) {
                    for (var i = 0; i < scope.sectionData.people.individuals.length; i++) {
                        if (scope.sectionData.people.individuals[i].appliedBenefits != null) {
                            for (var j = 0; j < scope.sectionData.people.individuals[i].appliedBenefits.length; j++) {
                                if (isCIFS.indexOf(scope.sectionData.people.individuals[i].appliedBenefits[j].benefitName.code) < 0) {
                                    childCareFoodStampOnly = false;
                                    i = scope.sectionData.people.individuals.length;
                                    break;
                                }
                            }
                        }
                    }
                }

                if (childCareFoodStampOnly) {
                    return x;
                }
                else {
                    var isCACIHCHAApplicant = false;
      
                    if (x != null && x.appliedBenefits != null) {
                        for (var k = 0; k < x.appliedBenefits.length; k++) {
                            if (x.appliedBenefits[k].benefitName.code == "CA" || x.appliedBenefits[k].benefitName.code == "CAR" || x.appliedBenefits[k].benefitName.code == "CI" ||
                                x.appliedBenefits[k].benefitName.code == "CIR" || x.appliedBenefits[k].benefitName.code == "FS" || x.appliedBenefits[k].benefitName.code == "FSR" ||
                                x.appliedBenefits[k].benefitName.code == "HC" || x.appliedBenefits[k].benefitName.code == "HA" || x.appliedBenefits[k].benefitName.code == "MAR" ||
                                x.appliedBenefits[k].benefitName.code == "MCR" || x.appliedBenefits[k].benefitName.code == "CHR" || x.appliedBenefits[k].benefitName.code == "MI" ||
                                x.appliedBenefits[k].benefitName.code == "ES" || x.appliedBenefits[k].benefitName.code == "ESR") {
                                isCACIHCHAApplicant = true;
                                break;
                            }

                        }
                    }
                    return isCACIHCHAApplicant == true ? x : null;

                }
            });
        }
    }),

           app.filter("isCAApplicant", function () {
        return function (input, scope) {
            return input.filter(function (x) {

                var isCAHCHAApplicant = false;
                if (x != null && x.appliedBenefits != null) {
                    for (var i = 0; i < x.appliedBenefits.length; i++) {
                        if (x.appliedBenefits[i].benefitName.code == "CA" || x.appliedBenefits[i].benefitName.code == "CAR" ||
                            x.appliedBenefits[i].benefitName.code == "HC" || x.appliedBenefits[i].benefitName.code == "HA" || x.appliedBenefits[i].benefitName.code == "MAR" ||
                            x.appliedBenefits[i].benefitName.code == "MCR" || x.appliedBenefits[i].benefitName.code == "CHR") {
                            isCAHCHAApplicant = true;
                            break;
                        }

                    }
                }
                return isCAHCHAApplicant == true ? x : null;

            });
        };
      
                   });
            


   app.filter("filterPastInsuranceCoverages", function () {

   }),


    //From here its Benefits related Filters

app.filter("HAfilterForBenefits", function () {
    return function (input, scope) {

        return input.filter(function (x) {

            return input;
        });
    }
}),

    //National school, lunch show error if no child present
   app.filter("BLfilterForBenefits", ['UtilService', function (utilService) {
       return function (input, scope) {
           return input.filter(function (x) {
               var age = utilService.getAge(x.dateOfBirth);

               //  TODO: Please check exact age
               // return age < 22 && x.isThisIndividualOutsideHousehold == "N" ? x : null;
               return age < 22 ? x : null;
           });
       }
   }]),

   app.filter("CAfilterForBenefits", function () {
       return function (input, scope) {
           return input.filter(function (x) {

               return input;
           });
       }
   }),

    // and child care works - show error if no child present
   app.filter("CIfilterForBenefits", ['UtilService', function (utilService) {
       return function (input, scope) {
           return input.filter(function (x) {

               var age = utilService.getAge(x.dateOfBirth);
               //  console.log(age);
               return age < 19 ? x : null;
           });
       }
   }]),


    //Chip Renewal - Show if no under 19 present
   app.filter("CHRfilterForBenefits", ['UtilService', function (utilService) {
       return function (input, scope) {
           return input.filter(function (x) {

               var age = utilService.getAge(x.dateOfBirth);
               return age < 19 ? x : null;
           });
       }
   }]),


   

    //For LN or LI Do: Popup(model.resources.Longtermcarenonintermediatecarefacility_help)
   app.filter("LNfilterForBenefits", function () {
       return function (input, scope) {

           return input.filter(function (x) {

               return input;
           });
       }
   }),

   app.filter("BSfilterForBenefits", function () {
       return function (input, scope) {

           return input.filter(function (x) {

               return input;
           });
       }
   }),

   app.filter("CWfilterForBenefits", function () {
       return function (input, scope) {

           return input.filter(function (x) {

               return input;
           });
       }
   }),

   app.filter("PFfilterForBenefits", function () {
       return function (input, scope) {

           return input.filter(function (x) {

               return input;
           });
       }
   });

    //Household benefit seasonal - so return all individuals
    app.filter("LHPfilterForBenefits", function () {
        return function (input, scope) {

            return input.filter(function (x) {

                return input;
            });
        }
    }),

        //Household benefit - so return all individuals
        app.filter("LHfilterForBenefits", function () {
            return function (input, scope) {

                return input.filter(function (x) {

                    return input;
                });
            }
        }),

        //Household benefit Liheap crisis - so return all individuals
        app.filter("LHCRfilterForBenefits", function () {
            return function (input, scope) {

                return input.filter(function (x) {

                    return input;
                });
            };
        }),

        app.filter("FSfilterForBenefits", function () {

            return function (input, scope) {
                return input.filter(function (x) {

                    return input;
                });
            };
        }),

        app.filter("getUniquePolicyOwner", function () {
            return function (input, scope, index) {
                if (input === undefined || scope === null) {
                    return input;
                }
                else {
                    var policyOwners = [];
                    var numOfInsurances = scope.sectionData.household.insuranceInformation.haveMedicalInsurance.currentMedicares.length;
                    for (var i = 0; i < numOfInsurances; i++) {
                        if (scope.sectionData.household.insuranceInformation.haveMedicalInsurance.currentMedicares[i].policyOwner.individualNumber !== '' && i !== index) {
                            policyOwners.push(scope.sectionData.household.insuranceInformation.haveMedicalInsurance.currentMedicares[i].policyOwner.individualNumber);
                        }
                    }
                    return input.filter(function (x) {
                        for (var i = 0; i < numOfInsurances; i++) {
                            if (numOfInsurances > 1) {
                                if (i != index) {
                                    if (scope.sectionData.household.insuranceInformation.haveMedicalInsurance.currentMedicares[i].policyOwner.individualNumber != x.keyValue) {
                                        if (policyOwners.indexOf(x.keyValue) === -1) {
                                            return x.keyValue;
                                        }
                                    }
                                }
                            }
                            else {
                                return x.keyValue;
                            }
                        }                        
                    })
                }
            }
        })

}());;
/*jslint browser:true*/
/*global angular */
/* eslint eqeqeq: 0 */
(function () {
    // TODO - App: need to rewrite based on DE model
    "use strict";
    var app = angular.module("CustomSource", []);

    app.filter("peopleExceptCurrent", function () {
        return function (input, scope) {
            return scope.sectionData.people.individuals.filter(function (x) {
                if (scope.individual === null || scope.individual.individualNumber === null) {
                    return scope.sectionData.people.individuals;
                }
                else {
                    return x.individualNumber != scope.individual.individualNumber;
                }
            });
        };
    });

    app.filter("peopleExceptCurrentAndOther", function () {
        return function (input, scope) {
            return scope.sectionData.people.individuals.filter(function (x) {
                if (scope.individual === null || scope.individual.individualNumber === null) {
                    return scope.sectionData.people.individuals;
                }
                else {
                    return x.individualNumber != scope.individual.individualNumber;
                }
            });
        };
    });

    app.filter("peopleExceptMe", function () {
        return function (input) {
            /*Place the datasource logic here*/
            return input;
        };
    });

    app.filter("allPeople", function () {
        return function (input) {
            /*Place the datasource logic here*/
            return input;
        };
    });

    app.filter("peopleHaveChildJobInsurance", function () {
        return function (input) {
            /*Place the datasource logic here*/
            return input;
        };
    });

    app.filter("peoplePlusOther", function () {
        return function (input) {
            /*Place the datasource logic here*/
            return input;
        };
    });

    app.filter("lIHEAPElectricProvidersList", function () {
        return function (input) {
            /*Place the datasource logic here*/
            return input;
        };
    });

    app.filter("lIHEAPProvidersList", function () {
        return function (input) {
            /*Place the datasource logic here*/
            return input;
        };
    });
    app.filter("houseHoldSchoolDistricts", function () {
        return function (input) {
            /*Place the datasource logic here*/
            return input;
        };
    });

    //app.filter("guardian", function () {
    //    return function (input) {
    //        /*Place the datasource logic here*/
    //        return input;
    //    };
    //});

    app.filter("guardian", function () {
        return function (input, scope) {
            if (scope.individual.firstName != null) {
                var indivs = [];
                for (var i = 0; i < scope.sectionData.people.individuals.length; i++) {
                    if (scope.sectionData.people.individuals[i].individualNumber != scope.individual.individualNumber) {
                        if (scope.sectionData.people.individuals[i].age >= 18) {
                            indivs.push({ keyValue: scope.sectionData.people.individuals[i].individualNumber, displayValue: scope.sectionData.people.individuals[i].firstName });
                        }
                    }
                }
                return indivs;
            }
            else { return []; }
        };
    });

    app.filter("primarySchools", function () {
        return function (input) {
            /*Place the datasource logic here*/
            return input;
        };
    });

    app.filter("privateSchool", function () {
        return function (input) {
            /*Place the datasource logic here*/
            return input;
        };
    });

    app.filter("schoolDistricts", function () {
        return function (input) {
            /*Place the datasource logic here*/
            return input;
        };
    });

    app.filter("cityTownShips", function () {
        return function (input) {
            /*Place the datasource logic here*/
            return input;
        };
    });

    app.filter("charterSchools", function () {
        return function (input) {
            /*Place the datasource logic here*/
            return input;
        };
    });
}());

;
angular.module('showErrors', [])
.directive('showErrors', function ($timeout) {

    return {
        
                   restrict: 'A',
                   require: '^form',
                   link: function (scope, el, attrs, formCtrl) 
                   {
                       // find the text box element, which has the 'name' attribute
                       var inputEl = el[0].querySelector("[name]");
                       // convert the native text box element to an angular element
                       var inputNgEl = angular.element(inputEl);
                       // get the name on the text box
                       var inputName = inputNgEl.attr('name');

                       // only apply the has-error class after the user leaves the text box
                       var blurred = false;
                       
                       inputNgEl.bind('blur', function () {
                           blurred = true;
                           el.toggleClass('has-error', formCtrl[inputName].$invalid);
                       });

                       scope.$watch(function () {
                           return formCtrl[inputName].$invalid
                       }, function (invalid) {
                           // we only want to toggle the has-error class after the blur
                           // event or if the control becomes valid
                           if (!blurred && invalid) { return }
                           el.toggleClass('has-error', invalid);
                       });

                       scope.$on('show-errors-check-validity', function () {
                           el.toggleClass('has-error', formCtrl[inputName].$invalid);
                       });

                       scope.$on('show-errors-reset', function () {
                           $timeout(function () {
                               el.removeClass('has-error');
                           }, 0, false);
                       });
                   }
               }
           });


appRoot.directive('validateAmount', function() {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {

            scope.$watch( function() {
              return ngModel.$viewValue;
            }, function () {
                if (ngModel.$viewValue > 9999999.99) {
                    ngModel.$setValidity('invalidamount', false);
                }
                else {
                    ngModel.$setValidity('invalidamount', true);
                }                
            });
            
        }
      };
});

appRoot.directive('validateAmountdecimals', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {

            scope.$watch(function () {
                return ngModel.$viewValue;
            }, function () {
                if (angular.isUndefined(ngModel.$viewValue)) {
                    ngModel.$setValidity('invalidnumber', true);
                }
                else if (ngModel.$viewValue.toString().split(".").length <= 2) {
                    ngModel.$setValidity('invalidnumber', true);
                }
                //else if (ngModel.$viewValue.toString().split(".").length == 2 && ngModel.$viewValue.toString().split(".")[1].length == 2) {
                //    ngModel.$setValidity('invalidnumber', true);
                //}
                else {
                    ngModel.$setValidity('invalidnumber', false);
                }
            });
        }
    };
});

appRoot.directive('icisLazyName', function () {
    return {
        restrict: 'A',
        require: ['?ngModel', '^?form'],
        link: function postLink(scope, elem, attrs, ctrls) {
            attrs.$set('name', attrs.icisLazyName);

            var modelCtrl = ctrls[0];
            var formCtrl = ctrls[1];
            if (modelCtrl && formCtrl) {
                modelCtrl.$name = attrs.name;
                formCtrl.$addControl(modelCtrl);

                scope.$on('$destroy', function () {
                    formCtrl.$removeControl(modelCtrl);
                });
            }
        }
    };
});

appRoot.directive('validateDuedateinpast', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {

            scope.$watch(function () {
                return ngModel.$viewValue;
            }, function () {
                if (angular.isUndefined(ngModel.$viewValue) || ngModel.$viewValue == null) {
                    ngModel.$setValidity('invalidduedate', true);
                }
                else {
                    var today = new Date();
                    var dateEntered = new Date(ngModel.$viewValue);
                    if (dateEntered.getFullYear() < today.getFullYear()) {
                        ngModel.$setValidity('invalidduedate', false);
                    }
                    else if (dateEntered.getFullYear() == today.getFullYear() && dateEntered.getMonth() < today.getMonth()) {
                        ngModel.$setValidity('invalidduedate', false);
                    }
                    else if (dateEntered.getFullYear() == today.getFullYear() && dateEntered.getMonth() == today.getMonth() && dateEntered.getDate() < today.getDate()) {
                        ngModel.$setValidity('invalidduedate', false);
                    }
                    else {
                        ngModel.$setValidity('invalidduedate', true);
                    }
                }
            });
        }
    };
});

appRoot.directive('validateDuedateinfuture', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {

            scope.$watch(function () {
                return ngModel.$viewValue;
            }, function () {
                if (angular.isUndefined(ngModel.$viewValue) || ngModel.$viewValue == null) {
                    ngModel.$setValidity('incorrectduedate', true);
                }
                else {
                    var today = new Date();
                    var dateEntered = new Date(ngModel.$viewValue);
                    if (dateEntered.getFullYear() > today.getFullYear() + 1) {
                        ngModel.$setValidity('incorrectduedate', false);
                    }
                    else if (dateEntered.getFullYear() == today.getFullYear() + 1 && dateEntered.getMonth() > today.getMonth()) {
                        ngModel.$setValidity('incorrectduedate', false);
                    }
                    else if (dateEntered.getFullYear() == today.getFullYear() + 1 && dateEntered.getMonth() == today.getMonth() && dateEntered.getDate() > today.getDate()) {
                        ngModel.$setValidity('incorrectduedate', false);
                    }
                    else {
                        ngModel.$setValidity('incorrectduedate', true);
                    }
                }
            });
        }
    };
});

appRoot.directive('validateMonthanddate', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {

            scope.$watch(function () {
                return ngModel.$viewValue;
            }, function () {
                if (angular.isUndefined(ngModel.$viewValue) || ngModel.$viewValue == null) {
                    ngModel.$setValidity('incorrectmonth', true);
                    ngModel.$setValidity('incorrectdate', true);
                }
                else
                {
                    ngModel.$setValidity('incorrectmonth', true);
                    ngModel.$setValidity('incorrectdate', true);
                    var regex = /^([0-9]{2}\/[0-9]{2}\/[0-9]{4})$/;
                    if (regex.test(ngModel.$viewValue))
                    {
                        var monthArray1 = [1, 3, 5, 7, 8, 10, 12];
                        var monthArray2 = [4, 6, 9, 11];
                        if (parseInt(ngModel.$viewValue.toString().substring(0, 2)) > 12 || parseInt(ngModel.$viewValue.toString().substring(0, 2)) < 1)
                        {
                            ngModel.$setValidity('incorrectmonth', false);
                        }

                        else if ((monthArray1.indexOf(parseInt(ngModel.$viewValue.toString().substring(0, 2))) != -1 && parseInt(ngModel.$viewValue.toString().substring(3, 5)) > 31)
                                || (monthArray2.indexOf(parseInt(ngModel.$viewValue.toString().substring(0, 2))) != -1 && parseInt(ngModel.$viewValue.toString().substring(3, 5)) > 30)
                                || (parseInt(ngModel.$viewValue.toString().substring(0, 2)) == 2 && parseInt(ngModel.$viewValue.toString().substring(3, 5)) > 28)
                                || parseInt(ngModel.$viewValue.toString().substring(3, 5)) < 1)
                        {
                            ngModel.$setValidity('incorrectdate', false);
                        }
                    }
                }
            });
        }
    };
});;
