(function () {
    'use strict';

    var app = angular.module("labelApp", ["ngRoute", "ngResource", "ui.bootstrap", "ngAnimate", "ngMaterial", "vcRecaptcha", "moment-picker"]);

    app.config(function ($routeProvider, $locationProvider) {
        $routeProvider
        .when("/", {
            templateUrl: "/scripts/app/home/home.html",
        })
        .when("/Landlord", {
            templateUrl: "/scripts/app/Landlord/Landlord.html",
        })
        .when("/red", {
            templateUrl: "red.htm"
        })
        .when("/green", {
            templateUrl: "green.htm"
        })
        .when("/blue", {
            templateUrl: "blue.htm"
        });

        $locationProvider.html5Mode(true);
    });
   
})();
(function () {


    angular.module('labelApp')
        .controller('homeCtrl', ['$timeout', '$q', '$log', '$http', '$parse', '$mdDialog', 'homeService', 'vcRecaptchaService', '$scope', '$location', '$window', '$anchorScroll',  homeCtrl]);//AuthenticationService

    function homeCtrl($timeout, $q, $log, $http, $parse, $mdDialog, homeService, vcRecaptchaService, $scope, $location, $window, $anchorScroll ) {//AuthenticationService
        $scope.isDisabled = false;
        var vm = this;
        vm.count = 0;
        vm.countBSI = 0;
        vm.countSI = 0;
        vm.isDisabled = false;
        vm.showDiv = true;
        vm.showBSI = true;
        vm.showCSI = true;
        vm.seeInLast = 0;
        vm.showFinal = false;
        vm.promptflag = true;
        $scope.showSecond = true;
        vm.currencyInput = "12345";
        vm.checkRefrralRequired = false;
        vm.request = [];
        vm.response = [];
        vm.loading = true;
        vm.disabled = false;
        vm.state = {};
        vm.state.currentPage = 1;
        vm.state.displayCoverages = false;
        vm.state.displayNewBusinessQuote = true;
        vm.state.displayError = false;
        vm.state.rules = {};
        vm.agreement = false;
        vm.state.quoteResponse = { Coverages: [] };
        var states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Dakota", "North Carolina", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"];
        vm.state.states = states;
        vm.state.frequency = [];
        vm.state.coverages = [];
        vm.state.coveragesType = [];
        vm.isHiddenValue = [];
        vm.SpecifiedItems = [];
        vm.message = "";
        vm.addButtonCount = 0;
        vm.claimsCheckFlag = true;
        vm.HasChecked = false;
        vm.ValidForm1 = false;
        vm.mailFlag = true;
        vm.simulateQuery = false;
        $scope.BrokerPhoneNumberMsg = "";
        vm.BrokerEmailId = "";
        vm.brokerEmail = "";
        vm.showHideQuestions = false;
        vm.showfinalMessage = false;
        vm.showChoice = true;
        vm.repos = [];
        vm.devide = false;
        vm.querySearch = querySearch;
        vm.selectedItemChange = selectedItemChange;
        vm.state.moniker = "";
        vm.state.address = "";
        vm.maxPages = 1;
        vm.captchaflag = true;
        vm.valueFlag
        vm.fileName = ["KFS Listed Events Base Building IAL", "KFS Listed Events Base Contents IAL"];
        vm.state.captcha = {};
        vm.state.captcha.response = null;
        vm.valueCheckForSpecified = null;
        vm.state.captcha.widgetId = homeService.generateUID();
        vm.BrokerFile = "";
        vm.modalHead = "";
        vm.referralQuote = false;
        vm.completeQuote = false;
        vm.showTitle = true;
        vm.tempQuoteResponse = {};
        vm.token = "";
        vm.openAgreement = function () {
        vm.brokerPhoneNumber = "";
        window.open(pdfPolicy + "termsofuse.pdf");// +vm.BrokerFile

        }
        vm.openTab = function (coverFile) {
            if (vm.state.coveragesType[0] == " Building Only") {

                window.open(pdfBuilding)
            }
            else if (vm.state.coveragesType[0] == "Contents Only") {

                window.open(pdfContent)
            }
            else {
                if (coverFile == vm.fileName[0])
                    window.open(pdfBuilding)
                else
                    window.open(pdfContent)
                //vm.fileName[0] = "Content/Building";
                //vm.fileName[0] = "Content/Building";
                file[0] = pdfBuilding;
                file[1] = pdfContent;
                for (var i = 0; i < vm.fileName.length; i++) {
                    window.open(file[i]);
                }

            }
        }

        vm.state.captcha.model = {//prod==LcD7T8UAAAAAN2rPJoNHkTn3KckLjsQUSM0Bsw0   //  6LcD7T8UAAAAAN2rPJoNHkTn3KckLjsQUSM0Bsw0
            key: '6LeVRVIUAAAAAC1E06ZND6gNVf8m7rCnLoxWl49y'// QA/UAT -->6LeVRVIUAAAAAC1E06ZND6gNVf8m7rCnLoxWl49y
        };
        vm.state.captcha.setResponse = function (response) {

            vm.state.captcha.response = response;
            vm.captchaflag = false;
        };
        vm.state.captcha.setWidgetId = function (widgetId) {
            vm.state.captcha.widgetId = widgetId;
        };
        vm.state.captcha.cbExpiration = function () {
            vcRecaptchaService.reload(vm.state.captcha.widgetId);
            vm.state.captcha.response = null;
        };

        function test() {
            vcRecaptchaService.reload(vm.state.captcha.widgetId);
        }
     //   localStorage.clear();
        vm.init = function () {

            var storeVm = homeService.retrieveState();
            vm.showTitle = false; //--> Product name should be hidden all the time.
            if (storeVm == null) {
                homeService.getRules("Home").then(function (response) {
                    
                    $scope.BrokerPhoneNumberMsg = response.PhoneNumber;
                    vm.brokerPhoneNumber = response.PhoneNumber;
                    vm.BrokerEmailId = response.Email;
                    vm.BrokerFile = response.BrokerFile;

                    vm.loading = false;
                    vm.state.rules = response;

                    for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                        if (vm.maxPages < vm.state.rules.QuestionGroups[i].PageNumber) {
                            vm.maxPages = vm.state.rules.QuestionGroups[i].PageNumber;
                        }
                    }
                });
            }
            else {
                vm.state = storeVm;
                vm.loading = false;
                if (vm.state.coveragesType[0] == "Building Only") {
                    vm.fileName.splice(1, 1)
                }
                else if (vm.state.coveragesType[0] == "Contents Only") {
                    vm.fileName.splice(0, 1)
                }
                else vm.devide = true;
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    if (vm.maxPages < vm.state.rules.QuestionGroups[i].PageNumber) {
                        vm.maxPages = vm.state.rules.QuestionGroups[i].PageNumber;
                    }
                }
            }
        };

        vm.init();

        vm.pageChange = function (newPage) {
            vm.state.currentPage = newPage;
        }

        vm.removeLabel = function (labelValue) {
            if (!labelValue) {

                return 'display-none'
            }
            else
                return true;
        }




        vm.dropdownChanged = function (dropdownValue, targetElement, reverseHiddenCondition, hideResetValues) {
            var isPresent = false;
            var targetElementValue = targetElement;
            var matchFound = false;
            if (targetElementValue != null) {

                for (var l = 0; l < targetElementValue.length && !matchFound; l++) {
                    if (dropdownValue == targetElementValue[l].RemoveKey && reverseHiddenCondition) {
                        for (var j = 0; j < hideResetValues.length; j++) {
                            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == hideResetValues[j]) {
                                    vm.state.rules.QuestionGroups[i].IsHidden = false;
                                }
                                //To reset Contents and Building amount to 0
                                //if (vm.state.rules.QuestionGroups[i].GroupCode == 'SumInsured' && (dropdownValue == 'Contents' || dropdownValue == 'Building' || dropdownValue == 'Building and Contents')) {
                                //    for (var m = 0; m < vm.state.rules.QuestionGroups[i].Questions.length; m++) {
                                //        vm.state.rules.QuestionGroups[i].Questions[m].SelectedValue = '';
                                //    }

                                //}


                                if (vm.state.rules.QuestionGroups[i].GroupCode == 'ContentsSumInsured' && (dropdownValue == 'Contents' || dropdownValue == 'Building' || dropdownValue == 'Building and Contents')) {
                                    for (var n = 0; n < vm.state.rules.QuestionGroups[i].Questions.length; n++) {

                                        if (vm.state.rules.QuestionGroups[i].Questions[n].QuestionCode == 'Specific_Items') {
                                            if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == 'Yes') {
                                                isPresent = true;
                                            }
                                        }
                                        if (isPresent == true) {
                                            if (vm.state.rules.QuestionGroups[i].Questions[n].QuestionCode == 'AddSpecifiedItem') {
                                                vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue = '';
                                            }
                                        }

                                    }
                                }


                                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == hideResetValues[j]) {
                                        vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = false;
                                    }
                                }
                            }
                        }




                        var value = targetElementValue[l].RemoveValue;
                        for (var j = 0; j < value.length; j++) {
                            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {

                                if (vm.state.rules.QuestionGroups[i].GroupCode == value[j]) {
                                    vm.state.rules.QuestionGroups[i].IsHidden = true;
                                    matchFound = true;
                                }
                                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == value[j]) {
                                        vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = true;
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Specified_Items_List") {
                                            vm.valueCheckForSpecified = dropdownValue;
                                        }
                                        matchFound = true;

                                    }
                                }
                            }
                        }
                    }
                    else if (!reverseHiddenCondition) {
                        for (var j = 0; j < hideResetValues.length; j++) {
                            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == hideResetValues[j]) {
                                    vm.state.rules.QuestionGroups[i].IsHidden = true;
                                }
                                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == hideResetValues[j]) {
                                        vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = true;
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Specified_Items_List") {
                                            vm.valueCheckForSpecified = dropdownValue;
                                        }
                                    }
                                }
                            }
                        }
                        if (dropdownValue == targetElementValue[l].RemoveKey) {
                            var value = targetElementValue[l].RemoveValue;
                            for (var j = 0; j < value.length; j++) {
                                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                                    if (vm.state.rules.QuestionGroups[i].GroupCode == value[j]) {
                                        vm.state.rules.QuestionGroups[i].IsHidden = false;
                                        matchFound = true;
                                    }
                                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == value[j]) {
                                            vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = false;
                                            matchFound = true;
                                        }
                                    }
                                }
                            }
                        }

                    }
                    else {
                        var value = targetElementValue[l].RemoveValue;
                        for (var j = 0; j < value.length; j++) {
                            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == value[j]) {
                                    vm.state.rules.QuestionGroups[i].IsHidden = false;
                                    vm.isHiddenValue.pop(value[j]);
                                }
                                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == value[j]) {
                                        vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = false;
                                        vm.isHiddenValue.pop(value[j]);
                                    }
                                }
                            }
                        }
                    }

                }
            }


            if (vm.valueCheckForSpecified == "No") {
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Specified_Items_List") {
                            vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = true;
                        }
                    }

                }
            }

            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == 'Coverage_BuildingType') {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue != 'Townhouse' && vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue != 'Duplex') {
                            vm.hideStrata(true);
                        }
                        else {
                            vm.hideStrata(false);
                        }
                    }

                }

            }
        }
        vm.hideStrata = function (hideCheck) {

            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Coverage_PartOfStartaPlan") {
                        if (hideCheck) {
                            vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = true;
                        }
                        else {
                            vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = false;
                        }
                    }
                }
            }
        }

        vm.StrataPlanCheck = function (selectedValue, QuestionCode) {

            var isStrataSelectd = false;
            var isBuildingType = false;
            var isCoverageType = false;
            var isOccupancyType = false;
            var isOtherOccupancyType = false;
            var isNursingHome = false;
            //  var buildingType = "";
            if (selectedValue == "Townhouse" || selectedValue == "Apartment" || selectedValue == "Duplex" || selectedValue == "Townhouse" || selectedValue == "Building and Contents" || selectedValue == "Building" || selectedValue == "Tenant" || QuestionCode == 'Coverage_PartOfStartaPlan' || selectedValue == 'sf:NursingHomeUnit') {
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    for (var n = 0; n < vm.state.rules.QuestionGroups[i].Questions.length; n++) {
                        if (vm.state.rules.QuestionGroups[i].Questions[n].QuestionCode == 'Coverage_PartOfStartaPlan') {
                            if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Yes")
                                isStrataSelectd = true;
                        }

                        if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Townhouse" || vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Duplex") {
                            isBuildingType = true;
                        }
                        if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Apartment" || vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "sf:NursingHomeUnit") {
                            isOtherOccupancyType = true;
                            //     buildingType = selectedValue;
                        }
                        //if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Apartment" || vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "sf:NursingHomeUnit") {
                        //    isOtherOccupancyType = true;
                        //}

                        if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Building and Contents" || vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Building") {
                            isCoverageType = true;
                        }
                        if (vm.state.rules.QuestionGroups[i].Questions[n].QuestionCode == "Coverage_OccupancyType") {
                            if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Tenant")
                                isOccupancyType = true;
                        }

                    }
                }
                if ((isCoverageType && isBuildingType && isStrataSelectd) || isOccupancyType || isOtherOccupancyType) {
                    for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                        for (var n = 0; n < vm.state.rules.QuestionGroups[i].Questions.length; n++) {
                            if (vm.state.rules.QuestionGroups[i].Questions[n].QuestionCode == "Coverage_CoverageType") {
                                if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue != "Contents") {
                                    vm.state.rules.QuestionGroups[i].Questions[n].DefaultValue = "Contents Only";
                                    vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue = "Contents";
                                    //  vm.state.rules.QuestionGroups[i].Questions[n].ReadOnly = true;
                                    vm.modalHead = "Invalid Cover Type";
                                    if (!isOccupancyType && !isOtherOccupancyType)
                                        vm.message = "Only Contents Cover type is allowed when Part of Strata Plan.";
                                    else if (!isOccupancyType)
                                        vm.message = "Only Contents Cover type is allowed for this building type.";
                                    else
                                        vm.message = "Only Contents Cover type is allowed for this occupancy type.";
                                    vm.loading = false;
                                    $("#claimModel").modal({
                                        backdrop: 'static',
                                        keyboard: false
                                    });
                                    document.getElementById("onTop").scrollIntoView();

                                    vm.dropdownChanged("Contents", vm.state.rules.QuestionGroups[i].Questions[n].HiddenValue, true, vm.state.rules.QuestionGroups[i].Questions[n].HideResetValues)
                                }
                            }
                        }
                    }
                }
                else {
                    for (var p = 0; p < vm.state.rules.QuestionGroups.length; p++) {
                        for (var k = 0; k < vm.state.rules.QuestionGroups[p].Questions.length; k++) {
                            if (vm.state.rules.QuestionGroups[p].Questions[k].QuestionCode == "Coverage_CoverageType") {
                                vm.state.rules.QuestionGroups[p].Questions[k].ReadOnly = false;
                            }
                        }
                    }

                }

            }
        }



        vm.agreementChange = function (val) {

            if (val == undefined) {
                vm.agreement = false;
            }
            else
                vm.agreement = val
        }

        vm.Validformfun = function (validform) {
            var val = document.getElementById("getQuickQuote");
            vm.ValidForm1 = validform;
            if (vm.ValidForm1) {
                if (document.getElementById("getQuickQuote") != null)
                    document.getElementById("getQuickQuote").title = "";
            } else {
                if (document.getElementById("getQuickQuote") != null)
                    document.getElementById("getQuickQuote").title = "Please complete all questions above to submit your quote.";
            }
            return true;
        }



        vm.setQuestionsView = function (val) {
            if (!val) {
                vm.showHideQuestions = false;
                vm.showfinalMessage = true;
                vm.showChoice = false;


                homeService.clearState();
                //    $timeout(function () {
                //        window.location.reload(history.go(-1))
                //}, 3000);


            }
            else {
                vm.showHideQuestions = true;
                vm.showfinalMessage = false;
                vm.showChoice = false;

            }

        }

        vm.RemoveInterestedParties = function (answerSelected, questionCode) {
            var isInterestedPartyPresent = false;
            var isOtherinterestedParty = false;
            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Interested_Party") {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue == 'Other')
                            isOtherinterestedParty = true;

                    }
                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Interested_InterestedParties") {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue == 'Yes')
                            isInterestedPartyPresent = true;

                    }
                }
            }
            if (isInterestedPartyPresent && isOtherinterestedParty) {
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Interested_Party_Other") {
                            vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = false;

                        }
                    }
                }
            }
            else {
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Interested_Party_Other") {
                            vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = true;

                        }
                    }
                }

            }
        }

        vm.RemoveBuildingValue = function (dropDownValue, questionCode) {

            if (questionCode == "Coverage_BuildingType" || questionCode == "Coverage_OccupancyType") {
                if ((dropDownValue == "Townhouse" || dropDownValue == "NursingHomeUnit" || dropDownValue == "Duplex" || dropDownValue == "Apartment") || dropDownValue == "Tenant") {
                    for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                        for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                            if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Coverage_CoverageType") {
                                vm.state.rules.QuestionGroups[i].Questions[k].DefaultValue = "Contents Only";
                                vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue = "Contents";
                                vm.state.rules.QuestionGroups[i].Questions[k].ReadOnly = true;
                                vm.dropdownChanged("Contents", vm.state.rules.QuestionGroups[i].Questions[k].HiddenValue, true, vm.state.rules.QuestionGroups[i].Questions[k].HideResetValues)
                            }
                        }
                    }
                }
                else {
                    for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                        for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                            if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Coverage_CoverageType") {
                                vm.state.rules.QuestionGroups[i].Questions[k].ReadOnly = false;
                            }
                        }
                    }
                }
            }

        }

        vm.BuildingAndContentExcess = function (dropDownValue, questionCode) {
            if (questionCode == "ExcessOptions_BuildingExcess2" || questionCode == "ExcessOptions_ContentsExcess2" || questionCode == "ExcessOptions_BuildingExcess3" || questionCode == "ExcessOptions_ContentsExcess3") {
                var coverType = "";
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    if (vm.state.rules.QuestionGroups[i].GroupCode == "Coverage") {
                        for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                            if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Coverage_CoverageType") {
                                coverType = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            }
                        }
                    }
                }
                if (coverType != "Contents" && coverType != "Building" && coverType != "") {
                    if (questionCode == "ExcessOptions_BuildingExcess2") {
                        for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                            if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonContent") {
                                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_ContentsExcess2") {
                                        vm.state.rules.QuestionGroups[i].Questions[k].Required = true;
                                    }
                                }
                            }
                        }
                    }
                }
                if (coverType != "Contents" && coverType != "Building" && coverType != "") {
                    if (questionCode == "ExcessOptions_ContentsExcess2") {
                        for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                            if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonBuilding") {
                                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_BuildingExcess2") {
                                        vm.state.rules.QuestionGroups[i].Questions[k].Required = true;
                                    }
                                }
                            }
                        }
                    }
                }
                if (coverType != "Contents") {
                    if (questionCode == "ExcessOptions_BuildingExcess3") {
                        for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                            if (coverType != "Building" && coverType != "") {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonContent") {
                                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_ContentsExcess3") {
                                            vm.state.rules.QuestionGroups[i].Questions[k].Required = true;
                                        }
                                    }
                                }
                            }
                            else {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonBuilding") {
                                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_BuildingExcess2") {
                                            vm.state.rules.QuestionGroups[i].Questions[k].Required = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (coverType != "Building") {
                    if (questionCode == "ExcessOptions_ContentsExcess3") {
                        for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                            if (coverType != "Contents" && coverType != "") {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonBuilding") {
                                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_BuildingExcess3") {
                                            vm.state.rules.QuestionGroups[i].Questions[k].Required = true;
                                        }
                                    }
                                }
                            }
                            else {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonContent") {
                                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_ContentsExcess2") {
                                            vm.state.rules.QuestionGroups[i].Questions[k].Required = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }
        }

        vm.claimsCheck = function () {
            var excessBuilding1 = "";
            var excessBuilding2 = "";
            var excessBuilding3 = "";
            var excessContent1 = "";
            var excessContent2 = "";
            var excessContent3 = "";
            var coverType = "";
            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                if (vm.state.rules.QuestionGroups[i].GroupCode == "Coverage") {
                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Coverage_CoverageType") {
                            coverType = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                        }
                    }
                }
                if (coverType != "Contents") {
                    if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonBuilding") {

                        for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                            if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_BuildingExcess1") {
                                excessBuilding1 = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            } else if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_BuildingExcess2") {
                                excessBuilding2 = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            } else if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_BuildingExcess3") {
                                excessBuilding3 = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            }
                        }
                    }
                }
                if (coverType != "Building") {
                    if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonContent") {
                        for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                            if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_ContentsExcess1") {
                                excessContent1 = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            } else if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_ContentsExcess2") {
                                excessContent2 = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            } else if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_ContentsExcess3") {
                                excessContent3 = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            }
                        }
                    }
                }
            }
            if (coverType == "Building") {
                if (excessBuilding2 != null) {
                    if (excessBuilding1 == excessBuilding2 || excessBuilding2 == excessBuilding3 || excessBuilding3 == excessBuilding1) {
                        vm.modalHead = "Error"
                        vm.message = "Building Excess Option 2 cannot be the same as Building Excess Option 1 or 3";
                        $("#claimModel").modal();
                        vm.claimsCheckFlag = false;
                    }
                }
            }
            else if (coverType == "Contents") {
                if (excessContent2 != null) {
                    if (excessContent1 == excessContent1 || excessContent2 == excessContent3 || excessContent3 == excessContent1) {
                        vm.modalHead = "Error"
                        vm.message = "Content Excess Option 2 cannot be the same as Content Excess Option 1 or 3";
                        $("#claimModel").modal();
                        vm.claimsCheckFlag = false;
                    }
                }
            }
            else {
                if (excessBuilding2 != null && excessContent2 != null) {
                    if ((excessBuilding1 == excessBuilding2 && excessContent1 == excessContent1) || (excessBuilding2 == excessBuilding3 && excessContent2 == excessContent3) || (excessBuilding3 == excessBuilding1 && excessContent3 == excessContent1)) {
                        vm.modalHead = "Error"
                        vm.message = "Building and Content Excesses Option 2 cannot be the same as Building and Contents Excesses Option 1 or 3";
                        $("#claimModel").modal();
                        vm.claimsCheckFlag = false;
                    }
                }
            }
        }

        vm.AddCalimsYear = function () {

            vm.addButtonCount = vm.addButtonCount + 1;
            vm.SpecifiedItems.push({ Year: "Year", YearValue: "", TypeOfClaims: "TypeOfClaims", TypeOfClaimsValue: "", Required: true })

        }

        vm.RemoveClaims = function (dropDownValue, questionCode) {
            if (questionCode == "Other_ClaimIn3Years" && dropDownValue) {
                if (vm.SpecifiedItems.length > 0) {
                    vm.SpecifiedItems = [];
                }
            }
        }

        vm.RemoveCalimYears = function (index) {
            vm.addButtonCount = vm.addButtonCount - 1;
            vm.SpecifiedItems.pop(index);
        }

        vm.validateCaptcha = function () {

            vm.loading = true;
            //   window.scrollTo(0, document.body.scrollHeight);
            // $window.scrollTo(0, angular.element('onTop').offsetTop); 


            if (vm.state.captcha.response == null) {
                vm.modalHead = "Mandatory Field Required"
                vm.message = "Please complete the \"I'm not a Robot\" question to obtain your quote.";
                vm.loading = false;
                //  $("#claimModel").modal();
                $("#claimModel").modal({
                    backdrop: 'static',
                    keyboard: false
                });
                //   $anchorScroll('onTop');
            }
            else if (vm.agreement == false) {
                vm.modalHead = "Mandatory Field Required"
                vm.message = "Please review and agree to our terms of use before clicking Get quick quote.";
                vm.loading = false;
                $("#claimModel").modal({
                    backdrop: 'static',
                    keyboard: false
                });
            }
            else {
                homeService.validateCaptchaSer(vm.state.captcha.response).then(function (response) {

                    if (vm.checkRefrralRequired) {
                        vm.loading = false;
                        vm.getPremium();
                    }
                    if (!vm.checkRefrralRequired) {
                        if (true) {
                            window.scroll(0, 0);
                            vm.getPremium();
                        }
                        else {
                            vm.loading = false;
                            $window.location.pathname = '/Home/Error';
                        }
                    }
                });
            }
        }

        vm.getPremium = function () {

            if (true) {
                homeService.storeState(vm.state);

                var questionAnswer = new Object;
                var obj = new Object();
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {


                    var questions = vm.state.rules.QuestionGroups[i].Questions;
                    for (var j = 0; j < questions.length; j++) {

                        if (questions[j].QuestionType != "ShadedLabel" && questions[j].QuestionType != "Label" && questions[j].QuestionType != "ValueList" && questions[j].QuestionType != "Address") {

                            if (questions[j].SelectedValue == "") {
                                questions[j].SelectedValue = "null";
                            }
                            obj[questions[j].QuestionCode] = questions[j].SelectedValue;

                            //questionAnswer.push(
                            //    {
                            //        Key: questions[j].QuestionCode,
                            //        Value: questions[j].SelectedValue
                            //       //Original calling
                            //        //Question: questions[j].QuestionCode,
                            //        //Answer: questions[j].SelectedValue,
                            //        //ComplexAnswer: []
                            //    });
                        }
                        if (questions[j].QuestionType == "ValueList") {
                            if (questions[j].SelectedValue == "") {
                                questions[j].SelectedValue = "null";
                            }
                            obj[questions[j].QuestionCode] = questions[j].SelectedValue;

                            //questionAnswer.push(
                            //    {
                            //        Key: questions[j].QuestionCode,
                            //        Value: questions[j].SelectedValue
                            //        //Question: questions[j].QuestionCode,
                            //        //Answer: questions[j].SelectedValue,
                            //        //ComplexAnswer: getAnswerList()
                            //    });
                        }
                        if (questions[j].QuestionType == "Address") {
                            if (questions[j].SelectedValue == "") {
                                questions[j].SelectedValue = "null";
                            }
                            obj[questions[j].QuestionCode] = vm.state.address + "~" + vm.state.moniker;

                            //questionAnswer.push(
                            //    {
                            //        Key: questions[j].QuestionCode,
                            //        Value: vm.state.address + "~" + vm.state.moniker,
                            //        //Question: questions[j].QuestionCode,
                            //        //Answer: vm.state.address + "~" + vm.state.moniker,
                            //        //ComplexAnswer: []
                            //    })
                        }
                    }
                }

                questionAnswer = obj;
                var tokenRecieved = false;
                // console.log(questionAnswer);

             //   vm.getToken(function () {
                    var request = { Product: "Home", Quote: questionAnswer, UAGCode: "BRKBROKER_RC", BrokerCode: "IQBRKBROKER_IAL", email: "mailToBroker@brokersite.com", customReferralMessage: "", phone: "3456578976" };
                    vm.loading = true;
                    vm.disabled = true;
                    vm.request.push(request);

                    // homeService.saveReferrals(request,
                    //    function (resp) {

                    //        vm.loading = false;
                    //        vm.disabled = false;
                    //        vm.setDisplayCoverages(resp);
                    //    },
                    //    function (error) {
                    //        vm.loading = false;
                    //        vm.disabled = false;
                    //        console.log(error);
                    //    }
                    //);

                    homeService.qualifiedQuotes(request,
                        function (resp) {

                            vm.loading = false;
                            vm.disabled = false;
                            vm.state.displayError = false;
                            vm.setDisplayCoverages(resp);
                        },
                        function (error) {
                            vm.loading = false;
                            vm.disabled = false;
                            vm.state.displayError = true;
                        }
                    );
            //    });
            }

        }
        //vm.getToken = function () {
        //    debugger
        //    homeService.getToken(function (response) {
        //        debugger
        //        var TokenData = response;
        //        tokenRecieved = true;
        //        //vm.token = 
        //        console.log(TokenData);
        //    });
        //}
        vm.RemoveClaims = function (dropDownValue, questionCode) {
            if (questionCode == "Other_ClaimIn3Years" && dropDownValue) {
                if (vm.SpecifiedItems.length > 0) {
                    vm.SpecifiedItems = [];
                }
            }
        }
        vm.NoOfClaims = function (val) {
            if (val >= 0 && val <= 10) {
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == 'Other_recentCalims') {
                            if (val == 0) {
                                vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = true;
                            }
                            else {
                                vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = false;
                            }
                            //if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Specified_Items_List") {
                            //    vm.valueCheckForSpecified = dropdownValue;
                        }
                    }
                }
                return true;
            }
            else
                return false;
        }
        vm.ShowLabel = function (question) {
            if (question.QuestionType == 'CheckBox') {
                return false;
            }

            if (question.QuestionType == 'ShadedLabel') {
                return false;
            }

            if (question.QuestionType == 'ValueList') {
                return false;
            }

            if (question.IsHidden == true) {
                return false;
            }
            return true;
        }

        vm.AddHelp = function (question) {

            if (question.QuestionCode == 'Specific_Items') {
                return true;
            }
            if (question.QuestionCode == 'Building_BuildingReplacementValue') {
                if (vm.showBSI == true)
                    return false;
                else
                    return true;
            }
            if (question.QuestionCode == 'SumInsured_ContentsSumInsured') {
                if (vm.showBSI == true)
                    return false;
                else
                    return true;
            }
            return false;
        }

        vm.alert = function (ev, val, code) {

            if (val == 1) {
                if (code.QuestionCode == 'Specific_Items') {
                    $scope.isDisabled = true;
                    if (this.count == 0) {
                        this.count = this.count + 1;
                        $mdDialog.show({

                            parent: angular.element(document.body),
                            clickOutsideToClose: false,
                            bindToController: true,
                            backdrop: false,
                            controllerAs: 'dialogCtrl',
                            templateUrl: '/image/HelpSpecificItems.html',
                            windowClass: 'large-Modal',
                            controller: function dialogCtrl() {
                                this.click = function click() {
                                    $scope.isDisabled = false;
                                    $mdDialog.hide();
                                    $mdDialog.cancel();
                                };
                            }
                        })
                    } else {
                        $scope.isDisabled = false;
                        this.showDiv = true;
                        $mdDialog.hide();
                    }
                }
                else if (code.QuestionCode == 'Building_BuildingReplacementValue') {
                    $scope.isDisabled = false;
                    if (this.countBSI == 0) {
                        this.countBSI = this.countBSI + 1;
                        this.showDiv = true;
                        $scope.showSecond = false;
                        $mdDialog.show({

                            parent: angular.element(document.body),
                            clickOutsideToClose: false,
                            bindToController: true,
                            backdrop: false,
                            controllerAs: 'dialogCtrl',
                            templateUrl: '/image/HelpRequiredLevelOfCover.html',
                            windowClass: 'large-Modal',
                            controller: function dialogCtrl() {
                                this.click = function click() {
                                    $scope.isDisabled = false;
                                    $mdDialog.hide();
                                    $mdDialog.cancel();
                                };
                            }
                        })
                    } else {
                        $scope.isDisabled = false;
                        this.showDiv = true;
                        $mdDialog.hide();
                    }
                }
                else if (code.QuestionCode == 'SumInsured_ContentsSumInsured') {
                    $scope.isDisabled = false;
                    if (this.countSI == 0) {
                        this.countSI = this.countSI + 1;
                        this.showDiv = true;
                        $scope.showSecond = false;
                        $mdDialog.show({

                            parent: angular.element(document.body),
                            clickOutsideToClose: false,
                            bindToController: true,
                            backdrop: false,
                            controllerAs: 'dialogCtrl',
                            templateUrl: '/image/HelpRequiredLevelOfCover.html',
                            windowClass: 'large-Modal',
                            controller: function dialogCtrl() {
                                this.click = function click() {
                                    $scope.isDisabled = false;
                                    $mdDialog.hide();
                                    $mdDialog.cancel();
                                };
                            }
                        })
                    } else {
                        $scope.isDisabled = false;
                        this.showDiv = true;
                        $mdDialog.hide();
                    }
                }
            }
            else if (val == 3) {
                vm.state.displayNewBusinessQuote = false
                vm.state.displayCoverages = false;
                vm.completeQuote = true;
                vm.showTitle = false;
                //$mdDialog.show({

                //    parent: angular.element(document.body),
                //    clickOutsideToClose: false,
                //    bindToController: true,
                //    backdrop: false,
                //    locals: {
                //        brokerName: vm.brokerName,
                //        brokerEmail: vm.brokerEmail,
                //        brokerPhoneNumber: vm.brokerPhoneNumber,
                //        brokerQuoteNumber: vm.quoteNumber
                //    },

                //    controllerAs: 'dialogCtrl',
                //    templateUrl: '/image/ThankYouNote.html',

                //    controller: function dialogCtrl(brokerName, brokerEmail, brokerPhoneNumber, brokerQuoteNumber) {
                //        var self = this;
                //        self.brokerName = brokerName;
                //        self.brokerEmail = brokerEmail;
                //        self.brokerPhoneNumber = brokerPhoneNumber;
                //        self.brokerQuoteNumber = brokerQuoteNumber;
                //        this.click = function click() {
                //            $scope.isDisabled = false;
                //            $mdDialog.hide();
                //        };

                //    }
                //});
            }

            else {
                if (code.QuestionCode == 'Specific_Items') {

                    $mdDialog.show({

                        parent: angular.element(document.body),
                        clickOutsideToClose: false,
                        bindToController: true,
                        backdrop: false,
                        controllerAs: 'dialogCtrl',
                        templateUrl: '/image/HelpSpecificItems.html',
                        controller: function dialogCtrl() {
                            this.click = function click() {
                                $scope.isDisabled = false;
                                $mdDialog.hide();
                                $mdDialog.cancel();
                            };
                        }
                    })

                }
                else if (code.QuestionCode == 'Building_BuildingReplacementValue') {

                    $scope.showSecond = false;
                    this.showDiv = true;
                    $mdDialog.show({

                        parent: angular.element(document.body),
                        clickOutsideToClose: false,
                        bindToController: true,
                        backdrop: false,
                        controllerAs: 'dialogCtrl',
                        templateUrl: '/image/HelpRequiredLevelOfCover.html',
                        controller: function dialogCtrl() {
                            this.click = function click() {
                                $scope.isDisabled = false;
                                $mdDialog.hide();
                                $mdDialog.cancel();
                            };
                        }
                    })

                }
                else if (code.QuestionCode == 'SumInsured_ContentsSumInsured') {

                    $scope.showSecond = false;
                    this.showDiv = true;
                    $mdDialog.show({

                        parent: angular.element(document.body),
                        clickOutsideToClose: false,
                        event: ev,
                        bindToController: true,
                        backdrop: false,
                        controllerAs: 'dialogCtrl',
                        templateUrl: '/image/HelpRequiredLevelOfCover.html',
                        controller: function dialogCtrl() {
                            this.click = function click() {
                                $scope.isDisabled = false;
                                $mdDialog.hide();
                                $mdDialog.cancel();
                            };
                        }
                    })

                }
            }



        };

        vm.mailSend = function () {
            vm.setSeeInLastValues();

        }

        vm.setSeeInLastValues = function () {
            if (true) {
                homeService.storeState(vm.state);
                
                var questionAnswerInLast = [];
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    var questions = vm.state.rules.QuestionGroups[i].Questions;

                    for (var j = 0; j < questions.length; j++) {
                        if (questions[j].SeeInLast == true && questions[j].QuestionCode != "Building_Address" && questions[j].QuestionCode != "Coverage_CoverageType") {
                            if (questions[j].QuestionType != "ShadedLabel" && questions[j].QuestionType != "Label" && questions[j].QuestionType != "ValueList" && questions[j].QuestionType != "Address") {
                                questionAnswerInLast.push(
                                    {
                                        Key: questions[j].QuestionCode,
                                        Value: questions[j].SelectedValue
                                        //Question: questions[j].QuestionCode,
                                        //Answer: questions[j].SelectedValue,

                                    });
                            }

                        }
                    }
                }
                for (var i = 0; i < vm.request.length; i++) {
                    for (var j = 0; j < vm.request[i].Quote.length; j++) {
                        if (vm.request[i].Quote.Key[j] == "Email" || vm.request[i].Quote.Key[j] == "Phone_Number") {
                            questionAnswerInLast.push(
                                     {
                                         Key: vm.request[i].Quote.Key[j],
                                         Value: vm.request[i].Quote.Value[j],
                                         //Question: vm.request[i].questionAnswers[j].Question,
                                         //Answer: vm.request[i].questionAnswers[j].Answer,

                                     });

                        }
                    }
                }
                if (true) {

                    for (var i = 0; i < questionAnswerInLast.length; i++) {
                        if (questionAnswerInLast[i].Key.indexOf("Interested") == -1 && questionAnswerInLast[i].Key != "Coverage_PropertyLocatedOn") {
                            {

                                if (questionAnswerInLast[i].Value == "Yes") {
                                    vm.promptflag = false;
                                }
                                else if (questionAnswerInLast[i].Key == "Other_CriminalConvictionsIn3Years") {
                                    if (questionAnswerInLast[i].Value != 0)
                                        vm.promptflag = false;
                                }
                            }
                        }
                    }
                    if (vm.promptflag == true) {
                        vm.alert(MouseEvent, 3)
                    }
                    else {
                        vm.state.displayNewBusinessQuote = false
                        vm.state.displayCoverages = false;

                        vm.referralQuote = true;
                        vm.showTitle = false;
                        //$mdDialog.show({
                        //    parent: angular.element(document.body),
                        //    clickOutsideToClose: false,
                        //    bindToController: true,
                        //    backdrop: false,
                        //    locals: { brokerPhoneNumbers: vm.brokerPhoneNumber },
                        //    controllerAs: 'dialogCtrl',
                        //    templateUrl: '/image/CannotGenerateQuote.html',

                        //    controller: function dialogCtrl(brokerPhoneNumbers) {
                        //        $scope.isDisabled = false;
                        //        var self = this;
                        //        homeService.clearState();
                        //        self.brokerPhoneNumber = brokerPhoneNumbers;
                        //        this.click = function click() {
                        //            //   window.location.reload(history.go(-1))
                        //            $mdDialog.hide();
                        //            $mdDialog.cancel();
                        //        };
                        //    }
                        //});
                    }
                }

                var mailToBroker = [];
                
                mailToBroker.push({
                    QuoteRequest: vm.request[0],
                    QuoteResponse: vm.response[0],
                    SendMail: false,
                    IsRefrral: false,
                    isUpdateRequired: false,
                    isSubmitValues: true,
                    QuestionAnswersSeenInLast: questionAnswerInLast
                });
                //if (vm.promptflag) {
                if (vm.mailFlag) {
                    homeService.mailSendService(mailToBroker,
                        function (resp) {

                            vm.loading = false;
                            vm.disabled = false;
                           
                        },
                        function (error) {
                            vm.loading = false;
                            vm.disabled = false;
                        }
                    );
                    vm.mailFlag = false;
                }
                //  }
            }
        }


        vm.buttonStatus = function () {

        }

        vm.checkSeeInLastCondition = function (objQuestionGroups) {
            for (var j = 0; j < objQuestionGroups.Questions.length; j++) {
                if (objQuestionGroups.Questions[j].SeeInLast == true) {
                    return true;
                }
                
            }
            return false;
        }

        vm.SingleQuestion = function (objQuestionGroups) {
            if (objQuestionGroups.Questions.length < 2) {
                if (objQuestionGroups.Questions[0].IsHidden == true)
                    return false;
            }
            return true;
        }
        vm.checkNotSeeInLastCondition = function (objQuestionGroups) {
            for (var j = 0; j < objQuestionGroups.Questions.length; j++) {
                if (objQuestionGroups.Questions[j].SeeInLast != true) {
                    return true;
                }
            }
            return false;
        }

        vm.ShowPanel = function (questionGroups) {
            if (questionGroups.IsHidden == true) {
                return false;
            }
            return true;
        }


        vm.ngModelOptionsSelected = function (value) {
            if (arguments.length) {
                _selected = value;
            } else {
                return _selected;
            }
        };

        vm.setDisplayCoverages = function (quoteResponse) {
            //  $anchorScroll('onTop');
            //if (quoteResponse.Coverages.length == 0 && quoteResponse.Messages.length==0) {
            //    quoteResponse.Messages.push("Thanks for requesting a quote through us. Unfortunately we are unable to provide you with an immediate quote in this instance. We will be in contact with you within 24 hours to assist you further. If you wish to contact us in the meantime please call us on 08 9349 7900 or email us at yourinsurance@centrewest.com.au .");
            //}
            //vm.state = quoteResponse;
            vm.state.quoteResponse = new Object();
            if (quoteResponse.Code == '400') {
                //vm.state.quoteResponse.Messages.push("We are unable to provide you a quote at this stage. We have your quote details and will be in contact with you within 24 hours. If you wish to contact us in the meantime please do call us on "+ quoteResponse.PhoneNumber);
                vm.state.displayError = true;
            }
            else {
                vm.state.displayError = false;
                vm.response.push(quoteResponse);
                vm.state.data = quoteResponse.data;
                vm.brokerEmail = quoteResponse.data.Email;
                vm.brokerName = quoteResponse.data.BrokerName;
                vm.brokerPhoneNumber = quoteResponse.data.PhoneNumber;
                vm.quoteNumber = quoteResponse.QuoteNumber;
                vm.tempQuoteResponse = quoteResponse;
                vm.state.quoteMessage = quoteResponse.CustomQuoteMessage;
            }
            vm.state.frequency = [];

            $anchorScroll();
            //if (vm.newState.quoteResponse.Code == "400") {
            //    vm.state.quoteResponse.Messages = vm.newState.quoteResponse.Error;
            //}
            
            if (vm.state.quoteResponse.Messages != null && vm.state.quoteResponse.Messages.length > 0) {
                var setReferralValues = [];
                var lastRequest = [];
                lastRequest.push(vm.request[vm.request.length - 1]);
                setReferralValues.push({
                    QuoteRequest: lastRequest[0],
                    QuoteResponse: quoteResponse,
          
                    IsRefrral: true,
                    isUpdateRequired: false,
                    isSubmitValues: false

                });
                //Save Quote Request and Quote Response Data From Front End-> for referral
                //homeService.mailSendService(setReferralValues,
                //    function (resp) {

                //        vm.loading = false;
                //        vm.disabled = false;

                //    },
                //    function (error) {
                //        vm.loading = false;
                //        vm.disabled = false;
                //    }
                //);
                var messages = [];
                /********** FOR SINGLE MESSSAGE  ****************/
                messages.push(vm.state.quoteResponse.Messages);
                /********** USE FOR MULTIPLE MESSAGES  DISPLAY  ****************/
                //for (var i = 0; i < vm.state.quoteResponse.Messages.length; i++) {
                //    var addNew = true;
                //    for (var j = 0; j < messages.length; j++) {
                //        if (vm.state.quoteResponse.Messages[i] == messages[j]) {
                //            addNew = false;
                //            break;
                //        }
                //    }
                //    if (addNew) {
                //        messages.push(vm.state.quoteResponse.Messages[i]);
                //    }
                //}
                //if (messages.indexOf('"') > -1) {//includes("") --> not supported for all the browsers
                //    for (var i = 0; i < messages.length; i++) {
                //        if (messages[i] == "") {
                //            messages.splice(i, 1)
                //        }
                //    }
                //}
                /***************************/
                vm.checkRefrralRequired = true;
                
                vm.state.quoteResponse.Messages.push("We are unable to provide you a quote at this stage. We have your quote details and will be in contact with you within 24 hours. If you wish to contact us in the meantime please do call us on "+quoteResponse.PhoneNumber);
                vm.state.displayError = true;
                vm.state.displayNewBusinessQuote = true;
                vm.state.displayCoverages = false;
            }
            else {
                vm.checkRefrralRequired = false;
                for (var i = 0; i < vm.state.data.coverages.length; i++) {
                    if (vm.state.frequency.filter(function (f) {
                        return f === vm.state.data.coverages[i].frequency;
                    }).length == 0) {
                        vm.state.frequency.push(vm.state.data.coverages[i].frequency);
                    }
                }
                vm.state.coverages = [];
                for (var j = 0; j < vm.state.data.coverages.length; j++) {
                    if (vm.state.coverages.filter(function (f) {
                        return f === vm.state.data.coverages[j].coverageName;
                    }).length == 0) {
                        //vm.state.coverages.push(vm.state.data.coverages[j].coverageName);
                        vm.state.coveragesType.push(vm.state.data.coverages[j].coverageType.replace(/['"]+/g, ''));
                    }
                }
                vm.state.coverages = ["ListedEventsBase"];

                if (vm.state.coveragesType[0] == "Building Only") {
                    vm.fileName.splice(1, 1)
                }
                else if (vm.state.coveragesType[0] == "Contents Only") {
                    vm.fileName.splice(0, 1)
                }
                else vm.devide = true

                vm.state.displayError = false;
                vm.state.displayCoverages = true;
                vm.showTitle = false;
                vm.state.displayNewBusinessQuote = false;
                var lastRequest = [];
                lastRequest.push(vm.request[vm.request.length - 1]);
                //var last = vm.request.pop();
                var setUpdatedValues = [];
                setUpdatedValues.push({
                    QuoteRequest: lastRequest[0],
                    QuoteResponse: quoteResponse,
                   
                    IsRefrral: false,
                    isUpdateRequired: true,
                    isSubmitValues: false

                });


                //Save Quote Request and Quote Response Data From Front End->
                //homeService.mailSendService(setUpdatedValues,
                //    function (resp) {

                //        vm.loading = false;
                //        vm.disabled = false;

                //    },
                //    function (error) {
                //        vm.loading = false;
                //        vm.disabled = false;
                //    }
                //);
            }
            homeService.storeState(vm.state);



        }

        vm.loadFrame = function () {
            //homeService.clearState();
            location.reload();

            setTimeout(function () {
                if (newState == -1) {
                    vm.showTitle = false;
                    vm.state.displayNewBusinessQuote = true;
                    vm.referralQuote = false;
                    vm.completeQuote = false;
                    vm.state.displayCoverages = false;
                }
            }, 5000);
            //vm.showTitle = true;
            //vm.state.displayNewBusinessQuote = true;
            //vm.referralQuote = false;
            //vm.completeQuote = false;
            //vm.state.displayCoverages = false;
            homeService.clearState();

        }
        vm.goBack = function () {
            vm.state.displayNewBusinessQuote = true;
            vm.state.displayCoverages = false;
            homeService.storeState(vm.state);
        }

        vm.getCoveragePremium = function (coverage, frequency, excess) {
            var premium = 0.00;
            if (excess == 500) {

                for (var i = 0; i < vm.state.data.coverages.length; i++) {
                    if (vm.state.data.coverages[i].frequency == frequency
                        && vm.state.data.coverages[i].coverageName == coverage) {
                        premium = vm.state.data.coverages[i].premium;
                        //  vm.state.quoteResponse.Coverages.splice(i,1)
                        return premium;
                    }
                }
            }
            else {
                for (var i = 2; i < vm.state.data.coverages.length; i++) {
                    if (vm.state.data.coverages[i].frequency == frequency
                        && vm.state.data.coverages[i].coverageName == coverage) {
                        premium = vm.state.data.coverages[i].premium;
                        //  vm.state.quoteResponse.Coverages.splice(i,1)
                        return premium;
                    }
                }
            }

            return premium;
        }

        vm.getCoverageName = function (coverage) {

            return AddSpace(coverage);
        }

        function AddSpace(string) {
            string = string.replace(/([a-z])([A-Z])/g, '$1 $2');
            string = string.replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')
            return string;
        }

        /**
         * Create filter function for a query string
         */
        function createFilterFor(query) {
            var lowercaseQuery = angular.lowercase(query);

            return function filterFn(item) {
                return (item.value.indexOf(lowercaseQuery) === 0);
            };


        }


        function selectedItemChange(item) {
            if (item) {
                vm.state.moniker = item.Moniker;
                vm.state.address = item.Address;
                //$log.info(vm.state.moniker);
                //$log.info(vm.state.address);
            }
            else {
                //   $log.info('invalid');
            }
        }




        /**
 * Search for repos... use $timeout to simulate
 * remote dataservice call.
 */
        function querySearch(query) {
            return $http.get('https://uatws.ial.com.au/api/B3U/GetResult?input=' + query + '&tkn=55123&BrokerCode=BRKBROKER_RC&userid=sbakshi')
                .then(function (response) {
                    if (response.data.CompacAddressList[0].Address == "") {
                        return false;
                    }
                    else {
                        return response.data.CompacAddressList;
                    }
                })
                .catch(function (error) {
                    return $q.reject({ msg: "Something went wrong." });
                });

        }
    };
})();
(function () {
    angular.module('labelApp')
        .controller('LandlordCtrl', ['$timeout', '$q', '$log', '$http', '$parse', '$mdDialog', 'LandlordService', 'vcRecaptchaService', '$scope', '$location', '$window', '$anchorScroll', LandlordCtrl]);

    function LandlordCtrl($timeout, $q, $log, $http, $parse, $mdDialog, LandlordService, vcRecaptchaService, $scope, $location, $window, $anchorScroll) {
        $scope.isDisabled = false;
        var vm = this;
        vm.count = 0;
        vm.countBSI = 0;
        vm.countSI = 0;
        vm.isDisabled = false;
        vm.showDiv = true;
        vm.showBSI = true;
        vm.showCSI = true;
        vm.seeInLast = 0;
        vm.showFinal = false;
        vm.promptflag = true;
        $scope.showSecond = true;
        vm.currencyInput = "12345";
        vm.BrokerEmailId = "";
        vm.checkRefrralRequired = false;
        vm.request = [];
        vm.loading = true;
        vm.disabled = false;
        vm.state = {};
        vm.state.currentPage = 1;
        vm.state.displayCoverages = false;
        vm.state.displayError = false;
        vm.state.rules = {};
        vm.agreement = false;
        vm.state.quoteResponse = { Coverages: [] };
        var states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Dakota", "North Carolina", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"];
        vm.state.states = states;
        vm.state.frequency = [];
        vm.state.coverages = [];
        vm.state.coveragesType = [];
        vm.isHiddenValue = [];
        vm.SpecifiedItems = [];
        vm.message = "";
        vm.addButtonCount = 0;
        vm.claimsCheckFlag = true;
        vm.HasChecked = false;
        vm.ValidForm1 = false;
        vm.mailFlag = true;
        vm.simulateQuery = false;
        $scope.BrokerPhoneNumberMsg = "";
        vm.BrokerEmailId = "";
        vm.brokerEmail = "";
        vm.showHideQuestions = false;
        vm.showfinalMessage = false;
        vm.showChoice = true;
        vm.repos = [];
        vm.devide = false;
        vm.querySearch = querySearch;
        vm.selectedItemChange = selectedItemChange;
        vm.state.moniker = "";
        vm.state.address = "";
        vm.maxPages = 1;
        vm.captchaflag = true;
        vm.valueFlag
        vm.fileName = ["KFS Listed Events Base Building IAL", "KFS Listed Events Base Contents IAL"];
        vm.state.captcha = {};
        vm.state.captcha.response = null;
        vm.valueCheckForSpecified = null;
        vm.state.captcha.widgetId = LandlordService.generateUID();
        vm.BrokerFile = "";
        vm.modalHead = "";
        vm.referralQuote = false;
        vm.state.displayNewBusinessQuote = true;
        vm.completeQuote = false;
        vm.showTitle = true;
        var file = new Array(3);
        vm.storeObj = {};
        vm.openAgreement = function () {
            $window.open(pdfPolicy + vm.BrokerFile);// +vm.BrokerFile
            //var win =
            //   win.focus();
        }
        vm.openTab = function (coverFile) {
            if (vm.state.coveragesType[0] == " Building Only") {

                window.open(pdfBuilding)
            }
            else if (vm.state.coveragesType[0] == "Contents Only") {

                window.open(pdfContent)
            }
            else {
                if (coverFile == vm.fileName[0])
                    window.open(pdfBuilding)
                else
                    window.open(pdfContent)
                //vm.fileName[0] = "Content/Building";
                //vm.fileName[0] = "Content/Building";

                file[0] = pdfBuilding;
                file[1] = pdfContent;
                for (var i = 0; i < vm.fileName.length; i++) {
                    window.open(file[i]);
                }

            }
        }


        vm.state.captcha.model = {//prod==6LcD7T8UAAAAAN2rPJoNHkTn3KckLjsQUSM0Bsw0
            key: '6LeVRVIUAAAAAC1E06ZND6gNVf8m7rCnLoxWl49y'// QA/UAT -->6Lfj7xQUAAAAAMUol-wsZSdC7n-ZBhD-QRv8jgiQ
        };
        vm.state.captcha.setResponse = function (response) {

            vm.state.captcha.response = response;
            vm.captchaflag = false;
        };
        vm.state.captcha.setWidgetId = function (widgetId) {
            vm.state.captcha.widgetId = widgetId;
        };
        vm.state.captcha.cbExpiration = function () {
            vcRecaptchaService.reload(vm.state.captcha.widgetId);
            vm.state.captcha.response = null;
        };

        function test() {
            vcRecaptchaService.reload(vm.state.captcha.widgetId);
        }

        vm.init = function () {
            var storeVm = LandlordService.retrieveState();
            vm.showTitle = false;
            window.addEventListener("message", receiveMessage, false);
            function receiveMessage(event) {
                if (event.data == "iframeHtml") {
                    LandlordService.clearState();
                }
            }
            if (storeVm == null) {
                LandlordService.getRules("Landlord").then(function (response) {



                    $scope.BrokerPhoneNumberMsg = response.PhoneNumber;


                    vm.BrokerFile = response.BrokerFile;

                    vm.BrokerEmailId = response.Email;
                    vm.loading = false;
                    vm.state.rules = response;


                    for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                        if (vm.maxPages < vm.state.rules.QuestionGroups[i].PageNumber) {
                            vm.maxPages = vm.state.rules.QuestionGroups[i].PageNumber;


                        }
                    }
                });
            }
            else {

                vm.state = storeVm;
                vm.loading = false;

                if (vm.state.coveragesType[0] == "Building Only") {
                    vm.fileName.splice(1, 1)
                }
                else if (vm.state.coveragesType[0] == "Contents Only") {
                    vm.fileName.splice(0, 1)
                }
                else vm.devide = true;
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    if (vm.maxPages < vm.state.rules.QuestionGroups[i].PageNumber) {
                        vm.maxPages = vm.state.rules.QuestionGroups[i].PageNumber;
                    }
                }
            }
        };

        vm.init();

        vm.pageChange = function (newPage) {
            vm.state.currentPage = newPage;
        }

        vm.removeLabel = function (labelValue) {
            if (!labelValue) {

                return 'display-none'
            }
            else
                return true;
        }




        vm.dropdownChanged = function (dropdownValue, targetElement, reverseHiddenCondition, hideResetValues) {

            var isPresent = false;
            var targetElementValue = targetElement;
            var matchFound = false;
            if (targetElementValue != null) {

                for (var l = 0; l < targetElementValue.length && !matchFound; l++) {
                    if (dropdownValue == targetElementValue[l].RemoveKey && reverseHiddenCondition) {
                        for (var j = 0; j < hideResetValues.length; j++) {
                            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == hideResetValues[j]) {
                                    vm.state.rules.QuestionGroups[i].IsHidden = false;
                                }

                                if (vm.state.rules.QuestionGroups[i].GroupCode == 'ContentsSumInsured' && (dropdownValue == 'Contents' || dropdownValue == 'Building' || dropdownValue == 'Building and Contents')) {
                                    for (var n = 0; n < vm.state.rules.QuestionGroups[i].Questions.length; n++) {

                                        if (vm.state.rules.QuestionGroups[i].Questions[n].QuestionCode == 'Specific_Items') {
                                            if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == 'Yes') {
                                                isPresent = true;
                                            }
                                        }
                                        if (isPresent == true) {
                                            if (vm.state.rules.QuestionGroups[i].Questions[n].QuestionCode == 'AddSpecifiedItem') {
                                                vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue = '';
                                            }
                                        }

                                    }
                                }


                                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == hideResetValues[j]) {
                                        vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = false;
                                    }
                                }
                            }
                        }
                        var value = targetElementValue[l].RemoveValue;
                        for (var j = 0; j < value.length; j++) {
                            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {

                                if (vm.state.rules.QuestionGroups[i].GroupCode == value[j]) {
                                    vm.state.rules.QuestionGroups[i].IsHidden = true;
                                    matchFound = true;
                                }
                                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == value[j]) {
                                        vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = true;
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Specified_Items_List") {
                                            vm.valueCheckForSpecified = dropdownValue;
                                        }
                                        matchFound = true;

                                    }
                                }
                            }
                        }
                    }
                    else if (!reverseHiddenCondition) {
                        for (var j = 0; j < hideResetValues.length; j++) {
                            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == hideResetValues[j]) {
                                    vm.state.rules.QuestionGroups[i].IsHidden = true;
                                }
                                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == hideResetValues[j]) {
                                        vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = true;
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Specified_Items_List") {
                                            vm.valueCheckForSpecified = dropdownValue;
                                        }
                                    }
                                }
                            }
                        }
                        if (dropdownValue == targetElementValue[l].RemoveKey) {
                            var value = targetElementValue[l].RemoveValue;
                            for (var j = 0; j < value.length; j++) {
                                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                                    if (vm.state.rules.QuestionGroups[i].GroupCode == value[j]) {
                                        vm.state.rules.QuestionGroups[i].IsHidden = false;
                                        matchFound = true;
                                    }
                                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == value[j]) {
                                            vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = false;// should be true
                                            matchFound = true;
                                        }
                                    }
                                }
                            }
                        }

                    }
                    else {
                        var value = targetElementValue[l].RemoveValue;
                        for (var j = 0; j < value.length; j++) {
                            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == value[j]) {
                                    vm.state.rules.QuestionGroups[i].IsHidden = false;
                                    vm.isHiddenValue.pop(value[j]);
                                }
                                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == value[j]) {
                                        vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = false;
                                        vm.isHiddenValue.pop(value[j]);
                                    }
                                }
                            }
                        }
                    }

                }
            }


            if (vm.valueCheckForSpecified == "No") {
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Specified_Items_List") {
                            vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = true;
                        }
                    }

                }
            }

            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == 'Coverage_BuildingType') {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue != 'Townhouse' && vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue != 'Duplex' && vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue != 'Apartment' && vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue != 'BlockOfUnits') {
                            vm.hideStrata(true);
                        }
                        else {
                            vm.hideStrata(false);
                        }
                    }

                }

            }
        }
        vm.hideStrata = function (hideCheck) {

            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Coverage_PartOfStartaPlan") {
                        if (hideCheck) {
                            vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = true;
                        }
                        else {
                            vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = false;
                        }
                    }
                }
            }
        }


        vm.StrataPlanCheck = function (selectedValue, QuestionCode) {
            var isStrataSelectd = false;
            var isBuildingType = false;
            var isCoverageType = false;
            var isOccupancyType = false;
            var isOtherOccupancyType = false;
            var isNursingHome = false;
            //  var buildingType = "";
            if (selectedValue == "Townhouse" || selectedValue == "Apartment" || selectedValue == "Duplex" || selectedValue == "Townhouse" || selectedValue == "Building and Contents" || selectedValue == "Building" || QuestionCode == 'Coverage_PartOfStartaPlan' || selectedValue == 'BlockOfUnits') {
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    for (var n = 0; n < vm.state.rules.QuestionGroups[i].Questions.length; n++) {
                        if (vm.state.rules.QuestionGroups[i].Questions[n].QuestionCode == 'Coverage_PartOfStartaPlan') {
                            if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Yes")
                                isStrataSelectd = true;
                        }

                        if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Townhouse" || vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Duplex") {
                            isBuildingType = true;
                        }
                        if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Apartment" || vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "BlockOfUnits") {
                            isOtherOccupancyType = true;
                            //     buildingType = selectedValue;
                        }
                        //if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Apartment" || vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "sf:NursingHomeUnit") {
                        //    isOtherOccupancyType = true;
                        //}

                        if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Building and Contents" || vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Building") {
                            isCoverageType = true;
                        }
                        if (vm.state.rules.QuestionGroups[i].Questions[n].QuestionCode == "Coverage_OccupancyType") {
                            if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue == "Tenant")
                                isOccupancyType = false;//true in case of home
                        }

                    }
                }
                if ((isCoverageType && isBuildingType && isStrataSelectd) || isOccupancyType || isOtherOccupancyType) {
                    for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                        for (var n = 0; n < vm.state.rules.QuestionGroups[i].Questions.length; n++) {
                            if (vm.state.rules.QuestionGroups[i].Questions[n].QuestionCode == "Coverage_CoverageType") {
                                if (vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue != "Contents") {
                                    vm.state.rules.QuestionGroups[i].Questions[n].DefaultValue = "Contents Only";
                                    vm.state.rules.QuestionGroups[i].Questions[n].SelectedValue = "Contents";
                                    //  vm.state.rules.QuestionGroups[i].Questions[n].ReadOnly = true;
                                    vm.modalHead = "Invalid Cover Type";
                                    if (!isOccupancyType && !isOtherOccupancyType)
                                        vm.message = "Only Contents Cover type is allowed when Part of Strata Plan.";
                                    else if (!isOccupancyType)
                                        vm.message = "Only Contents Cover type is allowed for this building type.";
                                    else
                                        vm.message = "Only Contents Cover type is allowed for this occupancy type.";
                                    vm.loading = false;
                                    $("#claimModel").modal({
                                        backdrop: 'static',
                                        keyboard: false
                                    });
                                    document.getElementById("onTop").scrollIntoView();

                                    vm.dropdownChanged("Contents", vm.state.rules.QuestionGroups[i].Questions[n].HiddenValue, true, vm.state.rules.QuestionGroups[i].Questions[n].HideResetValues)
                                }
                            }
                        }
                    }
                }
                else {
                    for (var p = 0; p < vm.state.rules.QuestionGroups.length; p++) {
                        for (var k = 0; k < vm.state.rules.QuestionGroups[p].Questions.length; k++) {
                            if (vm.state.rules.QuestionGroups[p].Questions[k].QuestionCode == "Coverage_CoverageType") {
                                vm.state.rules.QuestionGroups[p].Questions[k].ReadOnly = false;
                            }
                        }
                    }

                }

            }
        }

        vm.agreementChange = function (val) {

            if (val == undefined) {
                vm.agreement = false;
            }
            else
                vm.agreement = val
        }

        vm.Validformfun = function (validform) {

            var val = document.getElementById("getQuickQuote");
            vm.ValidForm1 = validform;
            if (vm.ValidForm1) {
                if (document.getElementById("getQuickQuote") != null)
                    document.getElementById("getQuickQuote").title = "";
            } else {
                if (document.getElementById("getQuickQuote") != null)
                    document.getElementById("getQuickQuote").title = "Please complete all questions above to submit your quote.";
            }
            return true;
        }



        vm.setQuestionsView = function (val) {
            if (!val) {
                vm.showHideQuestions = false;
                vm.showfinalMessage = true;
                vm.showChoice = false;


                homeService.clearState();
                //    $timeout(function () {
                //        window.location.reload(history.go(-1))
                //}, 3000);


            }
            else {
                vm.showHideQuestions = true;
                vm.showfinalMessage = false;
                vm.showChoice = false;

            }

        }

        vm.RemoveInterestedParties = function (answerSelected, questionCode) {
            var isInterestedPartyPresent = false;
            var isOtherinterestedParty = false;
            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Interested_Party") {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue == 'Other')
                            isOtherinterestedParty = true;

                    }
                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Interested_InterestedParties") {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue == 'Yes')
                            isInterestedPartyPresent = true;

                    }
                }
            }
            if (isInterestedPartyPresent && isOtherinterestedParty) {
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Interested_Party_Other") {
                            vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = false;

                        }
                    }
                }
            }
            else {
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Interested_Party_Other") {
                            vm.state.rules.QuestionGroups[i].Questions[k].IsHidden = true;

                        }
                    }
                }

            }
        }
        vm.agreementChange = function (val) {

            if (val == undefined) {
                vm.agreement = false;
            }
            else
                vm.agreement = val
        }

        vm.Validformfun = function (validform) {

            var val = document.getElementById("getQuickQuote");
            vm.ValidForm1 = validform;
            if (vm.ValidForm1) {
                if (document.getElementById("getQuickQuote") != null)
                    document.getElementById("getQuickQuote").title = "";
            } else {
                if (document.getElementById("getQuickQuote") != null)
                    document.getElementById("getQuickQuote").title = "Please complete all questions above to submit your quote.";
            }
            return true;
        }

        vm.setQuestionsView = function (val) {
            if (!val) {
                vm.showHideQuestions = false;
                vm.showfinalMessage = true;
                vm.showChoice = false;


                LandlordService.clearState();
                //    $timeout(function () {
                //        window.location.reload(history.go(-1))
                //}, 3000);


            }
            else {
                vm.showHideQuestions = true;
                vm.showfinalMessage = false;
                vm.showChoice = false;

            }

        }
        vm.RemoveBuildingValue = function (dropDownValue, questionCode) {

            if (questionCode == "Coverage_BuildingType" || questionCode == "Coverage_OccupancyType") {
                if ((dropDownValue == "Townhouse" || dropDownValue == "NursingHomeUnit" || dropDownValue == "Duplex" || dropDownValue == "Apartment")) {//|| dropDownValue == "Tenant"
                    for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                        for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                            if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Coverage_CoverageType") {
                                vm.state.rules.QuestionGroups[i].Questions[k].DefaultValue = "Contents Only";
                                vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue = "Contents";
                                vm.state.rules.QuestionGroups[i].Questions[k].ReadOnly = true;
                                vm.dropdownChanged("Contents", vm.state.rules.QuestionGroups[i].Questions[k].HiddenValue, true, vm.state.rules.QuestionGroups[i].Questions[k].HideResetValues)
                            }
                        }
                    }
                }
                else {
                    for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                        for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                            if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Coverage_CoverageType") {
                                vm.state.rules.QuestionGroups[i].Questions[k].ReadOnly = false;
                            }
                        }
                    }
                }
            }

        }

        vm.BuildingAndContentExcess = function (dropDownValue, questionCode) {
            if (questionCode == "ExcessOptions_BuildingExcess2" || questionCode == "ExcessOptions_ContentsExcess2" || questionCode == "ExcessOptions_BuildingExcess3" || questionCode == "ExcessOptions_ContentsExcess3") {
                var coverType = "";
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    if (vm.state.rules.QuestionGroups[i].GroupCode == "Coverage") {
                        for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                            if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Coverage_CoverageType") {
                                coverType = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            }
                        }
                    }
                }
                if (coverType != "Contents" && coverType != "Building" && coverType != "") {
                    if (questionCode == "ExcessOptions_BuildingExcess2") {
                        for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                            if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonContent") {
                                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_ContentsExcess2") {
                                        vm.state.rules.QuestionGroups[i].Questions[k].Required = true;
                                    }
                                }
                            }
                        }
                    }
                }
                if (coverType != "Contents" && coverType != "Building" && coverType != "") {
                    if (questionCode == "ExcessOptions_ContentsExcess2") {
                        for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                            if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonBuilding") {
                                for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                    if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_BuildingExcess2") {
                                        vm.state.rules.QuestionGroups[i].Questions[k].Required = true;
                                    }
                                }
                            }
                        }
                    }
                }
                if (coverType != "Contents") {
                    if (questionCode == "ExcessOptions_BuildingExcess3") {
                        for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                            if (coverType != "Building" && coverType != "") {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonContent") {
                                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_ContentsExcess3") {
                                            vm.state.rules.QuestionGroups[i].Questions[k].Required = true;
                                        }
                                    }
                                }
                            }
                            else {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonBuilding") {
                                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_BuildingExcess2") {
                                            vm.state.rules.QuestionGroups[i].Questions[k].Required = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (coverType != "Building") {
                    if (questionCode == "ExcessOptions_ContentsExcess3") {
                        for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                            if (coverType != "Contents" && coverType != "") {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonBuilding") {
                                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_BuildingExcess3") {
                                            vm.state.rules.QuestionGroups[i].Questions[k].Required = true;
                                        }
                                    }
                                }
                            }
                            else {
                                if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonContent") {
                                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_ContentsExcess2") {
                                            vm.state.rules.QuestionGroups[i].Questions[k].Required = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }
        }

        vm.claimsCheck = function () {
            var excessBuilding1 = "";
            var excessBuilding2 = "";
            var excessBuilding3 = "";
            var excessContent1 = "";
            var excessContent2 = "";
            var excessContent3 = "";
            var coverType = "";
            for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                if (vm.state.rules.QuestionGroups[i].GroupCode == "Coverage") {
                    for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                        if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "Coverage_CoverageType") {
                            coverType = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                        }
                    }
                }
                if (coverType != "Contents") {
                    if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonBuilding") {

                        for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                            if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_BuildingExcess1") {
                                excessBuilding1 = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            } else if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_BuildingExcess2") {
                                excessBuilding2 = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            } else if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_BuildingExcess3") {
                                excessBuilding3 = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            }
                        }
                    }
                }
                if (coverType != "Building") {
                    if (vm.state.rules.QuestionGroups[i].GroupCode == "ExcessOptionsForComparisonContent") {
                        for (var k = 0; k < vm.state.rules.QuestionGroups[i].Questions.length; k++) {
                            if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_ContentsExcess1") {
                                excessContent1 = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            } else if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_ContentsExcess2") {
                                excessContent2 = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            } else if (vm.state.rules.QuestionGroups[i].Questions[k].QuestionCode == "ExcessOptions_ContentsExcess3") {
                                excessContent3 = vm.state.rules.QuestionGroups[i].Questions[k].SelectedValue;
                            }
                        }
                    }
                }
            }
            if (coverType == "Building") {
                if (excessBuilding2 != null) {
                    if (excessBuilding1 == excessBuilding2 || excessBuilding2 == excessBuilding3 || excessBuilding3 == excessBuilding1) {
                        vm.modalHead = "Error"
                        vm.message = "Building Excess Option 2 cannot be the same as Building Excess Option 1 or 3";
                        $("#claimModel").modal();
                        vm.claimsCheckFlag = false;
                    }
                }
            }
            else if (coverType == "Contents") {
                if (excessContent2 != null) {
                    if (excessContent1 == excessContent1 || excessContent2 == excessContent3 || excessContent3 == excessContent1) {
                        vm.modalHead = "Error"
                        vm.message = "Content Excess Option 2 cannot be the same as Content Excess Option 1 or 3";
                        $("#claimModel").modal();
                        vm.claimsCheckFlag = false;
                    }
                }
            }
            else {
                if (excessBuilding2 != null && excessContent2 != null) {
                    if ((excessBuilding1 == excessBuilding2 && excessContent1 == excessContent1) || (excessBuilding2 == excessBuilding3 && excessContent2 == excessContent3) || (excessBuilding3 == excessBuilding1 && excessContent3 == excessContent1)) {
                        vm.modalHead = "Error"
                        vm.message = "Building and Content Excesses Option 2 cannot be the same as Building and Contents Excesses Option 1 or 3";
                        $("#claimModel").modal();
                        vm.claimsCheckFlag = false;
                    }
                }
            }
        }

        vm.AddCalimsYear = function () {

            vm.addButtonCount = vm.addButtonCount + 1;
            vm.SpecifiedItems.push({ Year: "Year", YearValue: "", TypeOfClaims: "TypeOfClaims", TypeOfClaimsValue: "", Required: true })

        }

        vm.RemoveClaims = function (dropDownValue, questionCode) {
            if (questionCode == "Other_ClaimIn3Years" && dropDownValue) {
                if (vm.SpecifiedItems.length > 0) {
                    vm.SpecifiedItems = [];
                }
            }
        }

        vm.RemoveCalimYears = function (index) {
            vm.addButtonCount = vm.addButtonCount - 1;
            vm.SpecifiedItems.pop(index);
        }

        vm.validateCaptcha = function () {

            vm.loading = true;
            //   window.scrollTo(0, document.body.scrollHeight);
            // $window.scrollTo(0, angular.element('onTop').offsetTop); 

            if (vm.state.captcha.response == null) {
                vm.modalHead = "Mandatory Field Required"
                vm.message = "Please complete the \"I'm not a Robot\" question to obtain your quote.";
                vm.loading = false;

                $("#claimModel").modal({
                    backdrop: 'static',
                    keyboard: false
                });
                //   $anchorScroll('onTop');
            }
            else if (vm.agreement == false) {
                vm.modalHead = "Mandatory Field Required"
                vm.message = "Please review and agree to our terms of use before clicking Get quick quote.";
                vm.loading = false;
                $("#claimModel").modal({
                    backdrop: 'static',
                    keyboard: false
                });
            }
            else {
                LandlordService.validateCaptchaSer(vm.state.captcha.response).then(function (response) {

                    if (vm.checkRefrralRequired) {
                        vm.loading = false;
                        vm.getPremium();
                    }
                    if (!vm.checkRefrralRequired) {

                        if (true) {
                            window.scroll(0, 0);
                            vm.getPremium();
                        }
                        else {
                            vm.loading = false;
                            $window.location.pathname = '/Home/Error';
                        }
                    }
                });
            }
        }

        vm.getPremium = function () {

            if (true) {
                LandlordService.storeState(vm.state);
                var questionAnswer = [];
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    var questions = vm.state.rules.QuestionGroups[i].Questions;
                    for (var j = 0; j < questions.length; j++) {
                        if (questions[j].QuestionType != "ShadedLabel" && questions[j].QuestionType != "Label" && questions[j].QuestionType != "ValueList" && questions[j].QuestionType != "Address") {
                            questionAnswer.push(
                                {
                                    Question: questions[j].QuestionCode,
                                    Answer: questions[j].SelectedValue,
                                    ComplexAnswer: []
                                });
                        }
                        if (questions[j].QuestionType == "ValueList") {
                            questionAnswer.push(
                                {
                                    Question: questions[j].QuestionCode,
                                    Answer: questions[j].SelectedValue,
                                    ComplexAnswer: getAnswerList()
                                });
                        }
                        if (questions[j].QuestionType == "Address") {
                            questionAnswer.push(
                                {
                                    Question: questions[j].QuestionCode,
                                    Answer: vm.state.address + "~" + vm.state.moniker,
                                    ComplexAnswer: []
                                })
                        }
                    }
                }
                function getAnswerList() {
                    var answerList = [];
                    angular.forEach(vm.SpecifiedItems, function (value, key) {
                        answerList.push({ key: value.YearValue, value: value.TypeOfCalimsValue });
                    });
                    return answerList;
                }
                var request = { questionAnswers: questionAnswer, packageName: "Landlord" };
                vm.loading = true;
                vm.disabled = true;
                vm.request.push(request);
                // LandlordService.saveReferrals(request,
                //    function (resp) {

                //        vm.loading = false;
                //        vm.disabled = false;
                //        vm.setDisplayCoverages(resp);
                //    },
                //    function (error) {
                //        vm.loading = false;
                //        vm.disabled = false;
                //        console.log(error);
                //    }
                //);

                LandlordService.qualifiedQuotes(request,
                    function (resp) {

                        vm.loading = false;
                        vm.disabled = false;
                        vm.setDisplayCoverages(resp);
                    },
                    function (error) {
                        vm.loading = false;
                        vm.disabled = false;
                        console.log(error);
                    }
                );
            }

        }

        vm.ShowLabel = function (question) {
            if (question.QuestionType == 'CheckBox') {
                return false;
            }

            if (question.QuestionType == 'ShadedLabel') {
                return false;
            }

            if (question.QuestionType == 'ValueList') {
                return false;
            }

            if (question.IsHidden == true) {
                return false;
            }
            return true;
        }

        vm.AddHelp = function (question) {

            if (question.QuestionCode == 'Specific_Items') {
                return true;
            }
            if (question.QuestionCode == 'Building_BuildingReplacementValue') {
                if (vm.showBSI == true)
                    return false;
                else
                    return true;
            }
            if (question.QuestionCode == 'SumInsured_ContentsSumInsured') {
                if (vm.showBSI == true)
                    return false;
                else
                    return true;
            }
            return false;
        }

        vm.alert = function (ev, val, code) {

            if (val == 1) {
                if (code.QuestionCode == 'Specific_Items') {
                    $scope.isDisabled = true;
                    if (this.count == 0) {
                        this.count = this.count + 1;
                        $mdDialog.show({

                            parent: angular.element(document.body),
                            clickOutsideToClose: false,
                            bindToController: true,
                            backdrop: false,
                            controllerAs: 'dialogCtrl',
                            templateUrl: '/image/HelpSpecificItems.html',
                            windowClass: 'large-Modal',
                            controller: function dialogCtrl() {
                                this.click = function click() {
                                    $scope.isDisabled = false;
                                    $mdDialog.hide();
                                    $mdDialog.cancel();
                                };
                            }
                        })
                    } else {
                        $scope.isDisabled = false;
                        this.showDiv = true;
                        $mdDialog.hide();
                    }
                }
                else if (code.QuestionCode == 'Building_BuildingReplacementValue') {
                    $scope.isDisabled = false;
                    if (this.countBSI == 0) {
                        this.countBSI = this.countBSI + 1;
                        this.showDiv = true;
                        $scope.showSecond = false;
                        $mdDialog.show({

                            parent: angular.element(document.body),
                            clickOutsideToClose: false,
                            bindToController: true,
                            backdrop: false,
                            controllerAs: 'dialogCtrl',
                            templateUrl: '/image/HelpRequiredLevelOfCover.html',
                            windowClass: 'large-Modal',
                            controller: function dialogCtrl() {
                                this.click = function click() {
                                    $scope.isDisabled = false;
                                    $mdDialog.hide();
                                    $mdDialog.cancel();
                                };
                            }
                        })
                    } else {
                        $scope.isDisabled = false;
                        this.showDiv = true;
                        $mdDialog.hide();
                    }
                }
                else if (code.QuestionCode == 'SumInsured_ContentsSumInsured') {
                    $scope.isDisabled = false;
                    if (this.countSI == 0) {
                        this.countSI = this.countSI + 1;
                        this.showDiv = true;
                        $scope.showSecond = false;
                        $mdDialog.show({

                            parent: angular.element(document.body),
                            clickOutsideToClose: false,
                            bindToController: true,
                            backdrop: false,
                            controllerAs: 'dialogCtrl',
                            templateUrl: '/image/HelpRequiredLevelOfCover.html',
                            windowClass: 'large-Modal',
                            controller: function dialogCtrl() {
                                this.click = function click() {
                                    $scope.isDisabled = false;
                                    $mdDialog.hide();
                                    $mdDialog.cancel();
                                };
                            }
                        })
                    } else {
                        $scope.isDisabled = false;
                        this.showDiv = true;
                        $mdDialog.hide();
                    }
                }
            }
            else if (val == 3) {
                vm.state.displayNewBusinessQuote = false
                vm.state.displayCoverages = false;
                vm.completeQuote = true;
                vm.showTitle = false;
                //$mdDialog.show({

                //    parent: angular.element(document.body),
                //    clickOutsideToClose: false,
                //    bindToController: true,
                //    backdrop: false,
                //    locals: {
                //        brokerName: vm.brokerName,
                //        brokerEmail: vm.brokerEmail,
                //        brokerPhoneNumber: vm.brokerPhoneNumber,
                //        brokerQuoteNumber: vm.quoteNumber
                //    },

                //    controllerAs: 'dialogCtrl',
                //    templateUrl: '/image/ThankYouNote.html',

                //    controller: function dialogCtrl(brokerName, brokerEmail, brokerPhoneNumber, brokerQuoteNumber) {
                //        var self = this;
                //        self.brokerName = brokerName;
                //        self.brokerEmail = brokerEmail;
                //        self.brokerPhoneNumber = brokerPhoneNumber;
                //        self.brokerQuoteNumber = brokerQuoteNumber;
                //        this.click = function click() {
                //            $scope.isDisabled = false;
                //            $mdDialog.hide();
                //        };

                //    }
                //});
            }

            else {
                if (code.QuestionCode == 'Specific_Items') {

                    $mdDialog.show({

                        parent: angular.element(document.body),
                        clickOutsideToClose: false,
                        bindToController: true,
                        backdrop: false,
                        controllerAs: 'dialogCtrl',
                        templateUrl: '/image/HelpSpecificItems.html',
                        controller: function dialogCtrl() {
                            this.click = function click() {
                                $scope.isDisabled = false;
                                $mdDialog.hide();
                                $mdDialog.cancel();
                            };
                        }
                    })

                }
                else if (code.QuestionCode == 'Building_BuildingReplacementValue') {

                    $scope.showSecond = false;
                    this.showDiv = true;
                    $mdDialog.show({

                        parent: angular.element(document.body),
                        clickOutsideToClose: false,
                        bindToController: true,
                        backdrop: false,
                        controllerAs: 'dialogCtrl',
                        templateUrl: '/image/HelpRequiredLevelOfCover.html',
                        controller: function dialogCtrl() {
                            this.click = function click() {
                                $scope.isDisabled = false;
                                $mdDialog.hide();
                                $mdDialog.cancel();
                            };
                        }
                    })

                }
                else if (code.QuestionCode == 'SumInsured_ContentsSumInsured') {

                    $scope.showSecond = false;
                    this.showDiv = true;
                    $mdDialog.show({

                        parent: angular.element(document.body),
                        clickOutsideToClose: false,
                        event: ev,
                        bindToController: true,
                        backdrop: false,
                        controllerAs: 'dialogCtrl',
                        templateUrl: '/image/HelpRequiredLevelOfCover.html',
                        controller: function dialogCtrl() {
                            this.click = function click() {
                                $scope.isDisabled = false;
                                $mdDialog.hide();
                                $mdDialog.cancel();
                            };
                        }
                    })

                }
            }
        };

        vm.mailSend = function () {
            vm.setSeeInLastValues();

        }

        vm.setSeeInLastValues = function () {
            if (true) {
                LandlordService.storeState(vm.state);

                var questionAnswerInLast = [];
                for (var i = 0; i < vm.state.rules.QuestionGroups.length; i++) {
                    var questions = vm.state.rules.QuestionGroups[i].Questions;

                    for (var j = 0; j < questions.length; j++) {
                        if (questions[j].SeeInLast == true && questions[j].QuestionCode != "Building_Address" && questions[j].QuestionCode != "Coverage_CoverageType") {
                            if (questions[j].QuestionType != "ShadedLabel" && questions[j].QuestionType != "Label" && questions[j].QuestionType != "ValueList" && questions[j].QuestionType != "Address") {
                                questionAnswerInLast.push(
                                    {
                                        Question: questions[j].QuestionCode,
                                        Answer: questions[j].SelectedValue,
                                    });
                            }
                        }
                    }
                }
                for (var i = 0; i < vm.request.length; i++) {
                    for (var j = 0; j < vm.request[i].questionAnswers.length; j++) {
                        if (vm.request[i].questionAnswers[j].Question == "Email" || vm.request[i].questionAnswers[j].Question == "Phone_Number") {
                            questionAnswerInLast.push(
                                     {
                                         Question: vm.request[i].questionAnswers[j].Question,
                                         Answer: vm.request[i].questionAnswers[j].Answer,
                                     });
                        }
                    }
                }
                if (true) {

                    for (var i = 0; i < questionAnswerInLast.length; i++) {
                        if (questionAnswerInLast[i].Question.indexOf("Interested") == -1 && questionAnswerInLast[i].Question != "Coverage_PropertyLocatedOn") {
                            {

                                if (questionAnswerInLast[i].Answer == "Yes") {
                                    vm.promptflag = false;
                                }
                                else if (questionAnswerInLast[i].Question == "Other_CriminalConvictionsIn3Years") {
                                    if (questionAnswerInLast[i].Answer != 0)
                                        vm.promptflag = false;
                                }
                            }
                        }
                    }
                    if (vm.promptflag == true) {
                        vm.alert(MouseEvent, 3)
                    }
                    else {
                        vm.state.displayNewBusinessQuote = false
                        vm.state.displayCoverages = false;
                        vm.referralQuote = true;
                        vm.showTitle = false;
                    }
                }

                var mailToBroker = [];
                mailToBroker.push({
                    QuoteRequest: vm.request,
                    QuoteResponse: vm.state.quoteResponse,
                    SendMail: false,
                    IsRefrral: false,
                    isUpdateRequired: false,
                    isSubmitValues: true,
                    QuestionAnswersSeenInLast: questionAnswerInLast
                });
                //if (vm.promptflag) {
                if (vm.mailFlag) {
                    LandlordService.mailSendService(mailToBroker,
                        function (resp) {

                            vm.loading = false;
                            vm.disabled = false;

                        },
                        function (error) {
                            vm.loading = false;
                            vm.disabled = false;
                            console.log(error);
                        }
                    );
                    vm.mailFlag = false;
                }
                //  }
            }
        }


        vm.buttonStatus = function () {

        }

        vm.checkSeeInLastCondition = function (objQuestionGroups) {
            for (var j = 0; j < objQuestionGroups.Questions.length; j++) {
                if (objQuestionGroups.Questions[j].SeeInLast == true) {
                    return true;
                }
            }
            return false;
        }

        vm.SingleQuestion = function (objQuestionGroups) {
            if (objQuestionGroups.Questions.length < 2) {
                if (objQuestionGroups.Questions[0].IsHidden == true)
                    return false;
            }
            return true;
        }
        vm.checkNotSeeInLastCondition = function (objQuestionGroups) {
            for (var j = 0; j < objQuestionGroups.Questions.length; j++) {
                if (objQuestionGroups.Questions[j].SeeInLast != true) {
                    return true;
                }
            }
            return false;
        }

        vm.ShowPanel = function (questionGroups) {
            if (questionGroups.IsHidden == true) {
                return false;
            }
            return true;
        }


        vm.ngModelOptionsSelected = function (value) {
            if (arguments.length) {
                _selected = value;
            } else {
                return _selected;
            }
        };

        vm.setDisplayCoverages = function (quoteResponse) {
            //  $anchorScroll('onTop');
            vm.state.quoteResponse = quoteResponse;
            vm.state.frequency = [];
            vm.brokerEmail = quoteResponse.Email;
            vm.brokerName = quoteResponse.BrokerName;
            vm.brokerPhoneNumber = quoteResponse.PhoneNumber;
            vm.quoteNumber = quoteResponse.QuoteNumber;
            vm.state.quoteMessage = quoteResponse.CustomQuoteMessage;
            $anchorScroll();
            if (vm.state.quoteResponse.Messages != null && vm.state.quoteResponse.Messages.length > 0) {
                var setReferralValues = [];
                var lastRequest = [];
                lastRequest.push(vm.request[vm.request.length - 1]);
                setReferralValues.push({
                    QuoteRequest: lastRequest,
                    QuoteResponse: vm.state.quoteResponse,
                    IsRefrral: true,
                    isUpdateRequired: false,
                    isSubmitValues: false
                });
                LandlordService.mailSendService(setReferralValues,
                    function (resp) {

                        vm.loading = false;
                        vm.disabled = false;
                    },
                    function (error) {
                        vm.loading = false;
                        vm.disabled = false;
                        console.log(error);

                    }


                );

                var messages = [];
                for (var i = 0; i < vm.state.quoteResponse.Messages.length; i++) {
                    var addNew = true;
                    for (var j = 0; j < messages.length; j++) {
                        if (vm.state.quoteResponse.Messages[i] == messages[j]) {
                            addNew = false;
                            break;
                        }
                    }
                    if (addNew) {
                        messages.push(vm.state.quoteResponse.Messages[i]);
                    }

                }
                if (messages.indexOf('"') > -1) {
                    for (var i = 0; i < messages.length; i++) {
                        if (messages[i] == "") {
                            messages.splice(i, 1)
                        }
                    }
                }
                vm.checkRefrralRequired = true;
                // messages = 'We are unable to provide you a quote at this stage. We have your quote details and will be in contact with you within 24 hours. If you wish to contact us in the meantime please do call us on ' + $scope.BrokerPhoneNumberMsg;
                vm.state.quoteResponse.Messages = messages;
                vm.state.displayError = true;
                vm.state.displayCoverages = false;

            }
            else {
                vm.checkRefrralRequired = false;
                for (var i = 0; i < vm.state.quoteResponse.Coverages.length; i++) {
                    if (vm.state.frequency.filter(function (f) {
                        return f === vm.state.quoteResponse.Coverages[i].Frequency;
                    }).length == 0) {
                        vm.state.frequency.push(vm.state.quoteResponse.Coverages[i].Frequency);
                    }

                }
                vm.state.coverages = [];
                for (var j = 0; j < vm.state.quoteResponse.Coverages.length; j++) {
                    if (vm.state.coverages.filter(function (f) {
                        return f === vm.state.quoteResponse.Coverages[j].CoverageName;
                    }).length == 0) {
                        vm.state.coverages.push(vm.state.quoteResponse.Coverages[j].CoverageName);
                        vm.state.coveragesType.push(vm.state.quoteResponse.Coverages[j].CoverageType.replace(/['"]+/g, ''));
                    }

                }
                if (vm.state.coveragesType[0] == "Building Only") {
                    vm.fileName.splice(1, 1)
                }
                else if (vm.state.coveragesType[0] == "Contents Only") {
                    vm.fileName.splice(0, 1)
                }
                else vm.devide = true
                vm.state.displayError = false;
                vm.state.displayCoverages = true;
                vm.showTitle = false;
                vm.state.displayNewBusinessQuote = false;
                var lastRequest = [];
                lastRequest.push(vm.request[vm.request.length - 1]);
                var setUpdatedValues = [];
                setUpdatedValues.push({
                    QuoteRequest: lastRequest,
                    QuoteResponse: vm.state.quoteResponse,
                    IsRefrral: false,
                    isUpdateRequired: true,
                    isSubmitValues: false

                });
                LandlordService.mailSendService(setUpdatedValues,
                    function (resp) {
                        vm.loading = false;
                        vm.disabled = false;

                    },
                    function (error) {
                        vm.loading = false;
                        vm.disabled = false;
                        console.log(error);

                    }
                );
            }

            LandlordService.storeState(vm.state);

        }

        vm.goBack = function () {

            vm.state.displayCoverages = false;
            LandlordService.storeState(vm.state);
        }
        vm.loadFrame = function () {
            //homeService.clearState();

            location.reload();

            setTimeout(function () {
                vm.showTitle = false;
                vm.state.displayNewBusinessQuote = true;
                vm.referralQuote = false;
                vm.completeQuote = false;
                vm.state.displayCoverages = false;
            }, 5000);
            //vm.showTitle = true;
            //vm.state.displayNewBusinessQuote = true;
            //vm.referralQuote = false;
            //vm.completeQuote = false;
            //vm.state.displayCoverages = false;
            LandlordService.clearState();

        }
        vm.goBack = function () {
            vm.state.displayNewBusinessQuote = true;
            vm.state.displayCoverages = false;
            LandlordService.storeState(vm.state);
        }

        vm.getCoveragePremium = function (coverage, frequency, excess) {
            var premium = 0.00;
            if (excess == 500) {

                for (var i = 0; i < vm.state.quoteResponse.Coverages.length; i++) {
                    if (vm.state.quoteResponse.Coverages[i].Frequency == frequency
                        && vm.state.quoteResponse.Coverages[i].CoverageName == coverage) {
                        premium = vm.state.quoteResponse.Coverages[i].Premium;
                        //  vm.state.quoteResponse.Coverages.splice(i,1)
                        return premium;
                    }
                }
            }
            else {
                for (var i = 2; i < vm.state.quoteResponse.Coverages.length; i++) {
                    if (vm.state.quoteResponse.Coverages[i].Frequency == frequency
                        && vm.state.quoteResponse.Coverages[i].CoverageName == coverage) {
                        premium = vm.state.quoteResponse.Coverages[i].Premium;
                        //  vm.state.quoteResponse.Coverages.splice(i,1)
                        return premium;
                    }
                }
            }

            return premium;
        }

        vm.getCoverageName = function (coverage) {

            return AddSpace(coverage);
        }

        function AddSpace(string) {
            string = string.replace(/([a-z])([A-Z])/g, '$1 $2');
            string = string.replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')
            return string;
        }
        /**
         * Create filter function for a query string
         */
        function createFilterFor(query) {
            var lowercaseQuery = angular.lowercase(query);

            return function filterFn(item) {
                return (item.value.indexOf(lowercaseQuery) === 0);
            };


        }
        function selectedItemChange(item) {
            if (item) {
                vm.state.moniker = item.Moniker;
                vm.state.address = item.Address;
                //$log.info(vm.state.moniker);
                //$log.info(vm.state.address);
            }
            else {
                //   $log.info('invalid');
            }
        }
        /**
 * Search for repos... use $timeout to simulate
 * remote dataservice call.
 */
        function querySearch(query) {
            return $http.get('https://uatws.ial.com.au/api/B3U/GetResult?input=' + query + '&tkn=55123&BrokerCode=BRKBROKER_RC&userid=sbakshi')
                .then(function (response) {
                    if (response.data.CompacAddressList[0].Address == "") {
                        return false;
                    }
                    else {
                        return response.data.CompacAddressList;
                    }
                })
                .catch(function (error) {
                    return $q.reject({ msg: "Something went wrong." });
                });

        }
    };
})();
