//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 inputValidity = iElement.prop("validity");
	                    if (newValue === "" && iElement.attr("type") === "number" && inputValidity && inputValidity.badInput) {
	                 
	                        evt.preventDefault();
	                        revertToPreviousValue();
	                    } else if (regex.test(newValue)) {
	                    
	                        updateCurrentValue(newValue);
	                    } else {
	                    
	                        evt.preventDefault();
	                        revertToPreviousValue();
	                    }
	                }

	                function revertToPreviousValue() {
	                    
	                    if (ngModelController) {
	                        scope.$apply(function () {
	                            ngModelController.$setViewValue(oldValue);
	                        });
	                    }
	                    iElement.val(oldValue);

	                    if (!angular.isUndefined(caretPosition)){
	                        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: icis-date-picker
//@Description:It attaches JQuery datepicker with the element. Also accepts standard datepicker options
//@Developed by: Jigar Naik , iCIS Architect Team
//@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 minDateRange, maxDateRange;

                //Additional Attributes for Calander 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":                        
                            minDateRange = 0;
                            maxDateRange = '+100Y';
                            break;
                        case "validateDateNotInFuture":
                        case "validateDateNotBeforeStartDate":
                            minDateRange = '-100Y';
                            maxDateRange = 0;
                            break;
                        case "validateRecentPayDateNotInFutureAndAfterStartDate":
                            minDateRange = '-100Y';
                            maxDateRange = 0;
                            break;
                        case "validatePastEmploymentStartDateNotInFuture":
                            minDateRange = '-100Y';
                            maxDateRange = 0;
                            break;
                        case "validateDateInFutureLessThan18Months":
                            minDateRange = 0;
                            maxDateRange = '+18M';
                            break;
                        case "validateDateInFutureLessThan3Months":
                            minDateRange = 0;
                            maxDateRange = '+3M';
                            break;
                        case "validateDateNotBeforeStartDate":
                            //TODO: Need to implement this
                            minDateRange = '-100Y';
                            maxDateRange = '+100Y';
                            break;
                        case "validateJobInPastOrWithin30Days":
                            minDateRange = '-100Y';
                            maxDateRange = '+30D';
                            break;
                        case "validateDateFieldInStartAndLastPayCheque":
                            minDateRange = '-100Y';
                            maxDateRange = '+30D';
                            break;
                        case "validateDateInFutureforOneYear":
                            minDateRange = 0;
                            maxDateRange = '+365D';
                            break;
                        case "changeYear":
                            changeYearVal = true;
                            yearRangeVal = "1900:+0";
                            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 "validateDateInPast60DaysOrFuture15Days":
                            minDateRange = '-60D';
                            maxDateRange = '+15D';
                            break;
                        case "validateDateInPast4YearsAndNotFuture":
                            minDateRange = '-4Y';
                            maxDateRange = 0;
                            break;
                        default:
                            minDateRange = '-100Y';
                            maxDateRange = '+100Y';
                    }
                }

                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
                });

                element.bind('change', function () {
                    if (parentScope.mode === "CompletionChecker") {
                        $("#" + elem.id).closest('div.ui-show.inputholder').css('background', 'white');
                    }
                });

                element.bind('paste', function () {
                    return false;
                });
            }
        };
    });
}());;
(function () {
    "use strict";
    var app = angular.module("CustomFilters", []);

    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) {
            //return input.filter(function (x) {
            //    if (angular.isUndefined(x.lastPayDate))
            //        return true;
            //    else
            //        return x.lastPayDate.length <= 0;
            //});
            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 i = 0; i < x.income.otherIncomeSources.length; i++) {
                                if (x.income.otherIncomeSources[i].incomeType.code == "SE" || x.income.otherIncomeSources[i].incomeType.code == "SF") {
                                    return x;
                                }
                            }
                        }
                    }
                    //else {
                    //  return null;
                    // }
                    // }
                });
            }

        }),

        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; }
        }),

        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("heatingSourceFilter", function () {
            return function (input, scope) { return input; }
        }),

        app.filter("nslpOnly", function () {
            return function (input, scope) { return input; }
        }),

        app.filter("removeUnknownCode", function () {
            return function (input, scope) { return input; }
        }),

        app.filter("guardiansOnlyOne", function () {
            return function (input, scope) { return input; }
        }),

        app.filter("guardiansOnlyTwo", function () {
            return function (input, scope) { return input; }
        }),

        app.filter("womanOnly", function () {
            return function (input, scope) { return input; }
        }),

        app.filter("AdultsOnly", function () {
            return function (input, scope) { return input; }
        }),

        app.filter("AdultsFromTargetSystemOnly", function () {
            return function (input, scope) { return input; }
        }),

        app.filter("getUtilFunctionByName", function () {
            return function (input, scope) { return input; }
        }),

        app.filter("overSixty", function () {
            return function (input, scope) { return input; }
        }),

        app.filter("filterPersonEmployer", function () {
            return function (input, scope) { return input; }
        }),

        app.filter("filterTransportationEmployer", function () {
            return function (input, scope) { return input; }
        }),


        app.filter("isCACIApplicant", function () {
            return function (input, scope) {
                return input.filter(function (x) {

                    var isCACIHCHAApplicant = false;
                    // angular.forEach(x.appliedBenefits,function(benefit)
                    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;
                        // angular.forEach(x.appliedBenefits,function(benefit)
                        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("isCAApplicant", function () {
            return function (input, scope) {
                return input.filter(function (x) {

                    var isCAHCHAApplicant = false;
                    // angular.forEach(x.appliedBenefits,function(benefit)
                    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;
                });
            }
        }]),


        ////Food stamps short application
        //app.filter("FSSAfilterForBenefits", function () {
        //	return function (input, scope) {
        //		return input.filter(function (x) {
        //			//benefit = FS//Flex logic
        //			//SET model.household.foodstamps.submitshortapplication = 'Y'
        //			return input;
        //		});
        //	}
        //}),

        //TODO: Refactor the code
        //currently ABR is not shown - throw error if no adults - check function applyNumberOfAdults

        //app.filter("ABRfilterForBenefits", 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;
        //            //console.log(age);
        //            return age >= 18 ? 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;
                });
            }
        })


    // HOUSEHOLD_BENEFITS: Array = [LIHEAP, LIHEAP_PRE_SEASON_APP, LIHEAP_CRISIS];

}());;
/*jslint browser:true*/
/*global angular */
(function () {
    "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("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);
                        }
                    }
                }
            });
        }
    };
});;
