PageSourceSearch

https://www.budget.ca/etc/designs/platform/landingpagelib/clientlib.min.26.08.26-RELEASE.js

js budget.ca collected 2026-10-03 21:20:31 UTC 816,027 bytes, 19,333 lines download raw bytes

1(function() {
2	'use strict';
3	
4	angular
5		.module('carRental')
6		.service('carGuideService', carGuideService);
7	
8	carGuideService.$inject = ['$http', '$q', 'utilityService', '$filter'];
9	
10	function carGuideService($http, $q, utilityService, $filter) {
11		var result = {
12			getVehicleTypeDisplayName: getVehicleTypeDisplayName,
13			getCountByVehicleType: getCountByVehicleType,
14			filterByVehicleClass: filterByVehicleClass,
15			getVehicleGroups: getVehicleGroups,
16			getVehicleClasses: getVehicleClasses,
17			filterBySpeacialFeatures: filterBySpeacialFeatures,
18			getOtherVehiclesList:getOtherVehiclesList,
19			getOrderedList:getOrderedList
20		};
21		
22		/**
23	     * Returns the default filter text for the vehicle filter
24	     * 
25	     * @param vehicleTypes	list of vehicle types supported in filter
26	     */
27		function getVehicleTypeDisplayName(data, vehicleTypes) {
28			var displayText;
29			if (angular.isDefined(vehicleTypes)) {
30				displayText = vehicleTypes[0].description + ' (' + getCountByVehicleType(data, vehicleTypes[0].cargroup) + ')';
31			}
32
33			return displayText;
34		}
35		
36	    /**
37	     * Returns the count of vehicles that matches the car class against the list passed
38	     * 
39	     * @param data contains the available vehicles
40	     * @param carGroup list of car classes
41	     */
42		function getCountByVehicleType(data, cargroup) {
43			var count = 0;
44			if (typeof cargroup === "object" && cargroup.length !== 0) {
45				angular.forEach(data, function(vehicle, key) {
46					if (utilityService.containsObject(vehicle.carClass, cargroup)) {
47						count++;
48					}
49				});
50			} else {
51				count = data.length; // count of all available cars
52			}
53			return count;
54		}
55		
56	    /**
57	     * Filters the set of vehicle classes from the available vehicles as filteredVehicles and the rest as additionalVehicles
58	     * 
59	     * @param data	contains the available vehicles
60	     * @param carClasses array of car classes
61	     */
62		function filterByVehicleClass(data, carClasses) {
63			
64			var filteredVehicles = []; // list of filtered vehicles
65
66			angular.forEach(data, function(vehicle, key) {
67				if(utilityService.containsObject(vehicle.carClass, getVehicleGroups(carClasses))) {
68					filteredVehicles.push(vehicle);
69				}
70			});
71
72			data = filteredVehicles;
73			return data;
74		}
75		
76	    /*
77	     * Takes object array of vehicle class objects and convert into string array of vehicle group code
78	     * 
79	     * @param vehicleClasses
80	     */
81	    function getVehicleGroups(vehicleClasses) {
82	    	var objArray = [];
83	    	var vehicleCarClass;
84	    	angular.forEach(vehicleClasses, function(vehicleClass) {
85	    		vehicleCarClass = vehicleClass.carClass ? vehicleClass.carClass : vehicleClass;
86	    		objArray.push(vehicleCarClass);
87	    	});
88	    	return objArray;
89	    }
90
91	    /**
92	     * Takes string vehicle type and returns corresponding car group object
93	     * 
94	     * @param vehicleGroups
95	     */
96	    function getVehicleClasses(vehicleGroups) {
97	    	var objArray = [];
98	    	var vehicleClass;
99	    	angular.forEach(vehicleGroups, function(vehicleGroup) {
100	    		vehicleClass = {'carClass' : vehicleGroup};
101	    		objArray.push(vehicleClass);
102	    	});
103	    	return objArray;
104	    }
105	    
106	    /**
107	    * Filter the car classes from the available vehicles by special features
108	    * 
109	    * @param data	contains the available vehicles
110	    * @specialFeatures	selected set of special features
111	    */
112	    function filterBySpeacialFeatures(data, specialFeatures) {
113
114		    var filteredVehicles = []; // list of filtered vehicles
115		    var filterCondition = {};
116	
117		    angular.forEach(specialFeatures, function(feature) {
118			    filterCondition[feature] = true;
119			    if (feature === "abg" || feature === "ABG") {
120				    filterCondition['abgquantity'] = {
121				    	'size': 6,
122				    	'condition': '>'
123				    };
124			    }
125		    });
126	
127		    var filteredVehicles = $filter('customFeaturesFilter')(data, filterCondition);	
128		    data = filteredVehicles;
129	
130		    return data;
131	    }
132	    
133	    /**
134	     * Function to get list of vehicles which couldn't make it to filtered fleet list
135	     * */
136	    
137	    function getOtherVehiclesList(fleetList, filteredList){
138	    	
139	    	var otherVehiclesList = [];
140	    	
141	    	angular.forEach(fleetList, function(vehicle, key) {
142				if(!utilityService.containsObject(vehicle, filteredList)) {
143					otherVehiclesList.push(vehicle);
144				}
145			});
146	    	
147	    	
148	    	return otherVehiclesList;
149	    	
150	    }
151	    /**
152	     * Function to get list of vehicles in the order authored on the car-guide page
153	     * */
154		function getOrderedList(apiFleetList,orderedList){
155			var newList = [];
156			angular.forEach(orderedList,function(value,key){
157				angular.forEach(apiFleetList , function(v,k){
158					if(value == v.makeModel){
159						newList.push(v);
160					}
161				});
162			});
163			return newList;
164		}
165		
166		return result;
167	}
168})();
169(function() {
170	'use strict';
171
172	angular
173		.module('carRental')
174		.controller('CarGuide', CarGuide);
175
176	CarGuide.$inject = ['$scope', '$rootScope', '$window', 'carRentalConstant', 'carGuideService', '$timeout', '$filter'];
177
178	function CarGuide($scope, $rootScope, $window, carRentalConstant, carGuideService, $timeout, $filter) {
179		
180		// vm object
181		var vm = this;
182		
183		// View Callable
184		vm.fleetInfo = fleetInfo;
185		vm.fleetReset = fleetReset;
186		//vm.selectCountry = selectCountry;
187		vm.toggleFilters = toggleFilters;
188		vm.getCarCountByClass = getCarCountByClass;
189		vm.filterVehicle = filterVehicle;
190		vm.getFeatureCount = getFeatureCount;
191		vm.showFeaturesForMobile = showFeaturesForMobile;
192		vm.specialFeatureDialogClose = specialFeatureDialogClose; 
193        vm.step1ARedirect = step1ARedirect;
194        vm.updateMobileView = updateMobileView;
195		vm.assignSelectedVehicleType = assignSelectedVehicleType;
196		vm.openSpecialFeatureModal = openSpecialFeatureModal;
197		vm.redirectCarGuidePage = redirectCarGuidePage;
198		vm.getFleetData = getFleetData;
199		// variables
200		vm.selectedCountry = {};
201		vm.fleetList = {};
202		vm.availableCarClass
203		vm.fleetFilteredList = [];
204		vm.filteredCarClass = [];
205		vm.vehicleTypes = {};
206		vm.specialFeaturesList = {};
207		vm.vehicleTypeDisplayName = carRentalConstant.defaultVehicleTypeDesc;
208		vm.vehicleTypeListDisplay = false;
209		vm.disableVehicleType = true;
210		vm.displayedVehicleType = carRentalConstant.defaultDisplayedVehicleType;
211		vm.selectedFeatures = {
212	      'list': []
213	    };
214		vm.otherfleet={};
215	    vm.fleetFeatures = {};
216	    vm.mobileSelectedVehicleType = {};
217		vm.orderedList = $window.orderedList;
218		vm.enableOrdering = $window.enableAuthorSort;
219		vm.filteredSearch = false;
220		
221		// Private Methods //
222		vm._loadCarGuideGrid = _loadCarGuideGrid;
223		vm._collapseSortFilter = _collapseSortFilter;
224		
225		
226		$rootScope.requestInProgress = true;
227		
228		function redirectCarGuidePage(selectedCountry){
229			$window.location.href = selectedCountry;
230
231		}
232		function getFleetData(fleet){
233			var fleetData = fleet.fleetJson;
234			var fleetJson = angular.fromJson(fleet);
235			return fleetJson;
236		}
237		
238		// page onload function
239		function _loadCarGuideGrid() {
240	    	
241			// getting the entire fleet data from java
242	    	var fleetData = angular.fromJson($window.fleetList);
243	    	vm.fleetList = fleetData;
244	    	vm.availableCarClass = _createCarClassList(vm.fleetList);
245	    	if(angular.isDefined(vm.enableOrdering) && vm.enableOrdering == 'true'){
246		    	var apiFleetList = angular.copy(vm.fleetList);
247		    	vm.orderedFleetList = carGuideService.getOrderedList(apiFleetList,vm.orderedList);
248	    	}
249	    	vm.filteredCarClass = vm.availableCarClass;
250	    	vm.fleetFilteredList = vm.fleetList;
251	    	
252	    	
253			// vehicle types
254			var vehicleTypeList = angular.fromJson($window.vehicleTypes);
255			if(vehicleTypeList != '' && vehicleTypeList != undefined) {
256				vm.vehicleTypes = vehicleTypeList.CarGroups;
257				
258				if ($rootScope.deviceType === carRentalConstant.deviceTypeMobile && angular.isDefined(vm.vehicleTypes)) {
259					var specialFeature = {'code': 'spl', 'description': Dictionary.I18n.get('lbl.res.step2.specialFeaturesFilter')};
260					vm.vehicleTypes.push(specialFeature);
261				}
262				vm.specialFeaturesList = vehicleTypeList.specialFeatures;
263				angular.forEach(vm.specialFeaturesList, function(specialFeature, key) {
264					specialFeature.name = (specialFeature.name).toLowerCase();
265					specialFeature.value = false;
266				});
267			}
268			
269			// get the vehicle type display name
270			if(fleetData != '' && fleetData != undefined && !(angular.equals({}, vehicleTypeList))) {
271				vm.vehicleTypeDisplayName = carGuideService.getVehicleTypeDisplayName(fleetData, vm.vehicleTypes);
272				vm.disableVehicleType = false;
273				vm.vehicleTypeListDisplay = false;
274			}
275			if($window.brand == 'avis' || $window.brand == 'budget'){
276				vm.electricVehicleFeatures = true;
277			}
278			$rootScope.requestInProgress = false;
279		}
280		
281		/**
282		 * Method returning list of all the car classes which are available for the selected country
283		 */
284		function _createCarClassList(fleetList){
285			var list = [], index;
286			angular.forEach(fleetList, function(fleet){
287				if(list.indexOf(fleet.carClass) == -1){
288					list.push(fleet.carClass);
289				}
290			});
291			return list;
292		}
293		
294		// fleet facilities
295		function fleetInfo(event) {
296			var el = event.currentTarget,
297			titleContainer = angular.element(el).closest('.car-title-container');
298			angular.element(titleContainer).find(".car-title-box").toggleClass("image-opacity");
299			angular.element(el).toggleClass("icon-remove");
300			angular.element(titleContainer).find(".feature-car-facilities").toggleClass("bg-grey slide-bottom");
301		}
302		function fleetReset(){
303			if(angular.element('.car-title-container')){
304				var titleContainer = angular.element('.car-title-container');
305				angular.element(titleContainer).find(".car-title-box").removeClass("image-opacity");
306				angular.element("icon-remove").removeClass("icon-remove");
307				angular.element(titleContainer).find(".feature-car-facilities").removeClass("bg-grey slide-bottom");
308			}	
309		}
310		
311		
312		/**
313	     * Handles the on-click event to expand the vehicle type filter 
314	     */
315	    function toggleFilters(event) {
316	    	if(!vm.disableVehicleType) {
317	    		vm.vehicleTypeListDisplay = !vm.vehicleTypeListDisplay;
318	    	} else {
319	    		return false;
320	    	}
321	    };
322		
323	    /**
324	     * Returns the number of vehicles of the specific type
325	     *
326	     * @param cargroup
327	     */
328	    function getCarCountByClass(cargroup) {
329	    	return carGuideService.getCountByVehicleType(vm.fleetList, cargroup);
330	    }
331	    
332	    /**
333	     * Method that processes the filter selected
334	     *
335	     * @param vehicleType vehicle type filter selected
336	     */
337	    function filterVehicle(vehicleType, isFeatureFilter) {
338	    	// creating a list of filtered car classes
339	    	vm.filteredCarClass = vehicleType.cargroup;
340	    	if(vm.filteredCarClass.length == 0 || vm.filteredCarClass == vm.availableCarClass){
341	    		vm.showAdditionalVehicles = false;
342	    		vm.filteredCarClass = vm.availableCarClass;
343	    	}else {
344	    		vm.showAdditionalVehicles = true;
345	    	}
346	    	
347	    	vm.selectedFilter = vehicleType;
348	    	vm.mobileSelectedVehicleType = vehicleType;
349	    	vm.filteredSearch = false;
350	    	if(vehicleType.code != carRentalConstant.defaultDisplayedVehicleType){
351	    		vm.filteredSearch = true;
352	    	}
353	    	vm.displayedVehicleType = vehicleType.code;
354	    	vm.visibleVehicleType = (vehicleType.code === carRentalConstant.defaultDisplayedVehicleType) ? '' : vehicleType.description;
355	    	vm.vehicleTypeListDisplay = false; 
356	    	vm.vehicleTypeDisplayName = vehicleType.description + ' (' + vm.getCarCountByClass(vehicleType.cargroup) + ')';
357			
358	    	var selectedCarGroup = carGuideService.getVehicleClasses(vehicleType.cargroup);
359	    	if (isFeatureFilter) { 
360	    		vm.vehicleTypeDisplayName = Dictionary.I18n.get('msg.res.specialFeature');
361	      		vm.fleetFilteredList = carGuideService.filterBySpeacialFeatures(vm.fleetList, vm.selectedFeatures.list);
362	      		vm.otherfleet = carGuideService.getOtherVehiclesList(vm.fleetList,vm.fleetFilteredList);
363	    	} else if(selectedCarGroup == '') {
364	    		vm.fleetFilteredList = vm.fleetList;
365	    		vm.otherfleet = [];
366	    	} else {
367	    		vm.fleetFilteredList = carGuideService.filterByVehicleClass(vm.fleetList, carGuideService.getVehicleClasses(vehicleType.cargroup));
368	    		vm.otherfleet = carGuideService.getOtherVehiclesList(vm.fleetList,vm.fleetFilteredList);
369	    	}
370	    	
371	    	// collapse the sort and filter details
372	    	vm.fleetReset();
373	    	vm._collapseSortFilter();
374	    	
375	    	// TODO see if this belong here or to be moved somewhere else
376	    	var tellAngular = function(event) {
377	    		/*var infoTriggerEvent = (isTouchDevice() || (is_winphone() || is_wintablet())) ? 'focus' : 'hover';*/
378	    		var infoTriggerEvent = ($rootScope.deviceType === carRentalConstant.deviceTypeMobile) ? 'focus' : 'hover';
379	    		jQuery('a.popOver[data-toggle="popover"], a.steptwoinfo[data-toggle="popover"], a.info-icon[data-toggle="popover"]').attr('data-trigger', infoTriggerEvent);
380	    	}
381
382	    	$timeout(function() {
383	    		tellAngular();
384	    		jQuery('[data-toggle="popover"]').popover();
385	    	}, 0);
386	    }
387	    
388	    /**
389	     * Returns true if any vehicle with the special feature 
390	     * @param special feature
391	     */
392	    function getFeatureCount(feature) {
393	    	var filterCondition = {};
394	    	filterCondition[feature] = true;
395	    	if (feature === 'abg' || feature === 'ABG') {
396	    		filterCondition['abgquantity'] = {
397	    			'size': 6,
398	    			'condition': '>'
399	    		};
400	    	}
401	    	
402	    	var fileredList = $filter('customFeaturesFilter')(vm.fleetList, filterCondition);
403	    	return fileredList.length === 0 ? true : false
404	    }
405	    
406	    // special features for mobile
407	    function showFeaturesForMobile(fleet) {
408    		vm.fleetFeatures = fleet;
409      	}
410	    
411	    // on click of special feature in mobile
412	    function openSpecialFeatureModal() {
413	    	jQuery('.myModalSpecial').modal('show');
414	    }
415      	
416	    // to close the special feature dialog
417	    function specialFeatureDialogClose() {
418	    	jQuery('.myModalSpecial').modal('hide');
419	    	jQuery("body").removeClass("modal-open");
420	    }
421	    
422	    // redirect to step1A
423	    function step1ARedirect(fleet) {
424	    	var redirectPath;
425	    	redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + "/" + "reservation/make-reservation" + htmlExtension + "?preferredCarClass=" + fleet.carClass;
426	    	$window.location.href = redirectPath;
427	    }
428	    
429	    // refine and sort mobile
430	    function updateMobileView() {
431	    	if(!angular.equals({}, vm.mobileSelectedVehicleType) && vm.mobileSelectedVehicleType){
432	    		vm.filterVehicle(vm.mobileSelectedVehicleType, false);
433	    	} else {
434	    		vm._collapseSortFilter(); 
435	    	}
436	    }
437	    
438	    /*
439	     * Collapses the filter and sort details
440	     */
441	    function _collapseSortFilter() {
442	    	if (angular.element('#vehicleModal')) {
443	    		angular.element('#vehicleModal').modal('hide');
444	    	}
445
446	    	//used below  function for refine and sort desktop
447	    	if (angular.element('.allvehimodalformob')) {
448	    		angular.element('.allvehimodalformob').modal('hide');
449	    	}
450
451	    	// to close 'refine & sort' popup on filter selection without loader
452	    	if (angular.element('.myModalVehicleDrpDwn')) {
453	    		angular.element('.myModalVehicleDrpDwn').modal('hide');
454	    	}
455	    	
456	    	// to close the vehicle dropdown for mobile
457	    	if(angular.element('#mobile-drop')) {
458	    		angular.element('#mobile-drop').removeClass('open');
459	    	}
460	    }
461	    
462	    // to assign the selected vehicle type to display in front end
463	    function assignSelectedVehicleType(vehicleType) {
464	        vm.mobileSelectedVehicleType = vehicleType;
465	        vm.vehicleTypeDisplayName = vehicleType.description + ' (' + vm.getCarCountByClass(vehicleType.cargroup) + ')';
466	        if (jQuery('.allvehimodalformob')) {
467	        	jQuery('.allvehimodalformob').modal('hide');
468	        }
469	    }
470	    
471		// page onload function
472		jQuery(document).ready(function() {
473			vm._loadCarGuideGrid();
474		});
475	}
476})();
477(function() {
478  'use strict';
479
480  angular
481    .module('carRental')
482    .controller('SignUpCntrl', SignUpCntrl);
483
484  SignUpCntrl.$inject = ['$scope','$window',  'storageService', '$controller', 'carRentalConstant', 'getVehicles', '$timeout', 'language', '$validation', '$location', '$state'];
485
486  function SignUpCntrl($scope, $window, storageService, $controller, carRentalConstant, getVehicles,  $timeout, language, $validationProvider, $location, $state) {
487
488    // View Models
489    var vm = this;
490    vm.offerSignup = {};
491    vm.emailErrmsg = false;
492    vm.showSuccessCon = false;
493    vm.offerSignup.business = false;
494    
495   /* vm.uEmail = '';*/
496
497    // View Callables	
498    vm.signUpSubmit = signUpSubmit;
499    vm.getCSSClass = getCSSClass;
500    
501    vm._validationSuccess = _validationSuccess;
502    vm._validationFailure = _validationFailure;
503    
504    var hostName = window.location.hostname;
505    var pathname = window.location.pathname;
506    var queryString = $location.search();
507	var countries = $window.countryList;
508	
509	vm.countriesList = angular.fromJson(countries); 
510
511    var customer = storageService.getStorageData("customer");
512    var session = storageService.getStorageData("session"); 
513    
514    vm.hostNameSuccess = "https://" + hostName + pathname +"#/?flag=SUCCESS";
515    vm.hostNameFailure = "https://" + hostName + pathname +"#/?flag=FAILURE";
516    vm.hostNameUnsub = "https://" + hostName + pathname +"#/?flag=UNSUB";
517
518    if (queryString.flag) {
519      if (queryString.flag === "SUCCESS") {
520
521        vm.showSuccessCon = true;
522      } else if (queryString.flag === "FAILURE") {
523        vm.emailErrmsg = true;
524      }
525    }
526    
527    if(angular.isDefined(session) && (session.status == "AUTHENTICATED" || session.status == "RECOGNIZED") ){
528    	vm.uEmail = customer.contacts.email;
529    }
530    else{
531    	vm.uEmail='';
532    } 
533    
534
535	$timeout(function() {
536    	if(queryString.flag){
537      	  var offset=jQuery('.offers-grids.deals-signup').offset().top-70;	//offset-height of header/navbar i.e 70px
538      	  $("body,html").animate({ "scrollTop":offset});
539    	}
540    }, 3000);
541    //form event
542    function signUpSubmit(emailForm) {
543      $validationProvider.validate(emailForm)
544        .success(vm._validationSuccess).error(vm._validationFailure);
545    };
546    
547    function _validationSuccess() {
548    	//    	vm.showSuccessCon = true;
549    	if($window.brand == carRentalConstant.brandName.PAYLESS){    	
550    		
551    		var _URL = '/mail/subscribe';
552    		getVehicles.httpPost(vm.offerSignup, _URL).then(function(data){ 
553    			
554    			if(angular.isDefined(data) && angular.isDefined(data.instructionList) && data.instructionList.length>0 && data.instructionList[0].code == "07002"){
555    				vm.mainErrorFlag = false;   
556    				vm.successFlag = true;
557//  				vm.successMessage = Granite.I18n.get(data.message.code);
558    				vm.successMessage= data.instructionList[0].message;
559    			} else if(angular.isDefined(data) && angular.isDefined(data.message)){
560    				vm.mainErrorFlag = true;   
561    				vm.successFlag = false;
562  				vm.errorMessage = angular.isDefined(data.message.message) ? data.message.message:"";
563//  				vm.errorMessage = Granite.I18n.get(data.message.code);
564//    				vm.successMessage = data.errorList[0].message;
565    			}
566    		});
567    	}else{
568    		angular.element("#signUpEmail2").attr("disabled",false);
569    		document.subscribeFooterForm.submit();
570    	}
571    }
572    
573    function _validationFailure(response){ 
574    	vm.mainErrorFlag = false;  
575    	if (response.errorCount > 1) {
576    		vm.mainErrorFlag = true;   
577    		vm.successFlag = false;
578    		vm.errorMessage  = Dictionary.I18n.get('err.res.mutliplemsg');
579    	}				 
580    }
581    
582    //for reusing this component in home page for personalization story.
583    function getCSSClass(cssClass){
584    	var css='';
585    	if($state.current.name=='' && pathname.indexOf('home') > -1){
586    		css ='offers-emailcontainer-homepage';
587    	}else if($state.current.name==''){
588    		css=cssClass;
589    	}
590    	
591    	return css;
592    }
593    
594    
595    var extendedController= $controller('SignUpExnCntrl', {
596        $scope: $scope
597      });
598    angular.extend(this, extendedController);
599
600  }
601})();
602
603(function () {
604  'use strict';
605
606  angular
607    .module('reservation')
608    .controller('rentalExtController', rentalExtController);
609
610  rentalExtController.$inject = [
611    'rentalService',
612    '$scope',
613    '$rootScope',
614    '$filter',
615    '$state',
616    '$controller',
617    '$window',
618    '$validation',
619    'reservationModelService',
620    'gaService',
621    'carRentalConstant',
622    'travelService',
623    'lookupService',
624    'locationService',
625    'getDataService',
626    'vehicleService',
627    'authenticationService',
628    'confirmCancelService',
629    'BackButtonFactory',
630    'storageService',
631    'geoservices',
632    'datePickerInit',
633    '$timeout',
634    'getVehicles',
635    '$sce',
636    '$location',
637    'optionalService',
638    'rentalUtil',
639    'utilityService',
640  ];
641
642  function rentalExtController(
643    rentalService,
644    $scope,
645    $rootScope,
646    $filter,
647    $state,
648    $controller,
649    $window,
650    $validationProvider,
651    reservationModelService,
652    gaService,
653    carRentalConstant,
654    travelService,
655    lookupService,
656    locationService,
657    getDataService,
658    vehicleService,
659    authenticationService,
660    confirmCancelService,
661    BackButtonFactory,
662    storageService,
663    geoservices,
664    datePickerInit,
665    $timeout,
666    getVehicles,
667    $sce,
668    $location,
669    optionalService,
670    rentalUtil,
671    utilityService
672  ) {
673    var vm = this;
674    vm.showPromo = false;
675    vm.shuttleError = false;
676    vm.init = init;
677    vm.rentalDetails = {};
678    vm.rentalExtension = {};
679    vm.rateSummary = {};
680    vm.returnLoc = '';
681    vm.returnDate = '';
682    vm.pickDate = '';
683    vm.dropTime = '';
684    // vm.dropDate="";
685    vm.helpURL = '';
686    vm.cubsideSelected = {};
687    vm.previousSplitType = '';
688    vm.secondaryCardSelected = {
689      number: '',
690    };
691    vm.oldSecondaryCardSummary = {};
692    vm.dropDownValue = {
693      proDropDownPri: {},
694      insDropDownPri: {},
695      proDropDownSec: {},
696      insDropDownSec: {},
697      primaryValue: null,
698      secondaryValue: null,
699    };
700    /*
701     * Story 689-Added warningMsgPC,warningMsgSC attributes for Displaying
702     * warning message when credit card is about to expire-->
703     */
704    vm.brand = $window.brand;
705    vm.warningMsgPC = {};
706    vm.warningMsgSC = {};
707    vm.domain = $window.domain.toUpperCase();
708    vm.expMonths = [];
709    vm.rentalDays = {
710      productDays: {
711        primaryValues: [],
712        secondaryValues: [],
713      },
714      insuranceDays: {
715        primaryValues: [],
716        secondaryValues: [],
717      },
718      vehicleDays: [],
719    };
720    vm.totalDays = '';
721    var review_creditCard = {
722      rentalLocation: '',
723    };
724    vm.secondaryValue = null;
725    vm.prefilledZipcode = '';
726    vm.primaryValue = null;
727    vm.selectedAddress = '';
728    vm.rentalModel = {
729      primary: false,
730      changedCard: false,
731      loc: false,
732      newLoc: false,
733      showCity: false,
734      showState: false,
735      showZipcode: false,
736      showSuburb: false,
737      epIndicator: false,
738      saveCreditCard: false,
739      enableCta: false,
740      formValidated: false,
741      latError: false,
742      hideItemizedTab: false,
743      unsplit: false,
744      date: false,
745      time: false,
746      locationChanged: false,
747      confirmSuccess: false,
748      amountSplitConfirmCTA: false,
749      daySplitConfirmCTA: false,
750      rentalSummary: true,
751      tabFocus: false,
752      showSplitOpt: false,
753      showExtras: false,
754      showModifiedReturns: false,
755      dateTimeSelected: false,
756      confirmMessage: false,
757      modifyReturnActive: false,
758      addtionalTrue: false,
759      failExtras: false,
760      showAlertMessage: false,
761    };
762
763    vm.countryList = {};
764    vm.prodItemizedPri = {};
765    vm.prodItemizedSec = {};
766    vm.insuranceItemizedPri = {};
767    vm.insuranceItemizedSec = {};
768    vm.addresses = [];
769    vm.billingAddress = {
770      address1: '',
771      address2: '',
772      address3: '',
773      city: '',
774      state: null,
775      zipCode: '',
776    };
777    vm.additionalVehicleData = {
778      licensePlateNumber: '',
779      lotSpaceNumber: '',
780    };
781    vm.displayAdditionalVehicleData = false;
782    vm.split = {};
783    vm.clickedtab = '';
784    vm.instructionMessageList = [];
785    vm.addressDisplayList = [];
786    vm.pageArray = [];
787    vm.rentalState = {
788      value: false,
789      tab: '',
790    };
791    vm.indicatorMap = {
792      credit_id: '',
793      address_id: '',
794    };
795    vm.modifiedData = {};
796    vm.extentionSplitData = {};
797    vm.primaryAmountOldValue = '';
798    vm.secondaryAmountOldValue = '';
799    vm.rentalNumber = '';
800    vm.Insurance = {
801      selectedInsurance: [],
802      selectedAvailableInsurances: [],
803    };
804    vm.product = {
805      selectedProduct: [],
806      selectedAvailableProducts: [],
807    };
808    vm.isBackButton = true;
809    vm.hidePaymentInfo = false;
810    vm.splitOptionTab = {};
811    // cbs, cfs, cis, csb, css
812    vm.cssDropDown = {};
813    vm.cssDropDownValues = {
814      CBS: [],
815      CFS: [],
816      CIS: [],
817      CSB: [],
818      CSS: [],
819      BXM: [],
820      BXS: [],
821      BXL: [],
822    };
823    vm.expandCSS = false;
824    vm.expandCSSServ = false;
825    vm.thresholdMsg = false;
826    vm.vehicleExchangeObj = {
827      flow: false,
828      thresholdError: false,
829    };
830    vm.rentalUtil = rentalUtil;
831
832    // reservationModel for credit card
833    vm.reservationModel = angular.copy(reservationModelService.bookingModel);
834    vm._loadMnthYrDropdown = _loadMnthYrDropdown;
835    vm._itemizedDropdown = _itemizedDropdown;
836    vm.getStatesForCountry = getStatesForCountry;
837    vm._getAddressList = _getAddressList;
838    // itemized tab
839    vm._populateRentalDays = _populateRentalDays;
840    vm._displayCarFeatures = _displayCarFeatures;
841    vm._add = _add;
842    vm._populateAddressFields = _populateAddressFields;
843    vm.hideStickySection = false;
844    vm.getExtrasDays = getExtrasDays;
845    vm.findFeatureByKeyName = findFeatureByKeyName;
846    vm.checkUserStatus = checkUserStatus;
847    vm.getZoneNumber = getZoneNumber;
848    vm.shouldDisableLink = shouldDisableLink;
849  vm.handleModifyReturnLocationClick = handleModifyReturnLocationClick;
850    //vm.processDays = processDays;
851
852    // <!-- split enable flag from api -->
853
854    var estimateCall = '';
855    var splitOpted = '';
856    var emailNotifiedProduct = '';
857    var rentalSummaryTab = false;
858    var modifyReturnTab = false;
859    var review_creditCard = {
860      rentalLocation: '',
861    };
862    var splitConfirmed = false;
863    var splitType = '';
864    var secondaryCard = '';
865    vm.hideVehicleInfo = true;
866    vm.footerClass = footerClass;
867    vm.leaveSplitChanges = leaveSplitChanges;
868    // variable for unsplitting the rental
869
870    vm.saveCard = saveCard;
871    vm.productVisible = false;
872    vm.insuranceVisible = false;
873    vm.os = ABG.getMobileOperatingSystem();
874    vm.productSelected = productSelected;
875    vm.insuranceSelected = insuranceSelected;
876    // split details call for enabling split after product selection
877    vm.extrasSplitEnable = extrasSplitEnable;
878    // function for disabling split
879    vm.splitDisable = splitDisable;
880    // Split frommodify return tab
881    vm.selectedAddressList = selectedAddressList;
882    vm.selectSecondaryCC = selectSecondaryCC;
883    vm.selectPrimaryCC = selectPrimaryCC;
884    vm.splitPaymentAmount = splitPaymentAmount;
885
886    vm.splitByTypeAPICall = splitByTypeAPICall;
887    vm.splitPaymentConfirm = splitPaymentConfirm;
888    vm.pointCheckbox = {};
889    vm.productCheckbox = {};
890    vm.insuranceCheckbox = {};
891    vm.selectedProductsCodeForExpansion = {};
892    vm.confirmAddOn = confirmAddOn;
893    vm.confirmRentalExt = confirmRentalExt;
894    vm.updateTime = updateTime;
895    vm.updateLoc = updateLoc;
896    vm.close = close;
897    vm.analytics = analytics;
898    vm.displayPromo = displayPromo;
899    vm.clearLoc = clearLoc;
900    vm.setPickupHeader = setPickupHeader;
901
902    vm._setDateFormatPreference = _setDateFormatPreference;
903    vm._displayFunction = _displayFunction;
904
905    vm._setTimeFormatPreference = _setTimeFormatPreference;
906    vm._populateBillingInfoCountryList = _populateBillingInfoCountryList;
907    vm.loadHelpModal = loadHelpModal;
908    vm.expandChildSafety = expandChildSafety;
909    vm.checkForMaxDaysExtras = checkForMaxDaysExtras;
910
911    $controller('ExceptionHandlerController', { $scope: $scope });
912
913    angular.isUndefinedOrNull = function (val) {
914      return angular.isUndefined(val) || val === null;
915    };
916
917    var _setCurrentURL = function () {
918      var url = new URL(window.location);
919      window.history.pushState(url.href, '', url);
920    };
921
922    /*
923     * Story 689-Modified this function for Displaying warning message when
924     * credit card is about to expire-Ends-->
925     */
926
927    function init() {
928      vm.sessionErrorMessage = storageService.getStorageData('sessionErrMsg');
929      reservationModelService.deleteDataBeforeLogoClick();
930
931      _setCurrentURL();
932
933      $rootScope.requestInProgress = true;
934      vm.vehicleExchangeObj = angular.isDefined(
935        storageService.getStorageData('vehicleExchangeObj')
936      )
937        ? storageService.getStorageData('vehicleExchangeObj')
938        : vm.vehicleExchangeObj;
939      var emailUniqueID = locationService.readQuery('id');
940      if (
941        angular.isDefined(reservationModelService.getUrlParameter('vol_key'))
942      ) {
943        var urlProps = new Map();
944        urlProps.set(
945          'uniqueId',
946          reservationModelService.getUrlParameter('vol_key')
947        );
948        urlProps.set(
949          'ancillary',
950          reservationModelService.getUrlParameter('product')
951        );
952        urlProps.set(
953          'eventType',
954          reservationModelService.getUrlParameter('carrier')
955        );
956        rentalService
957          .init(
958            {
959              uniqueId:
960                urlProps.has('uniqueId') &&
961                  urlProps.get('uniqueId') != undefined &&
962                  urlProps.get('uniqueId').length > 0
963                  ? urlProps.get('uniqueId')
964                  : '',
965              ancillary:
966                urlProps.has('ancillary') &&
967                  urlProps.get('ancillary') != undefined &&
968                  urlProps.get('ancillary').length > 0
969                  ? urlProps.get('ancillary').toUpperCase()
970                  : '',
971            },
972            'new'
973          )
974          .then(
975            function (data) {
976              $rootScope.requestInProgress = false;
977              $rootScope.$broadcast('getRentalDetails', data);
978              vm.rentalDetails = data;
979              getAncillaryDetails();
980              openErrorModal();
981            },
982            function (_error) {
983              console.log('error in rental/extras call');
984              $rootScope.requestInProgress = false;
985              $window.location.href =
986                $rootScope.contextPath +
987                '/' +
988                $rootScope.locale +
989                '/' +
990                'reservation/view-modify-cancel' +
991                htmlExtension;
992            }
993          );
994      } else {
995        rentalService.init(emailUniqueID, 'old').then(
996          function (data) {
997            $rootScope.requestInProgress = false;
998            // Render banner image and confirmation number
999            $rootScope.$broadcast('getRentalDetails', data);
1000            vm.rentalDetails = data;
1001            getAncillaryDetails();
1002            openErrorModal();
1003          },
1004          function (error) {
1005            //Need to remove this block
1006            console.log('error in rental/extras call');
1007            $rootScope.requestInProgress = false;
1008            $window.location.href =
1009              $rootScope.contextPath +
1010              '/' +
1011              $rootScope.locale +
1012              '/' +
1013              'reservation/view-modify-cancel' +
1014              htmlExtension;
1015          }
1016        );
1017      }
1018
1019      if (
1020        angular.isDefined(vm.reservationModel.paymentRq.expMonth) &&
1021        vm.reservationModel.paymentRq.expMonth == ''
1022      ) {
1023        vm.reservationModel.paymentRq.expMonth = null;
1024      }
1025      if (
1026        angular.isDefined(vm.reservationModel.paymentRq.expYear) &&
1027        vm.reservationModel.paymentRq.expYear == ''
1028      ) {
1029        vm.reservationModel.paymentRq.expYear = null;
1030      }
1031    }
1032
1033    function openErrorModal() {
1034      if (vm.sessionErrorMessage) {
1035        $('#rentalErrorModal').modal('show');
1036        storageService.deleteStorageData('sessionErrMsg');
1037      }
1038    }
1039    function getAncillaryDetails() {
1040      /* show promotion only in desktop */
1041      /* TODO: Suppose to implement in media query */
1042
1043      $window.scrollTo(0, 0);
1044      vm.rentalModel.epIndicator = vm.rentalDetails.epIndicator;
1045      vm.rentalNumber =
1046        vm.rentalDetails.reservationSummary.rentalAgreementNumber;
1047      if (
1048        angular.isDefined(vm.rentalDetails.reservationSummary) &&
1049        angular.isDefined(
1050          vm.rentalDetails.reservationSummary.splitBillSummary
1051        ) &&
1052        angular.isDefined(
1053          vm.rentalDetails.reservationSummary.splitBillSummary.splitBillEnabled
1054        )
1055      ) {
1056        vm.rentalModel.availedSplitbill =
1057          vm.rentalDetails.reservationSummary.splitBillSummary.splitBillEnabled;
1058      }
1059
1060      if (
1061        angular.isDefined(vm.rentalDetails.reservationSummary) &&
1062        angular.isDefined(vm.rentalDetails.reservationSummary.personalInfo) &&
1063        angular.isDefined(
1064          vm.rentalDetails.reservationSummary.personalInfo.residency
1065        ) &&
1066        angular.isDefined(
1067          vm.rentalDetails.reservationSummary.personalInfo.residency.value
1068        )
1069      ) {
1070        vm.reservationModel.paymentRq.address.country =
1071          vm.rentalDetails.reservationSummary.personalInfo.residency.value;
1072      }
1073
1074      vm._populateAddressFields();
1075      vm._displayCarFeatures();
1076      vm._loadMnthYrDropdown();
1077      if (angular.isDefined(vm.addresses) && !$.isEmptyObject(vm.addresses)) {
1078        vm._getAddressList(vm.addresses);
1079      }
1080      vm._populateBillingInfoCountryList();
1081      if (vm.brand == 'avis') {
1082        vm.getStatesForCountry(
1083          vm.reservationModel.paymentRq.address.country,
1084          'onload'
1085        );
1086      }
1087      // vm._populateRentalDays();
1088      // pushing split opted to data layer to check whether Split is
1089      // opted at counter
1090
1091      //vm._populateRentalDays();
1092      //pushing split opted to data layer to check whether Split is o
1092pted at counter
1093
1094      if (
1095        angular.isDefined(vm.rentalDetails.reservationSummary.splitBillSummary)
1096      ) {
1097        var splitRequest = {
1098          splitOpted:
1099            vm.rentalDetails.reservationSummary.splitBillSummary
1100              .splitBillEnabled,
1101          cardNumber:
1102            angular.isDefined(
1103              vm.rentalDetails.reservationSummary.splitBillSummary
1104                .splitBillSecondary
1105            ) &&
1106              vm.rentalDetails.reservationSummary.splitBillSummary
1107                .splitBillSecondary != null &&
1108              angular.isDefined(
1109                vm.rentalDetails.reservationSummary.splitBillSummary
1110                  .splitBillSecondary.ccSummary
1111              ) &&
1112              vm.rentalDetails.reservationSummary.splitBillSummary
1113                .splitBillSecondary.ccSummary != null &&
1114              angular.isDefined(
1115                vm.rentalDetails.reservationSummary.splitBillSummary
1116                  .splitBillSecondary.ccSummary.number
1117              ) &&
1118              vm.rentalDetails.reservationSummary.splitBillSummary
1119                .splitBillSecondary.ccSummary.number != null
1120              ? vm.rentalDetails.reservationSummary.splitBillSummary
1121                .splitBillSecondary.ccSummary.number
1122              : '',
1123        };
1124      }
1125      getDataService.addToSplitDetails(splitRequest);
1126      /*
1127       * Story 689-Modified this function for Displaying warning
1128       * message when credit card is about to expire[Extras tab],
1129       * splitbill-42 changes for prefilling primary and secondary
1130       * card details in rental-creditcard.html -Starts-->
1131       */
1132      if (
1133        angular.isDefined(vm.rentalDetails.reservationSummary) &&
1134        angular.isDefined(
1135          vm.rentalDetails.reservationSummary.splitBillSummary
1136        ) &&
1137        angular.isDefined(
1138          vm.rentalDetails.reservationSummary.splitBillSummary
1139            .splitBillSecondary
1140        ) &&
1141        vm.rentalDetails.reservationSummary.splitBillSummary
1142          .splitBillSecondary != null &&
1143        angular.isDefined(
1144          vm.rentalDetails.reservationSummary.splitBillSummary
1145            .splitBillSecondary.ccSummary
1146        ) &&
1147        vm.rentalDetails.reservationSummary.splitBillSummary.splitBillSecondary
1148          .ccSummary != null
1149      ) {
1150        vm.secondaryCardSelected = angular.copy(
1151          vm.rentalDetails.reservationSummary.splitBillSummary
1152            .splitBillSecondary.ccSummary
1153        );
1154        if (angular.isDefined(vm.secondaryCardSelected.expiryMsg)) {
1155          vm.warningMsgSC = $scope.processErrorMessage(
1156            vm.secondaryCardSelected
1157          ).expiryMsg;
1158        }
1159      }
1160      if (
1161        angular.isDefined(vm.rentalDetails.reservationSummary) &&
1162        angular.isDefined(
1163          vm.rentalDetails.reservationSummary.splitBillSummary
1164        ) &&
1165        angular.isDefined(
1166          vm.rentalDetails.reservationSummary.splitBillSummary.splitBillPrimary
1167        ) &&
1168        vm.rentalDetails.reservationSummary.splitBillSummary.splitBillPrimary
1169          .ccSummary
1170      ) {
1171        vm.primaryCard = angular.copy(
1172          vm.rentalDetails.reservationSummary.splitBillSummary.splitBillPrimary
1173            .ccSummary
1174        );
1175        if (angular.isDefined(vm.primaryCard.expiryMsg)) {
1176          vm.warningMsgPC = $scope.processErrorMessage(
1177            vm.primaryCard
1178          ).expiryMsg;
1179        }
1180      }
1181      review_creditCard.rentalLocation =
1182        vm.rentalDetails.reservationSummary.pickLoc.address.country;
1183      $rootScope.$broadcast('setReviewCreditCard', review_creditCard);
1184
1185      if (vm.rentalDetails.emailSmsNotification.indicator) {
1186        angular.forEach(
1187          vm.rentalDetails.reservationSummary.productSummaryList,
1188          function (product) {
1189            if (
1190              (vm.rentalDetails.emailSmsNotification.product == 'XMR' &&
1191                product.code == 'XMR') ||
1192              (vm.rentalDetails.emailSmsNotification.product == 'CSD' &&
1193                product.code == 'CSD')
1194            ) {
1195              var code = product.code;
1196              vm.productCheckbox[code] = true;
1197              vm.productSelected(
1198                product,
1199                product.code,
1200                '',
1201                product.code + 'productCheck'
1202              );
1203            }
1204          }
1205        );
1206      }
1207      // Call for GA service
1208      try {
1209        gaService.analyticsRentalDetails(vm.rentalDetails, 'viewModifyPage');
1210      } catch (e) {
1211        // TODO: handle exception
1212      }
1213      var previousPageURL = document.referrer;
1214      var viewModifyUrl =
1215        document.location.origin +
1216        $rootScope.contextPath +
1217        '/' +
1218        $rootScope.locale +
1219        '/' +
1220        'rental/rental-dashboard' +
1221        htmlExtension; // if (reservationModelService.getUrlParameter('vol_key'))
1222      var url = $location.url();
1223      if (url.length > 0) {
1224        var tab = carRentalConstant.modifyRentalStateTabMap[url];
1225        vm.events.redirect(tab, true);
1226      } else {
1227        if (previousPageURL != viewModifyUrl) {
1228          vm.rentalDetails.tabDisplayControl.tab1.active = false;
1229          vm.rentalDetails.tabDisplayControl.tab2.active = false;
1230          vm.rentalDetails.tabDisplayControl.tab3.active = false;
1231          vm.rentalDetails.tabDisplayControl.tab4.active = false;
1232        }
1233        // both old and new should work
1234        if (
1235          reservationModelService.getUrlParameter('vol_key') ||
1236          locationService.readQuery('id')
1237        )
1238          vm.events.redirect('tab1');
1239        var visibleTabs = 0;
1240        for (var i = 1; i <= 4; i++) {
1241          var _tab = 'tab' + i;
1242          if (vm.rentalDetails.tabDisplayControl[_tab].visible == true) {
1243            visibleTabs++;
1244          }
1245        }
1246        if (visibleTabs <= 1 && previousPageURL != viewModifyUrl) {
1247          vm.rentalDetails.tabDisplayControl.tab3.active = true;
1248          vm.events.redirect('tab3');
1249        } else {
1250          vm.rentalDetails.tabDisplayControl.tab1.active = false;
1251          vm.rentalDetails.tabDisplayControl.tab2.active = false;
1252          vm.rentalDetails.tabDisplayControl.tab3.active = false;
1253          vm.rentalDetails.tabDisplayControl.tab4.active = false;
1254        }
1255      }
1256
1257      if (vm.rentalDetails.tabDisplayControl.tab1.active) {
1258        handleSelectedProducts();
1259      }
1260
1261      // to remove border bottom for rental summary tab if tab4 is not visible
1262      if (vm.rentalDetails.tabDisplayControl.tab4.visible == false) {
1263        angular
1264          .element('.sp-rental-container .nav-tabs li:nth-last-child(2) a')
1265          .css('border-bottom', 'none');
1266      }
1267
1268      jQuery('.hide-on-load-profile').removeClass('hide-on-load-profile');
1269    }
1270    // vm.rentalUtil = rentalUtil;
1271    function toggleTab(isEvent, selectedTab) {
1272      if (isEvent === true) {
1273        /* reset all active tabs */
1274        for (var i = 1; i <= 4; i++) {
1275          var _tab = 'tab' + i;
1276          if (_tab === selectedTab) {
1277            /* Activate selected tab */
1278            vm.rentalDetails.tabDisplayControl[_tab].active = true;
1279          } else {
1280            vm.rentalDetails.tabDisplayControl[_tab].active = false;
1281          }
1282        }
1283      }
1284
1285      /* resolve the active tab events and dependency */
1286      if (selectedTab === 'tab2') {
1287        setTimeout(function () {
1288          $('#rentalCal').click(function () {
1289            jQuery('.end-date-input').datepicker('show');
1290          });
1291        }, 500);
1292      } else if (selectedTab === 'tab3') {
1293      }
1294    }
1295
1296    /*
1297     * Story 689-Modified this function for Displaying warning message when
1298     * credit card is about to expire-Starts-->
1299     */
1300    // splitbill-49 Modify primary credit card implementation changes
1301    function selectSecondaryCC(ccSelected) {
1302      vm.warningMsgSC = {};
1303      vm.error = [];
1304      var secondaryCard = ccSelected.number;
1305      vm.oldSecondaryCardSummary = angular.copy(ccSelected);
1306      if (
1307        vm.rentalState.tab == 'Modify-Return' &&
1308        angular.isDefined(
1309          vm.rentalDetails.reservationSummary.splitBillSummary
1310            .splitBillEnabled == false
1311        ) &&
1312        angular.isDefined(
1313          vm.rentalDetails.reservationSummary.splitBillSummary.splitOpted ==
1314          true
1315        )
1316      ) {
1317        $rootScope.requestInProgress = true;
1318        vm.error = [];
1319
1320        var splitData = {
1321          secondaryCreditCard: ccSelected.number,
1322          splitOpted: vm.rentalModel.availedSplitbill,
1323        };
1324        getDataService.addToSplitDetails(splitData);
1325
1326        rentalService.rentalSplit(vm.extentionSplitData).then(
1327          function (data) {
1328            vm.rentalModel.availedSplitbill =
1329              data.reservationSummary.splitBillSummary.splitBillEnabled;
1330            /*if(angular.isDefined(data.reservationSummary) && angular.isDefined(data.reservationSummary.splitBillSummary) 
1331            && angular.isDefined(data.reservationSummary.splitBillSummary.splitBillPrimary) && angular.isDefined(data.reservationSummary.splitBillSummary.splitBillPrimary.ccSummary)){
1332            vm.primaryCard = angular.copy(data.reservationSummary.splitBillSummary.splitBillPrimary.ccSummary);
1333          }*/
1334            if (
1335              angular.isDefined(data.reservationSummary) &&
1336              angular.isDefined(data.reservationSummary.splitBillSummary) &&
1337              angular.isDefined(
1338                data.reservationSummary.splitBillSummary.splitBillSecondary
1339              ) &&
1340              data.reservationSummary.splitBillSummary.splitBillSecondary !=
1341              null &&
1342              angular.isDefined(
1343                data.reservationSummary.splitBillSummary.splitBillSecondary
1344                  .ccSummary
1345              )
1346            ) {
1347              vm.secondaryCardSelected = angular.copy(
1348                data.reservationSummary.splitBillSummary.splitBillSecondary
1349                  .ccSummary
1350              );
1351            }
1352            if (
1353              angular.isDefined(data.reservationSummary) &&
1354              angular.isDefined(data.reservationSummary.splitBillSummary)
1355            ) {
1356              //vm.rateSummary = data.reservationSummary.rateSummary;
1357              vm.rentalDetails.reservationSummary.splitBillSummary =
1358                data.reservationSummary.splitBillSummary;
1359            }
1360            $rootScope.requestInProgress = false;
1361          },
1362          function (error) {
1363            if (error.errorList && error.errorList.length > 0) {
1364              vm.error = $scope.processErrorMessage(error).errorList;
1365              vm.rentalModel.availedSplitbill =
1366                error.reservationSummary &&
1367                  error.reservationSummary.splitBillSummary &&
1368                  error.reservationSummary.splitBillSummary.splitOpted
1369                  ? error.reservationSummary.splitBillSummary.splitOpted
1370                  : false;
1371              $rootScope.requestInProgress = false;
1372            }
1373          }
1374        );
1375      }
1376
1377      if (angular.isDefined(ccSelected.expiryMsg)) {
1378        vm.warningMsgSC = $scope.processErrorMessage(ccSelected).expiryMsg;
1379      }
1380      if (
1381        vm.rentalState.tab == 'Rental-Summary' &&
1382        vm.rentalDetails.reservationSummary.splitBillSummary.splitBillEnabled
1383      ) {
1384        $rootScope.requestInProgress = true;
1385        var splitData = {
1386          splitOpted: vm.rentalModel.availedSplitbill,
1387          estimateCall: false,
1388          secondaryCreditCard: ccSelected.number,
1389          rentalNumber: vm.rentalNumber,
1390        };
1391        getDataService.addToSplitDetails(splitData);
1392
1393        vm.cardError = {};
1394        rentalService.getSplitInRental(vm.rentalNumber).then(
1395          function (data) {
1396            $rootScope.requestInProgress = true;
1397            if (
1398              angular.isDefined(data.reservationSummary) &&
1399              angular.isDefined(data.reservationSummary.splitBillSummary) &&
1400              angular.isDefined(
1401                data.reservationSummary.splitBillSummary.splitBillSecondary
1402              ) &&
1403              data.reservationSummary.splitBillSummary.splitBillSecondary !=
1404              null &&
1405              angular.isDefined(
1406                data.reservationSummary.splitBillSummary.splitBillSecondary
1407                  .ccSummary
1408              ) &&
1409              data.reservationSummary.splitBillSummary.splitBillSecondary
1410                .ccSummary != null
1411            ) {
1412              vm.secondaryCardSelected =
1413                data.reservationSummary.splitBillSummary.splitBillSecondary.ccSummary;
1414              vm.secondaryCCType = carRentalConstant.masterListForCC.filter(
1415                function (obj) {
1416                  return (
1417                    obj.code.toLowerCase() ==
1418                    vm.secondaryCardSelected.type.toLowerCase()
1419                  );
1420                }
1421              );
1422              if (
1423                angular.isDefined(secondaryCard) &&
1424                secondaryCard != vm.secondaryCardSelected.number
1425              ) {
1426                vm.rentalModel.changedCard = true;
1427              }
1428            }
1429
1430            $rootScope.requestInProgress = false;
1431          },
1432          function (data) {
1433            if (
1434              angular.isDefined(data.errorList) &&
1435              data.errorList.length > 0
1436            ) {
1437              if (vm.oldSecondaryCardSummary) {
1438                vm.secondaryCardSelected = vm.oldSecondaryCardSummary;
1439                vm.secondaryCCType = carRentalConstant.masterListForCC.filter(
1440                  function (obj) {
1441                    return obj.code == vm.oldSecondaryCardSummary.type;
1442                  }
1443                );
1444                if (
1445                  angular.isDefined(secondaryCard) &&
1446                  secondaryCard != vm.secondaryCardSelected.number
1447                ) {
1448                  vm.rentalModel.changedCard = false;
1449                }
1450              }
1451              vm.cardError = data.errorList;
1452              $('html, body').animate({
1453                scrollTop: $('#tabStart').position().top,
1454              });
1455              setTimeout(function () {
1456                $validationProvider.resetError(
1457                  'vm.secondaryCardSelected.number',
1458                  false
1459                );
1460              }, 100);
1461            }
1462            $rootScope.requestInProgress = false;
1463          }
1464        );
1465      } else {
1466        vm.secondaryCardSelected = ccSelected;
1467        vm.secondaryCCType = carRentalConstant.masterListForCC.filter(function (
1468          obj
1469        ) {
1470          return obj.code == ccSelected.type;
1471        });
1472        vm.rentalModel.changedCard = true;
1473      }
1474    }
1475    // splitbill-49 Modify primary credit card implementation changes
1476    function selectPrimaryCC(selectedCC) {
1477      vm.warningMsgPC = {};
1478      vm.primaryCard = angular.copy(selectedCC);
1479      vm.primaryCCType = carRentalConstant.masterListForCC.filter(function (
1480        obj
1481      ) {
1482        return obj.code.toLowerCase() == selectedCC.type.toLowerCase();
1483      });
1484      if (angular.isDefined(selectedCC.expiryMsg)) {
1485        vm.warningMsgPC = $scope.processErrorMessage(selectedCC).expiryMsg;
1486      }
1487    }
1488
1489    // function to form req obj based on primary/secondary amount field
1490    function splitPaymentAmount(field, e) {
1491      vm.rentalModel.amountSplitConfirmCTA = false;
1492      if (
1493        field == carRentalConstant.splitInRental.PRIMARYAMOUNT &&
1494        angular.isDefined(vm.split.primaryAmount) &&
1495        vm.split.primaryAmount != '' &&
1496        (angular.isUndefined(e) ||
1497          !angular.element(e.target).hasClass('ng-invalid'))
1498      ) {
1499        vm.split.primaryAmount = parseFloat(vm.split.primaryAmount).toFixed(2);
1500        if (
1501          vm.primaryAmountOldValue != vm.split.primaryAmount ||
1502          vm.split.secondaryAmount == '' ||
1503          angular.element('#secondaryAmount').hasClass('ng-invalid')
1504        ) {
1505          vm.primaryAmountOldValue = vm.split.primaryAmount;
1506          var splitData = {
1507            splitType: carRentalConstant.splitInRental.AMOUNT,
1508            dollarAmount: vm.split.primaryAmount,
1509            splitOpted: vm.rentalModel.availedSplitbill,
1510            estimateCall: true,
1511            primary: true,
1512            secondaryCreditCard: vm.secondaryCardSelected.number,
1513            rentalNumber: vm.rentalNumber,
1514          };
1515          getDataService.addToSplitDetails(splitData);
1516          vm.splitByTypeAPICall(splitData, field);
1517        } else {
1518          //sec value not getting updated when tried to split by same amount twice
1519          vm.split.secondaryAmount = vm.secondaryAmountOldValue;
1520          vm.rentalModel.amountSplitConfirmCTA = true;
1521        }
1522      } else if (
1523        field == carRentalConstant.splitInRental.SECONDARYAMOUNT &&
1524        angular.isDefined(vm.split.secondaryAmount) &&
1525        vm.split.secondaryAmount != '' &&
1526        (angular.isUndefined(e) ||
1527          !angular.element(e.target).hasClass('ng-invalid'))
1528      ) {
1529        vm.split.secondaryAmount = parseFloat(vm.split.secondaryAmount).toFixed(
1530          2
1531        );
1532        if (
1533          vm.secondaryAmountOldValue != vm.split.secondaryAmount ||
1534          vm.split.primaryAmount == '' ||
1535          angular.element('#primaryAmount').hasClass('ng-invalid')
1536        ) {
1537          vm.secondaryAmountOldValue = vm.split.secondaryAmount;
1538          var splitData = {
1539            splitType: carRentalConstant.splitInRental.AMOUNT,
1540            dollarAmount: vm.split.secondaryAmount,
1541            splitOpted: vm.rentalModel.availedSplitbill,
1542            estimateCall: true,
1543            primary: false,
1544            secondaryCreditCard: vm.secondaryCardSelected.number,
1545            rentalNumber: vm.rentalNumber,
1546          };
1547          getDataService.addToSplitDetails(splitData);
1548          vm.splitByTypeAPICall(splitData, field);
1549        } else {
1550          //pri value not getting updated when tried to split by same amount twice
1551          vm.split.primaryAmount = vm.primaryAmountOldValue;
1552          vm.rentalModel.amountSplitConfirmCTA = true;
1553        }
1554      } else if (
1555        !angular.isDefined(vm.split.primaryAmount) &&
1556        !angular.isDefined(vm.split.secondaryAmount)
1557      ) {
1558        vm.rentalModel.amountSplitConfirmCTA = false;
1559      }
1560    }
1561    /**
1562     * Set Date Format Preference
1563     */
1564    function _setDateFormatPreference(customer, data) {
1565      var resultDateFormatObj = vehicleService.getDateFormat(customer);
1566      vm.dateFormatPalceholder = resultDateFormatObj.dateFormatPalceholder;
1567
1568      datePickerInit.datePickerInitFun(
1569        $rootScope.deviceType,
1570        resultDateFormatObj.dateFormat.format
1571      );
1572      var pickUpDate = $filter('date')(
1573        data.reservationSummary.pickDateTime,
1574        'yyyy-MM-dd'
1575      );
1576      var dropDate = $filter('date')(
1577        data.reservationSummary.dropDateTime,
1578        'yyyy-MM-dd'
1579      );
1580      setPickUpDate(pickUpDate);
1581      setDropOffDate(dropDate);
1582    }
1583
1584    /**
1585     * Set Pickup Date
1586     */
1587    function setPickUpDate(pickDateString) {
1588      if (pickDateString != '') {
1589        var obj = jQuery.datepicker.parseDate('yy-mm-dd', pickDateString);
1590        jQuery('.start-date-input')
1591          .datepicker('setDate', obj)
1592          .trigger('change');
1593        jQuery('.start-date-input').datepicker(
1594          'option',
1595          'dpheaderlabel',
1596          headerDateFormat(obj)
1597        );
1598        /*setTimeout(function(){
1599          jQuery('.start-date-input').datepicker('setDate', obj).trigger('change');
1600        },1000); */
1601        date(obj);
1602      }
1603    }
1604
1605    /**
1606     * Set Dropoff Date
1607     */
1608    function setDropOffDate(dropDateString) {
1609      if (dropDateString != '') {
1610        var obj = jQuery.datepicker.parseDate('yy-mm-dd', dropDateString);
1611        jQuery('.end-date-input').datepicker('setDate', obj).trigger('change');
1612        jQuery('.end-date-input').datepicker(
1613          'option',
1614          'dpheaderlabel',
1615          headerDateFormat(obj)
1616        );
1617        /*jQuery('.end-date-input').datepicker("option", "returnonly", "true");
1618        jQuery('.end-date-input').datepicker('setDate', obj).trigger('change');*/
1619      }
1620    }
1621
1622    function headerDateFormat(selDate) {
1623      var day = selDate.getDate(),
1624        month = selDate.getMonth(),
1625        weekDay = selDate.getDay(),
1626        dayNames = jQuery.datepicker.regional[internalLocale].dayNames,
1627        monthNamesShort =
1628          jQuery.datepicker.regional[internalLocale].monthNamesShort;
1629
1630      return (
1631        dayNames[weekDay] +
1632        ' <span>' +
1633        monthNamesShort[month] +
1634        ' ' +
1635        day +
1636        '</span>'
1637      );
1638    }
1639
1640    //set pick up header on changing return date
1641    function setPickupHeader() {
1642      var pickUpDate = $filter('date')(
1643        vm.rentalDetails.reservationSummary.pickDateTime,
1644        'yyyy-MM-dd'
1645      );
1646      var obj = jQuery.datepicker.parseDate('yy-mm-dd', pickUpDate);
1647      jQuery('.start-date-input').datepicker('setDate', obj).trigger('change');
1648      jQuery('.start-date-input').datepicker(
1649        'option',
1650        'dpheaderlabel',
1651        headerDateFormat(obj)
1652      );
1653    }
1654
1655    /**
1656     * Set Time Format Preference
1657     */
1658    function _setTimeFormatPreference(customer, data) {
1659      if (
1660        customer &&
1661        customer.preferences.timeFmt === carRentalConstant.timeFmtHmm
1662      ) {
1663        // Military Time Format
1664        vm.times = carRentalConstant.timeMilitaryFormat;
1665      } else {
1666        // Standard Time Format
1667        vm.times = carRentalConstant.timeDefaultFormat;
1668      }
1669      vm.times[0].minits = Dictionary.I18n.get('msg.res.midnight'); // Granite.I18n.get('msg.res.midnight');
1670      vm.times[24].minits = Dictionary.I18n.get('msg.res.defaultTime'); // Granite.I18n.get('msg.res.defaultTime');
1671      // //Granite.I18n.get(vm.times[24].minits);
1672    }
1673
1674    function updateTime(option) {
1675      vm.selectedTime = option.value;
1676      if (vm.dropTime != vm.selectedTime) {
1677        var resultDateFormatObj = vehicleService.getDateFormat(
1678          authenticationService.getCustomerModel()
1679        );
1680        var date = $.datepicker.parseDate(
1681          resultDateFormatObj.dateFormat.format,
1682          angular.isDefined(vm.dropDate)
1683            ? vm.dropDate
1684            : $filter('date')(
1685              vm.rentalExtension.reservationSummary.dropDateTime,
1686              'dd/mm/yyyy'
1687            )
1688        );
1689        date = $filter('date')(date, 'MM/dd/yyyy');
1690        var modifiedData = {
1691          splitOpted: vm.rentalModel.availedSplitbill,
1692          rentalNumber: vm.rentalNumber,
1693          dropLocCode: angular.isDefined(vm.selectedLoc)
1694            ? vm.selectedLoc
1695            : vm.rentalExtension.reservationSummary.dropLoc.locationCode,
1696          dropDate: date,
1697          dropTime: vm.selectedTime,
1698        };
1699        vm.extentionSplitData = modifiedData;
1700        // Pushing card number to service layer for request object
1701        var splitData = {
1702          secondaryCreditCard:
1703            angular.isDefined(vm.secondaryCardSelected) &&
1704              angular.isDefined(vm.secondaryCardSelected.number)
1705              ? vm.secondaryCardSelected.number
1706              : '',
1707        };
1708        getDataService.addToSplitDetails(splitData);
1709
1710        vm.rentalModel.time = true;
1711        modifyReturn(modifiedData, 'Return Time');
1712        vm.dropTime = vm.selectedTime;
1713        if ($('.sp-time-dropdown').hasClass('open')) {
1714          jQuery('.sp-time-dropdown').removeClass('open');
1715        }
1716      }
1717    }
1718
1719    function updateLoc(loc) {
1720      $('.locations-form').find('input').val('');
1721      vm.rentalModel.dateTimeSelected = false;
1722      vm.selectedLoc = loc.locationCode;
1723      var resultDateFormatObj = vehicleService.getDateFormat(
1724        authenticationService.getCustomerModel()
1725      );
1726      var date = $.datepicker.parseDate(
1727        resultDateFormatObj.dateFormat.format,
1728        angular.isDefined(vm.dropDate)
1729          ? vm.dropDate
1730          : $filter('date')(
1731            vm.rentalExtension.reservationSummary.dropDateTime,
1732            'dd/mm/yyyy'
1733          )
1734      );
1735      date = $filter('date')(date, 'MM/dd/yyyy');
1736      var modifiedData = {
1737        splitOpted: vm.rentalModel.availedSplitbill,
1738        rentalNumber: vm.rentalNumber,
1739        dropLocCode: loc.locationCode,
1740        dropDate: date,
1741        dropTime: angular.isDefined(vm.selectedTime)
1742          ? vm.selectedTime
1743          : $filter('date')(
1744            vm.rentalExtension.reservationSummary.dropDateTime,
1745            'h:mm a'
1746          ),
1747      };
1748      vm.extentionSplitData = modifiedData;
1749      // Pushing card number to service layer for request object
1750      var splitData = {
1751        secondaryCreditCard:
1752          angular.isDefined(vm.secondaryCardSelected) &&
1753            angular.isDefined(vm.secondaryCardSelected.number)
1754            ? vm.secondaryCardSelected.number
1755            : '',
1756      };
1757      getDataService.addToSplitDetails(splitData);
1758
1759      vm.rentalModel.loc = true;
1760      modifyReturn(modifiedData, 'Return Location');
1761      vm.returnLoc = loc.description + ', ' + loc.locationCode;
1762    }
1763
1764    function _populateRentalDays(totalDays) {
1765      vm.totalDays = totalDays;
1766      for (var i = 1; i < vm.totalDays; i++) {
1767        var j = i;
1768        if (i == 1) {
1769          i = i + ' Day';
1770        } else {
1771          i = i + ' Days';
1772        }
1773        vm.rentalDays.vehicleDays.push(i);
1774        i = j;
1775      }
1776      for (var i = 0; i <= vm.totalDays; i++) {
1777        var j = i;
1778        if (i == 1) {
1779          i = i + ' Day';
1780        } else {
1781          i = i + ' Days';
1782        }
1783        vm.rentalDays.productDays.primaryValues.push(i);
1784        vm.rentalDays.productDays.secondaryValues.push(i);
1785        vm.rentalDays.insuranceDays.primaryValues.push(i);
1786        vm.rentalDays.insuranceDays.secondaryValues.push(i);
1787        i = j;
1788      }
1789    }
1790
1791    function displayPromo() {
1792      if (vm.showPromo) {
1793        vm.showPromo = false;
1794      } else {
1795        vm.showPromo = true;
1796      }
1797    }
1798
1799    // function for Rental Days and Itemized Tab
1800    function _add(num, product) {
1801      // Split by rental days tab
1802      if (angular.isDefined(product)) {
1803        var code = product.code;
1804      }
1805      // To set Days Value
1806      vm.primaryValue =
1807        typeof vm.primaryValue === 'string'
1808          ? parseInt(vm.primaryValue.replace(/^[^0-9]+/, ''))
1809          : vm.primaryValue;
1810      vm.secondaryValue =
1811        typeof vm.secondaryValue === 'string'
1812          ? parseInt(vm.secondaryValue.replace(/^[^0-9]+/, ''))
1813          : vm.secondaryValue;
1814      vm.totalDays =
1815        typeof vm.totalDays === 'string'
1816          ? parseInt(vm.totalDays.replace(/^[^0-9]+/, ''))
1817          : vm.totalDays;
1818
1819      if (
1820        vm.primaryDayValue == vm.totalDays ||
1821        vm.secondaryDayValue == vm.totalDays
1822      ) {
1823        vm.rentalModel.daySplitConfirmCTA = false;
1824      }
1825      if (
1826        num == carRentalConstant.splitInRental.PRIMARYDAY &&
1827        vm.primaryDayValue != vm.totalDays
1828      ) {
1829        vm.secondaryDayValue = vm.totalDays - vm.primaryDayValue;
1830
1831        var splitData = {
1832          splitType: carRentalConstant.splitInRental.DAY,
1833          days: vm.secondaryDayValue,
1834          splitOpted: vm.rentalModel.availedSplitbill,
1835          estimateCall: true,
1836          secondaryCreditCard: vm.secondaryCardSelected.number,
1837          rentalNumber: vm.rentalNumber,
1838        };
1839        getDataService.addToSplitDetails(splitData);
1840        vm.splitByTypeAPICall(splitData);
1841      } else if (
1842        num == carRentalConstant.splitInRental.SECONDARYDAY &&
1843        vm.secondaryDayValue != vm.totalDays
1844      ) {
1845        vm.primaryDayValue = vm.totalDays - vm.secondaryDayValue;
1846
1847        var splitData = {
1848          splitType: carRentalConstant.splitInRental.DAY,
1849          days: vm.secondaryDayValue,
1850          splitOpted: vm.rentalModel.availedSplitbill,
1851          estimateCall: true,
1852          secondaryCreditCard: vm.secondaryCardSelected.number,
1853          rentalNumber: vm.rentalNumber,
1854        };
1855        getDataService.addToSplitDetails(splitData);
1856        vm.splitByTypeAPICall(splitData);
1857      } else if (num == 'privalue-and-fees') {
1858        if (vm.primaryValue == null) {
1859          vm.secondaryValue = null;
1860        } else {
1861          vm.secondaryValue = vm.totalDays - vm.primaryValue;
1862          if (typeof vm.totalDays === 'number') {
1863            if (vm.secondaryValue > 1 || vm.secondaryValue == 0) {
1864              vm.secondaryValue = vm.secondaryValue + ' Days';
1865            } else {
1866              vm.secondaryValue = vm.secondaryValue + ' Day';
1867            }
1868          }
1869        }
1870
1871        if (vm.secondaryValue == 0 || vm.secondaryValue == '0 Days') {
1872          vm.dropDownValue.secondaryValue = '0 Days';
1873        }
1874        var extras = rentalService.itemizedDropdown(
1875          vm.primaryValue,
1876          vm.secondaryValue,
1877          vm.rentalDetails,
1878          '',
1879          num
1880        );
1881        vm.prodItemizedSec = extras.productItemizedSec;
1882        vm.insuranceItemizedSec = extras.insuranceItemizedSec;
1883        vm.prodItemizedPri = extras.productItemizedPri;
1884        vm.insuranceItemizedPri = extras.insuranceItemizedPri;
1885        vm.cubsideSelected = {};
1886        angular.forEach(vm.prodItemizedSec, function (value, key) {
1887          if (value == 'PER_RENTAL') {
1888            vm.cubsideSelected[key] = 'secondary';
1889          }
1890        });
1891
1892        /*if(vm.prodItemizedSec['CSD']){
1893          vm.cubsideSelected = 'secondary';
1894        }*/
1895
1896        var splitData = {
1897          days:
1898            typeof vm.secondaryValue == 'string'
1899              ? parseInt(vm.secondaryValue.replace(/^[^0-9]+/, ''))
1900              : vm.secondaryValue,
1901          splitOpted: vm.rentalModel.availedSplitbill,
1902          estimateCall: true,
1903          secondaryCreditCard: vm.secondaryCardSelected.number,
1904          rentalNumber: vm.rentalNumber,
1905          selectedProducts: extras.selectedProducts,
1906          selectedInsurances: extras.selectedInsurances,
1907          splitType: '',
1908        };
1909        getDataService.addToSplitDetails(splitData);
1910        vm.splitByTypeAPICall(splitData);
1911      } else if (num == 'secvalue-and-fees') {
1912        if (vm.secondaryValue == null) {
1913          vm.primaryValue = null;
1914        } else {
1915          vm.primaryValue = vm.totalDays - vm.secondaryValue;
1916          if (vm.primaryValue > 1 || vm.primaryValue == 0) {
1917            vm.primaryValue = vm.primaryValue + ' Days';
1918          } else {
1919            vm.primaryValue = vm.primaryValue + ' Day';
1920          }
1921        }
1922
1923        if (vm.primaryValue == 0 || vm.primaryValue == '0 Days') {
1924          vm.dropDownValue.primaryValue = '0 Days';
1925        }
1926
1927        var extras = rentalService.itemizedDropdown(
1928          vm.primaryValue,
1929          vm.secondaryValue,
1930          vm.rentalDetails,
1931          '',
1932          num
1933        );
1934        vm.prodItemizedSec = extras.productItemizedSec;
1935        vm.insuranceItemizedSec = extras.insuranceItemizedSec;
1936        vm.prodItemizedPri = extras.productItemizedPri;
1937        vm.insuranceItemizedPri = extras.insuranceItemizedPri;
1938        vm.cubsideSelected = {};
1939        angular.forEach(vm.prodItemizedSec, function (value, key) {
1940          if (value == 'PER_RENTAL') {
1941            vm.cubsideSelected[key] = 'secondary';
1942          }
1943        });
1944
1945        var splitData = {
1946          days:
1947            typeof vm.secondaryValue == 'string'
1948              ? parseInt(vm.secondaryValue.replace(/^[^0-9]+/, ''))
1949              : vm.secondaryValue,
1950          splitOpted: vm.rentalModel.availedSplitbill,
1951          estimateCall: true,
1952          secondaryCreditCard: vm.secondaryCardSelected.number,
1953          rentalNumber: vm.rentalNumber,
1954          selectedProducts: extras.selectedProducts,
1955          selectedInsurances: extras.selectedInsurances,
1956          splitType: '',
1957        };
1958        getDataService.addToSplitDetails(splitData);
1959        vm.splitByTypeAPICall(splitData);
1960      } else if (
1961        code != '' &&
1962        angular.isDefined(product) &&
1963        (product.category == '' || product.category == undefined)
1964      ) {
1965        var days = null;
1966        if (typeof vm.totalDays === 'string') {
1967          vm.totalDays = parseInt(vm.totalDays.replace(/^[^0-9]+/, ''));
1968        }
1969        vm.prodItemizedPri = vm.getExtrasDays(vm.prodItemizedPri);
1970        vm.insuranceItemizedPri = vm.getExtrasDays(vm.insuranceItemizedPri);
1971        vm.prodItemizedSec = vm.getExtrasDays(vm.prodItemizedSec);
1972        vm.insuranceItemizedSec = vm.getExtrasDays(vm.insuranceItemizedSec);
1973        if (num == 'primaryProduct') {
1974          vm.prodItemizedSec[code] = vm.totalDays - vm.prodItemizedPri[code];
1975          var extras = rentalService.itemizedDropdown(
1976            vm.prodItemizedPri,
1977            vm.prodItemizedSec,
1978            vm.rentalDetails,
1979            code,
1980            'product'
1981          );
1982          vm.dropDownValue.proDropDownPri[code] = 0;
1983        } else if (num == 'secondaryProduct') {
1984          vm.prodItemizedPri[code] = vm.totalDays - vm.prodItemizedSec[code];
1985          var extras = rentalService.itemizedDropdown(
1986            vm.prodItemizedPri,
1987            vm.prodItemizedSec,
1988            vm.rentalDetails,
1989            code,
1990            'product'
1991          );
1992          vm.dropDownValue.proDropDownSec[code] = 0;
1993        } else if (num == 'primaryInsurance') {
1994          vm.insuranceItemizedSec[code] =
1995            vm.totalDays - vm.insuranceItemizedPri[code];
1996          var extras = rentalService.itemizedDropdown(
1997            vm.insuranceItemizedPri,
1998            vm.insuranceItemizedSec,
1999            vm.rentalDetails,
2000            code,
2001            'insurance'
2002          );
2003          vm.dropDownValue.insDropDownPri[code] = 0;
2004        } else if (num == 'secondaryInsurance') {
2005          vm.insuranceItemizedPri[code] =
2006            vm.totalDays - vm.insuranceItemizedSec[code];
2007          var extras = rentalService.itemizedDropdown(
2008            vm.insuranceItemizedPri,
2009            vm.insuranceItemizedSec,
2010            vm.rentalDetails,
2011            code,
2012            'insurance'
2013          );
2014          vm.dropDownValue.insDropDownSec[code] = 0;
2015        }
2016        if (num == 'primaryProduct' || num == 'secondaryProduct') {
2017          if (vm.secondaryValue != null) {
2018            days = vm.secondaryValue;
2019          }
2020          var splitData = {
2021            days: days,
2022            splitOpted: vm.rentalModel.availedSplitbill,
2023            estimateCall: true,
2024            secondaryCreditCard: vm.secondaryCardSelected.number,
2025            rentalNumber: vm.rentalNumber,
2026            selectedProducts: extras.selectedProducts,
2027            selectedInsurances: extras.selectedInsurances,
2028            splitType: '',
2029          };
2030          getDataService.addToSplitDetails(splitData);
2031          vm.splitByTypeAPICall(splitData);
2032        } else if (num == 'primaryInsurance' || num == 'secondaryInsurance') {
2033          if (vm.secondaryValue != null) {
2034            days = vm.secondaryValue;
2035          }
2036          var splitData = {
2037            days: days,
2038            splitOpted: vm.rentalModel.availedSplitbill,
2039            estimateCall: true,
2040            secondaryCreditCard: vm.secondaryCardSelected.number,
2041            rentalNumber: vm.rentalNumber,
2042            selectedProducts: extras.selectedProducts,
2043            selectedInsurances: extras.selectedInsurances,
2044            splitType: '',
2045          };
2046          getDataService.addToSplitDetails(splitData);
2047          vm.splitByTypeAPICall(splitData);
2048        }
2049      } else if (
2050        num == 'primary' &&
2051        angular.isDefined(product) &&
2052        product.category == 'PER_RENTAL'
2053      ) {
2054        var extras = rentalService.itemizedDropdown(
2055          vm.prodItemizedPri,
2056          vm.prodItemizedSec,
2057          vm.rentalDetails,
2058          code,
2059          'product'
2060        );
2061        for (var i = 0; i < extras.selectedProducts.length; i++) {
2062          var obj = extras.selectedProducts[i];
2063          if (code === obj.code) {
2064            extras.selectedProducts.splice(i, 1);
2065            break;
2066          }
2067        }
2068        var product = {
2069          quantity: '1',
2070          code: code,
2071          days: 0,
2072        };
2073        extras.selectedProducts.push(product);
2074        var splitData = {
2075          days: 0,
2076          splitOpted: vm.rentalModel.availedSplitbill,
2077          estimateCall: true,
2078          secondaryCreditCard: vm.secondaryCardSelected.number,
2079          rentalNumber: vm.rentalNumber,
2080          selectedProducts: extras.selectedProducts,
2081          selectedInsurances: extras.selectedInsurances,
2082          splitType: '',
2083        };
2084        getDataService.addToSplitDetails(splitData);
2085        vm.splitByTypeAPICall(splitData);
2086      } else if (
2087        num == 'secondary' &&
2088        angular.isDefined(product) &&
2089        product.category == 'PER_RENTAL'
2090      ) {
2091        var extras = rentalService.itemizedDropdown(
2092          vm.prodItemizedPri,
2093          vm.prodItemizedSec,
2094          vm.rentalDetails,
2095          code,
2096          'product'
2097        );
2098        for (var i = 0; i < extras.selectedProducts.length; i++) {
2099          var obj = extras.selectedProducts[i];
2100          if (code === obj.code) {
2101            extras.selectedProducts.splice(i, 1);
2102            break;
2103          }
2104        }
2105        var product = {
2106          quantity: '1',
2107          code: code,
2108          days: vm.rentalDetails.reservationSummary.lengthOfRental,
2109        };
2110        extras.selectedProducts.push(product);
2111        var splitData = {
2112          days: 0,
2113          splitOpted: vm.rentalModel.availedSplitbill,
2114          estimateCall: true,
2115          secondaryCreditCard: vm.secondaryCardSelected.number,
2116          rentalNumber: vm.rentalNumber,
2117          selectedProducts: extras.selectedProducts,
2118          selectedInsurances: extras.selectedInsurances,
2119          splitType: '',
2120        };
2121        getDataService.addToSplitDetails(splitData);
2122        vm.splitByTypeAPICall(splitData);
2123      }
2124    }
2125    // function to make Estimate/confirm API call for split by amount &
2126    // rental days
2127    function splitByTypeAPICall(splitData, field) {
2128      splitType = splitData.splitType;
2129      if (splitData.splitType == carRentalConstant.splitInRental.DAY) {
2130        $rootScope.requestInProgress = true;
2131        rentalService.getSplitInRental(vm.rentalNumber).then(
2132          function (data) {
2133            $rootScope.requestInProgress = true;
2134            if (
2135              angular.isDefined(data.instructionList) &&
2136              data.instructionList.length > 0 &&
2137              data.instructionList[0].code == '5319'
2138            ) {
2139              splitConfirmed = true;
2140            } else {
2141              vm.previousSplitType = splitData.splitType;
2142              splitConfirmed = false;
2143            }
2144            if (
2145              angular.isDefined(data.reservationSummary) &&
2146              angular.isDefined(data.reservationSummary.splitBillSummary)
2147            ) {
2148              if (
2149                data.reservationSummary.rentalState ==
2150                carRentalConstant.splitInRental.ESTIMATE
2151              ) {
2152                clearAmountTabFields();
2153                vm.splitByDayPrimaryCardAmount =
2154                  data.reservationSummary.splitBillSummary.splitBillPrimary.cardAmount;
2155                vm.splitByDaySecondaryCardAmount =
2156                  data.reservationSummary.splitBillSummary.splitBillSecondary.cardAmount;
2157                vm.rentalModel.daySplitConfirmCTA = true;
2158              } else {
2159                vm.rentalDetails.reservationSummary.splitBillSummary.splitBillPrimary.cardAmount =
2160                  data.reservationSummary.splitBillSummary.splitBillPrimary.cardAmount;
2161                vm.rentalDetails.reservationSummary.splitBillSummary.splitBillSecondary.cardAmount =
2162                  data.reservationSummary.splitBillSummary.splitBillSecondary.cardAmount;
2163                if (
2164                  data.reservationSummary.splitBillSummary.numberOfDays == true
2165             
2165   ) {
2166                  vm.rentalDetails.reservationSummary.splitBillSummary =
2167                    data.reservationSummary.splitBillSummary;
2168                }
2169                if (
2170                  angular.isDefined(vm.primaryDayValue) &&
2171                  angular.isDefined(vm.secondaryDayValue)
2172                ) {
2173                  vm.primaryValue =
2174                    data.reservationSummary.splitBillSummary.splitBillPrimary.lengthOfRental;
2175                  vm.secondaryValue =
2176                    data.reservationSummary.splitBillSummary.splitBillSecondary.lengthOfRental;
2177                  if (vm.primaryValue > 1 || vm.primaryValue == 0) {
2178                    vm.primaryValue = vm.primaryValue + ' Days';
2179                  } else {
2180                    vm.primaryValue = vm.primaryValue + ' Day';
2181                  }
2182                  if (vm.secondaryValue > 1 || vm.secondaryValue == 0) {
2183                    vm.secondaryValue = vm.secondaryValue + ' Days';
2184                  } else {
2185                    vm.secondaryValue = vm.secondaryValue + ' Day';
2186                  }
2187
2188                  if (vm.secondaryValue && vm.primaryValue) {
2189                    vm._itemizedDropdown();
2190                  }
2191                  vm.prodItemizedPri =
2192                    data.reservationSummary.splitBillSummary.splitBillPrimary
2193                      .productmap == null
2194                      ? {}
2195                      : data.reservationSummary.splitBillSummary
2196                        .splitBillPrimary.productmap;
2197                  vm.insuranceItemizedPri =
2198                    data.reservationSummary.splitBillSummary.splitBillPrimary
2199                      .optionalServiceMap == null
2200                      ? {}
2201                      : data.reservationSummary.splitBillSummary
2202                        .splitBillPrimary.optionalServiceMap;
2203                  var dropDownValue = rentalService.displayDropDown(
2204                    vm.prodItemizedPri,
2205                    vm.insuranceItemizedPri,
2206                    'primary',
2207                    data
2208                  );
2209                  vm.dropDownValue.insDropDownPri = dropDownValue.insDrop;
2210                  vm.dropDownValue.proDropDownPri = dropDownValue.proDrop;
2211
2212                  vm.prodItemizedSec =
2213                    data.reservationSummary.splitBillSummary.splitBillSecondary
2214                      .productmap == null
2215                      ? {}
2216                      : data.reservationSummary.splitBillSummary
2217                        .splitBillSecondary.productmap;
2218                  vm.insuranceItemizedSec =
2219                    data.reservationSummary.splitBillSummary.splitBillSecondary
2220                      .optionalServiceMap == null
2221                      ? {}
2222                      : data.reservationSummary.splitBillSummary
2223                        .splitBillSecondary.optionalServiceMap;
2224                  var dropDownValue = rentalService.displayDropDown(
2225                    vm.prodItemizedSec,
2226                    vm.insuranceItemizedSec,
2227                    'secondary',
2228                    data
2229                  );
2230                  vm.dropDownValue.insDropDownSec = dropDownValue.insDrop;
2231                  vm.dropDownValue.proDropDownSec = dropDownValue.proDrop;
2232                  //vm.processDays(vm.dropDownValue);
2233                }
2234
2235                vm.errorDaySplit = '';
2236                vm.rentalModel.daySplitConfirmCTA = false;
2237                $('#splitAmount').modal('hide');
2238
2239                // GA-GTM implementation change for split by
2240                // amount confirm button
2241
2242                if (
2243                  angular.isDefined(data) &&
2244                  angular.isDefined(data.reservationSummary) &&
2245                  angular.isDefined(data.reservationSummary.gateExitDone)
2246                ) {
2247                  var ec = 'Mid Rental';
2248                } else {
2249                  var ec = 'Pre Rental';
2250                }
2251
2252                analytics(
2253                  true,
2254                  'Rental Summary - Confirm',
2255                  'splitByType',
2256                  angular.copy(data),
2257                  ec
2258                );
2259              }
2260            }
2261            $rootScope.requestInProgress = false;
2262          },
2263          function (error) {
2264            if (
2265              angular.isDefined(error.errorList) &&
2266              error.errorList.length > 0
2267            ) {
2268              vm.errorDaySplit = $scope.processErrorMessage(error).errorList;
2269              vm.rentalModel.daySplitConfirmCTA = false;
2270              $rootScope.requestInProgress = false;
2271            }
2272          }
2273        );
2274      } else if (
2275        splitData.splitType == carRentalConstant.splitInRental.AMOUNT
2276      ) {
2277        $rootScope.requestInProgress = true;
2278        rentalService.getSplitInRental(vm.rentalNumber).then(
2279          function (data) {
2280            $rootScope.requestInProgress = true;
2281            if (
2282              (angular.isDefined(data.instructionList) &&
2283                data.instructionList.length > 0 &&
2284                data.instructionList[0].code == '5319' &&
2285                vm.rentalDetails.reservationSummary &&
2286                vm.rentalDetails.reservationSummary.splitBillSummary &&
2287                vm.rentalDetails.reservationSummary.splitBillSummary
2288                  .counterProducts) ||
2289              vm.rentalDetails.reservationSummary.splitBillSummary
2290                .numberOfDays ||
2291              vm.rentalDetails.reservationSummary.splitBillSummary
2292                .counterProducts.optionalServices
2293            ) {
2294              vm.previousSplitType = '';
2295              splitConfirmed = true;
2296            } else {
2297              vm.previousSplitType = 'amount';
2298              splitConfirmed = false;
2299            }
2300            if (
2301              angular.isDefined(data.reservationSummary) &&
2302              angular.isDefined(data.reservationSummary.splitBillSummary)
2303            ) {
2304              if (
2305                data.reservationSummary.rentalState ==
2306                carRentalConstant.splitInRental.ESTIMATE
2307              ) {
2308                clearDaysTabFields();
2309                vm.primaryAmount =
2310                  data.reservationSummary.splitBillSummary.splitBillPrimary.cardAmount;
2311                if (
2312                  data.reservationSummary.splitBillSummary.splitBillSecondary
2313                    .cardAmount == null
2314                ) {
2315                  vm.secondaryAmount = '0.00';
2316                } else {
2317                  vm.secondaryAmount =
2318                    data.reservationSummary.splitBillSummary.splitBillSecondary.cardAmount;
2319                }
2320                vm.rentalModel.amountSplitConfirmCTA = true;
2321                if (
2322                  data.reservationSummary &&
2323                  data.reservationSummary.splitBillSummary &&
2324                  !data.reservationSummary.splitBillSummary.counterProducts &&
2325                  !data.reservationSummary.splitBillSummary.numberOfDays &&
2326                  !data.reservationSummary.splitBillSummary.optionalServices
2327                ) {
2328                  vm.rentalModel.enableCta = false;
2329                  if (
2330                    angular.isDefined(data.reservationSummary) &&
2331                    angular.isDefined(data.reservationSummary.lengthOfRental) &&
2332                    data.reservationSummary.lengthOfRental != null
2333                  ) {
2334                    vm.rentalDays.vehicleDays = [];
2335                    vm.rentalDays.productDays.primaryValues = [];
2336                    vm.rentalDays.productDays.secondaryValues = [];
2337                    vm.rentalDays.insuranceDays.primaryValues = [];
2338                    vm.rentalDays.insuranceDays.secondaryValues = [];
2339                    vm._populateRentalDays(
2340                      data.reservationSummary.lengthOfRental
2341                    );
2342                  }
2343                  setItemizedValues(data);
2344                }
2345                if (field == carRentalConstant.splitInRental.PRIMARYAMOUNT) {
2346                  vm.split.secondaryAmount =
2347                    data.reservationSummary.splitBillSummary.splitBillSecondary.cardAmount;
2348                  vm.secondaryAmountOldValue = vm.split.secondaryAmount;
2349                  var elem = angular.element('#secondaryAmount');
2350                  if (angular.element(elem).hasClass('ng-invalid')) {
2351                    $validationProvider.removeError(elem, true);
2352                  }
2353                } else {
2354                  vm.split.primaryAmount =
2355                    data.reservationSummary.splitBillSummary.splitBillPrimary.cardAmount;
2356                  vm.primaryAmountOldValue = vm.split.primaryAmount;
2357                  var elem = angular.element('#primaryAmount');
2358                  if (angular.element(elem).hasClass('ng-invalid')) {
2359                    $validationProvider.removeError(elem, true);
2360                  }
2361                }
2362              } else {
2363                if (
2364                  data.reservationSummary &&
2365                  data.reservationSummary.splitBillSummary &&
2366                  data.reservationSummary.splitBillSummary.dollarAmount == true
2367                ) {
2368                  vm.rentalDetails.reservationSummary.splitBillSummary =
2369                    angular.copy(data.reservationSummary.splitBillSummary);
2370                  vm.itemizedPrimaryAmount =
2371                    data.reservationSummary.splitBillSummary.splitBillPrimary.cardAmount;
2372                  vm.itemizedSecondaryAmount =
2373                    data.reservationSummary.splitBillSummary.splitBillSecondary.cardAmount;
2374                }
2375                setItemizedValues(data);
2376                vm.errorAmountSplit = '';
2377                vm.rentalModel.amountSplitConfirmCTA = false;
2378                $('#splitAmount').modal('hide');
2379
2380                // GA-GTM implementation change for split by
2381                // amount confirm button
2382                analytics(
2383                  true,
2384                  'Rental Summary - Confirm',
2385                  'splitByType',
2386                  angular.copy(data),
2387                  carRentalConstant.splitInRental.AMOUNT
2388                );
2389              }
2390            }
2391            $rootScope.requestInProgress = false;
2392          },
2393          function (error) {
2394            if (
2395              angular.isDefined(error.errorList) &&
2396              error.errorList.length > 0
2397            ) {
2398              vm.errorAmountSplit = $scope.processErrorMessage(error).errorList;
2399              vm.rentalModel.amountSplitConfirmCTA = false;
2400              $rootScope.requestInProgress = false;
2401            }
2402          }
2403        );
2404      } else {
2405        $rootScope.requestInProgress = true;
2406        rentalService.getSplitInRental(vm.rentalNumber).then(
2407          function (data) {
2408            $rootScope.requestInProgress = true;
2409            if (
2410              angular.isDefined(data.instructionList) &&
2411              data.instructionList.length > 0 &&
2412              data.instructionList[0].code == '5319' &&
2413              vm.rentalDetails.reservationSummary &&
2414              vm.rentalDetails.reservationSummary.splitBillSummary &&
2415              vm.rentalDetails.reservationSummary.splitBillSummary.dollarAmount
2416            ) {
2417              splitConfirmed = true;
2418              vm.previousSplitType = 'amount';
2419            } else {
2420              vm.previousSplitType = '';
2421              splitConfirmed = false;
2422            }
2423            if (
2424              angular.isDefined(data.reservationSummary) &&
2425              angular.isDefined(data.reservationSummary.splitBillSummary)
2426            ) {
2427              clearDaysTabFields();
2428              //vm.rentalDetails.reservationSummary.splitBillSummary = data.reservationSummary.splitBillSummary;
2429              //clearAmountTabFields();
2430              if (
2431                data.reservationSummary.rentalState ==
2432                carRentalConstant.splitInRental.ESTIMATE
2433              ) {
2434                vm.itemizedPrimaryAmount =
2435                  data.reservationSummary.splitBillSummary.splitBillPrimary.cardAmount;
2436                vm.itemizedSecondaryAmount =
2437                  data.reservationSummary.splitBillSummary.splitBillSecondary.cardAmount;
2438                if (
2439                  data.reservationSummary.splitBillSummary.splitBillSecondary
2440                    .cardAmount == null
2441                ) {
2442                  vm.itemizedSecondaryAmount = '0.00';
2443                } else {
2444                  vm.itemizedSecondaryAmount =
2445                    data.reservationSummary.splitBillSummary.splitBillSecondary.cardAmount;
2446                }
2447                vm.rentalModel.enableCta = true;
2448                if (
2449                  data.reservationSummary &&
2450                  data.reservationSummary.splitBillSummary &&
2451                  data.reservationSummary.splitBillSummary.dollarAmount == false
2452                ) {
2453                  vm.split.primaryAmount =
2454                    vm.rentalDetails.reservationSummary.rateSummary.estimatedTotal;
2455                  vm.split.secondaryAmount = '0.00';
2456                  vm.rentalModel.amountSplitConfirmCTA = false;
2457                }
2458
2459                if (
2460                  angular.isDefined(
2461                    data.reservationSummary.splitBillSummary.splitBillPrimary
2462                  )
2463                ) {
2464                  if (
2465                    angular.isDefined(
2466                      data.reservationSummary.splitBillSummary.splitBillPrimary
2467                        .productmap
2468                    )
2469                  ) {
2470                    vm.prodItemizedPri =
2471                      vm.rentalDetails.reservationSummary.splitBillSummary.splitBillPrimary.productmap =
2472                      data.reservationSummary.splitBillSummary
2473                        .splitBillPrimary.productmap == null
2474                        ? {}
2475                        : data.reservationSummary.splitBillSummary
2476                          .splitBillPrimary.productmap;
2477                  }
2478                  if (
2479                    angular.isDefined(
2480                      data.reservationSummary.splitBillSummary.splitBillPrimary
2481                        .optionalServiceMap
2482                    )
2483                  ) {
2484                    vm.insuranceItemizedPri =
2485                      vm.rentalDetails.reservationSummary.splitBillSummary.splitBillPrimary.optionalServiceMap =
2486                      data.reservationSummary.splitBillSummary
2487                        .splitBillPrimary.optionalServiceMap == null
2488                        ? {}
2489                        : data.reservationSummary.splitBillSummary
2490                          .splitBillPrimary.optionalServiceMap;
2491                  }
2492
2493                  var productMapPri = angular.copy(vm.prodItemizedPri);
2494                  var insuranceMapPri = angular.copy(vm.insuranceItemizedPri);
2495                  var dropDownValue = rentalService.displayDropDown(
2496                    productMapPri,
2497                    insuranceMapPri,
2498                    'primary',
2499                    data
2500                  );
2501                  vm.insuranceItemizedPri = vm.dropDownValue.insDropDownPri =
2502                    dropDownValue.insDrop;
2503                  vm.prodItemizedPri = vm.dropDownValue.proDropDownPri =
2504                    dropDownValue.proDrop;
2505                }
2506                if (
2507                  angular.isDefined(
2508                    data.reservationSummary.splitBillSummary.splitBillSecondary
2509                  )
2510                ) {
2511                  if (
2512                    angular.isDefined(
2513                      data.reservationSummary.splitBillSummary
2514                        .splitBillSecondary.productmap
2515                    )
2516                  ) {
2517                    if (
2518                      vm.rentalDetails.reservationSummary.splitBillSummary
2519                        .splitBillSecondary == null ||
2520                      vm.rentalDetails.reservationSummary.splitBillSummary
2521                        .splitBillSecondary.productmap == null
2522                    ) {
2523                      vm.rentalDetails.reservationSummary.splitBillSummary.split
2523BillSecondary =
2524                        data.reservationSummary.splitBillSummary.splitBillSecondary;
2525                    }
2526                    vm.prodItemizedSec =
2527                      vm.rentalDetails.reservationSummary.splitBillSummary.splitBillSecondary.productmap =
2528                      data.reservationSummary.splitBillSummary
2529                        .splitBillSecondary.productmap == null
2530                        ? {}
2531                        : data.reservationSummary.splitBillSummary
2532                          .splitBillSecondary.productmap;
2533                  }
2534                  if (
2535                    angular.isDefined(
2536                      data.reservationSummary.splitBillSummary
2537                        .splitBillSecondary.optionalServiceMap
2538                    )
2539                  ) {
2540                    vm.insuranceItemizedSec =
2541                      vm.rentalDetails.reservationSummary.splitBillSummary.splitBillSecondary.optionalServiceMap =
2542                      data.reservationSummary.splitBillSummary
2543                        .splitBillSecondary.optionalServiceMap == null
2544                        ? {}
2545                        : data.reservationSummary.splitBillSummary
2546                          .splitBillSecondary.optionalServiceMap;
2547                  }
2548
2549                  var productMapSec = angular.copy(vm.prodItemizedSec);
2550                  var insuranceMapSec = angular.copy(vm.insuranceItemizedSec);
2551                  var dropDownValue = rentalService.displayDropDown(
2552                    productMapSec,
2553                    insuranceMapSec,
2554                    'secondary',
2555                    data
2556                  );
2557                  vm.insuranceItemizedSec = vm.dropDownValue.insDropDownSec =
2558                    dropDownValue.insDrop;
2559                  vm.prodItemizedSec = vm.dropDownValue.proDropDownSec =
2560                    dropDownValue.proDrop;
2561                }
2562                angular.forEach(
2563                  data.reservationSummary.productSummaryList,
2564                  function (prod) {
2565                    if (prod.subProducts && prod.subProducts.length > 0) {
2566                      angular.forEach(prod.subProducts, function (subProduct) {
2567                        if (subProduct.category == 'PER_RENTAL') {
2568                          if (
2569                            vm.prodItemizedPri[subProduct.code] ==
2570                            vm.rentalDetails.reservationSummary.lengthOfRental
2571                          ) {
2572                            vm.cubsideSelected[subProduct.code] = 'primary';
2573                          } else if (
2574                            vm.prodItemizedSec[subProduct.code] ==
2575                            vm.rentalDetails.reservationSummary.lengthOfRental
2576                          ) {
2577                            vm.cubsideSelected[subProduct.code] = 'secondary';
2578                          } else {
2579                            vm.cubsideSelected[subProduct.code] = null;
2580                          }
2581                        }
2582                      });
2583                    } else {
2584                      if (prod.category == 'PER_RENTAL') {
2585                        if (
2586                          vm.prodItemizedPri[prod.code] ==
2587                          vm.rentalDetails.reservationSummary.lengthOfRental
2588                        ) {
2589                          vm.cubsideSelected[prod.code] = 'primary';
2590                        } else if (
2591                          vm.prodItemizedSec[prod.code] ==
2592                          vm.rentalDetails.reservationSummary.lengthOfRental
2593                        ) {
2594                          vm.cubsideSelected[prod.code] = 'secondary';
2595                        } else {
2596                          vm.cubsideSelected[prod.code] = null;
2597                        }
2598                      }
2599                    }
2600                  }
2601                );
2602
2603                if (vm.secondaryValue != null && vm.primaryValue != null) {
2604                  vm._itemizedDropdown();
2605                } else {
2606                  if (
2607                    angular.isDefined(data.reservationSummary) &&
2608                    angular.isDefined(data.reservationSummary.lengthOfRental) &&
2609                    data.reservationSummary.lengthOfRental != null
2610                  ) {
2611                    vm.rentalDays.vehicleDays = [];
2612                    vm.rentalDays.productDays.primaryValues = [];
2613                    vm.rentalDays.productDays.secondaryValues = [];
2614                    vm.rentalDays.insuranceDays.primaryValues = [];
2615                    vm.rentalDays.insuranceDays.secondaryValues = [];
2616                    vm._populateRentalDays(
2617                      data.reservationSummary.lengthOfRental
2618                    );
2619                  }
2620                }
2621                if (
2622                  data.reservationSummary &&
2623                  data.reservationSummary.splitBillSummary &&
2624                  data.reservationSummary.splitBillSummary.numberOfDays
2625                ) {
2626                  vm.rentalDetails.reservationSummary.splitBillSummary.numberOfDays =
2627                    data.reservationSummary.splitBillSummary.numberOfDays;
2628                }
2629              } else {
2630                if (
2631                  data.reservationSummary &&
2632                  data.reservationSummary.splitBillSummary &&
2633                  (data.reservationSummary.splitBillSummary.counterProducts ==
2634                    true ||
2635                    data.reservationSummary.splitBillSummary.optionalServices ==
2636                    true ||
2637                    data.reservationSummary.splitBillSummary.numberOfDays ==
2638                    true)
2639                ) {
2640                  vm.rentalDetails.reservationSummary.splitBillSummary =
2641                    angular.copy(data.reservationSummary.splitBillSummary);
2642                } else {
2643                  vm.rentalModel.availedSplitbill =
2644                    data.reservationSummary.splitBillSummary.splitBillEnabled;
2645                  vm.rentalDetails.reservationSummary.splitBillSummary =
2646                    angular.copy(data.reservationSummary.splitBillSummary);
2647                }
2648                if (
2649                  data.reservationSummary &&
2650                  data.reservationSummary.splitBillSummary &&
2651                  data.reservationSummary.splitBillSummary.dollarAmount == false
2652                ) {
2653                  vm.split.primaryAmount =
2654                    vm.rentalDetails.reservationSummary.rateSummary.estimatedTotal;
2655                  vm.split.secondaryAmount = '0.00';
2656                }
2657                setItemizedValues(data);
2658                vm.rentalModel.enableCta = false;
2659                $('#splitAmount').modal('hide');
2660                // GA-GTM implementation change for split by
2661                // amount confirm button
2662                analytics(
2663                  true,
2664                  'Rental Summary - Confirm',
2665                  'splitByType',
2666                  angular.copy(data)
2667                );
2668              }
2669            }
2670            $rootScope.requestInProgress = false;
2671          },
2672          function (data) {
2673            if (
2674              angular.isDefined(data.errorList) &&
2675              data.errorList.length > 0
2676            ) {
2677              vm.errorItemized = $scope.processErrorMessage(data).errorList;
2678              if (data.reservationSummary) {
2679                vm.rentalDays.vehicleDays = [];
2680                vm.rentalDays.productDays.primaryValues = [];
2681                vm.rentalDays.productDays.secondaryValues = [];
2682                vm.rentalDays.insuranceDays.primaryValues = [];
2683                vm.rentalDays.insuranceDays.secondaryValues = [];
2684                vm._populateRentalDays(data.reservationSummary.lengthOfRental);
2685                setItemizedValues(data);
2686              }
2687
2688              vm.rentalModel.enableCta = false;
2689              $rootScope.requestInProgress = false;
2690            }
2691          }
2692        );
2693      }
2694    }
2695
2696    // function to clear amount tab fields on some api call of either Days
2697    // or Itemized tab.
2698    function clearAmountTabFields() {
2699      vm.errorDaySplit = '';
2700      var e = angular.element('#primaryAmount');
2701      if (angular.element(e).hasClass('ng-invalid')) {
2702        $validationProvider.removeError(e, true);
2703      }
2704      var elem = angular.element('#secondaryAmount');
2705      if (angular.element(elem).hasClass('ng-invalid')) {
2706        $validationProvider.removeError(elem, true);
2707      }
2708      vm.split.primaryAmount = '';
2709      vm.split.secondaryAmount = '';
2710      vm.primaryAmountOldValue = '';
2711      vm.secondaryAmountOldValue = '';
2712      vm.rentalModel.amountSplitConfirmCTA = false;
2713      vm.errorAmountSplit = '';
2714    }
2715
2716    //Function to return Days:
2717    function getExtrasDays(extras) {
2718      angular.forEach(extras, function (value, key) {
2719        if (value != '0 Days' || value != 0) {
2720          extras[key] =
2721            typeof value == 'string'
2722              ? parseInt(value.replace(/^[^0-9]+/, ''))
2723              : value;
2724        } else {
2725          extras[key] =
2726            typeof value == 'string'
2727              ? parseInt(value.replace(/^[^0-9]+/, ''))
2728              : value;
2729        }
2730      });
2731
2732      //To check if any value is null-set to 0
2733      angular.forEach(extras, function (value, key) {
2734        if (value == null) {
2735          extras[key] = 0;
2736        }
2737      });
2738      return extras;
2739    }
2740
2741    // function to clear Days split tab fields on some api call of either
2742    // Amount or Itemized tab.
2743    function clearDaysTabFields() {
2744      vm.errorAmountSplit = '';
2745      vm.primaryDayValue = '';
2746      vm.secondaryDayValue = '';
2747      vm.rentalModel.daySplitConfirmCTA = false;
2748      vm.errorDaySplit = '';
2749    }
2750
2751    // confirm call requestObject for split by amount & rental days Tab
2752    function splitPaymentConfirm(splitByType) {
2753      if (splitConfirmed) {
2754        vm.rentalModel.showAlertMessage = true;
2755        splitType = splitByType;
2756      } else {
2757        if (splitByType == carRentalConstant.splitInRental.AMOUNT) {
2758          var splitData = {
2759            splitType: carRentalConstant.splitInRental.AMOUNT,
2760            dollarAmount: vm.split.secondaryAmount,
2761            splitOpted: vm.rentalModel.availedSplitbill,
2762            estimateCall: false,
2763            secondaryCreditCard: vm.secondaryCardSelected.number,
2764            rentalNumber: vm.rentalNumber,
2765          };
2766          getDataService.addToSplitDetails(splitData);
2767          vm.splitByTypeAPICall(splitData);
2768        } else if (splitByType == carRentalConstant.splitInRental.DAY) {
2769          var splitData = {
2770            splitType: carRentalConstant.splitInRental.DAY,
2771            days: vm.secondaryDayValue,
2772            splitOpted: vm.rentalModel.availedSplitbill,
2773            estimateCall: false,
2774            secondaryCreditCard: vm.secondaryCardSelected.number,
2775            rentalNumber: vm.rentalNumber,
2776          };
2777          getDataService.addToSplitDetails(splitData);
2778          vm.splitByTypeAPICall(splitData);
2779        } else {
2780          var extras = {
2781            selectedProducts: [],
2782            selectedInsurances: [],
2783          };
2784
2785          angular.forEach(vm.prodItemizedSec, function (value, key) {
2786            var product = {
2787              code: key,
2788              days:
2789                typeof value == 'string'
2790                  ? parseInt(value.replace(/^[^0-9]+/, ''))
2791                  : value,
2792            };
2793            extras.selectedProducts.push(product);
2794          });
2795          angular.forEach(vm.insuranceItemizedSec, function (value, key) {
2796            var insurance = {
2797              code: key,
2798              days:
2799                typeof value == 'string'
2800                  ? parseInt(value.replace(/^[^0-9]+/, ''))
2801                  : value,
2802            };
2803            extras.selectedInsurances.push(insurance);
2804          });
2805          var splitData = {
2806            days:
2807              angular.isDefined(vm.secondaryValue) && vm.secondaryValue != ''
2808                ? vm.secondaryValue
2809                : null,
2810            splitOpted: vm.rentalModel.availedSplitbill,
2811            estimateCall: false,
2812            secondaryCreditCard: vm.secondaryCardSelected.number,
2813            rentalNumber: vm.rentalNumber,
2814            selectedProducts: extras.selectedProducts,
2815            selectedInsurances: extras.selectedInsurances,
2816            splitType: '',
2817          };
2818          getDataService.addToSplitDetails(splitData);
2819          vm.splitByTypeAPICall(splitData);
2820        }
2821      }
2822    }
2823
2824    // GA-GTM implementation changes
2825    function analytics(
2826      isRedirect,
2827      eventLabel,
2828      eventCategory,
2829      data,
2830      rentalState
2831    ) {
2832      //$window.dataLayer = [];
2833      // Boolean isRedirect is added to call GTM script only if page is redirected.
2834      if (isRedirect) {
2835        window.dataLayer = [];
2836        reservationModelService.addGTMScript();
2837      }
2838      setTimeout(function () {
2839        if (eventCategory == 'splitbill' || eventCategory == 'splitByType') {
2840          var _bookingState =
2841            angular.isDefined(vm.rentalDetails.reservationSummary) &&
2842              angular.isDefined(
2843                vm.rentalDetails.reservationSummary.gateExitDone
2844              ) &&
2845              vm.rentalDetails.reservationSummary.gateExitDone === true
2846              ? 'Mid Rental'
2847              : 'Pre Rental';
2848          rentalState = angular.isDefinedAndNotNull(rentalState)
2849            ? rentalState
2850            : _bookingState;
2851          var _d = {
2852            eventCategory: eventCategory,
2853            eventLabel: eventLabel,
2854            data: data,
2855            rentalState: rentalState,
2856          };
2857
2858          gaService.analyticsSplitbillClickEvents(_d);
2859
2860          if (_bookingState == 'Mid Rental') {
2861            var bs = 'Mid-Rental';
2862          } else {
2863            var bs = 'Pre-Rental';
2864          }
2865
2866          dataLayer.push({
2867            event: 'customDimension',
2868            bookingState: bs,
2869            'resConfirmationNum-rentalAggrementNum':
2870              vm.rentalDetails.reservationSummary.confirmationNumber +
2871              '-' +
2872              vm.rentalDetails.reservationSummary.rentalAgreementNumber,
2873          });
2874        } else if (eventCategory == 'select' || eventCategory == 'unselect') {
2875          gaService.analyticsRentalClickEvents(
2876            vm.rentalDetails,
2877            eventLabel,
2878            eventCategory
2879          );
2880        } else {
2881          gaService.analyticsRentalClickEvents(vm.rentalDetails, eventLabel);
2882        }
2883      }, 100);
2884    }
2885
2886    // Added this function to fix the DP(document path)issue for GA/GTM
2887    function callbackFn(tabId, callback) {
2888      $location.url(carRentalConstant.modifyRentalTabMap[tabId]);
2889      callback();
2890    }
2891
2892    vm.events = {
2893      focusDropDown: function () {
2894        setTimeout(function () {
2895          ABG.focusBootstrapDropdown(
2896            $('#timeDropDown .sp-dmenu-inner'),
2897            'value',
2898            vm.dropTime,
2899            180
2900          );
2901        }, 100);
2902      },
2903      showPaymentOption: function () {
2904        /*
2905         * SPLITBILL-73- user views split selected at rental
2906         * selected by default
2907         */
2908        vm.errorAmountSplit = [];
2909        vm.errorItemized = [];
2910        vm.rentalModel.enableCta = false;
2911        vm.rentalModel.amountSplitConfirmCTA = false;
2912        var e = angular.element('#primaryAmount');
2913        if (angular.element(e).hasClass('ng-invalid')) {
2914          $validationProvider.removeError(e, true);
2915        }
2916        var elem = angular.element('#secondaryAmount');
2917        if (angular.element(elem).hasClass('ng-invalid')) {
2918          $validationProvider.removeError(elem, true);
2919        }
2920        vm.split.primaryAmount =
2921          vm.rentalDetails.reservationSummary.rateSummary.estimatedTotal;
2922        vm.split.secondaryAmount = '0.00';
2923        rentalService
2924          .displaySplitOption(angular.copy(vm.rentalDetails))
2925          .then(function (displayTab) {
2926            if (
2927              angular.isDefined(
2928                vm.rentalDetails.reservationSummary.splitBillSummary
2929              )
2930            ) {
2931              vm.splitOptionTab = displayTab;
2932              var splitBillSummary =
2933                vm.rentalDetails.reservationSummary.splitBillSummary;
2934              if (splitBillSummary.numberOfDays) {
2935                vm.primaryValue =
2936                  splitBillSummary.splitBillPrimary.lengthOfRental;
2937                vm.secondaryValue =
2938                  splitBillSummary.splitBillSecondary.lengthOfRental;
2939                if (vm.primaryValue > 1 || vm.primaryValue == 0) {
2940                  vm.primaryValue = vm.primaryValue + ' Days';
2941                } else {
2942                  vm.primaryValue = vm.primaryValue + ' Day';
2943                }
2944                if (vm.secondaryValue > 1 || vm.secondaryValue == 0) {
2945                  vm.secondaryValue = vm.secondaryValue + ' Days';
2946                } else {
2947                  vm.secondaryValue = vm.secondaryValue + ' Day';
2948                }
2949
2950                //To display dropdown Values on Modal click
2951                vm.prodItemizedPri =
2952                  vm.rentalDetails.reservationSummary.splitBillSummary
2953                    .splitBillPrimary.productmap == null
2954                    ? {}
2955                    : vm.rentalDetails.reservationSummary.splitBillSummary
2956                      .splitBillPrimary.productmap;
2957                vm.insuranceItemizedPri =
2958                  vm.rentalDetails.reservationSummary.splitBillSummary
2959                    .splitBillPrimary.optionalServiceMap == null
2960                    ? {}
2961                    : vm.rentalDetails.reservationSummary.splitBillSummary
2962                      .splitBillPrimary.optionalServiceMap;
2963                var dropDownValue = rentalService.displayDropDown(
2964                  vm.prodItemizedPri,
2965                  vm.insuranceItemizedPri,
2966                  'primary',
2967                  vm.rentalDetails
2968                );
2969                vm.dropDownValue.insDropDownPri = dropDownValue.insDrop;
2970                vm.dropDownValue.proDropDownPri = dropDownValue.proDrop;
2971                if (
2972                  vm.rentalDetails.reservationSummary.splitBillSummary
2973                    .splitBillSecondary != null
2974                ) {
2975                  vm.prodItemizedSec =
2976                    vm.rentalDetails.reservationSummary.splitBillSummary
2977                      .splitBillSecondary.productmap == null
2978                      ? {}
2979                      : vm.rentalDetails.reservationSummary.splitBillSummary
2980                        .splitBillSecondary.productmap;
2981                  vm.insuranceItemizedSec =
2982                    vm.rentalDetails.reservationSummary.splitBillSummary
2983                      .splitBillSecondary.optionalServiceMap == null
2984                      ? {}
2985                      : vm.rentalDetails.reservationSummary.splitBillSummary
2986                        .splitBillSecondary.optionalServiceMap;
2987                }
2988                var dropDownValue = rentalService.displayDropDown(
2989                  vm.prodItemizedSec,
2990                  vm.insuranceItemizedSec,
2991                  'secondary',
2992                  vm.rentalDetails
2993                );
2994                vm.dropDownValue.insDropDownSec = dropDownValue.insDrop;
2995                vm.dropDownValue.proDropDownSec = dropDownValue.proDrop;
2996                //handleCSSDisplay();
2997                //setItemizedValues(vm.rentalDetails);
2998              } else {
2999                vm.primaryValue = null;
3000                vm.secondaryValue = null;
3001                vm.rentalDays.vehicleDays = [];
3002                /*vm.prodItemizedPri={};
3003              vm.prodItemizedSec={};
3004              vm.insuranceItemizedPri={};
3005              vm.insuranceItemizedSec={};*/
3006                vm.rentalDays.productDays.primaryValues = [];
3007                vm.rentalDays.productDays.secondaryValues = [];
3008                vm.rentalDays.insuranceDays.primaryValues = [];
3009                vm.rentalDays.insuranceDays.secondaryValues = [];
3010                vm._populateRentalDays(
3011                  vm.rentalDetails.reservationSummary.lengthOfRental
3012                );
3013              }
3014              // * The code is commented as part of new CR (Please
3015              // do not remove this commented code) STARTS-*/
3016
3017              /*
3018               * if(displayTab.tab2.active===true){
3019               * vm.primaryDayValue =
3020               * splitBillSummary.splitBillPrimary.lengthOfRental;
3021               * vm.secondaryDayValue =
3022               * splitBillSummary.splitBillSecondary.lengthOfRental;
3023               * vm.rentalModel.daySplitConfirmCTA = false; }else
3024               */
3025
3026              // * The code is commented as part of new CR (Please
3027              // do not remove this commented code) ENDS-*/
3028
3029              $('.showTab-itemized, .showTab-amount').removeClass('active');
3030              angular.element('#tabItemized, #tabAmount').removeClass('active');
3031              if (displayTab.tab1.active === true) {
3032                vm.itemizedPrimaryAmount = vm.split.primaryAmount =
3033                  splitBillSummary.splitBillPrimary.cardAmount;
3034                vm.itemizedSecondaryAmount = vm.split.secondaryAmount =
3035                  splitBillSummary.splitBillSecondary.cardAmount;
3036
3037                $('.showTab-amount').addClass('active');
3038                angular.element('#tabAmount').addClass('active');
3039                vm.rentalModel.amountSplitConfirmCTA = false;
3040              } else if (displayTab.tab3.active === true) {
3041                $('.showTab-itemized').addClass('active');
3042                angular.element('#tabItemized').addClass('active');
3043                vm.rentalModel.enableCta = false;
3044              } else {
3045                vm.itemizedPrimaryAmount = vm.split.primaryAmount =
3046                  vm.rentalDetails.reservationSummary.rateSummary.estimatedTotal;
3047                vm.itemizedSecondaryAmount = vm.split.secondaryAmount = '0.00';
3048                $('.showTab-amount').addClass('active');
3049                angular.element('#tabAmount').addClass('active');
3050                vm.rentalModel.amountSplitConfirmCTA = false;
3051                vm.splitOptionTab.tab1.active = true;
3052              }
3053            }
3054            //GA GTM
3055            if (
3056              angular.isDefined(vm.rentalDetails) &&
3057              angular.isDefined(vm.rentalDetails.reservationSummary) &&
3058              angular.isDefined(
3059                vm.rentalDetails.reservationSummary.gateExitDone
3060              )
3061            ) {
3062              var ec = 'Mid Rental';
3063            } else {
3064              var ec = 'Pre Rental';
3065            }
3066
3067            analytics(true, 'Rental Summary - Split Payment', 'splitbill', ec);
3068          });
3069      },
3070      redirect: function (tabId, isBackButton) {
3071        vm.rentalModel.tabFocus = false;
3072        vm.rentalModel.confirmMessage = false;
3073        vm.shuttleError = false;
3074        vm.error = [];
3075        vm.errorDisplayInsurance = [];
3076        vm.errorDisplayProduct = [];
3077        vm.clickedtab = tabId;
3078        vm.cardError = [];
3079        vm.isBackButton = true;
3080        if (tabId && !isBackButton) {
3081          vm.isBackButton = false;
3082          /*setTimeout(function(){
3083            $location.url(carRentalConstant.modifyRentalTabMap[tabId]);
3084            dataLayer.push(['_trackPageview', $location.path()]);
3085
3086          },10)*/
3087          callbackFn(tabId, function () {
3088            dataLayer.push(['_trackPageview', $location.path()]);
3089          });
3090        }
3091        // vm.unsplit added for unsplit check condition
3092        if (!vm.rentalState.value && !vm.rentalModel.unsplit) {
3093          vm.rentalModel.confirmSuccess = false;
3094          toggleTab(true, tabId);
3095          if (vm.rentalDetails.tabDisplayControl['tab3'].active == true) {
3096            rentalSummaryTab = true;
3097            $rootScope.requestInProgress = true;
3098            vm.oldSecondaryCardSummary = {};
3099            rentalService.getRentalSummary().then(
3100              function (data) {
3101                vm.rentalDetails = data;
3102                vm.rentalDetails.tabDisplayControl['tab1'].active = false;
3103                vm.rentalDetails.tabDisplayControl['tab2'].active = false;
3104                vm.rentalDetails.tabDisplayControl['tab3'].active = true;
3105                vm.rentalDetails.tabDisplayControl['tab4'].active = false;
3106                //if (jQuery(window).width() <= 767) {
3107                jQuery('.showTab-tab3').addClass('active');
3108                jQuery('.sp-rental-container')
3109                  .find('.sp-nav-wrap')
3110                  .addClass('cus-d-sm-none');
3111
3112                //}
3113                $rootScope.requestInProgress = true;
3114                if (
3115                  angular.isDefined(data.errorList) &&
3116                  data.errorList.length > 0
3117                ) {
3118                  vm.errorList = $scope.processErrorMessage(data).errorList;
3119                } else {
3120                  vm.errorList = [];
3121                  /* TODO- Need to have one generic method */
3122                  $validationProvider.resetError(
3123                    'vm.secondaryCardSelected.number',
3124                    true
3125                  );
3126                  if (
3127                    angular.isDefined(data.reservationSummary) &&
3128                    angular.isDefined(data.reservationSummary.splitBillSummary)
3129                  ) {
3130                    if (
3131                      angular.isDefined(
3132                        data.reservationSummary.splitBillSummary
3133                          .splitBillEnabled
3134                      )
3135                    ) {
3136                      vm.rentalModel.availedSplitbill =
3137                        data.reservationSummary.splitBillSummary.splitBillEnabled;
3138                    }
3139                    if (
3140                      angular.isDefined(data.reservationSummary.gebUser) &&
3141                      data.reservationSummary.gebUser
3142                    ) {
3143                      vm.rentalModel.availedSplitbill = true;
3144                    }
3145                    vm.rentalDetails.reservationSummary.splitBillSummary =
3146                      data.reservationSummary.splitBillSummary;
3147                    if (
3148                      data.reservationSummary.splitBillSummary &&
3149                      data.reservationSummary.splitBillSummary
3150                        .splitBillSecondary != null &&
3151                      data.reservationSummary.splitBillSummary
3152                        .splitBillSecondary.ccSummary != null
3153                    ) {
3154                      vm.secondaryCardSelected =
3155                        data.reservationSummary.splitBillSummary.splitBillSecondary.ccSummary;
3156                    }
3157                    if (
3158                      vm.rentalDetails.reservationSummary.gebUser &&
3159                      (vm.secondaryCardSelected.number == '' ||
3160                        (vm.secondaryCardSelected.number !== '' &&
3161                          vm.secondaryCardSelected.number !== undefined &&
3162                          vm.rentalDetails.reservationSummary.splitBillSummary
3163                            .splitBillSecondary.cardAmount === null))
3164                    ) {
3165                      vm.hidePaymentInfo = true;
3166                    } else {
3167                      vm.hidePaymentInfo = false;
3168                    }
3169                  }
3170                  vm.rentalModel.changedCard = false;
3171                  /* TODO- Need to have one generic method */
3172                  // vm.rentalModel.availedSplitbill =
3173                  // data.reservationSummary.splitBillSummary.splitBillEnabled;
3174                  /*
3175                   * if(angular.isDefined(data.reservationSummary) &&
3176                   * angular.isDefined(data.reservationSummary.splitBillSummary)){
3177                   * vm.rentalDetails.reservationSummary.splitBillSummary =
3178                   * data.reservationSummary.splitBillSummary;
3179                   *
3180                   * //To update data @ handleSplitModal
3181                   * function, after opt of any split and
3182                   * navigate to rentalSummary tab from other
3183                   * tab.
3184                   * //vm.rentalDetails.reservationSummary.splitBillSummary =
3185                   * data.reservationSummary.splitBillSummary; }
3186                   */
3187                  // Calling function based on rentalSummary
3188                  // response to populate updated values, even
3189                  // after any rental extension if any.
3190                  if (
3191                    angular.isDefined(data.reservationSummary) &&
3192                    angular.isDefined(data.reservationSummary.lengthOfRental) &&
3193                    data.reservationSummary.lengthOfRental != null
3194                  ) {
3195                    vm.rentalDays.vehicleDays = [];
3196                    vm.rentalDays.productDays.primaryValues = [];
3197                    vm.rentalDays.productDays.secondaryValues = [];
3198                    vm.rentalDays.insuranceDays.primaryValues = [];
3199                    vm.rentalDays.insuranceDays.secondaryValues = [];
3200                    vm._populateRentalDays(
3201                      data.reservationSummary.lengthOfRental
3202                    );
3203                  }
3204
3205                  // splitbill-396 condition added to show
3206                  // Toggle option on rental summary based on
3207                  // splitEligible
3208                  if (
3209                    angular.isDefined(data.reservationSummary) &&
3210                    angular.isDefined(data.reservationSummary.splitEligible)
3211                  ) {
3212                    vm.rentalModel.showSplitOpt =
3213                      data.reservationSummary.splitEligible;
3214                  }
3215                  vm.rentalState.tab = 'Rental-Summary';
3216                  // vm.unsplit added for unsplit check
3217                  // condition
3218                  vm.rentalModel.unsplit = false;
3219                  // SPLITBILL-1342 toggle missing on rental
3220                  // summary after confirming an product
3221                  // vm.rentalModel.showExtras=false;
3222
3223                  // vm.rentalDetails.reservationSummary.splitBillSummary=data.reservationSummary.splitBillSummary
3224                  // ;
3225                  if (
3226                    vm.rentalModel.availedSplitbill &&
3227                    angular.isDefined(
3228                      data.reservationSummary.splitBillSummary
3229                    ) &&
3230                    data.reservationSummary.splitBillSummary.dollarAmount &&
3231                    data.reservationSummary.splitBillSummary.splitBillPrimary
3232                      .cardAmount != null &&
3233                    data.reservationSummary.splitBillSummary.splitBillSecondary
3234                      .cardAmount != null
3235                  ) {
3236                    vm.split.primaryAmount = $filter('currency')(
3237                      data.reservationSummary.splitBillSummary.splitBillPrimary
3238                        .cardAmount
3239                    );
3240                    vm.split.secondaryAmount = $filter('currency')(
3241                      data.reservationSummary.splitBillSummary
3242                        .splitBillSecondary.cardAmount
3243                    );
3244                  }
3245
3246                  // <!-- splitbill-63 -->
3247                  if (
3248                    vm.rentalModel.availedSplitbill &&
3249                    angular.isDefined(
3250                      data.reservationSummary.splitBillSummary
3251                    ) &&
3252                    !data.reservationSummary.gebUser
3253                  ) {
3254                    if (
3255                      data.reservationSummary.splitBillSummary
3256                        .counterProducts ||
3257                      data.reservationSummary.splitBillSummary.optionalServices
3258                    ) {
3259                      setItemizedValues(data);
3260                    } else {
3261                      if (
3262                        angular.isDefined(
3263                          data.reservationSummary.splitBillSummary
3264                            .splitBillPrimary
3265                        ) &&
3266                        angular.isDefined(
3267                          data.reservationSummary.splitBillSummary
3268                            .splitBillPrimary.lengthOfRental
3269                        ) &&
3270                        angular.isDefined(
3271                          data.reservationSummary.splitBillSummary
3272                            .splitBillSecondary
3273                        ) &&
3274                        angular.isDefined(
3275                          data.reservationSummary.splitBillSummary
3276                            .splitBillSecondary.lengthOfRental
3277                        ) &&
3278                        data.reservationSummary.splitBillSummary.numberOfDays
3279                      ) {
3280                        vm.primaryValue =
3281                          data.reservationSummary.splitBillSummary.splitBillPrimary.lengthOfRental;
3282                        vm.secondaryValue =
3283                          data.reservationSummary.splitBillSummary.splitBillSecondary.lengthOfRental;
3284                        if (vm.primaryValue > 1 || vm.primaryValue == 0) {
3285                          vm.primaryValue = vm.primaryValue + ' Days';
3286                        } else {
3287                          vm.primaryValue = vm.primaryValue + ' Day';
3288                        }
3289                        if (vm.secondaryValue > 1 || vm.secondaryValue == 0) {
3290                          vm.secondaryValue = vm.secondaryValue + ' Days';
3291                        } else {
3292                          vm.secondaryValue = vm.secondaryValue + ' Day';
3293                        }
3294                      }
3295                      if (vm.secondaryValue && vm.primaryValue) {
3296                        vm._itemizedDropdown();
3297                      }
3298                      setItemizedValues(data);
3299                    }
3300                  }
3301                  /* splitbill-63 */
3302                  if (
3303                    angular.isDefined(
3304                      vm.rentalDetails.reservationSummary.productSummaryList
3305                    ) &&
3306                    vm.rentalDetails.reservationSummary.productSummaryList
3307                      .length == 0 &&
3308                    angular.isDefined(
3309                      vm.rentalDetails.reservationSummary.insuranceSummaryList
3310                    ) &&
3311                    vm.rentalDetails.reservationSummary.insuranceSummaryList
3312                      .length == 0
3313                  ) {
3314                    vm.rentalModel.hideItemizedTab = true;
3315                  }
3316                  if (
3317                    angular.isDefined(vm.addresses) &&
3318                    !$.isEmptyObject(vm.addresses)
3319                  ) {
3320                    vm._getAddressList(vm.addresses);
3321                  }
3322                  if (
3323                    angular.isDefined(vm.rentalDetails.reservationSummary) &&
3324                    angular.isDefined(
3325                      vm.rentalDetails.reservationSummary.personalInfo
3326                    ) &&
3327                    angular.isDefined(
3328                      vm.rentalDetails.reservationSummary.personalInfo.residency
3329                    ) &&
3330                    angular.isDefined(
3331                      vm.rentalDetails.reservationSummary.personalInfo.residency
3332                        .value
3333                    )
3334                  ) {
3335                    vm.reservationModel.paymentRq.address.country =
3336                      vm.rentalDetails.reservationSummary.personalInfo.residency.value;
3337                  }
3338
3339                  /*
3340                   * Story 689-Modified this function for
3341                   * Displaying warning message when credit
3342                   * card is about to expire[Rental Summary
3343                   * tab]-Starts-->
3344                   */
3345
3346                  if (
3347                    vm.rentalDetails &&
3348                    vm.rentalDetails.reservationSummary &&
3349                    vm.rentalDetails.reservationSummary.splitBillSummary &&
3350                    vm.rentalDetails.reservationSummary.splitBillSummary
3351                      .splitBillSecondary &&
3352                    vm.rentalDetails.reservationSummary.splitBillSummary
3353                      .splitBillSecondary.ccSummary
3354                  ) {
3355                    vm.secondaryCardSelected = angular.copy(
3356                      vm.rentalDetails.reservationSummary.splitBillSummary
3357                        .splitBillSecondary.ccSummary
3358                    );
3359                    if (angular.isDefined(vm.secondaryCardSelected.expiryMsg)) {
3360                      vm.warningMsgSC = $scope.processErrorMessage(
3361                        vm.secondaryCardSelected
3362                      ).expiryMsg;
3363                    }
3364                  }
3365                  if (
3366                    angular.isDefined(
3367                      vm.rentalDetails &&
3368                      vm.rentalDetails.reservationSummary &&
3369                      vm.rentalDetails.reservationSummary.splitBillSummary &&
3370                      vm.rentalDetails.reservationSummary.splitBillSummary
3371                        .splitBillPrimary &&
3372                      vm.rentalDetails.reservationSummary.splitBillSummary
3373                        .splitBillPrimary.ccSummary
3374                    )
3375                  ) {
3376                    vm.primaryCard = angular.copy(
3377                      vm.rentalDetails.reservationSummary.splitBillSummary
3378                        .splitBillPrimary.ccSummary
3379                    );
3380                    if (angular.isDefined(vm.primaryCard.expiryMsg)) {
3381                      vm.warningMsgPC = $scope.processErrorMessage(
3382                        vm.primaryCard
3383                      ).expiryMsg;
3384                    }
3385                  }
3386                  /*
3387                   * Story 689-Modified this function for
3388                   * Displaying warning message when credit
3389                   * card is about to expire[Rental Summary
3390                   * Tab]-Ends-->
3391                   */
3392
3393                  vm._loadMnthYrDropdown();
3394                  vm._populateBillingInfoCountryList();
3395                  if (vm.brand == 'avis') {
3396                    vm.getStatesForCountry(
3397                      vm.reservationModel.paymentRq.address.country,
3398                      'onload'
3399                    );
3400                  }
3401                }
3402                rentalSummaryTab = false;
3403                $rootScope.requestInProgress = false;
3404
3405                //GA-GTM implementation change - eventcategory is based on splitbillenabled.
3406                if (vm.rentalModel.availedSplitbill) {
3407                  analytics(true, 'rental summary-Tab', 'splitbill');
3408                } else {
3409                  analytics(true, 'rental summary-Tab');
3410                }
3411              },
3412              function (error) {
3413                $window.location.href =
3414                  $rootScope.contextPath +
3415                  '/' +
3416                  $rootScope.locale +
3417                  '/' +
3418                  'reservation/view-modify-cancel' +
3419                  htmlExtension;
3420              }
3421            );
3422          } else if (
3423            vm.rentalDetails.tabDisplayControl['tab1'].active == true
3424          ) {
3425            vm.rentalDetails.reservationSummary.gebUser
3426              ? (vm.rentalState.tab = 'Extras')
3427              : null;
3428            vm.requestInProgress = true;
3429            $rootScope.requestInProgress = true;
3430            vm.rentalModel.showExtras = false;
3431            callExtras();
3432            //if (jQuery(window).width() <= 767) {
3433            jQuery('.showTab-tab1').addClass('active');
3434            jQuery('.sp-rental-container')
3435              .find('.sp-nav-wrap')
3436              .addClass('cus-d-sm-none');
3437            //}
3438            //GA-GTM implementation change - eventcategory is based on splitbillenabled.
3439            if (vm.rentalModel.availedSplitbill) {
3440              analytics(true, 'add rental extras-Tab', 'splitbill');
3441            } else {
3442              analytics(true, 'add rental extras-Tab');
3443            }
3444          } else if (
3445            vm.rentalDetails.tabDisplayControl['tab2'].active == true
3446          ) {
3447            vm.rentalDetails.reservationSummary.gebUser
3448              ? (vm.rentalState.tab = 'Modify-Return')
3449              : null;
3450            $rootScope.requestInProgress = true;
3451            vm.clearLoc(true);
3452            rentalService.getRentalExtension().then(
3453              function (data) {
3454                $rootScope.requestInProgress = true;
3455                vm.rentalDetails.tabDisplayControl['tab1'].active = false;
3456                vm.rentalDetails.tabDisplayControl['tab2'].active = true;
3457                vm.rentalDetails.tabDisplayControl['tab3'].active = false;
3458                vm.rentalDetails.tabDisplayControl['tab4'].active = false;
3459                //if (jQuery(window).width() <= 767) {
3460                jQuery('.showTab-tab2').addClass('active');
3461                jQuery('.sp-rental-container')
3462                  .find('.sp-nav-wrap')
3463                  .addClass('cus-d-sm-none');
3464                //}
3465                vm.rentalExtension = data;
3466                if (
3467                  angular.isDefined(data.reservationSummary) &&
3468                  angular.isDefined(data.reservationSummary.rateSummary)
3469                ) {
3470                  vm.rateSummary = data.reservationSummary.rateSummary;
3471                }
3472                // initialising availed splitbill variable
3473                // and secondary Credit card after rental
3474                // extension call
3475
3476                if (
3477                  angular.isDefined(data.reservationSummary) &&
3478                  angular.isDefined(data.reservationSummary.splitBillSummary) &&
3479                  angular.isDefined(
3480                    data.reservationSummary.splitBillSummary.splitBillEnabled
3481                  )
3482                ) {
3483                  vm.rentalModel.availedSplitbill =
3484                    data.reservationSummary.splitBillSummary.splitBillEnabled;
3485                  if (
3486                    angular.isDefined(
3487                      vm.rentalExtension.reservationSummary.splitBillSummary
3488                        .splitBillSecondary
3489                    ) &&
3490                    vm.rentalExtension.reservationSummary.splitBillSummary
3491                      .splitBillSecondary != null &&
3492                    angular.isDefined(
3493                      vm.rentalExtension.reservationSummary.splitBillSummary
3494                        .splitBillSecondary.ccSummary
3495                    ) &&
3496                    vm.rentalExtension.reservationSummary.splitBillSummary
3497                      .splitBillSecondary.ccSummary != null
3498                  ) {
3499                    vm.secondaryCardSelected =
3500                      vm.rentalExtension.reservationSummary.splitBillSummary.splitBillSecondary.ccSummary;
3501                  }
3502                }
3503                // initialising Primary Credit card after
3504                // rental extension call
3505                if (
3506                  angular.isDefined(vm.rentalExtension.reservationSummary) &&
3507                  angular.isDefined(
3508                    vm.rentalExtension.reservationSummary.splitBillSummary
3509                  ) &&
3510                  angular.isDefined(
3511                    vm.rentalExtension.reservationSummary.splitBillSummary
3512                      .splitBillPrimary
3513                  ) &&
3514                  vm.rentalExtension.reservationSummary.splitBillSummary
3515                    .splitBillPrimary != null &&
3516                  angular.isDefined(
3517                    vm.rentalExtension.reservationSummary.splitBillSummary
3518                      .splitBillPrimary.ccSummary
3519                  ) &&
3520                  vm.rentalExtension.reservationSummary.splitBillSummary
3521                    .splitBillPrimary.ccSummary != null
3522                ) {
3523                  vm.primaryCard =
3524                    vm.rentalExtension.reservationSummary.splitBillSummary.splitBillPrimary.ccSummary;
3525                }
3526
3527                if (
3528                  angular.isDefined(data.reservationSummary) &&
3529                  angular.isDefined(data.reservationSummary.rentalState)
3530                ) {
3531                  vm.rentalState = {
3532                    value:
3533                      data.reservationSummary.rentalState == 'estimate'
3534                        ? true
3535                        : false,
3536                    tab: 'Modify-Return',
3537                  };
3538                }
3539
3540                if (
3541                  vm.rentalDetails.reservationSummary.gebUser &&
3542                  data.reservationSummary.splitBillSummary.splitBillSecondary &&
3543                  data.reservationSummary.splitBillSummary.splitBillSecondary
3544                    .ccSummary &&
3545                  data.reservationSummary.splitBillSummary.splitBillSecondary
3546                    .ccSummary.number
3547                ) {
3548                  vm.rentalModel.availedSplitbill = true;
3549                }
3550
3551                if (
3552                  angular.isDefined(
3553                    vm.rentalExtension.reservationSummary.splitBillSummary
3554                  )
3555                ) {
3556                  var splitRequest = {
3557                    splitOpted:
3558                      vm.rentalExtension.reservationSummary.splitBillSummary
3559                        .splitBillEnabled,
3560                    secondaryCreditCard:
3561                      angular.isDefined(
3562                        vm.rentalExtension.reservationSummary.splitBillSummary
3563                          .splitBillSecondary
3564                      ) &&
3565                        vm.rentalExtension.reservationSummary.splitBillSummary
3566                          .splitBillSecondary != null &&
3567                        angular.isDefined(
3568                          vm.rentalExtension.reservationSummary.splitBillSummary
3569                            .splitBillSecondary.ccSummary
3570                        ) &&
3571                        angular.isDefined(
3572                          vm.rentalExtension.reservationSummary.splitBillSummary
3573                            .splitBillSecondary.ccSummary.number
3574                        )
3575                        ? vm.rentalExtension.reservationSummary.splitBillSummary
3576                          .splitBillSecondary.ccSummary.number
3577                        : '',
3578                  };
3579                }
3580                if (vm.rentalDetails.reservationSummary.gebUser) {
3581                  vm.rateSummary.totalAdditonalCharges = 0;
3582                }
3583
3584                getDataService.addToSplitDetails(splitRequest);
3585                vm.returnLoc =
3586                  vm.rentalExtension.reservationSummary.dropLoc.name +
3587                  ', ' +
3588                  vm.rentalExtension.reservationSummary.dropLoc.locationCode;
3589                vm.returnDate = $filter('ModifiedDate')(
3590                  vm.rentalExtension.reservationSummary.dropDateTime
3591                );
3592                vm.dropTime = $filter('date')(
3593                  vm.rentalExtension.reservationSummary.dropDateTime,
3594                  'h:mm a'
3595                );
3596                var customer = authenticationService.getCustomerModel();
3597                _setDateFormatPreference(customer, data);
3598                _setTimeFormatPreference(customer, data);
3599                $rootScope.requestInProgress = false;
3600
3601                //GA-GTM implementation change - eventcategory is based on splitbillenabled.
3602                if (vm.rentalModel.availedSplitbill) {
3603                  analytics(true, 'modify return-Tab', 'splitbill');
3604                } else {
3605                  analytics(true, 'modify return-Tab');
3606                }
3607              },
3608              function (error) {
3609                if (
3610                  angular.isDefined(error.errorList) &&
3611                  error.errorList.length > 0
3612                ) {
3613                  vm.errorList = $scope.processErrorMessage(error).errorList;
3614                  $rootScope.requestInProgress = false;
3615                }
3616              }
3617            );
3618            rentalSummaryTab = false;
3619            if (vm.rentalDetails.reservationSummary.gebUser) {
3620              jQuery('.showTab-tab2').addClass('sp-tab-geb-user');
3621            }
3622          } else if (
3623            vm.rentalDetails.tabDisplayControl['tab4'].active == true
3624          ) {
3625            //for shuttle tracking
3626            vm.rentalDetails.tabDisplayControl['tab1'].active = false;
3627            vm.rentalDetails.tabDisplayControl['tab2'].active = false;
3628            vm.rentalDetails.tabDisplayControl['tab3'].active = false;
3629            vm.rentalDetails.tabDisplayControl['tab4'].active = true;
3630            jQuery('.showTab-tab4').addClass('active');
3631            jQuery('.sp-rental-container')
3632              .find('.sp-nav-wrap')
3633              .addClass('cus-d-sm-none');
3634            $rootScope.requestInProgress = true;
3635            var scope = angular
3636              .element($('.bingMap'))
3637              .injector()
3638              .get('$rootScope');
3639            navigator.geolocation.getCurrentPosition(
3640              function (result) {
3641                //scope.LoadMap(result.coords.latitude, result.coords.longitude);
3642                rentalService
3643                  .getShuttleDetails('42.2379436', '-83.3297705')
3644                  .then(
3645                    function (data) {
3646                      vm.shuttleDetails = data;
3647                      vm.shuttleDetails['position'] =
3648                        vm.rentalDetails.reservationSummary.pickLoc.position;
3649                      scope.LoadMap(
3650                        '42.2379436',
3651                        '-83.3297705',
3652                        15,
3653                        vm.shuttleDetails
3654                      );
3655                      $timeout(function () {
3656                        $rootScope.requestInProgress = false;
3657                      }, 1000);
3658                    },
3659                    function (error) {
3660                      if (error.errorList && error.errorList.length > 0) {
3661                        vm.error = $scope.processErrorMessage(error).errorList;
3662                        vm.shuttleError = true;
3663                        $rootScope.requestInProgress = false;
3664                      }
3665                    }
3666                  );
3667              },
3668              function (error) {
3669                vm.shuttleError = true;
3670                $timeout(function () {
3671                  $rootScope.requestInProgress = false;
3672                }, 1000);
3673              }
3674            );
3675          }
3676        }
3677        // vm.unsplit added for unsplit check condition
3678        else if (vm.rentalState.value && !vm.rentalModel.unsplit) {
3679          if (vm.rentalDetails.tabDisplayControl['tab1'].active == true) {
3680            vm.rentalDetails.tabDisplayControl['tab1'].disabled = true;
3681            vm.rentalModel.confirmSuccess = true;
3682            // toggleTab(true,tabId);
3683          } else if (
3684            vm.rentalDetails.tabDisplayControl['tab2'].active == true
3685          ) {
3686            vm.rentalDetails.tabDisplayControl['tab2'].disabled = true;
3687            vm.rentalModel.modifyReturnActive = true;
3688          }
3689        }
3690        if (angular.isDefined(tabId)) {
3691          $('html, body').animate({
3692            scrollTop: $('#tabStart').position().top,
3693          });
3694        } else {
3695          $window.scrollTo(0, 0);
3696        }
3697      },
3698      leaveChanges: function (field) {
3699        if (field == 'splitPaymentModal') {
3700          $rootScope.requestInProgress = true;
3701          rentalService.getRentalExtension().then(
3702            function (data) {
3703              $rootScope.requestInProgress = true;
3704              if (
3705                angular.isDefined(data.reservationSummary) &&
3706                angular.isDefined(data.reservationSummary.splitBillSummary)
3707              ) {
3708                vm.rentalDetails.reservationSummary.splitBillSummary =
3709                  data.reservationSummary.splitBillSummary;
3710                if (
3711                  angular.isDefined(data.reservationSummary.splitBillSummary) &&
3712                  data.reservationSummary.splitBillSummary.numberOfDays
3713                ) {
3714                  if (
3715                    angular.isDefined(
3716                      data.reservationSummary.splitBillSummary.splitBillPrimary
3717                    ) &&
3718                    angular.isDefined(
3719                      data.reservationSummary.splitBillSummary.splitBillPrimary
3720                        .lengthOfRental
3721                    )
3722                  ) {
3723                    vm.primaryValue = vm.primaryDayValue =
3724                      data.reservationSummary.splitBillSummary.splitBillPrimary.lengthOfRental;
3725                  }
3726                  if (
3727                    angular.isDefined(
3728                      data.reservationSummary.splitBillSummary
3729                        .splitBillSecondary
3730                    ) &&
3731                    data.reservationSummary.splitBillSummary
3732                      .splitBillSecondary != null &&
3733                    angular.isDefined(
3734                      data.reservationSummary.splitBillSummary
3735                        .splitBillSecondary.lengthOfRental
3736                    ) &&
3737                    angular.isDefined(
3738                      data.reservationSummary.splitBillSummary
3739                        .splitBillSecondary.lengthOfRental != null
3740                    )
3741                  ) {
3742                    vm.secondaryValue = vm.secondaryDayValue =
3743                      data.reservationSummary.splitBillSummary.splitBillSecondary.lengthOfRental;
3744                  }
3745                }
3746
3747                if (
3748                  angular.isDefined(
3749                    data.reservationSummary.splitBillSummary.splitBillPrimary
3750                  ) &&
3751                  (angular.isDefined(
3752                    data.reservationSummary.splitBillSummary.splitBillPrimary
3753                      .optionalServiceMap
3754                  ) ||
3755                    angular.isDefined(
3756                      data.reservationSummary.splitBillSummary.splitBillPrimary
3757                        .productmap
3758                    ))
3759                ) {
3760                  vm.insuranceItemizedPri =
3761                    data.reservationSummary.splitBillSummary.splitBillPrimary
3762                      .optionalServiceMap == null
3763                      ? {}
3764                      : data.reservationSummary.splitBillSummary
3765                        .splitBillPrimary.optionalServiceMap;
3766                  vm.prodItemizedPri =
3767                    data.reservationSummary.splitBillSummary.splitBillPrimary
3768                      .productmap == null
3769                      ? {}
3770                      : data.reservationSummary.splitBillSummary
3771                        .splitBillPrimary.productmap;
3772                }
3773                if (
3774                  angular.isDefined(
3775                    data.reservationSummary.splitBillSummary.splitBillSecondary
3776                  ) &&
3777                  data.reservationSummary.splitBillSummary.splitBillSecondary !=
3778                  null &&
3779                  (angular.isDefined(
3780                    data.reservationSummary.splitBillSummary.splitBillSecondary
3781                      .optionalServiceMap
3782                  ) ||
3783                    angular.isDefined(
3784                      data.reservationSummary.splitBillSummary
3785                        .splitBillSecondary.productmap
3786                    ))
3787                ) {
3788                  vm.insuranceItemizedSec =
3789                    data.reservationSummary.splitBillSummary.splitBillSecondary
3790                      .optionalServiceMap == null
3791                      ? {}
3792                      : data.reservationSummary.splitBillSummary
3793                        .splitBillSecondary.optionalServiceMap;
3794                  vm.prodItemizedSec =
3795                    data.reservationSummary.splitBillSummary.splitBillSecondary
3796                      .productmap == null
3797                      ? {}
3798                      : data.reservationSummary.splitBillSummary
3799                        .splitBillSecondary.productmap;
3800                } else if (
3801                  data.reservationSummary.splitBillSummary.splitBillSecondary ==
3802                  null
3803                ) {
3804                  vm.insuranceItemizedSec = {};
3805                  vm.prodItemizedSec = {};
3806                }
3807                vm.cubsideSelected = {};
3808                angular.forEach(
3809                  data.reservationSummary.productSummaryList,
3810                  function (prod) {
3811                    if (prod.subProducts && prod.subProducts.length > 0) {
3812                      angular.forEach(prod.subProducts, function (subProduct) {
3813                        if (subProduct.category == 'PER_RENTAL') {
3814                          if (
3815                            vm.prodItemizedPri[subProduct.code] ==
3816                            vm.rentalDetails.reservationSummary.lengthOfRental
3817                          ) {
3818                            vm.cubsideSelected[subProduct.code] = 'primary';
3819                          } else if (
3820                            vm.prodItemizedSec[subProduct.code] ==
3821                            vm.rentalDetails.reservationSummary.lengthOfRental
3822                          ) {
3823                            vm.cubsideSelected[subProduct.code] = 'secondary';
3824                          } else {
3825                            vm.cubsideSelected[subProduct.code] = null;
3826                          }
3827                        }
3828                      });
3829                    } else {
3830                      if (prod.category == 'PER_RENTAL') {
3831                        if (
3832                          vm.prodItemizedPri[prod.code] ==
3833                          vm.rentalDetails.reservationSummary.lengthOfRental
3834                        ) {
3835                          vm.cubsideSelected[prod.code] = 'primary';
3836                        } else if (
3837                          vm.prodItemizedSec[prod.code] ==
3838                          vm.rentalDetails.reservationSummary.lengthOfRental
3839                        ) {
3840                          vm.cubsideSelected[prod.code] = 'secondary';
3841                        } else {
3842                          vm.cubsideSelected[prod.code] = null;
3843                        }
3844                      }
3845                    }
3846                  }
3847                );
3848
3849                vm.events.showPaymentOption();
3850              } else {
3851                var e = angular.element('#primaryAmount');
3852                if (angular.element(e).hasClass('ng-invalid')) {
3853                  $validationProvider.removeError(e, true);
3854                }
3855                var elem = angular.element('#secondaryAmount');
3856                if (angular.element(elem).hasClass('ng-invalid')) {
3857                  $validationProvider.removeError(elem, true);
3858                }
3859                vm.split.primaryAmount = '';
3860                vm.primaryAmountOldValue = '';
3861                vm.split.secondaryAmount = '';
3862                vm.secondaryAmountOldValue = '';
3863                vm.rentalModel.amountSplitConfirmCTA = false;
3864                vm.primaryDayValue = '';
3865                vm.secondaryDayValue = '';
3866                vm.primaryValue = '';
3867                vm.secondaryValue = '';
3868                vm.prodItemizedPri = {};
3869                vm.prodItemizedSec = {};
3870                vm.insuranceItemizedPri = {};
3871                vm.insuranceItemizedSec = {};
3872                vm.rentalModel.daySplitConfirmCTA = false;
3873              }
3874              $rootScope.requestInProgress = false;
3875            },
3876            function (error) {
3877              if (
3878                angular.isDefined(error.errorList) &&
3879                error.errorList.length > 0
3880              ) {
3881                vm.errorList = $scope.processErrorMessage(error).errorList;
3882                $rootScope.requestInProgress = false;
3883              }
3884            }
3885          );
3886        } else {
3887          $rootScope.requestInProgress = true;
3888          vm.rentalModel.confirmSuccess = false;
3889          vm.rentalState.value = false;
3890          vm.rentalModel.modifyReturnActive = false;
3891          vm.shuttleError = false;
3892          vm.rentalModel.time = false;
3893          vm.rentalModel.loc = false;
3894          vm.product.selectedProduct = [];
3895
3896          vm.close(vm.accordianClicked);
3897          rentalService.getRentalExtension().then(
3898            function (data) {
3899              vm.returnDate = $filter('ModifiedDate')(
3900                data.reservationSummary.dropDateTime
3901              );
3902              $rootScope.requestInProgress = false;
3903            },
3904            function (error) { }
3905          );
3906        }
3907      },
3908      showMap: function (locationCode) {
3909        geoservices.getLangLat(locationCode).then(
3910          function (data) {
3911            if (data.errorList && data.errorList.length > 0) {
3912              vm.rentalModel.latError = true;
3913            } else {
3914              vm.rentalModel.latError = false;
3915              var _path =
3916                'http://www.google.com/maps/dir//' +
3917                data.stationInfoList[0].latitude +
3918                ',' +
3919                data.stationInfoList[0].longitude +
3920                '/@' +
3921                data.stationInfoList[0].latitude +
3922                ',' +
3923                data.stationInfoList[0].longitude +
3924                ',12z';
3925              window.open(_path, '_blank');
3926            }
3927          },
3928          function (error) {
3929            console.log('error in lat-lng call');
3930          }
3931        );
3932      },
3933      goBack: function () {
3934        if (vm.rentalDetails.tabDisplayControl['tab1'].active == true) {
3935          vm.rentalModel.confirmSuccess = false;
3936          vm.rentalModel.showExtras = false;
3937          // vm.unsplit added for unsplit check condition
3938          if (vm.rentalState.value) {
3939            hideStickySection(true);
3940          } else {
3941            hideStickySection(false);
3942          }
3943          if (vm.rentalModel.unsplit == true) {
3944            vm.rentalModel.unsplit = false;
3945            vm.rentalModel.availedSplitbill = true;
3946          }
3947        }
3948        if (vm.rentalDetails.tabDisplayControl['tab2'].active == true) {
3949          vm.rentalModel.modifyReturnActive = false;
3950          if (vm.rentalState.value) {
3951            hideStickySection(true);
3952          } else {
3953            hideStickySection(false);
3954          }
3955          // vm.unsplit added for unsplit check condition
3956          if (vm.rentalModel.unsplit == true) {
3957            vm.rentalModel.unsplit = false;
3958            vm.rentalModel.availedSplitbill = true;
3959          }
3960        }
3961        if (vm.rentalDetails.tabDisplayControl['tab3'].active == true) {
3962          // vm.unsplit added for unsplit check condition
3963          if (vm.rentalModel.unsplit == true) {
3964            vm.rentalModel.unsplit = false;
3965            vm.rentalModel.availedSplitbill = true;
3966          }
3967          if (vm.rentalModel.showAlertMessage) {
3968            $('.showTab-itemized, .showTab-days, .showTab-amount').removeClass(
3969              'active'
3970            );
3971            angular
3972              .element('#tabItemized, #tabRentalDays, #tabAmount')
3973              .removeClass('active');
3974            if (splitType == carRentalConstant.splitInRental.AMOUNT) {
3975              $('.showTab-amount').addClass('active');
3976              angular.element('#tabAmount').addClass('active');
3977              vm.amountSplitConfirmCTA = false;
3978            } else if (splitType == carRentalConstant.splitInRental.DAY) {
3979              $('.showTab-days').addClass('active');
3980              angular.element('#tabRentalDays').addClass('active');
3981              vm.daySplitConfirmCTA = false;
3982            } else {
3983              $('.showTab-itemized').addClass('active');
3984              angular.element('#tabItemized').addClass('active');
3985            }
3986            vm.rentalModel.showAlertMessage = false;
3987          }
3988        }
3989        if (vm.rentalDetails.tabDisplayControl['tab4'].active == true) {
3990          jQuery('.showTab-tab4').removeClass('active');
3991          jQuery('.sp-nav-wrap').removeClass('cus-d-sm-none');
3992        }
3993        // ga-gtm implementation to track event of opting unsplit and click on go back button
3994
3995        if (vm.rentalState.tab == 'Extras') {
3996          var eventLabel = carRentalConstant.unsplitExtraGoback;
3997        } else if (vm.rentalState.tab == 'Modify-Return') {
3998          if (vm.rentalModel.tabFocus) {
3999            hideStickySection(true);
4000          } else {
4001            hideStickySection(false);
4002          }
4003          var eventLabel = carRentalConstant.unsplitModifyGoback;
4004        } else {
4005          var eventLabel = carRentalConstant.unsplitSummaryGoback;
4006        }
4007
4008        if (
4009          angular.isDefined(vm.rentalDetails) &&
4010          angular.isDefined(vm.rentalDetails.reservationSummary) &&
4011          angular.isDefined(vm.rentalDetails.reservationSummary.gateExitDone)
4012        ) {
4013          var ec = 'Mid Rental';
4014        } else {
4015          var ec = 'Pre Rental';
4016        }
4017
4018        analytics(false, eventLabel, 'splitbill', ec);
4019      },
4020    };
4021
4022    function setItemizedValues(data) {
4023      vm.prodItemizedPri =
4024        data.reservationSummary.splitBillSummary.splitBillPrimary.productmap ==
4025          null
4026          ? {}
4027          : data.reservationSummary.splitBillSummary.splitBillPrimary
4028            .productmap;
4029      vm.insuranceItemizedPri =
4030        data.reservationSummary.splitBillSummary.splitBillPrimary
4031          .optionalServiceMap == null
4032          ? {}
4033          : data.reservationSummary.splitBillSummary.splitBillPrimary
4034            .optionalServiceMap;
4035      var dropDownValue = rentalService.displayDropDown(
4036        vm.prodItemizedPri,
4037        vm.insuranceItemizedPri,
4038        'primary',
4039        data
4040      );
4041      vm.dropDownValue.insDropDownPri = dropDownValue.insDrop;
4042      vm.dropDownValue.proDropDownPri = dropDownValue.proDrop;
4043      if (data.reservationSummary.splitBillSummary.splitBillSecondary != null) {
4044        vm.prodItemizedSec =
4045          data.reservationSummary.splitBillSummary.splitBillSecondary
4046            .productmap == null
4047            ? {}
4048            : data.reservationSummary.splitBillSummary.splitBillSecondary
4049              .productmap;
4050        vm.insuranceItemizedSec =
4051          data.reservationSummary.splitBillSummary.splitBillSecondary
4052            .optionalServiceMap == null
4053            ? {}
4054            : data.reservationSummary.splitBillSummary.splitBillSecondary
4055              .optionalServiceMap;
4056      }
4057      //Added for SPLITBILL-3394 CR-starts
4058      if (
4059        angular.isDefinedAndNotNull(
4060          data.reservationSummary.splitBillSummary.splitBillPrimary.cardAmount
4061        ) &&
4062        angular.isDefinedAndNotNull(
4063          data.reservationSummary.splitBillSummary.splitBillSecondary
4064        ) &&
4065        data.reservationSummary.splitBillSummary.splitBillPrimary.cardAmount !=
4066        null &&
4067        data.reservationSummary.splitBillSummary.splitBillSecondary
4068          .cardAmount != null &&
4069        angular.isUndefined(vm.primaryAmount) &&
4070        angular.isUndefined(vm.secondaryAmount)
4071      ) {
4072        vm.itemizedPrimaryAmount =
4073          data.reservationSummary.splitBillSummary.splitBillPrimary.cardAmount;
4074        vm.itemizedSecondaryAmount =
4075          data.reservationSummary.splitBillSummary.splitBillSecondary.cardAmount;
4076      }
4077      //Added for SPLITBILL-3394 CR-Ends
4078      var dropDownValue = rentalService.displayDropDown(
4079        vm.prodItemizedSec,
4080        vm.insuranceItemizedSec,
4081        'secondary',
4082        data
4083      );
4084      vm.dropDownValue.insDropDownSec = dropDownValue.insDrop;
4085      vm.dropDownValue.proDropDownSec = dropDownValue.proDrop;
4086      if (data.reservationSummary.splitBillSummary.numberOfDays == true) {
4087        vm.primaryValue =
4088          data.reservationSummary.splitBillSummary.splitBillPrimary.lengthOfRental;
4089        vm.secondaryValue =
4090          data.reservationSummary.splitBillSummary.splitBillSecondary.lengthOfRental;
4091        if (vm.primaryValue > 1 || vm.primaryValue == 0) {
4092          vm.primaryValue = vm.primaryValue + ' Days';
4093        } else {
4094          vm.primaryValue = vm.primaryValue + ' Day';
4095        }
4096        if (vm.secondaryValue > 1 || vm.secondaryValue == 0) {
4097          vm.secondaryValue = vm.secondaryValue + ' Days';
4098        } else {
4099          vm.secondaryValue = vm.secondaryValue + ' Day';
4100        }
4101      } else {
4102        vm.primaryValue = null;
4103        vm.secondaryValue = null;
4104      }
4105
4106      angular.forEach(
4107        data.reservationSummary.productSummaryList,
4108        function (prod) {
4109          if (prod.subProducts && prod.subProducts.length > 0) {
4110            angular.forEach(prod.subProducts, function (subProduct) {
4111              if (subProduct.category == 'PER_RENTAL') {
4112                if (
4113                  vm.prodItemizedPri[subProduct.code] ==
4114                  vm.rentalDetails.reservationSummary.lengthOfRental
4115                ) {
4116                  vm.cubsideSelected[subProduct.code] = 'primary';
4117                } else if (
4118                  vm.prodItemizedSec[subProduct.code] ==
4119                  vm.rentalDetails.reservationSummary.lengthOfRental
4120                ) {
4121                  vm.cubsideSelected[subProduct.code] = 'secondary';
4122                } else {
4123                  vm.cubsideSelected[subProduct.code] = null;
4124                }
4125              }
4126            });
4127          } else {
4128            if (prod.category == 'PER_RENTAL') {
4129              if (
4130                vm.prodItemizedPri[prod.code] ==
4131                vm.rentalDetails.reservationSummary.lengthOfRental
4132              ) {
4133                vm.cubsideSelected[prod.code] = 'primary';
4134              } else if (
4135                vm.prodItemizedSec[prod.code] ==
4136                vm.rentalDetails.reservationSummary.lengthOfRental
4137              ) {
4138                vm.cubsideSelected[prod.code] = 'secondary';
4139              } else {
4140                vm.cubsideSelected[prod.code] = null;
4141              }
4142            }
4143          }
4144        }
4145      );
4146    }
4147
4148    // To store selected products in reservationModel
4149    function productSelected(
4150      productObj,
4151      code,
4152      isSelectValChanged,
4153      extrasId,
4154      quantity
4155    ) {
4156      var isPresent = false;
4157
4158      if (vm.productCheckbox[code]) {
4159        if (productObj.selected == true) {
4160          arrayPop(code, true);
4161        }
4162        productObj.selected = true;
4163        if (quantity == undefined || quantity == '') {
4164          quantity = productObj.quantity = 1;
4165        } else {
4166          productObj.quantity = quantity;
4167        }
4168        vm.analytics(false, 'rental-' + productObj.code, 'select');
4169
4170        if (extrasId) {
4171          var extraIndex = extrasId.indexOf('_ext');
4172          if (extraIndex == -1) {
4173            productObj.productId = extrasId;
4174          } else {
4175            productObj.productId = productObj.code + 'chk_ext';
4176          }
4177        }
4178        var addProduct = {
4179          quantity: productObj.quantity,
4180          code: productObj.code,
4181          selected: productObj.selected,
4182        };
4183
4184        vm.product.selectedProduct.push(addProduct);
4185        getDataService.addRentalProducts(vm.product.selectedProduct);
4186      } else if (
4187        !vm.productCheckbox[code] &&
4188        angular.isDefined(quantity) &&
4189        quantity != ''
4190      ) {
4191        productObj.selected = true;
4192        productObj.quantity = quantity;
4193        var addProduct = {
4194          quantity: productObj.quantity,
4195          code: productObj.code,
4196          selected: productObj.selected,
4197        };
4198        vm.product.selectedProduct.push(addProduct);
4199        getDataService.addRentalProducts(vm.product.selectedProduct);
4200      } else {
4201        arrayPop(code, true);
4202        vm.cssDropDown[code] = 0;
4203        //To remove sub products when CSSG is unchecked
4204        if (code == 'CSSG') {
4205          for (var i = 0; i < productObj.subProducts.length; i++) {
4206            var key = productObj.subProducts[i].code;
4207            vm.productCheckbox[key] = false;
4208            vm.cssDropDown[key] = 0;
4209            arrayPop(key, true);
4210          }
4211        }
4212        vm.analytics(false, 'rental-' + productObj.code, 'unselect');
4213        getDataService.addRentalProducts(vm.product.selectedProduct);
4214      }
4215
4216      //Below code for CSS display in options page
4217      // assign the quantity for CSS and subproducts of boxes(BXS,BXL,BXM)
4218      if (angular.isDefined(quantity)) {
4219        if (angular.isDefined(vm.cssDropDown[code])) {
4220          quantity = vm.cssDropDown[code];
4221        }
4222        // check for dropdown and checkbox
4223        if (isSelectValChanged) {
4224          if (quantity == 0) {
4225            vm.productCheckbox[code] = false;
4226          } else if (quantity > 0) {
4227            vm.productCheckbox[code] = true;
4228          }
4229        } else {
4230          if (vm.productCheckbox[code]) {
4231            if (quantity == 0) {
4232              vm.cssDropDown[code] = 1;
4233              quantity = 1;
4234            }
4235          } else {
4236            vm.cssDropDown[code] = 0;
4237            quantity = 0;
4238          }
4239        }
4240        // to check whether any of the dropDown is selected
4241        var valChecked = optionalService.checkDropDownSelected(
4242          vm.product,
4243          vm.cssDropDown
4244        );
4245
4246        // if not selected, then unselect the CSSG checkbox and collapse the CSS div
4247        if (!valChecked) {
4248          vm.productCheckbox['CSSG'] = false;
4249        }
4250      }
4251
4252      if (
4253        angular.isDefined(vm.rentalDetails.reservationSummary.gebUser) &&
4254        vm.rentalDetails.reservationSummary.gebUser &&
4255        angular.isDefined(vm.secondaryCardSelected.number) &&
4256        vm.secondaryCardSelected.number == ''
4257      ) {
4258        vm.rentalModel.availedSplitbill = false;
4259      }
4260
4261      var splitRequest = {
4262        splitOpted: vm.rentalModel.availedSplitbill,
4263        cardNumber:
4264          vm.secondaryCardSelected &&
4265            vm.secondaryCardSelected.number &&
4266            vm.secondaryCardSelected.number != ''
4267            ? vm.secondaryCardSelected.number
4268            : '',
4269      };
4270
4271      getDataService.addToSplitDetails(splitRequest);
4272      $rootScope.requestInProgress = true;
4273      rentalService.AddOnExtras(vm.rentalNumber).then(
4274        function (data) {
4275          $rootScope.requestInProgress = true;
4276          if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
4277            vm.errorDisplayProduct = $scope.processErrorMessage(data).errorList;
4278            vm.error = $scope.processErrorMessage(data).errorList;
4279            if (vm.error[0].code != '5313') {
4280              vm.product.selectedProduct = [];
4281              getDataService.addRentalProducts(vm.product.selectedProduct);
4282              handleSelectedProducts();
4283              vm.rentalState = {
4284                value:
4285                  data.reservationSummary.rentalState == 'estimate' ||
4286                    data.reservationSummary.rentalState == 'EmailSmsNotification'
4287                    ? true
4288                    : false,
4289                tab: 'Extras',
4290              };
4291              // to fix rental extras tab activation
4292              /*if (angular.isDefined(vm.rentalDetails) && angular.isDefined(vm.rentalDetails.emailSmsNotification) && vm.rentalDetails.emailSmsNotification.indicator) {
4293              vm.rentalState.value = false;
4294            }*/
4295            }
4296          } else {
4297            vm.rateSummary = data.reservationSummary.rateSummary;
4298            vm.rentalDetails.reservationSummary.splitBillSummary =
4299              data.reservationSummary.splitBillSummary;
4300
4301            /* TODO- Need to have one generic method */
4302            if (
4303              angular.isDefined(data.reservationSummary) &&
4304              angular.isDefined(data.reservationSummary.splitBillSummary)
4305            ) {
4306              vm.rentalDetails.reservationSummary.splitBillSummary =
4307                data.reservationSummary.splitBillSummary;
4308            }
4309            // <!-- split enable flag from api -->
4310
4311            /* TODO- Need to have one generic method */
4312            if (
4313              angular.isDefined(data.reservationSummary) &&
4314              angular.isDefined(data.reservationSummary.splitBillSummary) &&
4315              angular.isDefined(
4316                data.reservationSummary.splitBillSummary.splitBillEnabled
4317              )
4318            ) {
4319              vm.rentalModel.availedSplitbill =
4320                data.reservationSummary.splitBillSummary.splitBillEnabled;
4321            }
4322
4323            if (
4324              vm.rentalDetails.reservationSummary.gebUser &&
4325              angular.isUndefined(vm.rateSummary.totalAdditonalCharges)
4326            ) {
4327              vm.rateSummary.totalAdditonalCharges = 0;
4328            }
4329
4330            // vm.rentalModel.availedSplitbill =
4331            // data.reservationSummary.splitBillSummary.splitBillEnabled;
4332            // To load months and years in add new card modal
4333            vm._loadMnthYrDropdown();
4334            vm._populateBillingInfoCountryList();
4335            if (
4336              angular.isDefined(vm.addresses) &&
4337              !$.isEmptyObject(vm.addresses)
4338            ) {
4339              vm._getAddressList(vm.addresses);
4340            }
4341            if (
4342              angular.isDefined(data.reservationSummary) &&
4343              angular.isDefined(data.reservationSummary.personalInfo) &&
4344              angular.isDefined(
4345                data.reservationSummary.personalInfo.residency
4346              ) &&
4347              angular.isDefined(
4348                data.reservationSummary.personalInfo.residency.value
4349              )
4350            ) {
4351              vm.reservationModel.paymentRq.address.country =
4352                data.reservationSummary.personalInfo.residency.value;
4353            }
4354            if (vm.brand == 'avis') {
4355              vm.getStatesForCountry(
4356                vm.reservationModel.paymentRq.address.country,
4357                'onload'
4358              );
4359            }
4360            // splitbill-396 condition added to show or hide Toggle
4361            // option on add of rental extras.
4362            if (
4363              angular.isDefined(data.reservationSummary) &&
4364              angular.isDefined(data.reservationSummary.rateSummary) &&
4365              angular.isDefined(data.reservationSummary.splitBillSummary) &&
4366              data.reservationSummary.rentalState == 'estimate' &&
4367              (data.reservationSummary.rateSummary.totalAdditonalCharges > 0 ||
4368                (data.reservationSummary.splitBillSummary.splitBillSecondary !=
4369                  null &&
4370                  data.reservationSummary.splitBillSummary.splitBillSecondary
4371                    .cardAmount > 0))
4372            ) {
4373              vm.rentalModel.showSplitOpt = true;
4374            } else {
4375              vm.rentalModel.showSplitOpt = false;
4376            }
4377
4378            // split enable flag from api
4379            if (
4380              angular.isDefined(data.reservationSummary.splitBillSummary) &&
4381              angular.isDefined(
4382                data.reservationSummary.splitBillSummary.splitBillEnabled
4383              )
4384            ) {
4385              vm.rentalModel.availedSplitbill =
4386                data.reservationSummary.splitBillSummary.splitBillEnabled;
4387            }
4388            // commented out the below line to resolve IE issues
4389            // $('.showTab-tab1').attr("disabled",true);
4390            if (
4391              angular.isDefined(data.reservationSummary.gebUser) &&
4392              data.reservationSummary.gebUser &&
4393              angular.isDefined(data.reservationSummary.splitBillSummary) &&
4394              data.reservationSummary.splitBillSummary.splitBillSecondary
4395            ) {
4396              vm.rentalModel.availedSplitbill = true;
4397            }
4398            vm.error = [];
4399            vm.errorDisplayInsurance = [];
4400            vm.errorDisplayProduct = [];
4401            vm.rentalState = {
4402              value:
4403                data.reservationSummary.rentalState == 'estimate' ||
4404                  data.reservationSummary.rentalState == 'EmailSmsNotification'
4405                  ? true
4406                  : false,
4407              tab: 'Extras',
4408            };
4409            // to fix rental extras tab activation
4410            /*if(angular.isDefined(vm.rentalDetails) && angular.isDefined(vm.rentalDetails.emailSmsNotification) && vm.rentalDetails.emailSmsNotification.indicator) {
4411            vm.rentalState.value = false;
4412          }*/
4413          }
4414          $timeout(function () {
4415            $rootScope.requestInProgress = false;
4416          }, 1000);
4417        },
4418        function (data) {
4419          if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
4420            vm.errorDisplayProduct = $scope.processErrorMessage(data).errorList;
4421            vm.error = $scope.processErrorMessage(data).errorList;
4422            if (vm.error[0].code != '5313') {
4423              vm.product.selectedProduct = [];
4424              getDataService.addRentalProducts(vm.product.selectedProduct);
4425              vm.rentalDetails = data.reservationSummary;
4426              vm.rentalState = {
4427                value:
4428                  data.reservationSummary.rentalState == 'estimate'
4429                    ? true
4430                    : false,
4431                tab: 'Extras',
4432              };
4433            }
4434          }
4435          $rootScope.requestInProgress = false;
4436        }
4437      );
4438    }
4439
4440    // To remove unselected product from reservationModel
4441    function arrayPop(deleteCode, insArray) {
4442      if (insArray) {
4443        for (var i = 0; i < vm.product.selectedProduct.length; i++) {
4444          var obj = vm.product.selectedProduct[i];
4445          if (deleteCode === obj.code) {
4446            vm.product.selectedProduct.splice(i, 1);
4447            break;
4448          }
4449        }
4450      }
4451    }
4452
4453    function confirmAddOn() {
4454      if (!vm.rentalModel.showExtras && !vm.rentalModel.failExtras) {
4455        $rootScope.requestInProgress = true;
4456        if (
4457          angular.isDefined(
4458            vm.rentalDetails.reservationSummary.splitBillSummary
4459          ) &&
4460          angular.isDefined(
4461            vm.rentalDetails.reservationSummary.splitBillSummary.dollarAmount
4462          ) &&
4463          vm.rentalDetails.reservationSummary.splitBillSummary.dollarAmount
4464        ) {
4465          var splitRequest = {
4466            dollarAmount:
4467              vm.rentalDetails.reservationSummary.splitBillSummary
4468                .splitBillSecondary != null &&
4469                angular.isDefined(
4470                  vm.rentalDetails.reservationSummary.splitBillSummary
4471                    .splitBillSecondary.cardAmount
4472                )
4473                ? vm.rentalDetails.reservationSummary.splitBillSummary
4474                  .splitBillSecondary.cardAmount
4475                : '',
4476            splitOpted: vm.rentalModel.availedSplitbill,
4477            cardNumber: angular.isDefined(vm.secondaryCardSelected.number)
4478              ? vm.secondaryCardSelected.number
4479              : '',
4480          };
4481          getDataService.addToSplitDetails(splitRequest);
4482        } else {
4483          var splitRequest = {
4484            splitOpted: vm.rentalModel.availedSplitbill,
4485            cardNumber:
4486              angular.isDefined(vm.secondaryCardSelected) &&
4487                angular.isDefined(vm.secondaryCardSelected.number) &&
4488                vm.secondaryCardSelected.number != ''
4489                ? vm.secondaryCardSelected.number
4490                : '',
4491          };
4492          getDataService.addToSplitDetails(splitRequest);
4493        }
4494        rentalService.confirmAddOn(vm.rentalNumber).then(
4495          function (data) {
4496            $rootScope.requestInProgress = true;
4497            if (data.errorList && data.errorList.length > 0) {
4498              vm.error = $scope.processErrorMessage(data).errorList;
4499              vm.Insurance.selectedInsurance = [];
4500              getDataService.addRentalInsurances(
4501                vm.Insurance.selectedInsurance
4502              );
4503              vm.product.selectedProduct = [];
4504              getDataService.addRentalProducts(vm.product.selectedProduct);
4505              if (data.errorList[0].code != '5313') {
4506                vm.addtionalTrue = false;
4507                callExtras();
4508              }
4509              // $('.showTab-tab1').addClass('sp-confirm-footer');
4510            } else {
4511              if (
4512                angular.isDefined(data.instructionList) &&
4513                data.instructionList.length > 0
4514              ) {
4515                vm.instructionMessageList = [];
4516                angular.forEach(data.instructionList, function (instruction) {
4517                  var instructionMessage = {};
4518                  var instructionMessage = instruction;
4519                  vm.instructionMessageList.push(instructionMessage);
4520                });
4521              }
4522
4523              if (
4524                1 <= vm.instructionMessageList.length &&
4525                data.reservationSummary.productSummaryList &&
4526                data.reservationSummary.productSummaryList.length > 0 &&
4527                data.reservationSummary.insuranceSummaryList &&
4528                data.reservationSummary.insuranceSummaryList.length > 0
4529              ) {
4530                var extras = data.reservationSummary.productSummaryList.concat(
4531                  data.reservationSummary.insuranceSummaryList
4532                );
4533                vm.Extras = [];
4534                angular.forEach(extras, function (product) {
4535                  angular.forEach(
4536                    vm.instructionMessageList,
4537                    function (instruction) {
4538                      if (instruction.code == '5305-' + product.code) {
4539                        vm.Extras.push(product);
4540                      }
4541                      if (product.code == 'CSSG') {
4542                        angular.forEach(
4543                          product.subProducts,
4544                          function (subProduct) {
4545                            if (instruction.code == '5305-' + subProduct.code) {
4546                              vm.Extras.push(product);
4547                            }
4548                          }
4549                        );
4550                      }
4551                    }
4552                  );
4553                });
4554              } else if (
4555                1 <= vm.instructionMessageList.length &&
4556                data.reservationSummary.productSummaryList &&
4557                data.reservationSummary.productSummaryList.length > 0 &&
4558                !data.reservationSummary.insuranceSummaryList
4559              ) {
4560                var extras = data.reservationSummary.productSummaryList;
4561                vm.Extras = [];
4562                angular.forEach(extras, function (product) {
4563                  angular.forEach(
4564                    vm.instructionMessageList,
4565                    function (instruction) {
4566                      if (instruction.code == '5305-' + product.code) {
4567                        vm.Extras.push(product);
4568                      }
4569                    }
4570                  );
4571                });
4572              } else if (
4573                1 <= vm.instructionMessageList.length &&
4574                !data.reservationSummary.productSummaryList &&
4575                data.reservationSummary.insuranceSummaryList &&
4576                data.reservationSummary.insuranceSummaryList.length > 0
4577              ) {
4578                vm.Extras = [];
4579                angular.forEach(extras, function (product) {
4580                  angular.forEach(
4581                    vm.instructionMessageList,
4582                    function (instruction) {
4583                      if (instruction.code == '5305-' + product.code) {
4584                        vm.Extras.push(product);
4585                      }
4586                    }
4587                  );
4588                });
4589              }
4590
4591              /*
4592               * if(data.reservationSummary.rateSummary){
4593               * vm.rentalModel.showExtras=true; }
4594               */
4595              vm.error = [];
4596              vm.errorDisplayInsurance = [];
4597              vm.errorDisplayProduct = [];
4598              vm.rentalState = {
4599                value:
4600                  data.reservationSummary.rentalState == 'estimate'
4601                    ? true
4602                    : false,
4603                tab: 'Extras',
4604              };
4605              vm.Insurance.selectedInsurance = [];
4606              getDataService.addRentalInsurances(
4607                vm.Insurance.selectedInsurance
4608              );
4609              vm.product.selectedProduct = [];
4610              getDataService.addRentalProducts(vm.product.selectedProduct);
4611              var testInsurance = false;
4612              var testProduct = false;
4613              angular.forEach(
4614                data.reservationSummary.insuranceSummaryList,
4615                function (insurance) {
4616                  if (insurance.visible == true) {
4617                    vm.rentalDetails.insuranceVisible = true;
4618                    testInsurance = true;
4619                  } else if (!testInsurance) {
4620                    vm.rentalDetails.insuranceVisible = false;
4621                  }
4622                }
4623              );
4624              angular.forEach(
4625                data.reservationSummary.productSummaryList,
4626                function (product) {
4627                  if (product.visible == true) {
4628                    vm.rentalDetails.productVisible = true;
4629                    testProduct = true;
4630                  } else if (!testProduct) {
4631                    vm.rentalDetails.productVisible = false;
4632                  }
4633                }
4634              );
4635              if (1 <= vm.instructionMessageList.length) {
4636                if (jQuery(window).width() <= 767) {
4637                  vm.close('Rental Extras');
4638                }
4639                reservationModelService.addGTMScript();
4640                //$("#successAddon").modal('show');
4641                $('#successAddon').appendTo('body').modal('show');
4642              }
4643              // $('.showTab-tab1').addClass('sp-confirm-footer');
4644              // GA-GTM implementation change to capture confirm of
4645              // add rental extras
4646              var additionalCharges = '';
4647              if (
4648                angular.isDefined(vm.rateSummary) &&
4649                angular.isDefined(vm.rateSummary.totalAdditonalCharges) &&
4650                vm.rateSummary.totalAdditonalCharges != null
4651              ) {
4652                additionalCharges = vm.rateSummary.totalAdditonalCharges;
4653              }
4654              if (
4655                angular.isDefined(data.reservationSummary.splitBillSummary) &&
4656                data.reservationSummary.splitBillSummary.splitBillEnabled
4657              ) {
4658                gaService.analyticsRentalDetails(
4659                  data,
4660                  'addExtras',
4661                  true,
4662                  additionalCharges
4663                );
4664              } else {
4665                gaService.analyticsRentalDetails(
4666                  data,
4667                  'addExtras',
4668                  false,
4669                  additionalCharges
4670                );
4671              }
4672              //fivestar changes
4673              if (
4674                angular.isDefined(data.reservationSummary) &&
4675                angular.isDefined(data.reservationSummary.vehicle) &&
4676                angular.isDefined(
4677                  data.reservationSummary.vehicle.fiveStarSafetyRate
4678                )
4679              ) {
4680                gaService.analyticsRentalClickEvents(data, '', '');
4681              }
4682            }
4683
4684            $rootScope.requestInProgress = false;
4685          },
4686          function (error) {
4687            if (error.errorList && error.errorList.length > 0) {
4688              vm.error = $scope.processErrorMessage(error).errorList;
4689              vm.Insurance.selectedInsurance = [];
4690              getDataService.addRentalInsurances(
4691                vm.Insurance.selectedInsurance
4692              );
4693              vm.product.selectedProduct = [];
4694              getDataService.addRentalProducts(vm.product.selectedProduct);
4695              if (error.errorList[0].code != '5313') {
4696                vm.addtionalTrue = false;
4697                callExtras();
4698              }
4699              $rootScope.requestInProgress = false;
4700              // $('.showTab-tab1').addClass('sp-confirm-footer');
4701            }
4702          }
4703        );
4704      } else {
4705        vm.rentalModel.showExtras = false;
4706        vm.rentalModel.failExtras = false;
4707        // $('.showTab-tab1').removeClass('sp-confirm-footer');
4708        $rootScope.requestInProgress = true;
4709        callExtras();
4710      }
4711      vm.rentalModel.confirmSuccess = false;
4712      $('html, body').animate({
4713        scrollTop: $('#tabStart').position().top,
4714      });
4715      /*
4716       * handleSelectedProducts(); handleSelectedInsurance();
4717       */
4718    }
4719
4720    function handleSelectedProducts() {
4721      vm.product.selectedAvailableProducts = [];
4722      if (
4723        angular.isDefined(vm.rentalDetails) &&
4724        angular.isDefined(vm.rentalDetails.reservationSummary) &&
4725        angular.isDefined(
4726          vm.rentalDetails.reservationSummary.productSummaryList
4727        )
4728      ) {
4729        angular.forEach(
4730          vm.rentalDetails.reservationSummary.productSummaryList,
4731          function (product) {
4732            if (
4733              product.visible ||
4734              (angular.isDefined(product.ismandatory) &&
4735                product.ismandatory == 'true')
4736            ) {
4737              vm.product.selectedAvailableProducts.push(product);
4738            }
4739            if (product.selected == true && product.visible) {
4740              angular.forEach(
4741                vm.product.selectedProduct,
4742                function (selectedProduct) {
4743                  if (selectedProduct.code != product.code) {
4744                    vm.product.selectedProduct.push(product);
4745                  }
4746                }
4747              );
4748            }
4749            if (product.visible && product.selected == false) {
4750              vm.rentalDetails.productVisible = true;
4751            }
4752            // To handle itemized split for curbside
4753            vm.cubsideSelected = {};
4754            if (product.category == 'PER_RENTAL' && product.selected == true) {
4755              vm.rentalModel.enableCta = false;
4756              vm.cubsideSelected[product.code] = 'secondary';
4757            }
4758          }
4759        );
4760        if (
4761          vm.product.selectedAvailableProducts &&
4762          vm.product.selectedAvailableProducts.length > 0
4763        ) {
4764          vm.rentalDetails.reservationSummary.productSummaryList =
4765            vm.product.selectedAvailableProducts;
4766        }
4767        getDataService.addRentalProducts(vm.product.selectedProduct);
4768      }
4769    }
4770
4771    function handleCSSDisplay() {
4772      if (
4773        angular.isDefined(vm.rentalDetails) &&
4774        angular.isDefined(vm.rentalDetails.reservationSummary) &&
4775        angular.isDefined(
4776          vm.rentalDetails.reservationSummary.productSummaryList
4777        )
4778      ) {
4779        angular.forEach(
4780          vm.rentalDetails.reservationSummary.productSummaryList,
4781          function (product) {
4782            if (product.subProducts != undefined) {
4783              var subProducts = product.subProducts;
4784              angular.forEach(subProducts, function (subProduct) {
4785                // form the css quantity drop down values
4786                formDropDownList(subProduct.code, subProduct.displayQuantity);
4787                vm.cssDropDown[subProduct.code] = 0;
4788              });
4789            }
4790          }
4791        );
4792      }
4793    }
4794
4795    // CSS drop down values - cbs, cfs, cis, csb, css
4796    /*
4797     *
4798     */
4799    function formDropDownList(code, quantity) {
4800      for (var i = 0; i <= quantity; i++) {
4801        vm.cssDropDownValues[code].push({
4802          selectId: i,
4803          selectName: i,
4804        });
4805      }
4806    }
4807
4808    function expandChildSafety() {
4809      if (vm.expandCSS) {
4810        $('.cssProd').after($('#childSaftey'));
4811      } else if (vm.expandCSSServ) {
4812        $('.cssProd').after($('#childSaftey2'));
4813      }
4814    }
4815
4816    function handleSelectedInsurance() {
4817      vm.Insurance.selectedInsurance = [];
4818      if (
4819        angular.isDefined(vm.rentalDetails.reservationSummary) &&
4820        angular.isDefined(
4821          vm.rentalDetails.reservationSummary.insuranceSummaryList
4822        )
4823      ) {
4824        angular.forEach(
4825          vm.rentalDetails.reservationSummary.insuranceSummaryList,
4826          function (insurance) {
4827            if (insurance.visible) {
4828              vm.insuranceVisible = true;
4829            }
4830            if (insurance.selected && insurance.visible) {
4831              vm.Insurance.selectedInsurance.push(insurance);
4832            }
4833          }
4834        );
4835        getDataService.addRentalInsurances(vm.Insurance.selectedInsurance);
4836      }
4837    }
4838    // To store selected products in reservationModel
4839    function insuranceSelected(
4840      insuranceObj,
4841      code,
4842      isSelectValChanged,
4843      extrasId
4844    ) {
4845      var isPresent = false;
4846
4847      if (vm.insuranceCheckbox[code]) {
4848        insuranceObj.selected = true;
4849        vm.analytics(false, 'rental-' + insuranceObj.code, 'select');
4850
4851        if (extrasId) {
4852          var extraIndex = extrasId.indexOf('_ext');
4853          if (extraIndex == -1) {
4854            insuranceObj.productId = extrasId;
4855          } else {
4856            insuranceObj.productId = insuranceObj.code + 'chk_ext';
4857          }
4858        }
4859        var addInsurance = {
4860          code: insuranceObj.code,
4861          selected: insuranceObj.selected,
4862        };
4863
4864        vm.Insurance.selectedInsurance.push(addInsurance);
4865        getDataService.addRentalInsurances(vm.Insurance.selectedInsurance);
4866      } else {
4867        arrayPopInsurance(code, true);
4868        vm.analytics(false, 'rental-' + insuranceObj.code, 'unselect');
4869        getDataService.addRentalInsurances(vm.Insurance.selectedInsurance);
4870      }
4871      var splitRequest = {
4872        splitOpted: vm.rentalModel.availedSplitbill,
4873        cardNumber:
4874          vm.secondaryCardSelected &&
4875            vm.secondaryCardSelected.number &&
4876            vm.secondaryCardSelected.number != ''
4877            ? vm.secondaryCardSelected.number
4878            : '',
4879      };
4880      getDataService.addToSplitDetails(splitRequest);
4881      $rootScope.requestInProgress = true;
4882      rentalService.AddOnExtras(vm.rentalNumber).then(
4883        function (data) {
4884          $rootScope.requestInProgress = true;
4885          if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
4886            vm.errorDisplayInsurance =
4887              $scope.processErrorMessage(data).errorList;
4888            vm.error = $scope.processErrorMessage(data).errorList;
4889            vm.Insurance.selectedInsurance = [];
4890            getDataService.addRentalInsurances(vm.Insurance.selectedInsurance);
4891            handleSelectedInsurance();
4892            vm.rentalState = {
4893              value:
4894                data.reservationSummary.rentalState == 'estimate'
4895                  ? true
4896                  : false,
4897              tab: 'Extras',
4898            };
4899          } else {
4900            vm.rateSummary = data.reservationSummary.rateSummary;
4901            vm.rentalDetails.reservationSummary.splitBillSummary =
4902              data.reservationSummary.splitBillSummary;
4903            // split enable flag from api
4904            if (
4905              angular.isDefined(data.reservationSummary.splitBillSummary) &&
4906              angular.isDefined(
4907                data.reservationSummary.splitBillSummary.splitBillEnabled
4908              )
4909            ) {
4910              vm.rentalModel.availedSplitbill =
4911                data.reservationSummary.splitBillSummary.splitBillEnabled;
4912            }
4913
4914            if (
4915              vm.rentalDetails.reservationSummary.gebUser &&
4916              angular.isUndefined(vm.rateSummary.totalAdditonalCharges)
4917            ) {
4918              vm.rateSummary.totalAdditonalCharges = 0;
4919            }
4920
4921            // splitbill-396 condition added to show or hide Toggle
4922            // option on select of rental extras (quote call)
4923            if (
4924              angular.isDefined(data.reservationSummary) &&
4925              angular.isDefined(data.reservationSummary.rateSummary) &&
4926              angular.isDefined(data.reservationSummary.splitBillSummary) &&
4927              data.reservationSummary.rentalState == 'estimate' &&
4928              (data.reservationSummary.rateSummary.totalAdditonalCharges > 0 ||
4929                (data.reservationSummary.splitBillSummary.splitBillSecondary !=
4930                  null &&
4931                  data.reservationSummary.splitBillSummary.splitBillSecondary
4932                    .cardAmount > 0))
4933            ) {
4934              vm.rentalModel.showSplitOpt = true;
4935            } else {
4936              vm.rentalModel.showSplitOpt = false;
4937            }
4938
4939            if (
4940              angular.isDefined(data.reservationSummary.gebUser) &&
4941              data.reservationSummary.gebUser &&
4942              angular.isDefined(data.reservationSummary.splitBillSummary) &&
4943              data.reservationSummary.splitBillSummary.splitBillSecondary
4944            ) {
4945              vm.rentalModel.availedSplitbill = true;
4946            }
4947
4948            // $('.showTab-tab1').attr("disabled",true);
4949            // To load months and years in add new card modal
4950            vm._loadMnthYrDropdown();
4951            vm._populateBillingInfoCountryList();
4952            if (
4953              angular.isDefined(vm.addresses) &&
4954              !$.isEmptyObject(vm.addresses)
4955            ) {
4956              vm._getAddressList(vm.addresses);
4957            }
4958            if (
4959              angular.isDefined(data.reservationSummary) &&
4960              angular.isDefined(data.reservationSummary.personalInfo) &&
4961              angular.isDefined(
4962                data.reservationSummary.personalInfo.residency
4963              ) &&
4964              angular.isDefined(
4965                data.reservationSummary.personalInfo.residency.value
4966              )
4967            ) {
4968              vm.reservationModel.paymentRq.address.country =
4969                data.reservationSummary.personalInfo.residency.value;
4970            }
4971
4972            if (vm.brand == 'avis') {
4973              vm.getStatesForCountry(
4974                vm.reservationModel.paymentRq.address.country,
4975                'onload'
4976              );
4977            }
4978            vm.error = [];
4979            vm.errorDisplayInsurance = [];
4980            vm.errorDisplayProduct = [];
4981            vm.rentalState = {
4982              value:
4983                data.reservationSummary.rentalState == 'estimate'
4984                  ? true
4985                  : false,
4986              tab: 'Extras',
4987            };
4988            vm.errorDisplayInsurance = [];
4989          }
4990
4991          $rootScope.requestInProgress = false;
4992        },
4993        function (data) {
4994          if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
4995            vm.errorDisplayInsurance =
4996              $scope.processErrorMessage(data).errorList;
4997            vm.error = $scope.processErrorMessage(data).errorList;
4998            vm.Insurance.selectedInsurance = [];
4999            getDataService.addRentalInsurances(vm.Insurance.selectedInsurance);
5000            handleSelectedInsurance();
5001
5002            vm.rentalState = {
5003              value:
5004                data.reservationSummary.rentalState == 'estimate'
5005                  ? true
5006                  : false,
5007              tab: 'Extras',
5008            };
5009            $rootScope.requestInProgress = false;
5010          }
5011        }
5012      );
5013    }
5014
5015    // SPLITBILL-141 and 143-On enabling toggle, split details call will
5016    // happen to get primary and secondary card details
5017    function extrasSplitEnable(section) {
5018      if (vm.rentalModel.availedSplitbill) {
5019        vm.rentalModel.unsplit = false;
5020        var secondaryCardNumber = '';
5021        // splitbill-1467 - secondary card initialization fix
5022        if (section == 'addCard') {
5023          secondaryCardNumber = vm.secondaryCardSelected.number;
5024        } else if (
5025          angular.isDefined(vm.rentalDetails.reservationSummary) &&
5026          angular.isDefined(
5027            vm.rentalDetails.reservationSummary.splitBillSummary
5028          ) &&
5029          vm.rentalDetails.reservationSummary.splitBillSummary
5030            .splitBillSecondary != null
5031        ) {
5032          secondaryCardNumber =
5033            vm.rentalDetails.reservationSummary.splitBillSummary
5034              .splitBillSecondary.ccSummary.number;
5035        } else if (
5036          angular.isDefined(vm.rentalDetails.reservationSummary) &&
5037          angular.isDefined(vm.rentalDetails.reservationSummary.creditcards) &&
5038          angular.isDefined(
5039            vm.rentalDetails.reservationSummary.creditcards[1]
5040          ) &&
5041          angular.isDefined(
5042            vm.rentalDetails.reservationSummary.creditcards[1].number
5043          )
5044        ) {
5045          vm.secondaryCardSelected =
5046            vm.rentalDetails.reservationSummary.creditcards[1];
5047          vm.secondaryCCType = carRentalConstant.masterListForCC.filter(
5048            function (obj) {
5049              return obj.code == vm.secondaryCardSelected.type;
5050            }
5051          );
5052          secondaryCardNumber =
5053            vm.rentalDetails.reservationSummary.creditcards[1].number;
5054          vm.rentalDetails.reservationSummary.splitBillSummary.splitBillSecondary =
5055          {
5056            ccSummary: {
5057              number: secondaryCardNumber,
5058              type: vm.secondaryCardSelected.type,
5059            },
5060          };
5061        } else {
5062          secondaryCardNumber = '';
5063        }
5064        if (
5065          secondaryCardNumber != '' &&
5066          vm.rentalState.tab != '' &&
5067          vm.rentalState.value
5068        ) {
5069          var splitRequest = {
5070            splitOpted: vm.rentalModel.availedSplitbill,
5071            estimateCall: vm.rentalModel.availedSplitbill,
5072            secondaryCreditCard: secondaryCardNumber,
5073          };
5074          getDataService.addToSplitDetails(splitRequest);
5075
5076          if (vm.rentalState.tab == 'Extras') {
5077            $rootScope.requestInProgress = true;
5078            if (
5079              !vm.rentalDetails.reservationSummary.splitBillSummary
5080                .splitBillEnabled
5081            ) {
5082              rentalService.extrasSplit(vm.rentalNumber).then(
5083                function (data) {
5084                  // re-initialising availed splitbill to enable
5085                  // toggle to YES after adding new card
5086                  vm.rentalModel.availedSplitbill = true;
5087                  if (
5088                    angular.isDefined(data.reservationSummary) &&
5089                    angular.isDefined(
5090                      data.reservationSummary.splitBillSummary
5091                    ) &&
5092                    angular.isDefined(
5093                      data.reservationSummary.splitBillSummary.splitBillPrimary
5094                    ) &&
5095                    angular.isDefined(
5096                      data.reservationSummary.splitBillSummary.splitBillPrimary
5097                        .ccSummary
5098                    )
5099                  ) {
5100                    vm.primaryCard = angular.copy(
5101                      data.reservationSummary.splitBillSummary.splitBillPrimary
5102                        .ccSummary
5103                    );
5104                  }
5105                  if (
5106                    angular.isDefined(data.reservationSummary) &&
5107                    angular.isDefined(
5108                      data.reservationSummary.splitBillSummary
5109                    ) &&
5110                    angular.isDefined(
5111                      data.reservationSummary.splitBillSummary
5112                        .splitBillSecondary
5113                    ) &&
5114                    angular.isDefined(
5115                      data.reservationSummary.splitBillSummary
5116                        .splitBillSecondary.ccSummary
5117                    )
5118                  ) {
5119                    vm.secondaryCardSelected = angular.copy(
5120                      data.reservationSummary.splitBillSummary
5121                        .splitBillSecondary.ccSummary
5122                    );
5123                  }
5124                  if (
5125                    angular.isDefined(data.reservationSummary) &&
5126                    angular.isDefined(data.reservationSummary.rateSummary) &&
5127                    angular.isDefined(data.reservationSummary.splitBillSummary)
5128                  ) {
5129                    vm.rentalDetails.reservationSummary.splitBillSummary =
5130                      data.reservationSummary.splitBillSummary;
5131                  }
5132                  $rootScope.requestInProgress = false;
5133
5134                  // GA-GTM change to trigger click event on check of
5135                  // toggle option
5136
5137                  if (
5138                    angular.isDefined(data) &&
5139                    angular.isDefined(data.reservationSummary) &&
5140                    angular.isDefined(data.reservationSummary.gateExitDone)
5141                  ) {
5142                    var ec = 'Mid Rental';
5143                  } else {
5144                    var ec = 'Pre Rental';
5145                  }
5146
5147                  var eventLabel = carRentalConstant.toggleExtraCheck;
5148                  analytics(false, eventLabel, 'splitbill', true, ec);
5149                },
5150                function (error) {
5151                  if (error.errorList && error.errorList.length > 0) {
5152                    vm.error = $scope.processErrorMessage(error).errorList;
5153
5154                    vm.rentalModel.availedSplitbill =
5155                      error.reservationSummary &&
5156                        error.reservationSummary.splitBillSummary &&
5157                        error.reservationSummary.splitBillSummary.splitBillEnabled
5158      
5158                  ? error.reservationSummary.splitBillSummary
5159                          .splitBillEnabled
5160                        : false;
5161                    $rootScope.requestInProgress = false;
5162                  }
5163                }
5164              );
5165            } else if (section != 'addCard') {
5166              vm.secondaryCardSelected =
5167                vm.rentalDetails.reservationSummary.splitBillSummary.splitBillSecondary.ccSummary;
5168              vm.secondaryCCType = carRentalConstant.masterListForCC.filter(
5169                function (obj) {
5170                  return obj.code == vm.secondaryCardSelected.type;
5171                }
5172              );
5173            }
5174          } else if (vm.rentalState.tab == 'Modify-Return') {
5175            // enabling split from modify return Tab
5176            $rootScope.requestInProgress = true;
5177            if (
5178              !vm.rentalDetails.reservationSummary.splitBillSummary
5179                .splitBillEnabled
5180            ) {
5181              var splitData = {
5182                secondaryCreditCard:
5183                  angular.isDefined(vm.secondaryCardSelected) &&
5184                    angular.isDefined(vm.secondaryCardSelected.number)
5185                    ? vm.secondaryCardSelected.number
5186                    : '',
5187                splitOpted: vm.rentalModel.availedSplitbill,
5188              };
5189              getDataService.addToSplitDetails(splitData);
5190              rentalService.rentalSplit(vm.modifiedData).then(
5191                function (data) {
5192                  // re-initialising availed splitbill to
5193                  // enable toggle to YES after adding new
5194                  // card
5195                  vm.rentalModel.availedSplitbill = true;
5196                  if (
5197                    angular.isDefined(data.reservationSummary) &&
5198                    angular.isDefined(
5199                      data.reservationSummary.splitBillSummary
5200                    ) &&
5201                    angular.isDefined(
5202                      data.reservationSummary.splitBillSummary.splitBillPrimary
5203                    ) &&
5204                    angular.isDefined(
5205                      data.reservationSummary.splitBillSummary.splitBillPrimary
5206                        .ccSummary
5207                    )
5208                  ) {
5209                    vm.primaryCard = angular.copy(
5210                      data.reservationSummary.splitBillSummary.splitBillPrimary
5211                        .ccSummary
5212                    );
5213                  }
5214                  if (
5215                    angular.isDefined(data.reservationSummary) &&
5216                    angular.isDefined(
5217                      data.reservationSummary.splitBillSummary
5218                    ) &&
5219                    angular.isDefined(
5220                      data.reservationSummary.splitBillSummary
5221                        .splitBillSecondary
5222                    ) &&
5223                    data.reservationSummary.splitBillSummary
5224                      .splitBillSecondary != null &&
5225                    angular.isDefined(
5226                      data.reservationSummary.splitBillSummary
5227                        .splitBillSecondary.ccSummary
5228                    )
5229                  ) {
5230                    vm.secondaryCardSelected = angular.copy(
5231                      data.reservationSummary.splitBillSummary
5232                        .splitBillSecondary.ccSummary
5233                    );
5234                  }
5235                  if (
5236                    angular.isDefined(data.reservationSummary) &&
5237                    angular.isDefined(data.reservationSummary.rateSummary) &&
5238                    angular.isDefined(data.reservationSummary.splitBillSummary)
5239                  ) {
5240                    vm.rateSummary = data.reservationSummary.rateSummary;
5241                    // vm.rentalExtras.reservationSummary.splitBillSummary=data.reservationSummary.splitBillSummary;
5242                    vm.rentalDetails.reservationSummary.splitBillSummary =
5243                      data.reservationSummary.splitBillSummary;
5244                  }
5245                  $rootScope.requestInProgress = false;
5246
5247                  // GA-GTM change to trigger click event
5248                  // on check of toggle option
5249
5250                  if (
5251                    angular.isDefined(data) &&
5252                    angular.isDefined(data.reservationSummary) &&
5253                    angular.isDefined(data.reservationSummary.gateExitDone)
5254                  ) {
5255                    var ec = 'Mid Rental';
5256                  } else {
5257                    var ec = 'Pre Rental';
5258                  }
5259
5260                  var eventLabel = carRentalConstant.toggleModifyCheck;
5261                  analytics(false, eventLabel, 'splitbill', true, ec);
5262                },
5263                function (error) {
5264                  if (error.errorList && error.errorList.length > 0) {
5265                    vm.error = $scope.processErrorMessage(error).errorList;
5266                    vm.rentalModel.availedSplitbill =
5267                      error.reservationSummary &&
5268                        error.reservationSummary.splitBillSummary &&
5269                        error.reservationSummary.splitBillSummary.splitOpted
5270                        ? error.reservationSummary.splitBillSummary.splitOpted
5271                        : false;
5272                    vm.rentalDetails.reservationSummary.splitBillSummary.splitBillEnabled =
5273                      error.reservationSummary.splitBillSummary.splitBillEnabled;
5274                    vm.rentalDetails.reservationSummary.splitBillSummary.splitOpted =
5275                      error.reservationSummary.splitBillSummary.splitOpted;
5276                    if (vm.rentalDetails.reservationSummary.gebUser) {
5277                      vm.rentalDetails.reservationSummary.splitBillSummary =
5278                        error.reservationSummary.splitBillSummary;
5279                    }
5280                    $rootScope.requestInProgress = false;
5281                  }
5282                }
5283              );
5284            } else if (section != 'addCard') {
5285              vm.secondaryCardSelected =
5286                vm.rentalDetails.reservationSummary.splitBillSummary.splitBillSecondary.ccSummary;
5287              vm.secondaryCCType = carRentalConstant.masterListForCC.filter(
5288                function (obj) {
5289                  return obj.code == vm.secondaryCardSelected.type;
5290                }
5291              );
5292            }
5293          }
5294        } else if (
5295          secondaryCardNumber != '' &&
5296          vm.rentalState.tab == 'Rental-Summary' &&
5297          !vm.rentalState.value
5298        ) {
5299          vm.rentalModel.availedSplitbill = true;
5300          if (
5301            vm.rentalDetails.reservationSummary.splitBillSummary
5302              .splitBillEnabled == true
5303          ) {
5304            $rootScope.requestInProgress = true;
5305            if (section == 'addCard') {
5306              vm.secondaryCCType = carRentalConstant.masterListForCC.filter(
5307                function (obj) {
5308                  return obj.code == vm.secondaryCardSelected.type;
5309                }
5310              );
5311              vm.selectSecondaryCC(vm.secondaryCardSelected);
5312            } else {
5313              vm.secondaryCardSelected =
5314                vm.rentalDetails.reservationSummary.splitBillSummary.splitBillSecondary.ccSummary;
5315              vm.secondaryCCType = carRentalConstant.masterListForCC.filter(
5316                function (obj) {
5317                  return obj.code == vm.secondaryCardSelected.type;
5318                }
5319              );
5320              vm.selectSecondaryCC(
5321                vm.rentalDetails.reservationSummary.splitBillSummary
5322                  .splitBillSecondary.ccSummary
5323              );
5324            }
5325          } else if (section != 'addCard') {
5326            vm.secondaryCardSelected =
5327              vm.rentalDetails.reservationSummary.splitBillSummary.splitBillSecondary.ccSummary;
5328            vm.secondaryCCType = carRentalConstant.masterListForCC.filter(
5329              function (obj) {
5330                return obj.code == vm.secondaryCardSelected.type;
5331              }
5332            );
5333            //Added for SPLITBILL-3394 CR-starts
5334            if (vm.rentalDetails.reservationSummary.rateSummary != null) {
5335              vm.itemizedPrimaryAmount =
5336                vm.rentalDetails.reservationSummary.rateSummary.estimatedTotal;
5337              vm.itemizedSecondaryAmount = '0.00';
5338            }
5339
5340            //Added for SPLITBILL-3394 CR-Ends
5341            $('#splitAmount').modal('show');
5342            vm.events.showPaymentOption();
5343            // GA-GTM change to trigger click event on check of toggle option
5344
5345            if (
5346              angular.isDefined(data) &&
5347              angular.isDefined(data.reservationSummary) &&
5348              angular.isDefined(data.reservationSummary.gateExitDone)
5349            ) {
5350              var ec = 'Mid Rental';
5351            } else {
5352              var ec = 'Pre Rental';
5353            }
5354
5355            var eventLabel = carRentalConstant.toggleSummaryCheck;
5356            analytics(false, eventLabel, 'splitbill', true, ec);
5357          }
5358        } else if (secondaryCardNumber == '') {
5359          vm.primary = false;
5360          displayCreditCardModal();
5361          gaService.enableModal('add credit card modal', vm.rentalState.tab);
5362        }
5363      } else if (
5364        vm.rentalDetails.reservationSummary.splitBillSummary.splitBillEnabled
5365      ) {
5366        vm.rentalModel.unsplit = true;
5367        vm.rentalModel.availedSplitbill = false;
5368        vm.rentalDetails.reservationSummary.splitBillSummary.splitOpted = false;
5369        $('html, body').animate({
5370          scrollTop: $('#tabStart').position().top,
5371        });
5372      } else if (
5373        !vm.rentalDetails.reservationSummary.splitBillSummary
5374          .splitBillEnabled &&
5375        vm.rentalDetails.reservationSummary.splitBillSummary.splitOpted
5376      ) {
5377        vm.rentalDetails.reservationSummary.splitBillSummary.splitOpted = false;
5378      }
5379    }
5380
5381    // function to display add new card modal
5382    function displayCreditCardModal() {
5383      $('#modalAddCreditCard').modal('show');
5384      // capturing click event on add new card pop up
5385    }
5386
5387    // disabling split -SPLITBILL-214,216 and 389
5388    function splitDisable() {
5389      vm.rentalModel.availedSplitbill = false;
5390      var splitRequest = {
5391        splitOpted: vm.rentalModel.availedSplitbill,
5392        estimateCall: vm.rentalModel.availedSplitbill,
5393        secondaryCreditCard: '',
5394      };
5395
5396      // GA-GTM track for yes button on click of disable split toggle
5397      // option.
5398
5399      if (vm.rentalState.tab == 'Extras') {
5400        var eventLabelBtn = carRentalConstant.unsplitExtraYes;
5401      } else if (vm.rentalState.tab == 'Modify-Return') {
5402        var eventLabelBtn = carRentalConstant.unsplitModifyYes;
5403      } else {
5404        var eventLabelBtn = carRentalConstant.unsplitSummaryYes;
5405      }
5406
5407      if (
5408        angular.isDefined(vm.rentalDetails) &&
5409        angular.isDefined(vm.rentalDetails.reservationSummary) &&
5410        angular.isDefined(vm.rentalDetails.reservationSummary.gateExitDone)
5411      ) {
5412        var ec = 'Mid Rental';
5413      } else {
5414        var ec = 'Pre Rental';
5415      }
5416
5417      analytics(false, eventLabelBtn, 'splitbill', ec);
5418
5419      getDataService.addToSplitDetails(splitRequest);
5420      $rootScope.requestInProgress = true;
5421      rentalService.getUnsplitSummary().then(
5422        function (data) {
5423          if (
5424            angular.isDefined(data.reservationSummary) &&
5425            angular.isDefined(data.reservationSummary.splitBillSummary) &&
5426            angular.isDefined(
5427              data.reservationSummary.splitBillSummary.splitBillEnabled
5428            )
5429          ) {
5430            vm.rentalModel.availedSplitbill =
5431              data.reservationSummary.splitBillSummary.splitBillEnabled;
5432            vm.rentalDetails.reservationSummary = angular.copy(
5433              data.reservationSummary
5434            );
5435            setItemizedValues(data);
5436            if (
5437              data.reservationSummary.splitBillSummary != null &&
5438              data.reservationSummary.splitBillSummary.splitBillSecondary ==
5439              null
5440            ) {
5441              vm.secondaryCardSelected = {};
5442            }
5443          }
5444
5445          vm.rentalModel.unsplit = false;
5446          $rootScope.requestInProgress = false;
5447
5448          // GA-GTM track for split - unchecked.
5449          if (vm.rentalState.tab == 'Extras') {
5450            var eventLabel = carRentalConstant.toggleExtraUncheck;
5451          } else if (vm.rentalState.tab == 'Modify-Return') {
5452            var eventLabel = carRentalConstant.toggleModifyUncheck;
5453          } else {
5454            var eventLabel = carRentalConstant.toggleSummaryUncheck;
5455          }
5456
5457          if (
5458            angular.isDefined(vm.rentalDetails) &&
5459            angular.isDefined(vm.rentalDetails.reservationSummary) &&
5460            angular.isDefined(vm.rentalDetails.reservationSummary.gateExitDone)
5461          ) {
5462            var ec = 'Mid Rental';
5463          } else {
5464            var ec = 'Pre Rental';
5465          }
5466
5467          analytics(false, eventLabel, 'splitbill', ec);
5468        },
5469        function (error) {
5470          if (
5471            angular.isDefined(error.errorList) &&
5472            error.errorList.length > 0
5473          ) {
5474            vm.error = $scope.processErrorMessage(error).errorList;
5475            vm.rentalModel.unsplit = false;
5476            vm.rentalModel.availedSplitbill = true;
5477            $rootScope.requestInProgress = false;
5478          }
5479        }
5480      );
5481    }
5482
5483    function arrayPopInsurance(deleteCode, insArray) {
5484      if (insArray) {
5485        for (var i = 0; i < vm.Insurance.selectedInsurance.length; i++) {
5486          var obj = vm.Insurance.selectedInsurance[i];
5487          if (deleteCode === obj.code) {
5488            vm.Insurance.selectedInsurance.splice(i, 1);
5489            break;
5490          }
5491        }
5492      }
5493    }
5494
5495    function callExtras() {
5496      $rootScope.requestInProgress = true;
5497      vm.Insurance.selectedInsurance = [];
5498      getDataService.addRentalInsurances(vm.Insurance.selectedInsurance);
5499      vm.product.selectedProduct = [];
5500      getDataService.addRentalProducts(vm.product.selectedProduct);
5501      rentalService.getAncillaryList().then(function (data) {
5502        vm.rentalState.value =
5503          angular.isDefined(data.reservationSummary) &&
5504            angular.isDefined(data.reservationSummary.rentalState) &&
5505            data.reservationSummary.rentalState == 'estimate'
5506            ? true
5507            : false;
5508        vm.rentalDetails = data;
5509        if (vm.rentalDetails.reservationSummary.gebUser) {
5510          vm.rateSummary.totalAdditonalCharges = 0;
5511        }
5512        if (
5513          vm.rentalDetails.reservationSummary.gebUser &&
5514          data.reservationSummary.splitBillSummary.splitBillSecondary &&
5515          data.reservationSummary.splitBillSummary.splitBillSecondary
5516            .ccSummary &&
5517          data.reservationSummary.splitBillSummary.splitBillSecondary.ccSummary
5518            .number
5519        ) {
5520          vm.rentalModel.availedSplitbill = true;
5521        }
5522        handleSelectedProducts();
5523        handleCSSDisplay();
5524        handleSelectedInsurance();
5525        toggleTab(true, 'tab1');
5526        if (vm.rentalModel.failExtras) {
5527          vm.rentalModel.failExtras = false;
5528        }
5529        $rootScope.requestInProgress = false;
5530        vm.requestInProgress = false;
5531
5532        if (vm.rentalDetails.tabDisplayControl['tab3'].active == true) {
5533          vm.events.redirect('tab3');
5534        }
5535      });
5536    }
5537
5538    function modifyReturn(modifiedData, eventLabel) {
5539      vm.error = [];
5540      $rootScope.requestInProgress = true;
5541      vm.rentalModel.dateTimeSelected = false;
5542      // rental split variable
5543      vm.modifiedData = modifiedData;
5544      rentalService.modifyRentalExtension(modifiedData).then(
5545        function (data) {
5546          if (vm.hideStickySection) {
5547            vm.hideStickySection = false;
5548          }
5549          if (vm.rentalModel.tabFocus) {
5550            hideStickySection(true);
5551          } else {
5552            hideStickySection(false);
5553          }
5554          // <!-- split enable flag from api -->
5555          if (
5556         
5556   angular.isDefined(data.reservationSummary.splitBillSummary) &&
5557            angular.isDefined(
5558              data.reservationSummary.splitBillSummary.splitBillEnabled
5559            )
5560          ) {
5561            vm.rentalModel.availedSplitbill =
5562              data.reservationSummary.splitBillSummary.splitBillEnabled;
5563            vm.rentalDetails.reservationSummary.splitBillSummary.splitBillEnabled =
5564              vm.rentalModel.availedSplitbill;
5565          }
5566
5567          // flag to check new location selection based on this label
5568          // will be changed to "New Return Location"
5569          if (
5570            angular.isDefined(data.reservationSummary) &&
5571            angular.isDefined(data.reservationSummary.dropLoc) &&
5572            angular.isDefined(data.reservationSummary.dropLoc.locationCode)
5573          ) {
5574            if (
5575              data.reservationSummary.dropLoc.locationCode !=
5576              modifiedData.dropLocCode
5577            ) {
5578              vm.rentalModel.newLoc = true;
5579            } else {
5580              vm.rentalModel.newLoc = false;
5581            }
5582          }
5583
5584          // splitbill-396 condition added to show or hide Toggle
5585          // option on reduce of rental extension
5586          if (
5587            angular.isDefined(data.reservationSummary) &&
5588            angular.isDefined(data.reservationSummary.rateSummary) &&
5589            angular.isDefined(data.reservationSummary.splitBillSummary) &&
5590            data.reservationSummary.rentalState == 'estimate' &&
5591            (data.reservationSummary.rateSummary.totalAdditonalCharges > 0 ||
5592              (data.reservationSummary.splitBillSummary.splitBillSecondary !=
5593                null &&
5594                data.reservationSummary.splitBillSummary.splitBillSecondary
5595                  .cardAmount > 0))
5596          ) {
5597            vm.rentalModel.showSplitOpt = true;
5598          } else {
5599            vm.rentalModel.showSplitOpt = false;
5600          }
5601
5602          // To load months and years in add new card modal
5603          vm._loadMnthYrDropdown();
5604          vm._populateBillingInfoCountryList();
5605          if (
5606            angular.isDefined(vm.addresses) &&
5607            !$.isEmptyObject(vm.addresses)
5608          ) {
5609            vm._getAddressList(vm.addresses);
5610          }
5611          if (
5612            angular.isDefined(data.reservationSummary) &&
5613            angular.isDefined(data.reservationSummary.personalInfo) &&
5614            angular.isDefined(data.reservationSummary.personalInfo.residency) &&
5615            angular.isDefined(
5616              data.reservationSummary.personalInfo.residency.value
5617            )
5618          ) {
5619            vm.reservationModel.paymentRq.address.country =
5620              data.reservationSummary.personalInfo.residency.value;
5621          }
5622          if (vm.brand == 'avis') {
5623            vm.getStatesForCountry(
5624              vm.reservationModel.paymentRq.address.country,
5625              'onload'
5626            );
5627          }
5628          vm.rentalModel.showModifiedReturns = false;
5629          vm.rateSummary = data.reservationSummary.rateSummary;
5630
5631          // enabling split in modify return tab and initialising
5632          // vm.rentalDetails for primary and secondary amount
5633          if (
5634            angular.isDefined(data.reservationSummary) &&
5635            angular.isDefined(data.reservationSummary.splitBillSummary)
5636          ) {
5637            vm.rentalDetails.reservationSummary.splitBillSummary =
5638              data.reservationSummary.splitBillSummary;
5639          }
5640          // $('.showTab-tab2').attr("disabled",true);
5641          if (
5642            angular.isDefined(data.reservationSummary.gebUser) &&
5643            data.reservationSummary.gebUser &&
5644            angular.isDefined(data.reservationSummary.splitBillSummary) &&
5645            data.reservationSummary.splitBillSummary.splitBillSecondary
5646          ) {
5647            vm.rentalModel.availedSplitbill = true;
5648          }
5649          vm.rentalState = {
5650            value:
5651              data.reservationSummary.rentalState == 'estimate' ? true : false,
5652            tab: 'Modify-Return',
5653          };
5654
5655          analytics(false, eventLabel);
5656          $rootScope.requestInProgress = false;
5657          $('html, body').animate({
5658            scrollTop: $('#tabStart').position().top,
5659          });
5660        },
5661        function (error) {
5662          if (
5663            angular.isDefined(error.errorList) &&
5664            error.errorList.length > 0
5665          ) {
5666            if (vm.hideStickySection) {
5667              vm.hideStickySection = false;
5668            }
5669            hideStickySection(false);
5670            if (vm.rentalModel.tabFocus) {
5671              hideStickySection(true);
5672            } else {
5673              hideStickySection(false);
5674            }
5675            vm.error = $scope.processErrorMessage(error).errorList;
5676            $rootScope.requestInProgress = false;
5677          }
5678        }
5679      );
5680    }
5681
5682    function confirmRentalExt() {
5683      if (!vm.rentalModel.showModifiedReturns) {
5684        $rootScope.requestInProgress = true;
5685        var resultDateFormatObj = vehicleService.getDateFormat(
5686          authenticationService.getCustomerModel()
5687        );
5688        var date = $.datepicker.parseDate(
5689          resultDateFormatObj.dateFormat.format,
5690          vm.dropDate
5691        );
5692        date = $filter('date')(date, 'MM/dd/yyyy');
5693        var modifiedData = {
5694          splitOpted: vm.rentalModel.availedSplitbill,
5695          rentalNumber: vm.rentalNumber,
5696          dropLocCode: angular.isDefined(vm.selectedLoc)
5697            ? vm.selectedLoc
5698            : vm.rentalExtension.reservationSummary.dropLoc.locationCode,
5699          dropDate: angular.isDefined(vm.dropDate)
5700            ? date
5701            : $filter('date')(
5702              vm.rentalExtension.reservationSummary.dropDateTime,
5703              'MM/dd/yyyy'
5704            ),
5705          dropTime: angular.isDefined(vm.selectedTime)
5706            ? vm.selectedTime
5707            : $filter('date')(
5708              vm.rentalExtension.reservationSummary.dropDateTime,
5709              'h:mm a'
5710            ),
5711        };
5712        vm.extentionSplitData = modifiedData;
5713        // Pushing card number to service layer for request object
5714        var splitData = {
5715          secondaryCreditCard:
5716            angular.isDefined(vm.secondaryCardSelected) &&
5717              angular.isDefined(vm.secondaryCardSelected.number)
5718              ? vm.secondaryCardSelected.number
5719              : '',
5720        };
5721        getDataService.addToSplitDetails(splitData);
5722
5723        rentalService.confirmRentalExtension(modifiedData).then(
5724          function (data) {
5725            if (
5726              angular.isDefined(data.errorList) &&
5727              data.errorList.length > 0
5728            ) {
5729              vm.error = $scope.processErrorMessage(data).errorList;
5730              vm.rentalModel.modifyReturnActive = false;
5731              vm.rentalState.value =
5732                angular.isDefined(data.reservationSummary) &&
5733                  angular.isDefined(data.reservationSummary.rentalState) &&
5734                  data.reservationSummary.rentalState == 'estimate'
5735                  ? true
5736                  : false;
5737              // error check for return date -if exceeds 30 days
5738              // starts
5739              if (
5740                vm.error[0].code == '34027' ||
5741                vm.error[0].code == '34031' ||
5742                vm.error[0].code == '34003'
5743              ) {
5744                vm.rentalModel.date = false;
5745                vm.rentalModel.loc = false;
5746                vm.rentalModel.time = false;
5747                vm.rentalState.value = false;
5748                if (angular.isDefined(data.reservationSummary)) {
5749                  vm.returnLoc =
5750                    data.reservationSummary.dropLoc.name +
5751                    ', ' +
5752                    data.reservationSummary.dropLoc.locationCode;
5753                  vm.returnDate = $filter('ModifiedDate')(
5754                    data.reservationSummary.dropDateTime
5755                  );
5756                  vm.dropDate = vm.returnDate;
5757                  vm.dropTime = $filter('date')(
5758                    data.reservationSummary.dropDateTime,
5759                    'h:mm a'
5760                  );
5761                }
5762              }
5763              // error check for return date -if exceeds 30 days ends
5764            } else {
5765              vm.rentalModel.time = false;
5766              vm.rentalModel.loc = false;
5767              vm.rentalModel.date = false;
5768              vm.rentalExtension = data;
5769              vm.rentalModel.showModifiedReturns = true;
5770              vm.rentalModel.dateTimeSelected = false;
5771              vm.rentalModel.confirmMessage = true;
5772              vm.rentalModel.modifyReturnActive = false;
5773              vm.rentalState.value = false;
5774              vm.returnLoc =
5775                vm.rentalExtension.reservationSummary.dropLoc.name +
5776                ', ' +
5777                vm.rentalExtension.reservationSummary.dropLoc.locationCode;
5778              vm.returnDate = $filter('ModifiedDate')(
5779                vm.rentalExtension.reservationSummary.dropDateTime
5780              );
5781              vm.dropTime = $filter('date')(
5782                vm.rentalExtension.reservationSummary.dropDateTime,
5783                'h:mm a'
5784              );
5785              var customer = authenticationService.getCustomerModel();
5786              if (
5787                angular.isDefined(data.reservationSummary) &&
5788                angular.isDefined(data.reservationSummary.splitBillSummary) &&
5789                angular.isDefined(
5790                  data.reservationSummary.splitBillSummary.splitBillEnabled
5791                )
5792              ) {
5793                vm.rentalDetails.reservationSummary.splitBillSummary =
5794                  data.reservationSummary.splitBillSummary;
5795              }
5796              _setDateFormatPreference(customer, data);
5797              _setTimeFormatPreference(customer, data);
5798              // update rentalEndIns on date modify in rental page
5799              var balanceDaysData = {
5800                balanceDays: vm.rentalExtension.reservationSummary.rentalEndsIn,
5801                rentalNumber: vm.rentalNumber,
5802              };
5803              vm.rentalDetails.reservationSummary.rentalEndsIn =
5804                balanceDaysData.balanceDays;
5805              $rootScope.$emit('Rental.balanceDays', balanceDaysData);
5806              if (jQuery(window).width() <= 767) {
5807                vm.close('Modify Return');
5808              }
5809              $('html, body').animate({
5810                scrollTop: $('#tabStart').position().top,
5811              });
5812              //$("#successModifyReturn").modal('show');
5813              $('#successModifyReturn').appendTo('body').modal('show');
5814
5815              // GA/GTM implementation change to capture on
5816              // confirmation of modify return
5817              if (
5818                angular.isDefined(data.reservationSummary.splitBillSummary) &&
5819                data.reservationSummary.splitBillSummary.splitBillEnabled
5820              ) {
5821                gaService.analyticsRentalDetails(
5822                  data,
5823                  'modifyReturn',
5824                  true,
5825                  ''
5826                );
5827              } else {
5828                gaService.analyticsRentalDetails(
5829                  data,
5830                  'modifyReturn',
5831                  false,
5832                  ''
5833                );
5834              }
5835              //fivestar changes
5836              if (
5837                angular.isDefined(data.reservationSummary) &&
5838                angular.isDefined(data.reservationSummary.vehicle) &&
5839                angular.isDefined(
5840                  data.reservationSummary.vehicle.fiveStarSafetyRate
5841                )
5842              ) {
5843                gaService.analyticsRentalClickEvents(data, '', '');
5844              }
5845            }
5846            $rootScope.requestInProgress = false;
5847          },
5848          function (error) {
5849            if (
5850              angular.isDefined(error.errorList) &&
5851              error.errorList.length > 0
5852            ) {
5853              vm.error = error.errorList;
5854              vm.rentalModel.modifyReturnActive = false;
5855              vm.rentalState.value =
5856                angular.isDefined(error.reservationSummary) &&
5857                  angular.isDefined(error.reservationSummary.rentalState) &&
5858                  error.reservationSummary.rentalState == 'estimate'
5859                  ? true
5860                  : false;
5861              // error check for return date -if exceeds 30 days
5862              // starts
5863              if (
5864                vm.error[0].code == '34027' ||
5865                vm.error[0].code == '34031' ||
5866                vm.error[0].code == '34003'
5867              ) {
5868                vm.rentalModel.date = false;
5869                vm.rentalModel.loc = false;
5870                vm.rentalModel.time = false;
5871                vm.rentalState.value = false;
5872                if (angular.isDefined(error.reservationSummary)) {
5873                  vm.returnLoc =
5874                    error.reservationSummary.dropLoc.name +
5875                    ', ' +
5876                    error.reservationSummary.dropLoc.locationCode;
5877                  vm.returnDate = $filter('ModifiedDate')(
5878                    error.reservationSummary.dropDateTime
5879                  );
5880                  vm.dropDate = vm.returnDate;
5881                  vm.dropTime = $filter('date')(
5882                    error.reservationSummary.dropDateTime,
5883                    'h:mm a'
5884                  );
5885                }
5886              }
5887              // error check for return date -if exceeds 30 days ends
5888            }
5889            $rootScope.requestInProgress = false;
5890          }
5891        );
5892      } else {
5893        vm.rentalModel.showModifiedReturns = false;
5894        //$('.showTab-tab2').removeClass('sp-confirm-footer');
5895        $rootScope.requestInProgress = true;
5896      }
5897    }
5898    // <!-- to load help content modal -->
5899    function loadHelpModal(currentEle) {
5900      var target = currentEle.target.parentElement;
5901      if (
5902        angular.isDefined(vm.rentalExtension) &&
5903        angular.isDefined(vm.rentalExtension.reservationSummary)
5904      ) {
5905        var country =
5906          vm.rentalExtension.reservationSummary.pickLoc.address.country;
5907      } else if (
5908        angular.isDefined(vm.rentalDetails) &&
5909        angular.isDefined(vm.rentalDetails.reservationSummary)
5910      ) {
5911        var country =
5912          vm.rentalDetails.reservationSummary.pickLoc.address.country;
5913      } else if (
5914        angular.isDefined(vm.rentalDetails) &&
5915        angular.isDefined(vm.rentalDetails.reservationSummary)
5916      ) {
5917        var country =
5918          vm.rentalDetails.reservationSummary.pickLoc.address.country;
5919      }
5920      vm.helpURL = getVehicles.getUrl(target, country);
5921    }
5922
5923    $scope.$watch('vm.dropDate', function (newVal, oldVal) {
5924      if (angular.isDefined(newVal) && angular.isDefined(oldVal)) {
5925        var resultDateFormatObj = vehicleService.getDateFormat(
5926          authenticationService.getCustomerModel()
5927        );
5928        var date = $.datepicker.parseDate(
5929          resultDateFormatObj.dateFormat.format,
5930          newVal
5931        );
5932        newVal = $filter('ModifiedDate')(date);
5933        vm.rentalModel.date = false;
5934        if (
5935          newVal != oldVal &&
5936          !(
5937            new Date(newVal).getDate() == new Date(vm.returnDate).getDate() &&
5938            new Date(newVal).getMonth() == new Date(vm.returnDate).getMonth() &&
5939            new Date(newVal).getFullYear() ==
5940            new Date(vm.returnDate).getFullYear()
5941          )
5942        ) {
5943          var resultDateFormatObj = vehicleService.getDateFormat(
5944            authenticationService.getCustomerModel()
5945          );
5946          var date = $.datepicker.parseDate(
5947            resultDateFormatObj.dateFormat.format,
5948            vm.dropDate
5949          );
5950          vm.returnDate = $filter('ModifiedDate')(date);
5951
5952          var resultDateFormatObj = vehicleService.getDateFormat(
5953            authenticationService.getCustomerModel()
5954          );
5955          var date = $.datepicker.parseDate(
5956            resultDateFormatObj.dateFormat.format,
5957            vm.dropDate
5958          );
5959          date = $filter('date')(date, 'MM/dd/yyyy');
5960
5961          var modifiedData = {
5962            splitOpted: vm.rentalModel.availedSplitbill,
5963            rentalNumber: vm.rentalNumber,
5964            dropLocCode: angular.isDefined(vm.selectedLoc)
5965              ? vm.selectedLoc
5966              : vm.rentalExtension.reservationSummary.dropLoc.locationCode,
5967            dropDate: date,
5968            dropTime: angular.isDefined(vm.selectedTime)
5969              ? vm.selectedTime
5970              : $filter('date')(
5971                vm.rentalExtension.reservationSummary.dropDateTime,
5972                'h:mm a'
5973              ),
5974          };
5975          vm.extentionSplitData = modifiedData;
5976          // Pushing card number to service layer for request object
5977          var splitData = {
5978            secondaryCreditCard:
5979              angular.isDefined(vm.secondaryCardSelected) &&
5980                angular.isDefined(vm.secondaryCardSelected.number)
5981                ? vm.secondaryCardSelected.number
5982                : '',
5983          };
5984          getDataService.addToSplitDetails(splitData);
5985
5986          vm.rentalModel.date = true;
5987          modifyReturn(modifiedData, 'Return Date');
5988        }
5989      }
5990    });
5991
5992    function close(event) {
5993      if (event == 'Modify Return') {
5994        hideStickySection(true);
5995      }
5996      vm.accordianClicked = event;
5997      if (!vm.rentalState.value) {
5998        /*if(event == 'Rental Summary'){
5999          jQuery(".showTab-tab3").removeClass("active"); 
6000          jQuery(".sp-nav-wrap").removeClass('cus-d-sm-none');
6001        }else if(event == 'Modify Return' && !vm.rentalModel.tabFocus){
6002          jQuery(".showTab-tab2").removeClass("active");
6003          jQuery(".sp-nav-wrap").removeClass('cus-d-sm-none');
6004        }else if(event == 'Modify Return' && vm.rentalModel.tabFocus){
6005          vm.rentalModel.tabFocus = false; 
6006        }else if(event == 'Rental Extras'){
6007          jQuery(".showTab-tab1").removeClass("active");
6008          jQuery(".sp-nav-wrap").removeClass('cus-d-sm-none');
6009        }else if(event == 'Shuttle Tracking'){
6010          jQuery(".showTab-tab4").removeClass("active");
6011          jQuery(".sp-nav-wrap").removeClass('cus-d-sm-none');
6012        }*/
6013        $window.location.href =
6014          $rootScope.contextPath +
6015          '/' +
6016          $rootScope.locale +
6017          '/' +
6018          'rental/rental-dashboard' +
6019          htmlExtension;
6020      } else {
6021        if (event == 'Modify Return') {
6022          hideStickySection(true);
6023          vm.rentalModel.modifyReturnActive = true;
6024        } else if (event == 'Rental Extras') {
6025          vm.rentalModel.confirmSuccess = true;
6026          hideStickySection(true);
6027          jQuery('#tab1').css('padding-bottom', ''); // to remove padding bottom 173px that is added in footerClass() function
6028        }
6029      }
6030      $('html, body').animate({
6031        scrollTop: $('#tabStart').offset().top - 100,
6032      });
6033    }
6034
6035    // for pickupdate validation
6036    function date(obj) {
6037      var min = new Date();
6038      var max = new Date(obj);
6039      if (obj > min) {
6040        min = obj;
6041      }
6042      max.setDate(max.getDate() + 30);
6043      jQuery('.end-date-input').datepicker('option', {
6044        minDate: min,
6045        maxDate: max,
6046      });
6047    }
6048
6049    // Load expirymonth and expiryear drop down
6050    function _loadMnthYrDropdown() {
6051      var dropdownData = ABG.loadMonthAndYear();
6052      vm.expMonths = dropdownData.expMonths;
6053      vm.expYears = dropdownData.expYears;
6054    }
6055
6056    /*
6057     * Fetches country list from AEM and populates in Credit Card Billing
6058     * Information Section.
6059     */
6060    function _populateBillingInfoCountryList() {
6061      var countries = $window.countryList;
6062      vm.countryList = [];
6063      vm.countryList = angular.fromJson(countries ? countries : {});
6064    }
6065
6066    // To Prepopulate the country
6067    function getStatesForCountry(countryCode, callStatus) {
6068      if (callStatus == 'onchange') {
6069        // On Country change resetting all the address fields to blank
6070        vm.billingAddress.address1 = '';
6071        vm.billingAddress.address2 = '';
6072        vm.billingAddress.address3 = '';
6073        vm.billingAddress.suburb = '';
6074        vm.billingAddress.city = '';
6075        vm.billingAddress.state = '';
6076        vm.billingAddress.zipCode = '';
6077      }
6078      if (
6079        vm.countryList &&
6080        countryCode != undefined &&
6081        countryCode != '' &&
6082        (countryCode === carRentalConstant.countryCodeAU ||
6083          countryCode === carRentalConstant.countryCodeCA ||
6084          countryCode === carRentalConstant.countryCodeUS)
6085      ) {
6086        var index = vm.countryList.indexOf(
6087          $filter('filter')(vm.countryList, function (d) {
6088            return d.code === countryCode;
6089          })[0]
6090        );
6091
6092        vm.statesForCountry = vm.countryList[index].stateList;
6093      }
6094      // function to display address3, city, state, suburb and zipcode
6095      vm._displayFunction(countryCode);
6096    }
6097    // this function to display city, state, zipcode, suburb and address3
6098    function _displayFunction(residency) {
6099      // check for city - show for CA, PR, US and VI (CX and CV)
6100      if (
6101        residency == carRentalConstant.countryCodeCA ||
6102        residency == carRentalConstant.countryCodePR ||
6103        residency == carRentalConstant.countryCodeUS ||
6104        residency == carRentalConstant.countryCodeCX ||
6105        residency == carRentalConstant.countryCodeCV ||
6106        residency == carRentalConstant.countryCodeVI
6107      ) {
6108        vm.rentalModel.showCity = true;
6109      } else {
6110        vm.rentalModel.showCity = false;
6111      }
6112
6113      // check for state - show for AU, CA, US and NZ
6114      if (
6115        residency == carRentalConstant.countryCodeAU ||
6116        residency == carRentalConstant.countryCodeCA ||
6117        residency == carRentalConstant.countryCodeUS ||
6118        residency == carRentalConstant.countryCodeNZ
6119      ) {
6120        vm.rentalModel.showState = true;
6121      } else {
6122        vm.rentalModel.showState = false;
6123      }
6124
6125      // check for suburb - show for AU and NZ
6126      if (
6127        residency == carRentalConstant.countryCodeAU ||
6128        residency == carRentalConstant.countryCodeNZ
6129      ) {
6130        vm.rentalModel.showSuburb = true;
6131      } else {
6132        vm.rentalModel.showSuburb = false;
6133      }
6134
6135      // check for zipcode - show for AU, CA, NZ, PR, US and VI (CX CV)
6136      if (vm.rentalModel.showSuburb || vm.rentalModel.showCity) {
6137        vm.rentalModel.showZipcode = true;
6138      } else {
6139        vm.rentalModel.showZipcode = false;
6140      }
6141    }
6142    // To display address dropdown
6143    function _getAddressList(address) {
6144      vm.addressDisplayList = [];
6145      angular.forEach(address, function (address) {
6146        var addressList = {
6147          code: '',
6148          description: '',
6149        };
6150        if (address.maskId == '1') {
6151          addressList.code = '1';
6152          addressList.description = 'Primary Address';
6153          vm.addressDisplayList.push(addressList);
6154          vm.selectedAddress = 'Primary Address';
6155          vm.reservationModel.paymentRq.address.address1 = address.address1;
6156          vm.reservationModel.paymentRq.address.address2 = address.address2;
6157          vm.reservationModel.paymentRq.address.address3 = address.address3;
6158          vm.reservationModel.paymentRq.address.city = address.city;
6159          vm.reservationModel.paymentRq.address.state = address.state;
6160          vm.reservationModel.paymentRq.address.zipCode = address.zipCode;
6161          vm.reservationModel.paymentRq.address.country = address.country;
6162          angular.forEach(vm.countryList, function (selectedcountry) {
6163            if (selectedcountry.code == vm.addresses[0].country) {
6164              vm.reservationModel.paymentRq.address.country =
6165                selectedcountry.name;
6166            }
6167          });
6168          vm.indicatorMap.address_id = address.maskId;
6169        }
6170        if (address.maskId == '2') {
6171          addressList.code = '2';
6172          addressList.description = 'Secondary Address';
6173          vm.addressDisplayList.push(addressList);
6174        }
6175      });
6176      return vm.addressDisplayList;
6177    }
6178
6179    // Populate addressField according to response
6180    function _populateAddressFields() {
6181      if (vm.rentalModel.epIndicator) {
6182        if (
6183          angular.isDefined(vm.rentalDetails.reservationSummary.address) &&
6184          angular.isDefined(vm.rentalDetails.reservationSummary.addresses)
6185        ) {
6186          vm.addresses = vm.rentalDetails.reservationSummary.addresses;
6187          vm.prefilledZipcode =
6188            vm.rentalDetails.reservationSummary.addresses[0].zipCode;
6189        } else if (
6190          angular.isDefined(vm.rentalDetails.reservationSummary.address) &&
6191          !angular.isDefined(vm.rentalDetails.reservationSummary.addresses)
6192        ) {
6193          vm.addresses.push(vm.rentalDetails.reservationSummary.address);
6194          vm.prefilledZipcode =
6195            vm.rentalDetails.reservationSummary.address.zipCode;
6196        } else if (
6197          angular.isDefined(vm.rentalDetails.reservationSummary.addresses) &&
6198          !angular.isDefined(vm.rentalDetails.reservationSummary.address)
6199        ) {
6200          vm.addresses = vm.rentalDetails.reservationSummary.addresses;
6201          vm.prefilledZipcode =
6202            vm.rentalDetails.reservationSummary.addresses[0].zipCode;
6203        }
6204      } else if (
6205        vm.rentalDetails.reservationSummary &&
6206        vm.rentalDetails.reservationSummary.addresses
6207      ) {
6208        vm.state = vm.rentalDetails.reservationSummary.addresses[0].state;
6209        vm.billingAddress = vm.rentalDetails.reservationSummary.addresses[0];
6210        vm.prefilledZipcode =
6211          vm.rentalDetails.reservationSummary.addresses[0].zipCode;
6212      } else if (
6213        angular.isDefined(vm.rentalDetails.reservationSummary.userState) &&
6214        vm.rentalDetails.reservationSummary.userState == 'ANONYMOUS'
6215      ) {
6216        vm.state = vm.rentalDetails.reservationSummary.address.state;
6217        vm.billingAddress = vm.rentalDetails.reservationSummary.address;
6218        vm.prefilledZipcode =
6219          vm.rentalDetails.reservationSummary.address.zipCode;
6220      }
6221    }
6222
6223    // Add new card and address to profile
6224    function saveCard(billingDetailsForm) {
6225      $rootScope.requestInProgress = true;
6226      // document.getElementById("submit_button").disabled = true;
6227      vm.oldSecondaryCardSummary =
6228        angular.isDefined(
6229          vm.rentalDetails.reservationSummary.splitBillSummary
6230        ) &&
6231          vm.rentalDetails.reservationSummary.splitBillSummary
6232            .splitBillSecondary != null &&
6233          angular.isDefined(
6234            vm.rentalDetails.reservationSummary.splitBillSummary
6235              .splitBillSecondary.ccSummary
6236          )
6237          ? vm.rentalDetails.reservationSummary.splitBillSummary
6238            .splitBillSecondary.ccSummary.number
6239          : '';
6240      $validationProvider
6241        .validate(billingDetailsForm)
6242        .success(function () {
6243          var data = {
6244            cardNumber: vm.creditCardNumber,
6245            secureCode: vm.secureCode,
6246            saveCreditCard: vm.rentalModel.saveCreditCard,
6247            nickName: vm.nickName,
6248            primary: vm.rentalModel.primary,
6249          };
6250          if (vm.billingAddress && vm.billingAddress.address1 != '') {
6251            if (vm.reservationModel.paymentRq.address.state != '') {
6252              vm.state = vm.reservationModel.paymentRq.address.state;
6253            }
6254
6255            vm.reservationModel.paymentRq.address.address1 =
6256              vm.billingAddress.address1;
6257            vm.reservationModel.paymentRq.address.address2 =
6258              vm.billingAddress.address2;
6259            vm.reservationModel.paymentRq.address.address3 =
6260              vm.billingAddress.address3;
6261            vm.reservationModel.paymentRq.address.city = vm.billingAddress.city;
6262            vm.reservationModel.paymentRq.address.state =
6263              vm.billingAddress.state;
6264            vm.reservationModel.paymentRq.address.zipCode =
6265              vm.billingAddress.zipCode;
6266            if (
6267              /^[a-zA-Z0-9]*$/.test(
6268                vm.reservationModel.paymentRq.address.address1
6269              ) ||
6270              (angular.isDefined(
6271                vm.reservationModel.paymentRq.address.address2
6272              ) &&
6273                /^[a-zA-Z0-9]*$/.test(
6274                  vm.reservationModel.paymentRq.address.address2
6275                )) ||
6276              (angular.isDefined(
6277                vm.reservationModel.paymentRq.address.address3
6278              ) &&
6279                /^[a-zA-Z0-9]*$/.test(
6280                  vm.reservationModel.paymentRq.address.address3
6281                )) ||
6282              (angular.isDefined(
6283                vm.reservationModel.paymentRq.address.zipCode
6284              ) &&
6285                /^[a-zA-Z0-9]*$/.test(
6286                  vm.reservationModel.paymentRq.address.zipCode
6287                )) ||
6288              (angular.isDefined(vm.reservationModel.paymentRq.address.city) &&
6289                /^[a-zA-Z0-9]*$/.test(
6290                  vm.reservationModel.paymentRq.address.city
6291                )) ||
6292              vm.state != vm.billingAddress.state
6293            ) {
6294              if (vm.reservationModel.saveAddress) {
6295                vm.indicatorMap.address_id = '0';
6296              } else {
6297                vm.indicatorMap.address_id = '-1';
6298              }
6299            }
6300          }
6301          if (/^[0-9]*$/.test(vm.creditCardNumber)) {
6302            if (vm.rentalModel.saveCreditCard) {
6303              vm.indicatorMap.credit_id = '0';
6304            } else {
6305              vm.indicatorMap.credit_id = '-1';
6306            }
6307          }
6308
6309          var indicatorMap = {
6310            address_id:
6311              angular.isDefined(vm.indicatorMap.address_id) &&
6312                vm.indicatorMap.address_id != ''
6313                ? vm.indicatorMap.address_id
6314                : '',
6315            credit_id:
6316              angular.isDefined(vm.indicatorMap.credit_id) &&
6317                vm.indicatorMap.credit_id != ''
6318                ? vm.indicatorMap.credit_id
6319                : '',
6320            epIndicator: vm.rentalModel.epIndicator,
6321          };
6322          var splitRequest = {
6323            splitOpted: vm.rentalDetails.reservationSummary.gebUser
6324              ? true
6325              : vm.rentalModel.availedSplitbill,
6326          };
6327          getDataService.addToSplitDetails(splitRequest);
6328          getDataService.addToIndicatorMap(indicatorMap);
6329          getDataService.addToCreditCardData(data);
6330          reservationModelService.setReservationModel(vm.reservationModel);
6331          vm.error = [];
6332          vm.errorDisplayList = [];
6333          vm.rentalModel.formValidated = false;
6334          rentalService
6335            .addCreditCardToRental(vm.rentalNumber, vm.rentalState.tab)
6336            .then(
6337              function (data) {
6338                vm.rentalDetails.reservationSummary = data.reservationSummary;
6339                if (
6340                  angular.isDefined(data.reservationSummary) &&
6341                  angular.isDefined(data.reservationSummary.splitBillSummary) &&
6342                  angular.isDefined(
6343                    data.reservationSummary.splitBillSummary.splitBillPrimary
6344                  ) &&
6345                  angular.isDefined(
6346                    data.reservationSummary.splitBillSummary.splitBillPrimary
6347                      .ccSummary
6348                  )
6349                ) {
6350                  vm.primaryCard = angular.copy(
6351                    data.reservationSummary.splitBillSummary.splitBillPrimary
6352                      .ccSummary
6353                  );
6354                }
6355                if (
6356                  angular.isDefined(data.reservationSummary) &&
6357                  angular.isDefined(data.reservationSummary.creditcards) &&
6358                  angular.isDefined(
6359                    data.reservationSummary.creditcards.length > 0
6360                  )
6361                ) {
6362                  vm.secondaryCardSelected = angular.copy(
6363                    data.reservationSummary.creditcards[
6364                    data.reservationSummary.creditcards.length - 1
6365                    ]
6366                  );
6367                  //vm.secondaryCCType =carRentalConstant.masterListForCC.filter(function(obj){ return obj.code == vm.secondaryCardSelected.type});
6368                }
6369                if (
6370                  angular.isDefined(data.reservationSummary.gebUser) &&
6371                  data.reservationSummary.gebUser &&
6372                  angular.isDefined(data.reservationSummary.splitBillSummary) &&
6373                  data.reservationSummary.splitBillSummary.splitBillSecondary
6374                ) {
6375                  vm.rentalModel.availedSplitbill = true;
6376                }
6377                vm.errorDisplayList = [];
6378                vm.rentalModel.formValidated = false;
6379                vm.creditCardNumber = '';
6380                vm.nickName = '';
6381                vm.reservationModel.paymentRq.expMonth = null;
6382                vm.reservationModel.paymentRq.expYear = null;
6383                vm.secureCode = '';
6384                vm.reservationModel.addAuthUserEdit = false;
6385                vm._getAddressList(vm.addresses);
6386                review_creditCard.rentalLocation =
6387                  vm.reservationModel.paymentRq.address.country =
6388                  vm.rentalDetails.reservationSummary.pickLoc.address.country;
6389                $rootScope.$broadcast('setReviewCreditCard', review_creditCard);
6390                vm.getStatesForCountry(
6391                  vm.reservationModel.paymentRq.address.country,
6392                  'onload'
6393                );
6394                if (
6395                  vm.rentalDetails.reservationSummary &&
6396                  !vm.rentalDetails.reservationSummary.addresses[0] &&
6397                  !vm.rentalDetails.reservationSummary.address
6398                ) {
6399                  vm.billingAddress = {
6400                    address1: '',
6401                    address2: '',
6402                    address3: '',
6403                    city: '',
6404                    state: null,
6405                    zipCode: '',
6406                  };
6407                }
6408
6409                vm.rentalModel.saveCreditCard = false;
6410                vm.reservationModel.saveAddress = false;
6411                if (
6412                  vm.oldSecondaryCardSummary != vm.secondaryCardSelected.number
6413                ) {
6414                  vm.rentalModel.changedCard = true;
6415                }
6416                $('#modalAddCreditCard').modal('hide');
6417                if (
6418                  angular.isDefined(data.reservationSummary) &&
6419                  angular.isDefined(data.reservationSummary.creditcards) &&
6420                  data.reservationSummary.creditcards.length == 2 &&
6421                  angular.isDefined(data.reservationSummary.splitBillSummary) &&
6422                  angular.isDefined(
6423                    data.reservationSummary.splitBillSummary.splitBillSecondary
6424                  ) &&
6425                  data.reservationSummary.splitBillSummary.splitBillSecondary ==
6426                  null &&
6427                  vm.rentalState.tab == 'Rental-Summary'
6428                ) {
6429                  $timeout(function () {
6430                    $('#splitAmount').modal('show');
6431                  }, 1000);
6432                  vm.events.showPaymentOption();
6433                }
6434                vm.extrasSplitEnable('addCard');
6435
6436                // GA-GTM implementation changes for click of save
6437                // button to Add new card
6438                if (vm.rentalState.tab == 'Extras') {
6439                  var eventLabel = carRentalConstant.addCcExtraSave;
6440                } else if (vm.rentalState.tab == 'Modify-Return') {
6441                  var eventLabel = carRentalConstant.addCcModifySave;
6442                } else {
6443                  var eventLabel = carRentalConstant.addCcSummarySave;
6444                }
6445
6446                if (
6447                  angular.isDefined(data) &&
6448                  angular.isDefined(data.reservationSummary) &&
6449                  angular.isDefined(data.reservationSummary.gateExitDone)
6450                ) {
6451                  var ec = 'Mid Rental';
6452                } else {
6453                  var ec = 'Pre Rental';
6454                }
6455
6456                analytics(false, eventLabel, 'splitbill', ec);
6457
6458                $rootScope.requestInProgress = false;
6459              },
6460              function (error) {
6461                if (
6462                  angular.isDefined(error.errorList) &&
6463                  error.errorList.length > 0
6464                ) {
6465                  vm.errorDisplayList = error.errorList;
6466                }
6467                $rootScope.requestInProgress = false;
6468              }
6469            );
6470        })
6471        .error(function (data) {
6472          vm.secureCode = '';
6473          vm.formError = ABG.getFormValidationError(data, false)[0].message;
6474          vm.rentalModel.formValidated = true;
6475
6476          var errCount = data.errorCount;
6477          if (1 === errCount) {
6478            vm.pageError = $sce.trustAsHtml(data.MSG[0]);
6479          } else if (1 < errCount) {
6480            // call the message from the i18n ======= AEM
6481            vm.pageError = Dictionary.I18n.get('err.global.multi.errorMessage');
6482          }
6483          $rootScope.requestInProgress = false;
6484        });
6485    }
6486
6487    function footerClass() {
6488      rentalService.calculatePaddingFooter(vm.rentalModel.tabFocus);
6489    }
6490    function selectedAddressList(address) {
6491      if (address.code == '1') {
6492        angular.forEach(vm.countryList, function (selectedcountry) {
6493          if (
6494            selectedcountry.code ==
6495            vm.rentalDetails.reservationSummary.addresses[0].country
6496          ) {
6497            vm.reservationModel.paymentRq.address.country =
6498              selectedcountry.name;
6499          }
6500        });
6501        angular.forEach(
6502          vm.rentalDetails.reservationSummary.addresses,
6503          function (address) {
6504            if (address.primary == true) {
6505              vm.reservationModel.paymentRq.address.address1 = address.address1;
6506              vm.reservationModel.paymentRq.address.address2 = address.address2;
6507              vm.reservationModel.paymentRq.address.address3 = address.address3;
6508              vm.reservationModel.paymentRq.address.city = address.city;
6509              vm.reservationModel.paymentRq.address.state = address.state;
6510              vm.reservationModel.paymentRq.address.zipCode = address.zipCode;
6511              vm.indicatorMap.address_id = address.maskId;
6512              vm.selectedAddress = 'Primary Address';
6513            }
6514          }
6515        );
6516      } else if (address.code == '2') {
6517        angular.forEach(vm.countryList, function (selectedcountry) {
6518          if (
6519            selectedcountry.code ==
6520            vm.rentalDetails.reservationSummary.addresses[1].country
6521          ) {
6522            vm.reservationModel.paymentRq.address.country =
6523              selectedcountry.name;
6524          }
6525        });
6526        angular.forEach(
6527          vm.rentalDetails.reservationSummary.addresses,
6528          function (address) {
6529            if (address.primary == false) {
6530              vm.reservationModel.paymentRq.address.address1 = address.address1;
6531              vm.reservationModel.paymentRq.address.address2 = address.address2;
6532              vm.reservationModel.paymentRq.address.address3 = address.address3;
6533              vm.reservationModel.paymentRq.address.city = address.city;
6534              vm.reservationModel.paymentRq.address.state = address.state;
6535              vm.reservationModel.paymentRq.address.zipCode = address.zipCode;
6536              vm.indicatorMap.address_id = address.maskId;
6537              vm.selectedAddress = 'Secondary Address';
6538            }
6539          }
6540        );
6541      }
6542    }
6543
6544    function _itemizedDropdown() {
6545      vm.rentalDays.productDays.primaryValues = [];
6546      vm.rentalDays.productDays.secondaryValues = [];
6547      vm.rentalDays.insuranceDays.primaryValues = [];
6548      vm.rentalDays.insuranceDays.secondaryValues = [];
6549      if (typeof vm.primaryValue === 'number') {
6550        if (vm.primaryValue > 1 || vm.primaryValue == 0) {
6551          vm.primaryValue = vm.primaryValue + ' Days';
6552        } else {
6553          vm.primaryValue = vm.primaryValue + ' Day';
6554        }
6555      }
6556      if (typeof vm.secondaryValue === 'number') {
6557        if (vm.secondaryValue > 1 || vm.secondaryValue == 0) {
6558          vm.secondaryValue = vm.secondaryValue + ' Days';
6559        } else {
6560          vm.secondaryValue = vm.secondaryValue + ' Day';
6561        }
6562      }
6563
6564      if (vm.secondaryValue != 0 || vm.secondaryValue != '0 Days') {
6565        vm.rentalDays.productDays.secondaryValues.push(vm.secondaryValue);
6566        vm.rentalDays.insuranceDays.secondaryValues.push(vm.secondaryValue);
6567      }
6568      if (vm.primaryValue != 0 || vm.primaryValue != '0 Days') {
6569        vm.rentalDays.productDays.primaryValues.push(vm.primaryValue);
6570        vm.rentalDays.insuranceDays.primaryValues.push(vm.primaryValue);
6571      }
6572
6573      if (typeof vm.totalDays === 'number') {
6574        if (vm.totalDays > 1 || vm.totalDays == 0) {
6575          vm.totalDays = vm.totalDays + ' Days';
6576        } else {
6577          vm.totalDays = vm.totalDays + ' Day';
6578        }
6579      }
6580      var secValue = parseInt(vm.secondaryValue.replace(/^[^0-9]+/, ''));
6581      var totalDays = parseInt(vm.totalDays.replace(/^[^0-9]+/, ''));
6582      if (secValue != totalDays) {
6583        vm.rentalDays.productDays.secondaryValues.push(vm.totalDays);
6584        vm.rentalDays.insuranceDays.secondaryValues.push(vm.totalDays);
6585      }
6586
6587      //To check if any of product or insurance value is 0, push 0 day to set as default
6588      vm.checkForMaxDaysExtras(
6589        vm.prodItemizedPri,
6590        vm.insuranceItemizedPri,
6591        'primary'
6592      );
6593      vm.checkForMaxDaysExtras(
6594        vm.prodItemizedSec,
6595        vm.insuranceItemizedSec,
6596        'secondary'
6597      );
6598    }
6599
6600    //To check if maximum days selected, then push 0 Days to dropdown
6601    function checkForMaxDaysExtras(product, insurance, type) {
6602      if (type == 'primary') {
6603        angular.forEach(product, function (value, key) {
6604          if (value == '0 Days') {
6605            vm.rentalDays.productDays.primaryValues.unshift('0 Days');
6606          }
6607        });
6608        angular.forEach(insurance, function (value, key) {
6609          if (value == '0 Days') {
6610            vm.rentalDays.insuranceDays.primaryValues.unshift('0 Days');
6611          }
6612        });
6613      } else if (type == 'secondary') {
6614        angular.forEach(product, function (value, key) {
6615          if (value == '0 Days') {
6616            vm.rentalDays.productDays.secondaryValues.unshift('0 Days');
6617          }
6618        });
6619        angular.forEach(insurance, function (value, key) {
6620          if (value == '0 Days') {
6621            vm.rentalDays.insuranceDays.secondaryValues.unshift('0 Days');
6622          }
6623        });
6624      }
6625    }
6626
6627    function leaveSplitChanges() {
6628      vm.rentalModel.showAlertMessage = false;
6629      splitConfirmed = false;
6630      vm.splitPaymentConfirm(splitType);
6631    }
6632
6633    /* jQuery Listerner */
6634    $('#modalAddCreditCard').on('hidden.bs.modal', function () {
6635      $validationProvider.resetError(
6636        'vm.reservationModel.paymentRq.expMonth',
6637        true
6638      );
6639      $validationProvider.resetError(
6640        'vm.reservationModel.paymentRq.expYear',
6641        true
6642      );
6643      $validationProvider.resetError('vm.billingAddress', true);
6644      $validationProvider.resetError('vm.creditCardNumber', true);
6645      $validationProvider.resetError('vm.secureCode', true);
6646      if (
6647        vm.secondaryCardSelected.number == '' &&
6648        !vm.rentalDetails.reservationSummary.gebUser
6649      ) {
6650        $('#pay-CC').prop('checked', false);
6651        $timeout(function () {
6652          vm.rentalModel.availedSplitbill = false;
6653        }, 1);
6654      }
6655      vm.errorDisplayList = [];
6656      $rootScope.$broadcast('setReviewCreditCard', review_creditCard);
6657    });
6658    $('#splitAmount').on('hidden.bs.modal', function () {
6659      if (
6660        angular.isDefined(vm.rentalDetails.reservationSummary) &&
6661        angular.isDefined(
6662          vm.rentalDetails.reservationSummary.splitBillSummary
6663        ) &&
6664        vm.rentalDetails.reservationSummary.splitBillSummary.splitBillEnabled ==
6665        false
6666      ) {
6667        $('#pay-CC').prop('checked', false);
6668        $timeout(function () {
6669          vm.rentalModel.availedSplitbill = false;
6670        }, 1);
6671      }
6672    });
6673
6674    $scope.$on(
6675      '$locationChangeSuccess',
6676      function (event, newUrl, oldUrl, newState, oldState) {
6677        if (oldUrl.indexOf('#') != -1 && newUrl != oldUrl) {
6678          if (vm.isBackButton == true) {
6679            var url = $location.url();
6680            if (url != '') {
6681              $('#successAddon').modal('hide');
6682              var tab = carRentalConstant.modifyRentalStateTabMap[url];
6683              vm.events.redirect(tab, true);
6684            } else {
6685              history.go(-1);
6686            }
6687          } else {
6688            vm.isBackButton = true;
6689          }
6690        } else if (
6691          oldUrl.indexOf('#') == -1 &&
6692          newUrl != oldUrl &&
6693          vm.isBackButton == true
6694        ) {
6695          var url = $location.url();
6696          if (url != '') {
6697            var tab = carRentalConstant.modifyRentalStateTabMap[url];
6698            vm.events.redirect(tab, true);
6699          }
6700        } else {
6701          return;
6702        }
6703      }
6704    );
6705
6706    function _displayCarFeatures() {
6707      vm.vehicleFeatures = [];
6708      if (
6709        angular.isDefined(vm.rentalDetails.reservationSummary) &&
6710        angular.isDefined(vm.rentalDetails.reservationSummary.vehicle) &&
6711        angular.isDefined(
6712          vm.rentalDetails.reservationSummary.vehicle.vehicleFeatures
6713        )
6714      ) {
6715        angular.forEach(
6716          vm.rentalDetails.reservationSummary.vehicle.vehicleFeatures,
6717          function (features) {
6718            if (
6719              (features.name == 'Air' ||
6720                features.name == 'Auto' ||
6721                features.name == 'NS' ||
6722                features.name == 'mpg') &&
6723              features.webEnabled
6724            ) {
6725              vm.vehicleFeatures.push(features);
6726            }
6727          }
6728        );
6729      }
6730      if (
6731        angular.isDefined(vm.rentalDetails.reservationSummary) &&
6732        angular.isDefined(
6733          vm.rentalDetails.reservationSummary.onAirportIndicator
6734        ) &&
6735        vm.rentalDetails.reservationSummary.onAirportIndicator == true
6736      ) {
6737        if (
6738          angular.isDefined(vm.rentalDetails.reservationSummary.vehicle) &&
6739          angular.isDefined(
6740            vm.rentalDetails.reservationSummary.vehicle.vehicleFeatures
6741          )
6742        ) {
6743          angular.forEach(
6744            vm.rentalDetails.reservationSummary.vehicle.vehicleFeatures,
6745            function (features) {
6746              if (features.name == 'licensePlateNumber') {
6747                vm.additionalVehicleData.licensePlateNumber = features.value;
6748              } else if (features.name == 'lotSpaceNumber') {
6749                vm.additionalVehicleData.lotSpaceNumber = features.value;
6750              }
6751              vm.displayAdditionalVehicleData = true;
6752            }
6753          );
6754        }
6755      }
6756    }
6757
6758    function clearLoc(flag) {
6759      flag ? (vm.hideStickySection = false) : (vm.hideStickySection = true);
6760      hideStickySection(vm.hideStickySection);
6761      $('.locations-form').find('input').val('');
6762      $('.locations-form').removeClass('.platform-element-error');
6763      $rootScope.$broadcast('removeLocation', function () { });
6764    }
6765
6766    $('#successAddon').on('hidden.bs.modal', function () {
6767      vm.events.redirect('tab3');
6768    });
6769
6770    $('#successModifyReturn').on('hidden.bs.modal', function () {
6771      vm.events.redirect('tab3');
6772    });
6773
6774    function hideStickySection(flag) {
6775      if (flag) {
6776        jQuery('.showTab-tab2').removeClass('sp-tab-geb-user');
6777      } else {
6778        jQuery('.showTab-tab2').addClass('sp-tab-geb-user');
6779      }
6780    }
6781
6782    function findFeatureByKeyName(key) {
6783      if (
6784        angular.isDefined(vm.rentalDetails.reservationSummary.vehicle) &&
6785        angular.isDefined(
6786          vm.rentalDetails.reservationSummary.vehicle.vehicleFeatures
6787        )
6788      ) {
6789        return vm.rentalDetails.reservationSummary.vehicle.vehicleFeatures.filter(
6790          function (data) {
6791            return data.name == key;
6792          }
6793        ).length
6794          ? vm.rentalDetails.reservationSummary.vehicle.vehicleFeatures.filter(
6795            function (data) {
6796              return data.name == key;
6797            }
6798          )[0]
6799          : '';
6800      } else {
6801        return false;
6802      }
6803    }
6804    /**
6805     * This method is used for checking the user status if user is eligible or not  for vehicle exchange
6806     */
6807    function checkUserStatus() {
6808      $rootScope.requestInProgress = true;
6809gaService.trackVehicleExchangeEvents('CHANGE_V_CTA', 'clicked');
6810      var promise = rentalService.checkUserForVehicleExchange(
6811        vm.rentalDetails.reservationSummary.rentalAgreementNumber, vm.rentalDetails.reservationSummary.confirmationNumber
6812      );
6813      promise.then(
6814        function success(data) {
6815          if (
6816            angular.isDefined(data.instructionList) &&
6817            data.instructionList.length > 0
6818          ) {
6819            if (
6820              data.instructionList[0].code == '20024' ||
6821              data.instructionList[0].code == '20023'
6822            ) {
6823              vm.vehicleExchangeObj.flow = true;
6824              storageService.setStorageData(
6825                'vehicleExchangeObj',
6826                vm.vehicleExchangeObj
6827              );
6828              _getLoginModalWindow();
6829            } else {
6830              vm.thresholdMsg = data.instructionList[0].message;
6831              vm.vehicleExchangeObj.thresholdError = true;
6832              storageService.setStorageData(
6833                'vehicleExchangeObj',
6834                vm.vehicleExchangeObj
6835              );
6836            }
6837          } else {
6838            vm.vehicleExchangeObj.flow = true;
6839            gaService.trackVehicleExchangeEvents('SIGN_IN_MODAL', 'AlreayAuthenticated');
6840            storageService.setStorageData(
6841              'vehicleExchangeObj',
6842              vm.vehicleExchangeObj
6843            );
6844            $window.location.href =
6845              $rootScope.contextPath +
6846              '/' +
6847              $rootScope.locale +
6848              '/' +
6849              'rental' +
6850              htmlExtension +
6851              '#/select-vehicle';
6852          }
6853          $rootScope.requestInProgress = false;
6854        },
6855        function error(err) {
6856          $rootScope.requestInProgress = false;
6857          if (err && err.fieldErrors) {
6858            var fieldError = $scope.processErrorMessage(err);
6859            vm.errorDisplayList = fieldError;
6860            $rootScope.requestInProgress = false;
6861          } else {
6862            if (err && err.errorList) {
6863              vm.errorDisplayList = err.errorList;
6864            }
6865            $rootScope.requestInProgress = false;
6866          }
6867        }
6868      );
6869    }
6870
6871    function getZoneNumber() {
6872      var onLotConfirmVehicleData = storageService.getStorageData(
6873        'onLotConfirmVehicleData'
6874      );
6875      if (angular.isDefined(onLotConfirmVehicleData))
6876        return onLotConfirmVehicleData.reservationSummary.pickLoc.zoneNumber;
6877      return utilityService.mapZoneDetails(vm.rentalDetails.reservationSummary)
6878        .pickLoc.zoneNumber;
6879    }
6880
6881    function _getLoginModalWindow() {
6882      gaService.trackVehicleExchangeEvents('SIGN_IN_MODAL', 'OPEN');
6883      $rootScope.$broadcast('LoginActivity', {
6884        requestType: 'Login',
6885        variance: 'Small',
6886        redirectFlow: 'vehicleExchangeFromRD'
6887      });
6888    }
6889
6890    function _authenticationHandler(arg) {
6891      if ($state.current.name == 'rental-dashboard') {
6892        if (
6893          arg.reservationSummary.userState ==
6894          carRentalConstant.userStateAuthenticated
6895        ) {
6896          vm.vehicleExchangeObj.flow = true;
6897          storageService.setStorageData(
6898            'vehicleExchangeObj',
6899            vm.vehicleExchangeObj
6900          );
6901          $window.location.href =
6902            $rootScope.contextPath +
6903            '/' +
6904            $rootScope.locale +
6905            '/' +
6906            'rental' +
6907            htmlExtension +
6908            '#/select-vehicle';
6909        } else {
6910          vm.loginValidated = true;
6911          vm.loginFormPageError = Dictionary.I18n.get(
6912            'err.prof.login.authenticationFailedAction'
6913          );
6914        }
6915      }
6916    }
6917
6918    /**
6919		 * Checks if the rental location is an Avis first rental location based on the location code.
6920		 * 
6921		 * @param {Object} summary - The reservation summary object from the rental/display API
6922		 * @param {Object} summary.pickLoc - The pickup location object
6923		 * @param {string} summary.pickLoc.locationCode - The location code to validate
6924		 * @returns {boolean} True if the location code is a valid Avis first rental location (5 characters starting with 'A1'), false otherwise
6925		 */
6926		function isAvisFirstRental(summary) {
6927			if (!summary || !summary.pickLoc || !summary.pickLoc.locationCode) {
6928				return false;
6929			}
6930
6931			var locationCode /** @type {string} */ = summary.pickLoc.locationCode;
6932			return angular.isString(locationCode) && locationCode.length === 5 && locationCode.indexOf('A1') === 0;
6933		}
6934
6935    /**
6936     * Determines whether a link should be disabled based on rental details.
6937     * Logs the ID being checked and returns whether this is an Avis first rental.
6938     *
6939     * @param {string|number} id - The identifier of the link to check
6940     * @returns {boolean} True if the link should be disabled (when it's an Avis first rental), false otherwise
6941     */
6942    function handleModifyReturnLocationClick(event, id) {
6943      if (shouldDisableLink(id)) {
6944        if (event && angular.isFunction(event.preventDefault)) {
6945          event.preventDefault();
6946        }
6947        return;
6948      }
6949
6950      vm.clearLoc();
6951      vm.rentalModel.tabFocus = !vm.rentalModel.tabFocus;
6952    }
6953
6954    /**
6955     * Determines whether a link should be disabled based on rental details.
6956     * 
6957     * @param {string} id - The identifier for the link to check
6958     * @returns {boolean} True if the link should be disabled (when it's an Avis first rental), false otherwise
6959     * @throws {Error} Logs error to console if an exception occurs during processing
6960     */
6961    function shouldDisableLink(id) {
6962      try {
6963        var summary = angular.isDefined(vm.rentalDetails)
6964          ? vm.rentalDetails.reservationSummary
6965          : null;
6966          
6967        return isAvisFirstRental(summary);
6968      } catch (error_) {
6969        console.error('Error checking if link should be disabled for id: ' + id, error_);
6970        return false;
6971      }
6972    }
6973
6974    /* login happen in a page */
6975    $rootScope.$on('Profile.successAuthentication', function (event, arg) {
6976      _authenticationHandler(arg);
6977    });
6978
6979    init();
6980  }
6981})();
6982
6983(function () {
6984  'use strict';
6985  angular
6986    .module('reservation')
6987    .controller('expressExitController', expressExitController);
6988  expressExitController.$inject = ['$rootScope', 'utilityService', 'rentalUtil'];
6989
6990  function expressExitController($rootScope, utilityService, rentalUtil) {
6991    var vm = this;
6992    vm.data = {}; // stores the session data
6993    vm.walkingDirectionContent = '';
6994    vm.exitQRCode = '';
6995    vm.errorMessage = '';
6996    vm.qrAction = {
6997      generate: true,
6998      view: false,
6999    };
7000    vm.exitQRCodePrivacy = {
7001      termsAccepted: false,
7002      dlVerify: false,
7003    };
7004    vm.walkingDirectionShowCard = false;
7005    vm.init = _init;
7006    vm.closeModal = closeModal;
7007    vm.gateExitQRCode = gateExitQRCode;
7008    vm.showWalkingDirection = true;
7009
7010    function _init() {
7011      // vm.data =
7012      //   angular.isUndefined(_dependency("storageService").getStorageData("equipmentCSSList")) ? _dependency("storageService").getStorageData('reservationModelSelfCheckOut')
7013      //     : _dependency("storageService").getStorageData('equipmentCSSList');
7014      vm.expressExitData =
7015        _dependency('storageService').getStorageData('expressExit');
7016      if (
7017        angular.isUndefined(vm.expressExitData) ||
7018        angular.isUndefined(vm.expressExitData.exitQRCode)
7019      ) {
7020        vm.expressExitData = {};
7021        vm.expressExitData.exitQRCode = {};
7022      }
7023      // expiry already triggered scenario
7024      if (
7025        angular.isDefined(vm.expressExitData) &&
7026        angular.isDefined(vm.expressExitData.exitQRCode)
7027      ) {
7028        _alreadyExpiredScenario(vm.expressExitData);
7029      }
7030      vm.customerInfo = rentalUtil.loadCustomerInfo();
7031      vm.wizardNum = angular.isDefined(vm.customerInfo) && angular.isDefined(vm.customerInfo.wizardNumberMasked) ? vm.customerInfo.wizardNumberMasked : '';
7032      if (rentalUtil.expressExitPass()) {
7033        _dependency('gaService').trackExpressExitPass(
7034          'initiated',
7035          vm.data.reservationSummary,
7036          vm.wizardNum
7037        );
7038      }
7039      vm.showWalkingDirection = !rentalUtil.isOnLotScanned();
7040
7041    }
7042
7043    vm.action = {
7044      submit: function callback(whatAction) {
7045        if (whatAction == 'walking-direction') {
7046          var existingSessionData =
7047            _dependency('storageService').getStorageData('expressExit');
7048          if (
7049            angular.isDefined(existingSessionData) &&
7050            angular.isDefined(existingSessionData.expressExitParams) &&
7051            angular.isDefined(
7052              existingSessionData.expressExitParams.walkingDirections
7053            ) &&
7054            existingSessionData.expressExitParams.walkingDirections.length > 0
7055          ) {
7056            vm.walkingDirectionContent =
7057              existingSessionData.expressExitParams.walkingDirections;
7058          } else {
7059            var locCode =
7060              angular.isDefined(vm.data) &&
7061                angular.isDefined(vm.data.reservationSummary) &&
7062                angular.isDefined(vm.data.reservationSummary.pickLoc) &&
7063                angular.isDefined(vm.data.reservationSummary.pickLoc.locationCode)
7064                ? vm.data.reservationSummary.pickLoc.locationCode
7065                : '';
7066            $rootScope.requestInProgress = true;
7067            vm.action._callService({
7068              locationCode: locCode,
7069              type: 'lat_long',
7070              rqHeader: {
7071                locale: $rootScope.locale,
7072                domain: _dependency('$window').domain.toLowerCase(),
7073              },
7074            });
7075          }
7076          vm.walkingDirectionShowCard = true;
7077          // var element = document.getElementById('walkingDerectionBox');
7078          setTimeout(function () {
7079            // element.scrollIntoView({ behavior: "smooth",  block: "end", inline: "nearest"});
7080            jQuery('html, body').animate(
7081              {
7082                scrollTop: jQuery('.walking_direction_box').offset().top - 100,
7083              },
7084              1000
7085            );
7086          }, 100);
7087        }
7088      },
7089      _callService: function callback(latLongRQ) {
7090        var expressExit = {
7091          expressExitParams: {
7092            walkingDirections: '',
7093          },
7094        };
7095        var promise = vm.action._latLong(latLongRQ);
7096        promise.then(
7097          function success(data) {
7098            $rootScope.requestInProgress = false;
7099            if (
7100              angular.isDefined(data) &&
7101              angular.isDefined(data.stationInfoList) &&
7102              data.stationInfoList.length > 0
7103            ) {
7104              var stationInfoList = data.stationInfoList;
7105              var stationInfo = stationInfoList[0];
7106              if (angular.isDefined(stationInfo.augmentDataMap)) {
7107                var augmentDataMap = stationInfo.augmentDataMap;
7108                if (angular.isDefined(augmentDataMap.CTR2LOT_DIR)) {
7109                  vm.walkingDirectionContent = augmentDataMap.CTR2LOT_DIR;
7110                  expressExit.expressExitParams.walkingDirections =
7111                    vm.walkingDirectionContent;
7112                } else if (angular.isUndefined(augmentDataMap.CTR2LOT_DIR)) {
7113                  vm.walkingDirectionContent = Dictionary.I18n.get(
7114                    'walking_direction_error_message'
7115                  );
7116                  expressExit.expressExitParams.walkingDirections =
7117                    vm.walkingDirectionContent;
7118                }
7119              }
7120            } else if (
7121              angular.isDefined(data) &&
7122              angular.isDefined(data.errorList) &&
7123              data.errorList.length > 0
7124            ) {
7125              vm.walkingDirectionContent = Dictionary.I18n.get(
7126                'walking_direction_error_message'
7127              );
7128              expressExit.expressExitParams.walkingDirections =
7129                vm.walkingDirectionContent;
7130            }
7131          },
7132          function error(err) {
7133            $rootScope.requestInProgress = false;
7134            if (
7135              angular.isDefined(err) &&
7136              angular.isDefined(err.errorList) &&
7137              data.errorList.length > 0
7138            ) {
7139              vm.walkingDirectionContent = Dictionary.I18n.get(
7140                'walking_direction_error_message'
7141              );
7142              expressExit.expressExitParams.walkingDirections =
7143                vm.walkingDirectionContent;
7144            }
7145          }
7146        );
7147        vm.expressExitData.expressExitParams = expressExit.expressExitParams;
7148        _dependency('storageService').setStorageData(
7149          'expressExit',
7150          vm.expressExitData
7151        );
7152      },
7153      _latLong: function callback(latLongRQ) {
7154        var reqObj = {
7155          locationCode: latLongRQ.locationCode,
7156          type: latLongRQ.type,
7157          rqHeader: {
7158            locale: internalLocale,
7159            domain: domain,
7160          },
7161        };
7162        var deferred = _dependency('$q').defer();
7163        var url = apiurl + '/station/lat-long';
7164        _dependency('$http')({
7165          method: 'POST',
7166          url: url,
7167          data: reqObj,
7168        })
7169          .then(function onSuccess(response) {
7170            var data = response.data;
7171            if (
7172              _dependency('$window').brand !=
7173              _dependency('carRentalConstant').brandName.PAYLESS
7174            ) {
7175              ABG.updateContextStores();
7176            }
7177            data = _dependency('exceptionHandler').processError(
7178              data,
7179              _dependency('reservationModelService').modelMap
7180            );
7181            if (
7182              angular.isDefined(data) &&
7183              angular.isUndefined(data.errorList)
7184            ) {
7185              deferred.resolve(data);
7186            } else {
7187              deferred.reject(data);
7188            }
7189          })
7190          .catch(function onError(response) {
7191            var data = response.data;
7192            deferred.reject(data);
7193          });
7194        return deferred.promise;
7195      },
7196    };
7197    vm.QrCodeAction = {
7198      _callService: function callback(consentTermsAccepted) {
7199        $rootScope.requestInProgress = true;
7200        var promise = vm.QrCodeAction._genarateQR(consentTermsAccepted);
7201        promise.then(
7202          function success(data) {
7203            if (angular.isDefined(data.reservationSummary)) {
7204              if (data.reservationSummary.qrSummary) {
7205                vm.exitQRCode = data.reservationSummary.qrSummary;
7206                if (
7207                  angular.isDefined(vm.expressExitData) &&
7208                  angular.isDefined(vm.expressExitData.exitQRCode) &&
7209                  angular.isUndefined(vm.expressExitData.termsAccepted)
7210                ) {
7211                  vm.expressExitData.termsAccepted = consentTermsAccepted;
7212                  // vm.exitQRCode.dlVerify = vm.expressExitData.exitQRCode.dlVerify;
7213                }
7214                vm.expressExitData.exitQRCode = vm.exitQRCode;
7215                _dependency('storageService').setStorageData(
7216                  'expressExit',
7217                  vm.expressExitData
7218                );
7219                if (vm.exitQRCode.qrCode) {
7220                  _dependency('gaService').trackExpressExitPass(
7221                    'success',
7222                    vm.data.reservationSummary,
7223                    vm.wizardNum
7224                  );
7225                  if (vm.exitQRCode.secondsUntilExpire) {
7226                    vm.exitQRCode.timeOfExpired =
7227                      Math.floor(vm.exitQRCode.secondsUntilExpire / 60) +
7228                      ' Minutes';
7229                  }
7230                } else {
7231                  if (vm.exitQRCode.errorCode == '50002') {
7232                    vm.errorMessage = vm.exitQRCode.message;
7233                    _dependency('gaService').expressExitPassErrorTracking(
7234                      'Your Express Exit Pass has expired'
7235                    );
7236                  }
7237                }
7238                $('#myModal-terms-condition').modal('hide'); // hide the terms modal
7239                if (
7240                  vm.exitQRCode.qrCode != null &&
7241                  vm.exitQRCode.expireDate != null &&
7242                  vm.exitQRCode.errorCode != '50002'
7243                )
7244                  $('#myModal').modal({ backdrop: 'static', keyboard: false }); // open the QR modal
7245                vm.qrAction = {
7246                  generate: false,
7247                  view: true,
7248                };
7249              }
7250            }
7251            $rootScope.requestInProgress = false;
7252          },
7253          function error(err) {
7254            $rootScope.requestInProgress = false;
7255            if (err && err.fieldErrors) {
7256              var fieldError = $scope.processErrorMessage(err);
7257              vm.errorDisplayList = fieldError;
7258              $rootScope.requestInProgress = false;
7259            } else {
7260              if (err && err.errorList) {
7261                vm.errorMessage = err.errorList[0].message;
7262              }
7263              $rootScope.requestInProgress = false;
7264            }
7265            $('#myModal-terms-condition').modal('hide'); // hide the terms modal
7266          }
7267        );
7268      },
7269      _genarateQR: function callback(consentTermsAccepted) {
7270        var reqObj = {
7271          rentalAgreementNumber:
7272            vm.data.reservationSummary.rentalAgreementNumber,
7273          consentTermsAccepted: consentTermsAccepted,
7274        };
7275        var deferred = _dependency('$q').defer();
7276        var url = apiurl + '/self-checkout/gateExitQRCode';
7277        _dependency('$http')({
7278          method: 'POST',
7279          url: url,
7280          data: reqObj,
7281        })
7282          .then(function onSuccess(response) {
7283            var data = response.data;
7284            if (
7285              _dependency('$window').brand !=
7286              _dependency('carRentalConstant').brandName.PAYLESS
7287            ) {
7288              ABG.updateContextStores();
7289            }
7290            data = _dependency('exceptionHandler').processError(
7291              data,
7292              _dependency('reservationModelService').modelMap
7293            );
7294            if (
7295              angular.isDefined(data) &&
7296              angular.isUndefined(data.errorList)
7297            ) {
7298              deferred.resolve(data);
7299            } else {
7300              deferred.reject(data);
7301            }
7302          })
7303          .catch(function onError(response) {
7304            var data = response.data;
7305            deferred.reject(data);
7306          });
7307        return deferred.promise;
7308      },
7309    };
7310
7311    function _dependency(param) {
7312      return angular.element(document).injector().get(param);
7313    }
7314
7315    function _closeWalkingDirection() {
7316      vm.walkingDirectionShowCard = false;
7317      scrollToQRCard();
7318
7319      // document.getElementById('walkingdirectionCol').classList.toggle("collapsed");
7320      // document.getElementById('walkingdirectionbox').classList.remove("in");
7321    }
7322    function scrollToQRCard() {
7323      var element = document.getElementById('qr-details-card');
7324      element.scrollIntoView({
7325        behavior: 'smooth',
7326        block: 'end',
7327        inline: 'nearest',
7328      });
7329    }
7330    function _closeTncModal() {
7331      _closeWalkingDirection();
7332      $('#myModal-terms-condition').modal('hide');
7333      $window.scroll(0, 0); // scrolling top
7334    }
7335
7336    function _closeQRModal() {
7337      _closeWalkingDirection();
7338      $('#myModal').modal('hide');
7339      scrollToQRCard();
7340    }
7341
7342    function closeModal(whichModal, formObj) {
7343      if (whichModal == 'QR') {
7344        _closeQRModal();
7345      } else if (whichModal == 'TNC') {
7346        _closeTncModal();
7347      } else if (whichModal == 'walking-direction') {
7348        _closeWalkingDirection();
7349      }
7350    }
7351
7352    function _alreadyExpiredScenario(sessionObj) {
7353      var exitQRCode = sessionObj.exitQRCode;
7354      if (exitQRCode.errorCode == '50002' && exitQRCode.qrCode === null) {
7355        vm.qrAction = {
7356          generate: false,
7357          view: true,
7358        };
7359      }
7360    }
7361
7362    function gateExitQRCode() {
7363      if (_checkExpressPresence(vm.expressExitData)) {
7364        // QR is already generated only view logics
7365        if (vm.expressExitData.exitQRCode.errorCode == 50002) {
7366          // no need to open modal as there is no QR Code for the user to see.
7367          // $('#myModal').modal({ backdrop: 'static', keyboard: false });
7368          vm.qrAction = {
7369            generate: false,
7370            view: true,
7371          };
7372          vm.errorMessage = vm.expressExitData.exitQRCode.message;
7373        } else if (vm.expressExitData.exitQRCode.errorCode == 50000) {
7374          if (vm.expressExitData.exitQRCode.qrCode) {
7375            vm.QrCodeAction._callService(true);
7376          }
7377        }
7378      }
7379      // else if (angular.isDefined(vm.data) && (angular.isUndefined(vm.data.exitQRCode) && !vm.data.exitQRCode.dlVerify || Object.keys(vm.data.exitQRCode).length === 0)) { // only show the terms and conditions modal during the generation
7380      //   $('#myModal-dl-verify').modal({ backdrop: 'static', keyboard: false });
7381      //   // $('#myModal-terms-condition').modal({ backdrop: 'static', keyboard: false });
7382      // }
7383      else if (
7384        angular.isDefined(vm.expressExitData) &&
7385        ((angular.isUndefined(vm.expressExitData.exitQRCode) &&
7386          !vm.expressExitData.exitQRCode.termsAccepted) ||
7387          Object.keys(vm.expressExitData.exitQRCode).length === 0)
7388      ) {
7389        $('#myModal-terms-condition').modal({
7390          backdrop: 'static',
7391          keyboard: false,
7392        });
7393      }
7394      _dependency('gaService').trackExpressExitPass(
7395        'requested',
7396        vm.data.reservationSummary,
7397        vm.wizardNum
7398      );
7399    }
7400
7401    function _checkExpressPresence(obj) {
7402      return (
7403        angular.isDefined(obj) &&
7404        angular.isDefined(obj.exitQRCode) &&
7405        obj.termsAccepted &&
7406        angular.isDefined(obj.exitQRCode.qrCode) &&
7407        angular.isDefined(obj.exitQRCode.message)
7408      );
7409    }
7410    $rootScope.$on('walkingDirection', function (event, walking) {
7411      vm.action.submit(walking.value);
7412    });
7413
7414    $rootScope.$on('getRentalDetails', function (event, data) {
7415      vm.data = data;
7416      vm.init();
7417    });
7418  }
7419})();
7420
7421(function () {
7422  'use strict';
7423  angular.module('reservation').service('rentalUtil', rentalUtil);
7424  rentalUtil.$inject = ['storageService'];
7425  function rentalUtil(storageService) {
7426    var resSum = {};
7427    var cdbSum = {};
7428
7429    var getData = function () {
7430      var rentalDetails = storageService.getStorageData('rentalDetails');
7431      var customer = rentalDetails && rentalDetails.customerInfo;
7432      var reservationModelSelfCheckout = storageService.getStorageData(
7433        'reservationModelSelfCheckOut'
7434      );
7435      var equipmentCSSList = storageService.getStorageData('equipmentCSSList');
7436
7437      return {
7438        reservationSummary:
7439          angular.isDefinedAndNotNull(rentalDetails) &&
7440            angular.isDefinedAndNotNull(rentalDetails.reservationSummary)
7441            ? rentalDetails.reservationSummary
7442            : (function () {
7443              return angular.isDefinedAndNotNull(
7444                reservationModelSelfCheckout
7445              ) &&
7446                angular.isDefinedAndNotNull(
7447                  reservationModelSelfCheckout.reservationSummary
7448                )
7449                ? reservationModelSelfCheckout.reservationSummary
7450                : {};
7451            })(),
7452        customer: angular.isDefinedAndNotNull(customer)
7453          ? customer
7454          : (function callback() {
7455            return angular.isDefinedAndNotNull(
7456              reservationModelSelfCheckout
7457            ) &&
7458              angular.isDefinedAndNotNull(
7459                reservationModelSelfCheckout.customerInfo
7460              )
7461              ? reservationModelSelfCheckout.customerInfo
7462              : {};
7463          })(),
7464        equipmentCSSList: angular.isDefinedAndNotNull(equipmentCSSList)
7465          ? equipmentCSSList
7466          : {},
7467        webHeader: rentalDetails && rentalDetails.webHeader ? rentalDetails.webHeader : reservationModelSelfCheckout && reservationModelSelfCheckout.webHeader ? reservationModelSelfCheckout.webHeader : {}
7468      };
7469    };
7470    resSum = getData().reservationSummary;
7471    cdbSum = getData().customer;
7472
7473    var userStatusHelper = {
7474      isAuthenticated: function () {
7475        if (angular.isDefined(resSum) && angular.isDefined(resSum.userState)) {
7476          var userState = resSum.userState;
7477          if (userState === 'AUTHENTICATED') return true;
7478          else if (userState === 'RECOGNIZED' || userState === 'ANONYMOUS')
7479            return false;
7480        }
7481        return false;
7482      },
7483      isPreferred: function () {
7484        return angular.isDefined(cdbSum) && angular.isDefined(cdbSum.preferred) && cdbSum.preferred && angular.isDefined(cdbSum.ftpreferred) && !cdbSum.ftpreferred;
7485      },
7486    };
7487
7488    var locationHelper = {
7489      mobileSelectLocation: function () {
7490        return angular.isDefined(resSum) &&
7491          angular.isDefined(resSum.pickLoc.airportIndicator) &&
7492          resSum.pickLoc.airportIndicator &&
7493          angular.isDefined(resSum.onAirportIndicator) &&
7494          resSum.onAirportIndicator
7495          ? true
7496          : false;
7497      },
7498      airportLocation: function () {
7499        return angular.isDefined(resSum) &&
7500          angular.isDefined(resSum.pickLoc.airportIndicator) &&
7501          resSum.pickLoc.airportIndicator &&
7502          angular.isDefined(resSum.onAirportIndicator) &&
7503          !resSum.onAirportIndicator
7504          ? true
7505          : false;
7506      },
7507      cityLocation: function () {
7508        return angular.isDefined(resSum) &&
7509          angular.isDefined(resSum.pickLoc.airportIndicator) &&
7510          resSum.pickLoc.airportIndicator === false
7511          ? true
7512          : false;
7513      },
7514    };
7515    var pseudoMVA = function () {
7516      // User can come from the VMC page and also the Express Exit SMS.
7517      return angular.isDefined(resSum) &&
7518        angular.isDefined(resSum.pseudoMVARental) &&
7519        resSum.pseudoMVARental
7520        ? true
7521        : false;
7522    };
7523    return {
7524      spaceNumber: function () {
7525        var vehicleFeatures =
7526          angular.isDefined(resSum.vehicle) &&
7527            angular.isDefined(resSum.vehicle.vehicleFeatures)
7528            ? resSum.vehicle.vehicleFeatures
7529            : [];
7530        for (var i = 0; i < vehicleFeatures.length; i++) {
7531          if (
7532            vehicleFeatures[i].name === 'lotSpaceNumber' &&
7533            vehicleFeatures[i].value !== 'See Counter'
7534          )
7535            return true;
7536        }
7537        return false;
7538      },
7539      vehicleReady: function () {
7540        return locationHelper.cityLocation();
7541      },
7542      fuelDetails: function () {
7543        return pseudoMVA() ? false : true;
7544      },
7545      bannerContent: function () {
7546        return !this.vehicleReady();
7547      },
7548      expressExitPass: function () {
7549        return (getData().webHeader && getData().webHeader.viewIndicator == 'PRE_RENTAL_DASHBOARD_EXPRSS_PASS') ? true : false;
7550      },
7551      isOnLotScanned: function () {
7552        return angular.isDefined(storageService.getStorageData(
7553          'onLotConfirmVehicleData'
7554        )) ? true : false;
7555      },
7556      vehicleExchange: function () {
7557        return (window.brand === "avis" || window.location.href.includes("avis")) && userStatusHelper.isPreferred() &&
7558          locationHelper.mobileSelectLocation() &&
7559          !pseudoMVA() && !resSum.gateExitDone && angular.isDefined(resSum.timeLapsedFromCheckOut) && resSum.timeLapsedFromCheckOut 
7559<= 120 && !this.isOnLotScanned(); // https://abg.atlassian.net/browse/ARSCU-4205
7560      },
7561       licensePlateNumber: function () {
7562        return pseudoMVA() ? false : true;
7563      },
7564      carModalName: function (modal) {
7565        return pseudoMVA()
7566          ? modal.includes('or similar')
7567            ? modal
7568            : modal + ' or similar'
7569          : modal;
7570      },
7571      loadActualCarImage: function () {
7572        return pseudoMVA() ? false : true;
7573      },
7574      loadCustomerInfo: function () {
7575        return getData().customer;
7576      }
7577    };
7578  }
7579})();
7580
7581(function() {
7582	'use strict';
7583
7584	angular
7585	.module('reservationServices')
7586	.service('curbsideService', curbsideService);
7587
7588	curbsideService.$inject = ['$http','$rootScope', '$q', 'exceptionHandler', 'reservationModelService',  'getDataService', 'authenticationService','optionalService','locationService','carRentalConstant'];
7589
7590	function curbsideService($http,$rootScope, $q, exceptionHandler, reservationModelService, getDataService, authenticationService, optionalService, locationService,carRentalConstant) {
7591
7592		var result = {
7593				loadProducts: loadProducts,
7594				productSelection : productSelection,
7595				confirmProduct : confirmProduct,
7596				mergeAvailableProductDetails : mergeAvailableProductDetails,
7597				getCurbsideData :getCurbsideData
7598				
7599		};
7600		
7601		//To load available curbside product details
7602		function loadProducts() {
7603			var url = apiurl + "/notification/event/rental";
7604			var deferred = $q.defer();
7605			var uniqueID = locationService.readQuery('id');
7606			var requestObj = {
7607					"uniqueId": uniqueID
7608			}
7609			
7610			$http({
7611				method: 'POST',
7612				url: url,
7613				data: requestObj
7614	  		}).then(function onSuccess(response) {
7615	  			var data = response.data;		
7616	  			data = exceptionHandler.processError(data);
7617				mergeAvailableProductDetails(data).then(function(response){
7618					deferred.resolve(data);
7619				});
7620	  		}).catch(function onError(response) {
7621	  			var data = response.data;
7622	  			deferred.reject(data);
7623	  		});
7624			 $rootScope.requestInProgress = false;
7625			return deferred.promise;
7626			
7627		};
7628
7629       //To merge curbside available products and supported extras into productSummarylist
7630		function mergeAvailableProductDetails(data) {
7631			var deferred = $q.defer();
7632			if (data && data.productSummaryList) {
7633				var availableProducts = data.productSummaryList;
7634				
7635				optionalService.loadSupportedExtras('und').then(function(supportedExtras) {
7636					var supportedProducts = supportedExtras.supportedProducts;
7637					var products = mergeProductDetails(supportedProducts, availableProducts);
7638					data.productSummaryList = products;
7639					deferred.resolve(data);
7640				});
7641			} else {
7642				deferred.resolve(data);
7643			}
7644
7645			return deferred.promise;
7646		} 
7647
7648		//To merge curbside product details by comparing both available and supported products 
7649		function mergeProductDetails(supportedProducts, availableProducts, reservationSummary) {
7650			var products = [];
7651			angular.forEach(supportedProducts, function(supportedProduct, value) {
7652				var isAvailable = false;
7653
7654				angular.forEach(availableProducts, function(availableProduct) {
7655					if (supportedProduct.code === availableProduct.code) {
7656						isAvailable = true;
7657						var product = createProduct(supportedProduct, availableProduct);
7658						products.push(product);
7659					}
7660				});
7661			});
7662
7663			return products;
7664		}
7665		
7666		//To create a product list with available and supported products
7667		function createProduct(supportedProduct, availableProduct) {
7668
7669			var product = {
7670					"name": supportedProduct.name,
7671					"description": supportedProduct.description,
7672					"information": supportedProduct.information,
7673					"image": supportedProduct.image,
7674					"additionalnote": supportedProduct.additionalnote,
7675					"displayQuantity": supportedProduct.quantity,
7676					"code": availableProduct.code,
7677					"dailyCharge": availableProduct.dailyCharge,
7678					"quantity": availableProduct.quantity,
7679					"totalPrice": availableProduct.totalPrice,
7680					"inclRateInEstTotal": availableProduct.inclRateInEstTotal,
7681					"selected": (availableProduct.productDisplay != undefined && availableProduct.productDisplay.selected != undefined && availableProduct.productDisplay.selected == 'TRUE'),
7682					"disabled": (availableProduct.productDisplay != undefined && availableProduct.productDisplay.editable != undefined && availableProduct.productDisplay.editable == 'FALSE'),
7683					"supported": availableProduct.supported,
7684					"type": availableProduct.type,
7685					"additionalDetails": availableProduct.additionalDetails, // TODO make changes to the mark-up
7686					"productMessage":(angular.isDefined(availableProduct.productMessage) && angular.isDefined(availableProduct.productMessage.type) && availableProduct.productMessage.type === 'INSTRUCTION') ? availableProduct.productMessage.code : '',
7687					"productInfoMessage": Dictionary.I18n.get((angular.isDefined(availableProduct.productMessage) && angular.isDefined(availableProduct.productMessage.type)) ? availableProduct.productMessage.code : ''),
7688					"included":availableProduct.included
7689			};
7690
7691			return product;
7692		}
7693
7694		//To send the selected curbside products from reservationModel
7695		function productSelection(){
7696			var url= apiurl + "/notification/rental/extras";
7697			var deferred = $q.defer();
7698			var reservationModel = reservationModelService.getReservationModel();
7699			var selectedProducts = reservationModel.selectedProducts;
7700			var payload = {
7701					"selectedProducts": selectedProducts					
7702			}
7703			
7704			$http({
7705				method: 'POST',
7706				url: url,
7707				data: payload
7708	  		}).then(function onSuccess(response) {
7709	  			var data = response.data;		
7710	  			data = exceptionHandler.processError(data);
7711				deferred.resolve(data);
7712	  		}).catch(function onError(response) {
7713	  			var data = response.data;
7714	  			deferred.reject(data);
7715	  		});
7716			return deferred.promise;
7717		}
7718		
7719		//Confirming the selected products from reservationModel and sending details for summary page
7720		function confirmProduct(){
7721			var url;
7722			var reservationModel = reservationModelService.getReservationModel();
7723			var selectedProducts = reservationModel.selectedProducts;
7724			var payload = {
7725					"selectedProducts": selectedProducts
7726			}
7727
7728			var deferred = $q.defer();
7729			url = apiurl + "/notification/rental/modify";
7730			$http({
7731				method: 'POST',
7732				url: url,
7733				data: payload
7734	  		}).then(function onSuccess(response) {
7735	  			var data = response.data;			
7736	  			data = exceptionHandler.processError(data);
7737				deferred.resolve(data);
7738	  		}).catch(function onError(response) {
7739	  			var data = response.data;
7740	  			deferred.reject(data);
7741	  		});
7742			return deferred.promise;
7743		}
7744		
7745		
7746		function getCurbsideData(pageName) {
7747			// get the page url from the constants
7748			var pageUrl = carRentalConstant.endPointArray[pageName];	
7749			var deferred = $q.defer();	
7750			$http({
7751				method: 'GET',
7752				url: apiurl +"/summary/reservation?url="+ pageUrl,
7753	  		}).then(function onSuccess(response) {
7754	  			var data = response.data;		
7755	  			data = exceptionHandler.processError(data);				
7756				deferred.resolve(data);	  
7757	  		}).catch(function onError(response) {
7758	  			var data = response.data;
7759	  			deferred.reject(data);
7760	  		});
7761			return deferred.promise;
7762
7763		}
7764		
7765		
7766		return result;
7767	}
7768})();
7769(function() {
7770	'use strict';
7771
7772	angular
7773	.module('reservation')
7774	.controller('curbsideController', curbsideController);
7775
7776	curbsideController.$inject = ['$scope', '$state', '$rootScope', '$window', 'reservationModelService', 'curbsideService','getDataService', 'authenticationService','carRentalConstant', 'gaService'];
7777
7778	function curbsideController($scope,$state, $rootScope, $window, reservationModelService, curbsideService, getDataService, authenticationService, carRentalConstant, gaService) {
7779		var vm = this;
7780		vm.reservationModel = reservationModelService.bookingModel;	
7781		vm.productSelected = productSelected;
7782		vm.productCheckbox = {};
7783		var quantity = 0;
7784		vm.confirm = confirm;
7785		vm.cancel = cancel;
7786		vm.additionalCharges = '';
7787		var processBridge  = false;
7788		vm._init=init;
7789		vm.curbsideLanding = $window.Ancillary;
7790		vm.productDescription = '';
7791		vm.hazardInstruction =  false;
7792		vm.xmrInformation = false;
7793		vm.hazardAndXmrInstruction = false;
7794		vm.instruction = '';
7795     
7796	
7797	   $rootScope.$on("TCInitSuccess", function(event, arg) {
7798			if(authenticationService.getXsrfToken() && processBridge===false && vm.curbsideLanding == carRentalConstant.curbside ){
7799				travelInit();
7800			 }
7801		});
7802		
7803	   //Initial  call to check the authentication issue and landing page 
7804		function init() {
7805			$rootScope.requestInProgress = true;	
7806			if($window.location.pathname.indexOf('rental/confirmation') !== -1){			
7807				curbsideService.getCurbsideData('CURBIDE_CONFIRMATION_URL').then(function(data) {							
7808					$rootScope.requestInProgress = true;
7809//					vm.taxesAndFees = Granite.I18n.get('lbl.taxesAndFees.included');
7810					vm.taxesAndFees = data.webHeader.i18nSummary.lbl_taxesAndFees_included;
7811//				    vm.anAdditional = Granite.I18n.get('lbl.anAdditional');
7812				    vm.anAdditional = data.webHeader.i18nSummary.lbl_anAdditional;
7813					if(angular.isDefined(data.rentalSummary.selectedProducts)&& data.rentalSummary.selectedProducts.length > 0){
7814						angular.forEach(data.rentalSummary.selectedProducts,function(product,key){
7815							if(data.rentalSummary.selectedProducts.length > 1){
7816								vm.hazardAndXmrInstruction = true;
7817//								vm.productDescription =  Granite.I18n.get('lbl.thankYouMessage') +" "+ Granite.I18n.get('lbl.productDescription');	
7818								vm.productDescription =  product.selectedProductDesc;	
7819								if(product.code == 'CSD'){
7820								vm.additionalProductChargeCSD=  product.dailyCharge;
7821								}
7822								if(product.code == 'XMR'){
7823								vm.additionalProductChargeXMR =  product.dailyCharge;
7824								}
7825								vm.instruction = data.rentalSummary.instruction;
7826								
7827							}				
7828							else if(product.code == 'CSD'){
7829								vm.hazardInstruction = true;			
7830//								vm.productDescription= Granite.I18n.get('lbl.thankYouMessage')+" "+ Granite.I18n.get('lbl.productDescription.csd');	
7831								vm.productDescription= product.selectedProductDesc;	
7832								vm.instruction = data.rentalSummary.instruction;
7833								vm.additionalProductChargeCSD = product.dailyCharge;
7834							}else{
7835								vm.xmrInformation = true;
7836//								vm.productDescription = Granite.I18n.get('lbl.thankYouMessage')+" "+ Granite.I18n.get('lbl.productDescription.xmr');
7837								vm.productDescription = product.selectedProductDesc;
7838								vm.additionalProductChargeXMR =  product.dailyCharge;
7839							}
7840
7841						})
7842						try {
7843							if(vm.reservationModel){
7844								gaService.analyticsDimension(data.rentalSummary.selectedProducts, 'curbside-conf', data);
7845							}				            
7846				          } catch (e) {
7847				            // TODO: handle exception
7848				         }
7849					}
7850					$rootScope.requestInProgress = false;
7851				});				
7852			}										
7853			if(authenticationService.getXsrfToken() && vm.curbsideLanding == carRentalConstant.curbside){
7854				processBridge  = true;
7855				travelInit();
7856			}			
7857		}
7858		
7859		
7860		
7861		//Navigating to summary page , if products are selected 
7862		function confirm(){		
7863			$rootScope.requestInProgress = true;
7864			curbsideService.confirmProduct().then(function(data) {						 
7865				 if (data  && data.errorList && data.errorList.length > 0) {
7866					 	$window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + "/" + "reservation" + htmlExtension + "#/time-and-place";
7867					}else{						
7868						$window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + "/rental/confirmation" + htmlExtension ;
7869					}	
7870			}, function(error) {});
7871		}
7872		
7873		//On click of cancel button in curbside product page to step1 page
7874		function cancel(){
7875			$window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + "/" + "reservation" + htmlExtension + "#/time-and-place";
7876		}
7877		
7878		//To load product details from productsummary list 
7879		function travelInit(){
7880			$rootScope.requestInProgress = true;
7881			curbsideService.loadProducts().then(function(data){
7882				vm.products = data.productSummaryList.reverse();	
7883				if (vm.products && vm.products.errorList && vm.products.errorList.length>0) {
7884					 $window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + "/" + "reservation" + htmlExtension + "#/time-and-place";
7885				};
7886				$rootScope.requestInProgress = false;
7887				try {
7888		            gaService.analyticsDimension(vm.products, 'curbside-anc', data);
7889		          } catch (e) {
7890		            // TODO: handle exception
7891		         }
7892			});
7893						
7894		}
7895
7896		//To store selected products in reservationModel
7897		function productSelected(productObj, code, isSelectValChanged, extrasId) {
7898			var isPresent = false;
7899			if (vm.productCheckbox[code]) {
7900				quantity = 1;
7901			}
7902
7903			angular.forEach(vm.reservationModel['selectedProducts'], function(selectedProduct, key) {
7904				if (selectedProduct.code === code) {
7905					vm.reservationModel['selectedProducts'].splice(key, 1);
7906				}
7907			});
7908
7909			if (vm.productCheckbox[code]) {
7910				productObj.selected = true;
7911				productObj.quantity = quantity;
7912
7913				if (extrasId) {
7914					var extraIndex = extrasId.indexOf('_ext');
7915					if (extraIndex == -1) {
7916						productObj.productId = extrasId;
7917					} else {
7918
7919						productObj.productId = productObj.code + 'chk_ext';
7920
7921					}
7922				}
7923				vm.reservationModel['selectedProducts'].push(productObj);
7924			} else{
7925				arrayPop(code,true);
7926			}
7927			reservationModelService.setReservationModel(vm.reservationModel);
7928			curbsideService.productSelection().then(function(data){
7929				vm.additionalCharges = data.totalAdditionalCharges;
7930				if(vm.additionalCharges > 0){
7931					vm.addtionalTrue = true;
7932				}else{
7933					vm.addtionalTrue = false;
7934				}
7935			});
7936		}
7937		
7938		//To remove unselected product from reservationModel
7939		function arrayPop(deleteCode, insArray) {
7940			if (insArray) {
7941				for (var i = 0; i < vm.reservationModel.selectedProducts.length; i++) {
7942					var obj = vm.reservationModel.selectedProducts[i];
7943					if (deleteCode === obj.code) {
7944						vm.reservationModel.selectedProducts.splice(i, 1);
7945						break;
7946					}
7947				}
7948			} 
7949		}
7950
7951		init();
7952
7953	}
7954})();
7955
7956
7957(function() {
7958  'use strict';
7959
7960  angular
7961    .module('accountServices')
7962    .factory('accountModelService', accountModelService);
7963
7964  accountModelService.$inject = [];
7965
7966  function accountModelService() {
7967
7968	  
7969	  var validateOfflineProfileModelMap = {
7970		      "dlNumber": "vm.validateOfflineProfileModel.dlNumber",
7971		      "lastName": "vm.validateOfflineProfileModel.lastName",
7972		      "wizardNumber": "vm.validateOfflineProfileModel.wizardNumber",
7973		      "ccNumber": "vm.validateOfflineProfileModel.ccNumber"
7974		    };
7975	    var credentialModalMap = {
7976	        	"firstName": "vm.credentialModal.firstName",
7977	            "lastName": "vm.credentialModal.lastName",
7978	            "emailAddress": "vm.credentialModal.emailAddress",
7979	            "zipcode": "vm.credentialModal.zipCode",
7980	            "dlLastFourChar": "vm.credentialModal.dlLastFourChar",
7981	            "password": "vm.credentialModal.password",
7982	            "currentPassword": "vm.credentialModal.updatePassword.currentPassword",
7983	            "wizard": "vm.credentialModal.wizard",
7984	            "newPassword": "vm.credentialModal.updatePassword.newPassword",
7985	            "dobMonth": "vm.credentialModal.dobMonth",
7986	            "dobDate":" vm.credentialModal.dobDate",
7987	            "dobYear":" vm.credentialModal.dobYear"
7988	        };
7989	    var credentialModal = {
7990	        	"firstName": "",
7991	            "lastName": "",
7992	            "emailAddress": "",
7993	            "zipCode": "",
7994	            "dlLastFourChar": "", 
7995	            "dobMonth":"",
7996	            "dobDate":"",
7997	            "updatePassword": {
7998	    			"currentPassword": "",
7999	    			"newPassword": ""
8000	    		},	       
8001	            "wizard":"",
8002	            "dobYear":""
8003	        };
8004	    var saveIdentityModelMap = {
8005	      "emailAddress": "vm.saveIdentityModel.emailAddress",
8006	      "password": "vm.saveIdentityModel.password",
8007	      "discountNumber": "vm.saveIdentityModel.AWDNumber"
8008	    };
8009	  
8010	  
8011	    /* 1) create skeleton model
8012	       2) do the ng-model from skeleton
8013	       3) from ng-model to update the model map
8014	       Mapping  after updating ng-model update the model mapping
8015	      */
8016	    var accountModelMap = {
8017	    		  "contactInfoRQ.addressRQs[0].address1": "vm.accountModel.contactInfoRQ.address.address1",
8018	    		  "contactInfoRQ.addressRQs[0].address2": "vm.accountModel.contactInfoRQ.address.address2",
8019	    	      "contactInfoRQ.addressRQs[0].address3": "vm.accountModel.contactInfoRQ.address.address3",
8020	    	      "contactInfoRQ.addressRQs[0].city": "vm.accountModel.contactInfoRQ.address.city",
8021	    	      "contactInfoRQ.address.country": "vm.accountModel.contactInfoRQ.address.country",
8022	    	      "contactInfoRQ.address.locationDescription": "vm.accountModel.contactInfoRQ.address.locationDescription",
8023	    	      "contactInfoRQ.addressRQs[0].state": "vm.accountModel.contactInfoRQ.address.state",
8024	    		  "contactInfoRQ.address.suburb": "vm.accountModel.contactInfoRQ.address.suburb",
8025	    		  "contactInfoRQ.addressRQs[0].zipCode": "vm.accountModel.contactInfoRQ.address.zipCode",
8026	    		  "contactInfoRQ.contactEmailRQs[0].emailAddress": "vm.accountModel.contactInfoRQ.emailAddress",
8027	    		  "contactInfoRQ.contactPhoneRQs[0].phoneNumber": "vm.accountModel.contactInfoRQ.telephone",
8028	    		  "contactInfoRQ.telephone": "vm.accountModel.contactInfoRQ.phoneNumber",
8029	    		  "creditCardRQ.cardNumber": "vm.accountModel.cardNumber",
8030	    		  "creditCardRQ.cardType": "vm.accountModel.cardType",
8031	    		  "creditCardRQ.expMonth": "vm.accountModel.expMonth",
8032	    		  "creditCardRQ.expYear": "vm.accountModel.expYear",
8033	    		  "creditCardRQ.secureCode": "vm.accountModel.secureCode",
8034	    	      "identityPwdRQ.emailAddress": "",
8035	    	      "identityPwdRQ.firstName": "",
8036	    	      "identityPwdRQ.lastName": "",
8037	    	      "promotionalEmailOptin": "vm.accountModel.identityPwdRQ.promotionalEmailOptin",
8038	    			"driversLicenseRQ.country": "",
8039	    			"driversLicenseRQ.dateOfBirth": "",
8040	    			"driversLicenseRQ.dlNumber": "",
8041	    			"driversLicenseRQ.expMonth": "",
8042	    			"driversLicenseRQ.expYear": "",
8043	    			"driversLicenseRQ.state": "",
8044	    			"company": "",
8045	    			"preferenceRQ.discountNumberRQs[0].discountNumber": "vm.accountModel.preferenceRQ.discountNumber",
8046	    			"preferenceRQ.eRecieptOptin": true,
8047	    			"preferenceRQ.emailOptin": true,
8048	    			"preferenceRQ.freqPickUpLoc": "",
8049	    			"preferenceRQ.prefcarGroup": "",
8050	    			"profPersonalInfoRQ.firstName": "vm.accountModel.profPersonalInfoRQ.firstName",
8051	    			"profPersonalInfoRQ.lastName": "vm.accountModel.profPersonalInfoRQ.lastName",
8052	    			"profPersonalInfoRQ.title": "vm.accountModel.profPersonalInfoRQ.title",
8053	    			"profPersonalInfoRQ.userName" : "vm.accountModel.profPersonalInfoRQ.userName",
8054	    			"pointsProgram" : "vm.accountModel.program.pointsProgram",
8055	    			"partnerProgram" : "vm.accountModel.program.partnerProgram"
8056	    		
8057	    	}
8058	    
8059    // accountModel skeleton
8060    var accountModel = {
8061    		"contactInfoRQ": {
8062    			"address": {
8063    				"address1": "",
8064    				"address2": "",
8065    				"address3": "",
8066    				"city": "",
8067    				"country": "",
8068    				"locationDescription": "",
8069    				"state": "",
8070    				"suburb": "",
8071    				"zipCode": ""
8072    			},
8073    			"emailAddress": "",
8074    			"phoneNumber": ""
8075    		},
8076    		"creditCardRQ": {
8077    			"cardNumber": "",
8078    			"cardType": "",
8079    			"expMonth": "",
8080    			"expYear": "",
8081    			"secureCode": ""
8082    		},
8083    		"identityPwdRQ": {
8084    	        "currentPassword": "",
8085    	        "eRecieptEmailOptin": false,
8086    	        "emailAddress": "",
8087    	        "firstName": "",
8088    	        "lastName": "",
8089    	        "newPassword": "",
8090    	        "promotionalEmailOptin": false,
8091    	        "title": ""
8092    	      },
8093    		"driversLicenseRQ": {
8094    			"country": "",
8095    			"dateOfBirth": "",
8096    			"dlNumber": "",
8097    			"expMonth": "",
8098    			"expYear": "",
8099    			"state": ""
8100    		},
8101    		"preferenceRQ": {
8102    			"company": "",
8103    			"discountNumber": "",
8104    			"eRecieptOptin": true,
8105    			"emailOptin": true,
8106    			"freqPickUpLoc": "",
8107    			"prefcarGroup": "",
8108    			"profExtrasRQ": {
8109    				"productRQs": [{
8110    					"code": "",
8111    					"quantity": 0,
8112    					"redeemedQty": 0,
8113    					"selected": true,
8114    					"type": ""
8115    				}],
8116    				"protectionsRQs": [{
8117    					"code": "",
8118    					"included": true,
8119    					"selected": true
8120    				}]
8121    			},
8122    			"sitePrefRQ": {
8123    				"dateFormat": "",
8124    				"language": "",
8125    				"timeFormat": ""
8126    			},
8127    			"smsOptin": ""
8128    		},
8129    		"profPersonalInfoRQ": {
8130    			"firstName": "",
8131    			"lastName": "",
8132    			"title": "",
8133    			"userName" : ""
8134    		},
8135    		"rewardsRQ": {
8136
8137    		},
8138    		"termsAcceptanceRQ": {
8139    			"termsConditionAcceptance": true
8140    		},
8141    		"password":"",
8142    		"program": {
8143    			"pointsProgram": false,
8144    			"partnerProgram": false
8145    		}
8146    	}
8147    
8148    
8149     
8150	    var validateOfflineProfileModel = {
8151	    	      dlNumber: "",
8152	    	      lastName: "",
8153	    	      wizardNumber: ""
8154	    	    };
8155
8156    var saveIdentityModel = {
8157      awdNumber: "",
8158      eRecieptEmailOptin: true,
8159      emailAddress: "",
8160      password: "",
8161      promotionalEmailOptin: true
8162    };
8163
8164    var result = {
8165      validateOfflineProfileModel: validateOfflineProfileModel,
8166      validateOfflineProfileModelMap : validateOfflineProfileModelMap,
8167      saveIdentityModel: saveIdentityModel,
8168      saveIdentityModelMap: saveIdentityModelMap,
8169      accountModel: accountModel,
8170      accountModelMap: accountModelMap,
8171      credentialModalMap: credentialModalMap,
8172      credentialModal : credentialModal
8173      
8174    };
8175    return result;
8176  }
8177})();
8178
8179(function() {
8180  'use strict';
8181
8182  angular
8183    .module('accountServices')
8184    .service('securityService', securityService);
8185  securityService.$inject = ['$http', '$q', '$validation'];
8186
8187  function securityService($http, $q, $validationProvider) {
8188
8189    var result = {
8190    	generateOtp: generateOtp,
8191    	validateOtp : validateOtp
8192    }
8193    
8194    function generateOtp(){
8195    	var deferred = $q.defer();
8196        var url = apiurl + "/profile/otp";
8197        $http({
8198        	method: 'GET',
8199            url: url
8200  		}).then(function onSuccess(response) {
8201  			var data = response.data;		
8202  			deferred.resolve(data);
8203  		}).catch(function onError(response) {
8204  			var data = response.data;
8205  			deferred.reject(ABG.evaluateError(data));
8206  		});
8207        return deferred.promise;
8208    }
8209    
8210    function validateOtp(reqObj){
8211    	var deferred = $q.defer();
8212        var url = apiurl + "/profile/otp";
8213        $http({
8214        	method: 'POST',
8215            url: url,
8216            data: reqObj
8217  		}).then(function onSuccess(response) {
8218  			var data = response.data;		
8219  			deferred.resolve(data);
8220  		}).catch(function onError(response) {
8221  			var data = response.data;
8222  			deferred.reject(ABG.evaluateError(data));
8223  		});
8224        return deferred.promise;
8225    }
8226    
8227    return result;
8228  }
8229})();
8230
8231(function() {
8232  'use strict';
8233
8234  angular
8235    .module('accountServices')
8236    .service('signupService', signupService);
8237  signupService.$inject = ['$http', '$q', '$rootScope', '$window', 'exceptionHandler', 'storageService', 'accountModelService', 'authenticationService'];
8238
8239  function signupService($http, $q, $rootScope, $window, exceptionHandler, storageService, accountModelService, authenticationService) {
8240
8241    var result = {
8242      validateIdentity: validateIdentity,
8243      createProfile: createProfile,
8244      resendActivationEmail: resendActivationEmail,
8245      validateUserName : validateUserName,
8246      getAccountData: getAccountData,
8247      setConcurCustomerInfo: setConcurCustomerInfo,
8248      getConcurCustomerInfo: getConcurCustomerInfo,
8249      geteOffersSupportedCountry: geteOffersSupportedCountry,
8250      geteReceiptSupportedCountry: geteReceiptSupportedCountry,
8251      getAccountModel : getAccountModel,
8252      rulesToRedirect: rulesToRedirect,
8253      validatePartnerCustomerInfo: validatePartnerCustomerInfo
8254    }
8255    var output = {
8256    		'supported': false,
8257    		'optin': false
8258    		
8259    };
8260    //MPF flow redirection rule
8261    function rulesToRedirect(data){
8262    	var redirectPath;
8263    	if(angular.isDefined(data.enrollmentStep)){
8264			if(data.enrollmentStep == "credit-card-section"){
8265				redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot + "/credit-card" + htmlExtension;	
8266			}else if(data.enrollmentStep == "dl-section"){
8267				redirectPath = $rootScope.contextPath + "/" + $rootScope.locale +  $window.contentRoot+"/driving-licence" + htmlExtension;
8268			}else if(data.enrollmentStep == "protections-coverages-section"){
8269				redirectPath = $rootScope.contextPath + "/" + $rootScope.locale +  $window.contentRoot+"/protections-coverages" + htmlExtension;
8270			}else if(data.enrollmentStep == "tnc-section"){
8271				redirectPath = $rootScope.contextPath + "/" + $rootScope.locale +  $window.contentRoot+"/terms-condition" + htmlExtension;
8272			}else if(data.enrollmentStep == "enroll-rewards-section" && angular.isDefined(data.loyaltyEligible) && data.loyaltyEligible.visible){
8273				redirectPath = $rootScope.contextPath + "/" + $rootScope.locale +  $window.contentRoot+"/rewards" + htmlExtension;
8274			}else{
8275				redirectPath = $rootScope.contextPath + "/" + $rootScope.locale +$window.contentRoot+"/activation" + htmlExtension;
8276			}
8277    	}else{
8278    		redirectPath = $rootScope.contextPath + "/" + $rootScope.locale +$window.contentRoot+"/activation" + htmlExtension;
8279    	}
8280    	return redirectPath;
8281    }
8282    
8283    function getAccountModel(accountModel){ 
8284    	var accountModel = {
8285    	        	"contactInfoRQ": {
8286    	        		  "address": {        
8287    	                  "address1": accountModel.contactInfoRQ.address.address1,
8288    	                  "address2": accountModel.contactInfoRQ.address.address2,
8289    	                  "address3": accountModel.contactInfoRQ.address.address3,
8290    	                  "city": accountModel.contactInfoRQ.address.city,
8291    	                  "country": accountModel.contactInfoRQ.address.country,
8292    	                  "state": accountModel.contactInfoRQ.address.state,
8293    	                  "suburb": accountModel.contactInfoRQ.address.address3,
8294    	                  "zipCode": accountModel.contactInfoRQ.address.zipCode
8295    	                  },
8296    	                  "emailAddress": accountModel.contactInfoRQ.emailAddress,
8297    	                  "phoneNumber": accountModel.contactInfoRQ.telephone,
8298    	                  "smsOptin": accountModel.contactInfoRQ.smsOptin
8299    	        	},
8300	        	    "identityRQ": {
8301	        		   "password": accountModel.password
8302	        		 },
8303	        	    "preferenceRQ": {
8304	        		   "discountNumber": accountModel.preferenceRQ.discountNumber,
8305	        		   "eRecieptOptin": accountModel.identityPwdRQ.eRecieptEmailOptin,
8306	        		   "emailOptin": accountModel.identityPwdRQ.promotionalEmailOptin,
8307	        		   "costControlNumber": accountModel.preferenceRQ.costControlNumber
8308	        		 },
8309	        		 "profPersonalInfoRQ": {
8310	        			"firstName": accountModel.profPersonalInfoRQ.firstName,
8311	        	        "lastName": accountModel.profPersonalInfoRQ.lastName,
8312	        	        "userName" : accountModel.profPersonalInfoRQ.userName,
8313	        	        "dateOfBirth" : angular.isDefined(accountModel.dobMonth)?(accountModel.dobMonth+"/"+accountModel.dobDate+"/"+accountModel.dobYear):undefined
8314	        		 }
8315       };
8316     return accountModel;
8317    }
8318
8319    
8320    var ConcurCustomerInfo = {};
8321    
8322    function getAccountData(data){
8323        var customerInfo = {
8324                    "contactInfoRQ": {
8325                          "address": {
8326                                        "address1": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.contacts) && angular.isDefined(data.customerInfo.contacts.address)) ? data.customerInfo.contacts.address.address1 : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.address) && angular.isDefined(data.partnerCustomerInfo.address.address1))? data.partnerCustomerInfo.address.address1: "",
8327                                  "address2": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.contacts) && angular.isDefined(data.customerInfo.contacts.address)) ? data.customerInfo.contacts.address.address2 : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.address) && angular.isDefined(data.partnerCustomerInfo.address.address2)) ? data.partnerCustomerInfo.address.address2 : "",
8328                                  "address3": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.contacts) && angular.isDefined(data.customerInfo.contacts.address)) ? data.customerInfo.contacts.address.address3 : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.address) && angular.isDefined(data.partnerCustomerInfo.address.address3)) ? data.partnerCustomerInfo.address.address3 : "",
8329                                  "city": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.contacts) && angular.isDefined(data.customerInfo.contacts.address)) ? data.customerInfo.contacts.address.city : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.address) && angular.isDefined(data.partnerCustomerInfo.address.city)) ? data.partnerCustomerInfo.address.city : "",
8330                                  "country": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.address) && angular.isDefined(data.customerInfo.address.country)) ? data.customerInfo.address.country : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.address))?data.partnerCustomerInfo.address.country:"",
8331                                  "state": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.contacts) && angular.isDefined(data.customerInfo.contacts.address)) ? data.customerInfo.contacts.address.state : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.address) && angular.isDefined(data.partnerCustomerInfo.address.state)) ? data.partnerCustomerInfo.address.state : "",
8332                                  "suburb": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.contacts) && angular.isDefined(data.customerInfo.contacts.address)) ? data.customerInfo.contacts.address.address3 : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.address) && angular.isDefined(data.partnerCustomerInfo.address.address3)) ? data.partnerCustomerInfo.address.address3 : "",
8333                                  "zipCode": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.contacts) && angular.isDefined(data.customerInfo.contacts.address)) ? data.customerInfo.contacts.address.zipCode : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.address) && angular.isDefined(data.partnerCustomerInfo.address.zipCode)) ? data.partnerCustomerInfo.address.zipCode : ""
8334                          },
8335                          "emailAddress": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.contacts) && angular.isDefined(data.customerInfo.contacts.email)) ? data.customerInfo.contacts.email : (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.email)) ? data.customerInfo.email : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.email)) ? data.partnerCustomerInfo.email : "",
8336                          "telephone" : (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.cellPhone)) ? data.customerInfo.cellPhone : ""
8337                    },
8338                    "preferenceRQ": {
8339                          "discountNumber": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.awd))?data.customerInfo.awd : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.discountNumber)) ? data.partnerCustomerInfo.discountNumber : ""    
8340                    },
8341                    "profPersonalInfoRQ": {
8342                          "firstName": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.firstName)) ? data.customerInfo.firstName : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.firstName))? data.partnerCustomerInfo.firstName : "",
8343                          "lastName": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.lastName)) ? data.customerInfo.lastName : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.lastName))? data.partnerCustomerInfo.lastName : "",
8344                          "userName" : (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.userName)) ? data.customerInfo.userName : (angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.userName))? data.partnerCustomerInfo.userName : "",                               
8345                    },
8346                    "identityPwdRQ": {
8347                     "eRecieptEmailOptin": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.eRecieptEmailOptin)) ? data.customerInfo.eRecieptEmailOptin : undefined,
8348                     "promotionalEmailOptin": (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.promoMails)) ? data.customerInfo.promoMails : undefined
8349                  }
8350        }
8351              return customerInfo
8352        };
8353
8354
8355    // Webapi end-point call to create profile. 
8356    //recaptcha variable added as part of ABGTTT-170
8357    function createProfile(profileFormData,recaptcha) {
8358    	var requestObj = createRequest(profileFormData,recaptcha);
8359      var deferred = $q.defer();
8360      // construct api request
8361      var url = apiurl + "/profile/create";
8362      $http({
8363    	  method: 'POST',
8364          url: url,
8365          data:  requestObj,
8366          headers:{
8367            	'g-recaptcha-response': (recaptcha) ? recaptcha : ''
8368            }
8369		}).then(function onSuccess(response) {
8370			var data = response.data;		
8371			if(angular.isDefined(data.iconographyList)) {
8372		        storageService.setStorageData('iconographyList',data.iconographyList);
8373		        }
8374	        data = exceptionHandler.processError(data, accountModelService.accountModelMap);
8375	        authenticationService.setCustomerModel(authenticationService.setCustomerData(data));
8376	        authenticationService.setAdditionalCustomerInfoModel(authenticationService.setAdditionalCustomerInfo(data));
8377	        authenticationService.setSessionModel(authenticationService.setSessionData(data));
8378	        $rootScope.$broadcast('Update.Notificationdisplay');
8379	        deferred.resolve(data);
8380		}).catch(function onError(response) {
8381			var data = response.data;
8382			deferred.reject(ABG.evaluateError(data));
8383		});
8384      return deferred.promise;
8385    };
8386
8387    //Validates offline profile for online account sign up.// TODO - need to relook at the method n
8387ame
8388    function validateIdentity(identityData) {
8389      var deferred = $q.defer();
8390      var url = apiurl + "/profile/validate-offlineProfile"; // TODO - webapi naming convention..
8391      $http({
8392    	  method: 'POST',
8393          url: url,
8394          data: identityData
8395		}).then(function onSuccess(response) {
8396			var data = response.data;	
8397			data = exceptionHandler.processError(data, accountModelService.expressValidateModelMap);
8398	        //data.customerInfo = vm.validatedCustomer; //TODO commented, handle if required
8399	        //data.customerInfo.email = data.customerInfo.email;
8400	        authenticationService.setCustomerModel(authenticationService.setCustomerData(data));
8401	        authenticationService.setSessionModel(authenticationService.setSessionData(data));
8402	        deferred.resolve(data);
8403		}).catch(function onError(response) {
8404			var data = response.data;
8405			deferred.reject(ABG.evaluateError(data));
8406		});
8407      return deferred.promise;
8408    };
8409
8410    /*Resend activation link*/
8411    function resendActivationEmail() {
8412      var deferred = $q.defer();
8413      var url = apiurl + '/profile/send-activationemail';
8414
8415      $http({
8416    	  method: 'POST',
8417          url: url
8418		}).then(function onSuccess(response) {
8419			var data = response.data;	
8420			deferred.resolve(data);
8421		}).catch(function onError(response) {
8422			var data = response.data;
8423			deferred.reject(ABG.evaluateError(data));
8424		});
8425
8426      return deferred.promise;
8427    }
8428
8429    //return the e-offer checkbox result whether to hide or display and optin or optout
8430    function geteOffersSupportedCountry(countryCode){
8431    	var eOffersSupportedCountries = $window.eOffersSupportedCountries;
8432    	var expressConsentCountries = $window.expressConsentCountries;
8433    	//check whether selected country supports e-offers
8434    	if(eOffersSupportedCountries.indexOf(countryCode.toUpperCase()) != -1){
8435    		output.supported = true;    		
8436    	}
8437    	//check whether e-offers will be defaulted to Yes or No
8438    	if(expressConsentCountries.indexOf(countryCode.toUpperCase()) != -1){
8439    		output.optin = false;
8440    	}else{
8441    		output.optin = true;
8442    	}
8443    	return output;
8444    }
8445    
8446  //return the e-receipt checkbox result whether to hide or display and optin or optout
8447    function geteReceiptSupportedCountry(countryCode){
8448    	var eReceiptSupportedCountries = $window.eReceiptSupportedCountries;
8449    	var expressConsentCountries = $window.expressConsentCountries;
8450    	var output = {};
8451    	//check whether selected country supports e-offers
8452    	if(eReceiptSupportedCountries.indexOf(countryCode.toUpperCase()) != -1){
8453    		output.supported = true;    		
8454    	}
8455    	//check whether e-offers will be defaulted to Yes or No
8456    	if(expressConsentCountries.indexOf(countryCode.toUpperCase()) != -1){
8457    		output.optin = false;
8458    	}else{
8459    		output.optin = true;
8460    	}
8461    	
8462    	return output;
8463    }
8464    function discountRequest(request,accountModel){
8465    	request.preferenceRQ.discountNumberRQs = [{
8466    		"discountNumber" : accountModel.preferenceRQ.discountNumber,
8467    		"maskId":"",
8468    		"operation":'add',
8469    		"primary":true
8470    	}];
8471    }
8472    
8473    //WebApi call to check for the uniqueness of email ID
8474    //recaptcha variable added as part of ABGTTT-170
8475    function validateUserName(emailAddress,recaptcha) {
8476    	var deferred = $q.defer();
8477        var url = apiurl + "/profile/validate-username";
8478        var requestObj = {
8479        		  "emailAddress": emailAddress
8480        }
8481        $http({
8482        	method: 'POST',
8483            url: url,
8484            data: requestObj,
8485            headers:{
8486              	'g-recaptcha-response': (recaptcha) ? recaptcha : ''
8487              }
8488  		}).then(function onSuccess(response) {
8489  			var data = response.data;		
8490  			deferred.resolve(data);
8491  		}).catch(function onError(response) {
8492  			var data = response.data;
8493  			deferred.reject(data);
8494  		});
8495        return deferred.promise;
8496    }
8497    
8498    function validatePartnerCustomerInfo(awd, cor) {
8499    	var deferred = $q.defer();
8500    	var url = apiurl+"/partner/segmentDetails";
8501        var requestObj={
8502            "discountNumber": awd,
8503            "country": cor
8504        }
8505        $http({
8506        	method: 'POST',
8507            url: url,
8508            data: requestObj
8509  		}).then(function onSuccess(response) {
8510  			var data = response.data;
8511  			 deferred.resolve(data);
8512  		}).catch(function onError(response) {
8513  			var data = response.data;
8514  			deferred.reject(data);
8515  		});
8516        return deferred.promise;
8517    }
8518    
8519    //sets customerInfo for partners flow
8520    function setConcurCustomerInfo(data) {
8521    	if(angular.isDefined(data)) {
8522    		ConcurCustomerInfo = data;
8523    	}
8524    }
8525    
8526    //sets customerInfo for partners flow
8527    function getConcurCustomerInfo() {
8528    	return angular.isDefined(ConcurCustomerInfo) ? ConcurCustomerInfo : {}
8529    }
8530    //recCheck in the request being sent .added as part of ABGTTT-170
8531    function createRequest(accountModel,recaptcha){
8532    	var requestObj;
8533    	requestObj = {
8534    			"contactInfoRQ": {
8535    			    "addressRQs": [
8536    			      {
8537    			        "address1": accountModel.contactInfoRQ.address.address1,
8538    			        "address2": accountModel.contactInfoRQ.address.address2,
8539    			        "address3": accountModel.contactInfoRQ.address.address3,
8540    			        "city":  accountModel.contactInfoRQ.address.city,
8541    			        "country":  accountModel.contactInfoRQ.address.country,
8542    			        "maskId": "",
8543    			        "operation": "add",
8544    			        "primary": true,
8545    			        "state":  accountModel.contactInfoRQ.address.state,
8546    			        "suburb":  accountModel.contactInfoRQ.address.suburb,
8547    			        "zipCode":  accountModel.contactInfoRQ.address.zipCode
8548    			      }
8549    			    ],
8550    			    "contactEmailRQs": [
8551    			      {
8552    			        "eRecieptOptin":(angular.isDefined(accountModel.preferenceRQ.eRecieptOptin)&& accountModel.preferenceRQ.eRecieptOptin==true)?"Y":"N" ,
8553    			        "emailAddress":accountModel.contactInfoRQ.emailAddress,
8554    			        "emailOptin": (angular.isDefined(accountModel.preferenceRQ.emailOptin)&& accountModel.preferenceRQ.emailOptin==true)?"Y":"N" ,
8555    			        "maskId": (angular.isDefined(accountModel.maskId)?accountModel.maskId:"1"),
8556    			        "operation": "add",
8557    			        "primary": true
8558    			      }
8559    			    ],
8560    			    // ARD2-508 changes as part of pre-otp changes 
8561    			    "contactPhoneRQs": [
8562    			      {
8563    			    	 "phoneNumber": accountModel.contactInfoRQ.phoneNumber,
8564    			    	 "primary": true,
8565    			    	 "smsOptIn": (angular.isDefined(accountModel.contactInfoRQ.smsOptin) && accountModel.contactInfoRQ.smsOptin==true)?"T":"N",
8566    			    	 "operation": "add",
8567    			    	 "maskId":  (angular.isDefined(accountModel.maskId)?accountModel.maskId:"1"),
8568    			      }
8569    			    ]
8570    			},
8571    			  "identityRQ": {
8572    			    "password": accountModel.identityRQ.password
8573    			  },
8574    			
8575
8576    			  "profPersonalInfoRQ": {
8577    			    "firstName":accountModel.profPersonalInfoRQ.firstName,
8578    			    "lastName": accountModel.profPersonalInfoRQ.lastName,
8579    			    "userName": accountModel.profPersonalInfoRQ.userName,
8580    			    "dateOfBirth":accountModel.profPersonalInfoRQ.dateOfBirth
8581    			  },
8582    			 "recCheck": (angular.isDefined(recaptcha) && recaptcha != '') ? true : false
8583
8584    	
8585    }
8586    	if(angular.isDefined(accountModel.preferenceRQ.discountNumber)&& accountModel.preferenceRQ.discountNumber!=""){
8587    		requestObj.preferenceRQ ={};
8588    		discountRequest(requestObj,accountModel);
8589    	}
8590    	
8591    	// ARD2-2157 Adding for CostControl field in request payload
8592    	    	if(angular.isDefined(accountModel.preferenceRQ.costControlNumber)&& accountModel.preferenceRQ.costControlNumber!=""){
8593    	    		
8594    	    		requestObj.preferenceRQ.costControlNumber = accountModel.preferenceRQ.costControlNumber;
8595    	     	}	
8596    	    	   	
8597    		return requestObj;
8598    	}
8599    	
8600    
8601    
8602    
8603    return result;
8604  }
8605})();
8606
8607(function() {
8608  'use strict';
8609
8610  angular
8611    .module('accountServices')
8612    .service('corporateService', corporateService);
8613  corporateService.$inject = ['$http', '$q', '$validation', 'storageService'];
8614
8615  function corporateService($http, $q, $validationProvider, storageService) {
8616
8617    var result = {
8618    	setCbpData : setCbpData,
8619    	getCbpData : getCbpData,
8620    	deleteCbpData : deleteCbpData,
8621    	getChildSegmentInfo : getChildSegmentInfo,
8622    	validateCbp : validateCbp
8623    }
8624    
8625    function setCbpData(data){
8626		storageService.setStorageData('cbpData', data);
8627    }
8628    
8629    function getCbpData(){
8630		var data = storageService.getStorageData('cbpData');
8631    	return data;
8632    }
8633    
8634    function deleteCbpData(){
8635    	storageService.deleteStorageData('cbpData');
8636    }
8637    
8638	function getChildSegmentInfo(awd) {
8639		var deferred = $q.defer();
8640		// construct api request
8641		var url = apiurl + "/profile/cbpsegment-form/"+awd;
8642		$http({
8643			method: 'GET',
8644			url: url
8645		}).then(function onSuccess(response) {
8646			var data = response.data;	
8647			deferred.resolve(data);
8648		}).catch(function onError(response) {
8649			var data = response.data;
8650			deferred.reject(data);
8651		});
8652		return deferred.promise;
8653	};
8654	
8655	function validateCbp(segmentID){
8656		var deferred = $q.defer();
8657		// construct api request
8658		var url = apiurl + "/profile/validate-cbpsegment/"+segmentID;
8659		$http({
8660			method: 'GET',
8661			url: url
8662		}).then(function onSuccess(response) {
8663			var data = response.data;	
8664			deferred.resolve(data);
8665		}).catch(function onError(response) {
8666			var data = response.data;
8667			deferred.reject(data);
8668		});
8669		return deferred.promise;
8670	}
8671
8672    return result;
8673  }
8674})();
8675
8676(function() {
8677  'use strict';
8678
8679  angular
8680    .module('accountServices')
8681    .service('credentialService', credentialService);
8682  credentialService.$inject = ['$http', '$q', 'exceptionHandler', 'accountModelService'];
8683
8684  function credentialService($http, $q, exceptionHandler, accountModelService) {
8685
8686    var result = {
8687    		forgotUserName: forgotUserName,
8688    		forgotPassword: forgotPassword,
8689        forgotPasswordNew: forgotPasswordNew,
8690    		getPasswordExpireLogin: getPasswordExpireLogin
8691    }
8692
8693    function forgotUserName(credentialModal,recaptcha) {
8694      var deferred = $q.defer();
8695      if(ABG.isDefined(credentialModal, "firstName")){
8696    	  credentialModal.firstName=credentialModal.firstName.toUpperCase();
8697      }
8698      if(ABG.isDefined(credentialModal, "lastName")){
8699    	  credentialModal.lastName=credentialModal.lastName.toUpperCase();
8700      } 
8701      if(ABG.isDefined(credentialModal, "emailAddress")){
8702    	  credentialModal.emailAddress=credentialModal.emailAddress.toUpperCase();
8703      }
8704      var reqObj = {
8705    		  "firstName": credentialModal.firstName,
8706    		  "lastName": credentialModal.lastName,
8707    		  "emailAddress":  credentialModal.emailAddress,
8708    		  "zipcode": credentialModal.zipCode,
8709    		  "dlLastFourChar": credentialModal.dlLastFourChar,
8710    		  "dateOfBirth" : (angular.isDefined(credentialModal.dobMonth))?(credentialModal.dobMonth+"/"+credentialModal.dobDate+"/"+credentialModal.dobYear):undefined
8711      }
8712      var url = apiurl + "/profile/wizard-lookup";
8713      $http({
8714    	  method: 'POST',
8715          url: url,
8716          data: reqObj,
8717          headers:{
8718          	'g-recaptcha-response': (recaptcha) ? recaptcha : ''
8719          }
8720		}).then(function onSuccess(response) {
8721			var data = response.data;		
8722			data = exceptionHandler.processError(data, accountModelService.credentialModalMap);
8723	        deferred.resolve(data);
8724		}).catch(function onError(response) {
8725			var data = response.data;
8726			deferred.reject(ABG.evaluateError(data));
8727		});
8728      return deferred.promise;
8729    };
8730    
8731   
8732    function forgotPassword(credentialModal,recaptcha) {
8733      var deferred = $q.defer();
8734     //TODO:Review Below code will be changed once service implemented the changes.
8735      if(ABG.isDefined(credentialModal, "firstName")){
8736    	  credentialModal.firstName=credentialModal.firstName.toUpperCase();
8737      }
8738      if(ABG.isDefined(credentialModal, "lastName")){
8739    	  credentialModal.lastName=credentialModal.lastName.toUpperCase();
8740      } 
8741      if(ABG.isDefined(credentialModal, "emailAddress")){
8742    	  credentialModal.emailAddress=credentialModal.emailAddress.toUpperCase();
8743      }
8744      if(ABG.isDefined(credentialModal, "zipCode")){
8745    	  credentialModal.zipCode=credentialModal.zipCode.toUpperCase();
8746      }
8747      if(ABG.isDefined(credentialModal, "dlLastFourChar")){
8748    	  credentialModal.dlLastFourChar=credentialModal.dlLastFourChar.toUpperCase();
8749      }
8750      
8751      var reqObj = {
8752    		  "firstName": credentialModal.firstName,
8753    		  "lastName": credentialModal.lastName,
8754    		  "emailAddress":  credentialModal.emailAddress,
8755    		  "zipcode": credentialModal.zipCode,
8756    		  "dlLastFourChar": credentialModal.dlLastFourChar,
8757    		  "dateOfBirth" : (angular.isDefined(credentialModal.dobMonth))?(credentialModal.dobMonth+"/"+credentialModal.dobDate+"/"+credentialModal.dobYear):undefined
8758      }
8759      var url = apiurl + "/profile/forget-password";
8760      $http({
8761    	  method: 'POST',
8762          url: url,
8763          data: reqObj,
8764          headers:{
8765          	'g-recaptcha-response': (recaptcha) ? recaptcha : ''
8766          }
8767		}).then(function onSuccess(response) {
8768			var data = response.data;	
8769			data = exceptionHandler.processError(data, accountModelService.credentialModalMap)
8770	        deferred.resolve(data);
8771		}).catch(function onError(response) {
8772			var data = response.data;
8773			deferred.reject(ABG.evaluateError(data));
8774		});
8775      return deferred.promise;
8776    };
8777    
8778    function forgotPasswordNew(credentialModal,recaptcha) {
8779      var deferred = $q.defer();
8780     //TODO:Review Below code will be changed once service implemented the changes.
8781      if(ABG.isDefined(credentialModal, "wizard")){
8782    	  credentialModal.wizard=credentialModal.wizard.toUpperCase();
8783      }
8784      
8785      if(ABG.isDefined(credentialModal, "lastName")){
8786    	  credentialModal.lastName=credentialModal.lastName.toUpperCase();
8787      } 
8788
8789      var reqObj = {
8790    		  "userName": credentialModal.wizard,
8791    		  "dateOfBirth" : (angular.isDefined(credentialModal.dobMonth))?(credentialModal.dobDate+"/"+credentialModal.dobMonth+"/"+credentialModal.dobYear):undefined,
8792          "lastName": credentialModal.lastName
8793      }
8794      var url = apiurl + "/profile/forget-password";
8795      $http({
8796    	  method: 'POST',
8797          url: url,
8798          data: reqObj,
8799          headers:{
8800          	'g-recaptcha-response': (recaptcha) ? recaptcha : ''
8801          }
8802		}).then(function onSuccess(response) {
8803			var data = response.data;	
8804			data = exceptionHandler.processError(data, accountModelService.credentialModalMap)
8805	        deferred.resolve(data);
8806		}).catch(function onError(response) {
8807			var data = response.data;
8808			deferred.reject(ABG.evaluateError(data));
8809		});
8810      return deferred.promise;
8811    };
8812
8813    function getPasswordExpireLogin(){   	   	
8814    	var deferred = $q.defer();
8815        var url = apiurl + "/profile/loginid";
8816        $http({
8817        	method: 'GET',
8818            url: url,
8819  		}).then(function onSuccess(response) {
8820  			var data = response.data;
8821  			deferred.resolve(data);
8822  		}).catch(function onError(response) {
8823  			var data = response.data;
8824  			deferred.reject(ABG.evaluateError(data));
8825  		});
8826        return deferred.promise;
8827    }; 
8828    
8829    return result;
8830  }
8831})();
8832
8833(function() {
8834	'use strict';
8835
8836	angular
8837	.module('accountServices')
8838	.service('accountgaService', accountgaService);
8839
8840	accountgaService.$inject = ['$http', '$q', '$window', 'carRentalConstant', '$locale', '$filter', '$rootScope'];
8841
8842	function accountgaService($http, $q, $window, carRentalConstant, $locale, $filter, $rootScope) {
8843		
8844		var result = {
8845				analyticsDimension : analyticsDimension,
8846				paylessDimension : paylessDimension
8847		}
8848		
8849		var memberShipStatus = '';
8850		var enrollmentFlow = '';
8851		var profilePercentage = '';
8852		var profileCompletePage = '';
8853		
8854		function analyticsDimension(data, pageView) {
8855			var isMPFFlow = angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.partnerType) ? true : false;
8856			var isOfflineEnrollmentFlow = angular.isDefined(data.webHeader) && data.webHeader.offlineUser ? true : false;
8857			   if(!isMPFFlow && angular.isDefined(data) && angular.isDefined(data.activationStatus)) {
8858				   if(data.activationStatus == '0' && !isOfflineEnrollmentFlow) {
8859						memberShipStatus = data.membershipStatus;
8860						enrollmentFlow = 'Basic SignUp'; //will be sent to GA. i18n is not needed
8861				   } else if(data.activationStatus == '0' && isOfflineEnrollmentFlow) {
8862					    memberShipStatus = data.membershipStatus;
8863					    enrollmentFlow = 'Offline to Online'; //will be sent to GA. i18n is not needed
8864				   } else if(data.activationStatus == '1' && data.profileCompletionPercentage > 30 && data.profileCompletionPercentage < 100) {
8865						profilePercentage = data.profileCompletionPercentage;
8866						profileCompletePage = angular.isDefined(pageView) ? pageView : '';
8867				   } else if(data.activationStatus == '1' && data.profileCompletionPercentage == 100) {
8868						memberShipStatus = data.membershipStatus;
8869						enrollmentFlow = 'Profile Upgrade'; //will be sent to GA. i18n is not needed
8870						profileCompletePage = '';
8871						profilePercentage = '';
8872				   } 
8873				   dataLayer.push({
8874						'event': 'profileTrigger',
8875						'memberShipStatus': memberShipStatus,
8876						'enrollmentFlow' : enrollmentFlow,
8877						'profilePercentage' : profilePercentage,
8878						'pageName' : profileCompletePage
8879				    });
8880			   } else if(isMPFFlow && angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.webCustomer) && 
8881					     angular.isDefined(data.customerInfo.profileCompletionPercentage)) {
8882				   if(data.customerInfo.profileCompletionPercentage > 30 && data.customerInfo.profileCompletionPercentage < 100) {
8883					   profilePercentage = data.customerInfo.profileCompletionPercentage;
8884					   profileCompletePage = angular.isDefined(pageView) ? pageView : '';
8885				   } else if(data.customerInfo.webCustomer.activationStatus == '1' && data.customerInfo.profileCompletionPercentage == 100) {
8886					   memberShipStatus = data.customerInfo.membershipStatus;
8887					   if($window.brand == carRentalConstant.brandName.BUDGET) {
8888						   enrollmentFlow = 'Mandatory FastBreak'; //will be sent to GA. i18n is not needed   
8889					   } else {
8890						   enrollmentFlow = 'Mandatory Preferred'; //will be sent to GA. i18n is not needed
8891					   }
8892					   profileCompletePage = '';
8893					   profilePercentage = '';
8894				   }
8895				   dataLayer.push({
8896						'event': 'profileTrigger',
8897						'memberShipStatus': memberShipStatus,
8898						'enrollmentFlow' : enrollmentFlow,
8899						'profilePercentage' : profilePercentage,
8900						'pageName' : profileCompletePage
8901					});
8902			    }
8903			}
8904		
8905		function paylessDimension(data, pageView) {
8906			if(angular.isDefined(data) && angular.isDefined(data.activationStatus) && data.activationStatus == '1') {
8907				memberShipStatus = data.membershipStatus;
8908				enrollmentFlow = 'Basic SignUp';
8909			}
8910			dataLayer.push({
8911				'event': 'profileTrigger',
8912				'memberShipStatus': memberShipStatus,
8913				'enrollmentFlow' : enrollmentFlow,
8914			});
8915		}
8916		
8917		return result;
8918	}
8919})();
8920
8921//TODO Move to platform under common
8922(function() {
8923	'use strict';
8924	angular
8925		.module('dashboard')
8926		.directive('typeAhead',['$http', 'carRentalConstant', '$filter', typeAhead])
8927		
8928	function typeAhead($http, carRentalConstant, $filter){
8929		
8930		function link(scope, elem, attrs, ctrl){
8931			
8932			/* initializes the directive
8933			 * only after the loading of scope.list is completed, this directive is loaded*/
8934			function initDirective(){
8935				if(angular.isDefined(scope.list) && angular.isDefined(scope.modelObject) && scope.list !== ""
8936					&& scope.modelObject !== "" && scope.list.length > 0){
8937		    		var index = scope.list.indexOf($filter('filter')(
8938		    		scope.list,
8939		    		function(d) {
8940		    			return d[scope.listCode] === scope.modelObject;
8941		    		})[0]);
8942		    		scope.searchStr = angular.isDefined(scope.list[index])?scope.list[index][scope.listName]:"";
8943		    		//filters the scope.list based on web API response and hides the list 
8944		    		if(angular.isDefined(scope.searchStr)){
8945		    			scope.filterList(scope.searchStr);
8946		    			scope.hideDropdownList();
8947		    		}
8948		    	}
8949			}			
8950			
8951			//to clear the partner selection details
8952			scope.$on("clearPartnerDetails",function(event,response){        	
8953				scope.searchStr = '';
8954     	        });
8955			
8956			/* filters the partner dropdown based on input string */
8957			scope.filterList = function(inputStr){
8958				scope.showSuggestions = true;
8959				if(angular.isDefined(inputStr) && inputStr.length >2){
8960					//scope.searching = true;
8961					scope.showSuggestions = true;
8962					scope.suggestions = [];
8963					scope.tempList = [];
8964					angular.forEach(scope.list, function(listItem) {
8965					  var pos = listItem[scope.listName].toUpperCase().indexOf(inputStr.toUpperCase());
8966	    			  if(pos != -1){
8967	    				  scope.tempList.push(listItem);
8968	    			  }
8969					});					
8970					scope.suggestions = scope.tempList;					
8971				}else {
8972					scope.hideDropdownList();
8973				}
8974			}
8975			
8976			/* opens the partner dropdown */
8977			scope.openDropdownList = function(){
8978				if(!angular.isDefined(scope.searchStr) || scope.searchStr == ''){
8979					scope.suggestions = scope.list;
8980				}else{
8981					scope.filterList(scope.searchStr);
8982				}				
8983				scope.showSuggestions = true;
8984                if(ABG.getClientInfo().browser== 'ie'){
8985				$("#"+scope.inputId).val();
8986                }
8987                else{
8988                  $("#"+scope.inputId).select();
8989                }
8990			}
8991			
8992			/*function to call when a suggestion is selected*/
8993			scope.selectSuggestion = function(suggestion){
8994				scope.searchStr = suggestion[scope.listName];				
8995				scope.modelObject = suggestion[scope.listCode];
8996				scope.showSuggestions = false;
8997				scope.onChangeOfPartner(scope.modelObject);
8998			}
8999			
9000			/*hiding suggestions on blur*/
9001			scope.hideDropdownList = function(){
9002				scope.showSuggestions = false;
9003				scope.suggestions = [];
9004			}
9005			
9006			/*sending rewardsPartnerDetails to gtm. its not used in html so no need of i18n*/
9007			scope.rewardspartnertogtm = function(string, inputId) {
9008				if(inputId == 'airlines') {
9009					var string1 = 'rewardsairlinepartner';
9010					var inputType = 'dropdown';
9011				} else if (inputId == 'hotels') {
9012					var string1 = 'rewardshotelpartner';
9013					var inputType = 'dropdown';
9014				} else if (inputId == 'others') {
9015					var string1 = 'rewardsotherpartner';
9016					var inputType = 'dropdown';
9017				}
9018				if (inputType == 'text') {
9019	                var inputAction = string ? 'Filled In' : 'Skipped';
9020	            } else if (inputType == 'checkbox') {
9021	                var inputAction = string ? 'Selected as Y' : 'Selected as N';
9022	            } else if (inputType == 'dropdown') {
9023	                var inputAction = string ? 'Selected' : 'Not Selected';
9024	            }
9025	            dataLayer.push({
9026	                'event': 'trackEvent',
9027	                'eventCategory': 'Tracking Form: ' + 'Profile-Form',
9028	                'eventLabel': string1,
9029	                'eventAction': inputAction
9030	            });
9031			}
9032			
9033			/*clearing input text field*/
9034			scope.removeText = function(evt){    	
9035				angular.element(evt.target).prev('input').focus();
9036				scope.searchStr = '';
9037				scope.modelObject = '';				
9038				evt.target.style.display = 'none';    	  
9039			}
9040			/*called on selecting a different partner from dropdown list*/
9041			scope.onChangeOfPartner = function(selectedObject){				
9042				if(scope.$parent.vm && angular.isDefined(scope.$parent.vm.onChangeRewardPreference)){
9043					scope.$parent.vm.onChangeRewardPreference(true,'partnerPrgm',selectedObject);
9044				}
9045			} 
9046			initDirective();
9047		}
9048		
9049		return {
9050			restrict: 'EA',
9051			scope : {
9052				list: '=',
9053				listName : '=',
9054				listCode : '=',
9055				modelObject : '=',
9056		        disableInput: '=',
9057		        inputId: '@',
9058		        placeholder: '@',
9059		        inputClass: '@',
9060		        inputName: '@',
9061		        dropdownClass : '@',
9062		        requiredErrorMessage:'@',
9063		        searchDelayMsg : '@',
9064		        validationList:'@',
9065		        validMethod:'@'
9066			},
9067			link: link,
9068			template: '<input type="text" class="{{inputClass}}" id="{{inputId}}" name="{{inputName}}" ' +
9069					'ng-model="searchStr"' +
9070					'ng-blur="hideDropdownList();rewardspartnertogtm(searchStr, inputId);"'+
9071					'ng-keyup="filterList(searchStr)"' +
9072					'ng-focus="openDropdownList()"' + 
9073					'placeholder="{{placeholder}}" ' +
9074					'valid-method="blur"' +
9075					'filtered-length="{{tempList.length}}"'+
9076					'validator="{{validationList}}"' +
9077					'required-error-message="{{requiredErrorMessage}}"' +
9078					'valid-method="blur">'+
9079					'<div ng-click="removeText($event)" ng-if="searchStr.length > 0" class="clearTxt" style="display: block;"></div>' +
9080					'<button ng-click="openDropdownList()"><span class="s-dropdown wrap-down-arrow"></span></button>'+					
9081					'<div class="wrap-angucomplete-dropdown {{dropdownClass}}" ng-if="showSuggestions">'+
9082						'<div class="angucomplete-dropdown toKeepDropdown" >'+
9083							'<div class="angucomplete-searching" ng-show="searching">{{searchDelayMsg}}</div>'+
9084							'<div class="angucomplete-results">'+
9085								'<div ng-repeat="suggestion in suggestions" ng-mousedown="selectSuggestion(suggestion)">'+
9086									'<div>'+
9087										'{{suggestion[listName]}}'+
9088									'</div>'+
9089								'</div>'+
9090							'</div>'+
9091						'</div>'+
9092					'</div>'
9093		}
9094		
9095	}
9096})();
9097(function() {
9098	'use strict';
9099	angular
9100		.module('dashboard')
9101		.directive('preventcutcopypaste',preventcutcopypaste)
9102		
9103	function preventcutcopypaste(){
9104		function link(scope,element){
9105            element.on('cut copy paste', function (event) {
9106                event.preventDefault();
9107              })
9108          }
9109		 return {
9110			 restrict: 'A',
9111             link:link
9112		 };
9113	}
9114})();
9115
9116(function() {
9117	'use strict';
9118
9119	angular
9120	.module('account')
9121	.controller('SignupController', SignupController);
9122
9123	SignupController.$inject = ['$scope', '$state', '$rootScope', '$window', 'authenticationService', '$filter', 'carRentalConstant', 'signupService', '$validation', '$controller', 'accountModelService', 'accountUtilityService', 'getDataService', 'reservationModelService'];
9124
9125	function SignupController($scope, $state, $rootScope, $window, authenticationService, $filter, carRentalConstant, signupService, $validationProvider, $controller, accountModelService, accountUtilityService, getDataService, reservationModelService) {
9126
9127		$controller('ExceptionHandlerController', {
9128			$scope: $scope
9129		});
9130
9131		// View Model.....
9132		var vm = this;
9133		var promise = {};
9134		vm.statesForCountry = [];
9135		vm.accountFormValidation = false;
9136		vm.showUniquenessError = false;
9137		vm.showEmailReceipt = false;
9138		vm.csUpdation = false;
9139		vm.countryData = "";
9140		vm.enrollmentPageError = "";
9141		vm.showSmsOptIn = true; //ARD2-508 change as part of pre-otp changes
9142		vm.emailAddressAsUsername = true;
9143		vm.showUniquenessCheckbox = true;
9144		vm.usernameLookupCalled = false;
9145		vm.country = $window.domain.toUpperCase();
9146		vm.suggestions = [];
9147		vm.accountModel = accountModelService.accountModel; // This is to get the account model from accountModelService
9148		vm.saveIdentityModel = {};
9149		vm.pageName = $state.current.name;
9150		var showInlineErrorMsg = "";
9151		vm.domain = $window.domain.toUpperCase();
9152		vm.enableCaptcha = enableCaptcha; 
9153		vm.captchaExecuted = false;
9154		vm.showInvalidPhoneNumberError = false;
9155		
9156		$rootScope.requestInProgress = true;
9157		vm.hideStateTextBox = false;
9158		vm.redirectionPage = '/activation';
9159		vm.memberRedirect= '/member-benefits';
9160		vm.avisMemberRedirect= '/member-rental-prices';
9161		vm.brand = $window.brand; 
9162		// View Callable.....
9163		vm.selectAddress = selectAddress;
9164		vm.passwordFieldValidation = passwordFieldValidation;
9165		vm.getState = getState;
9166		vm.hideStateFunction = hideStateFunction;
9167		vm.createAccount = createAccount;
9168		vm.checkUsernameUniqueness = checkUsernameUniqueness;
9169		vm.gtmBlur = gtmBlur;
9170		vm.clearAddress = clearAddress;
9171		vm.enableUserName = enableUserName;
9172		vm.validateCBPAwdNumber = validateCBPAwdNumber;
9173		vm.loadHelpModal = loadHelpModal;
9174		// vm.validatePhoneNumber = validatePhoneNumber;
9175		// Private Methods.....
9176		vm._validationSuccess = _validationSuccess;
9177		vm._validationError = _validationError;
9178		vm._mapPartnerCustomerInfo = _mapPartnerCustomerInfo;
9179		vm._onCallOfDisplayControl = _onCallOfDisplayControl;
9180		vm._loadCalendarDropdown = _loadCalendarDropdown;
9181		vm._UpdateCostControlfield = _UpdateCostControlfield;
9182		
9183		//Keycount section
9184		  vm.firstNamekeycount = _firstNamekeycount;
9185		  vm.firstNamecopyPaste = _firstNamecopyPaste;
9186		  vm.lastNamekeycount = _lastNamekeycount;
9187		  vm.lastNamecopyPaste = _lastNamecopyPaste;
9188		  
9189		  function _firstNamekeycount(){
9190		  	vm.fcount = vm.fcount+1;
9191		  	storageService.setStorageData('Keystrokecount', vm.fcount);
9192		  }
9193		  
9194		  function _firstNamecopyPaste(){
9195		  	vm.fcount = vm.fcount-1;
9196		  	storageService.setStorageData('Keystrokecount', vm.fcount);
9197		  }
9198		  
9199		  function _lastNamekeycount(){
9200		  	vm.lcount = vm.lcount+1;
9201		  	storageService.setStorageData('Keystrokecount', vm.lcount);
9202		  }
9203		  
9204		  function _lastNamecopyPaste(){
9205		  	vm.lcount = vm.lcount-1;
9206		  	storageService.setStorageData('Keystrokecount', vm.lcount);
9207		  }
9208		
9209		  function loadHelpModal(currentEle) {
9210				vm.country = $window.countrySelect?$window.countrySelect:'US';
9211				var target = currentEle.target.parentElement;
9212				vm.helpURL = getVehicles.getUrl(target, country);
9213			}
9214		// To handle validation we are using this method (to trigger blur)
9215		function passwordFieldValidation(enableMask) { // TODO method name should be changes based on functionality 
9216			if (enableMask) {
9217				setTimeout(function() {
9218					angular.element('#PasswordHide').blur();
9219				}, 5);
9220			} else {
9221				setTimeout(function() {
9222					angular.element('#PasswordShow').blur();
9223				}, 5);
9224			}
9225		}
9226
9227		function enableUserName(enable){
9228			if(enable){
9229				setTimeout(function() {
9230					angular.element('#email').blur();
9231				}, 5);
9232				vm.emailAddressAsUsername = false;
9233			}else{
9234				vm.accountModel.contactInfoRQ.emailAddress = "";
9235				angular.element('#email').focus()
9236			}
9237			vm.showUniquenessError = false;
9238		}
9239
9240		function validateCBPAwdNumber(AWDNumber,cor){
9241			if(angular.isDefined(AWDNumber) && AWDNumber.length < 6){
9242				vm.initializeDisplayElementMap.costControlNumber.visible = false;
9243				vm.costControlNumberRequired= "optional";
9244			}
9245			else{
9246				signupService.validatePartnerCustomerInfo(AWDNumber,cor).then(function(data) {
9247					if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0) {
9248						var field="";
9249						field = "vm.accountModel.preferenceRQ." + data.fieldErrors[0].fieldName;
9250						$validationProvider.displayServiceError(field, data.fieldErrors[0].classifier);
9251					}
9252					if(data.errorList){
9253						$rootScope.requestInProgress = false;
9254					}
9255					else{
9256						_UpdateCostControlfield(data);
9257					}
9258				}, function(error) {
9259					$rootScope.requestInProgress = false;
9260				});
9261			}
9262		}
9263
9264		function _UpdateCostControlfield(data){
9265			vm.initializeDisplayElementMap.costControlNumber.visible = angular.isDefined(data.costControlVisible) && (data.costControlVisible == "Y") ? true : false ;
9266			vm.costControlNumberRequired= "optional";
9267			vm.costControlNumberRequired = angular.isDefined(data.costControlRequired) && (data.costControlRequired == "Y") ? "required" : "optional" ;
9268			vm.accountModel.preferenceRQ.costControlNumber = angular.isDefined(data.costControlNumber)  ? data.costControlNumber : "" ;
9269			vm.initializeDisplayElementMap.costControlNumber.editable = angular.isDefined(data.costControlReadOnly) && (data.costControlReadOnly == "Y") ? false : true ;
9270			vm.initializeDisplayElementMap.costControlTitle = angular.isDefined(data.costControlTitle) ? data.costControlTitle: Dictionary.I18n.get('msg.enroll.CostControl') ;
9271		}
9272
9273		// Setting zipcode, city and state fields after making selection from address suggestions
9274		function selectAddress(suggestion, suggestionType) {
9275			if(suggestionType === carRentalConstant.address){
9276				if(angular.isDefined(suggestion.address.postalCode)){	
9277					vm.accountModel.contactInfoRQ.address.zipCode = suggestion.address.postalCode;
9278					angular.element('#zip').val(suggestion.address.postalCode);
9279					angular.element('#zip').trigger('change');
9280					setTimeout(function() {
9281						angular.element('#zip').blur();
9282					}, 5);
9283				}
9284			}
9285			if(angular.isDefined(suggestion.address.locality)){
9286				if(vm.accountModel.contactInfoRQ.address.city != suggestion.address.locality){
9287					vm.csUpdation = true;
9288				}
9289				vm.accountModel.contactInfoRQ.address.city = suggestion.address.locality;
9290			}
9291			if(angular.isDefined(suggestion.address.adminDistrict)){
9292				var selectedState = $filter('filter')(vm.statesForCountry, {stateCode : suggestion.address.adminDistrict}, true)[0];
9293				var index = vm.statesForCountry.indexOf(selectedState); 
9294				if(index > -1){
9295					if(vm.accountModel.contactInfoRQ.address.state != vm.statesForCountry[index].stateCode){
9296						vm.csUpdation = true;
9297					}
9298					vm.accountModel.contactInfoRQ.address.state = vm.statesForCountry[index].stateCode
9299				}
9300			}
9301		}
9302
9303		function clearAddress(suggestionType){
9304			if(suggestionType === carRentalConstant.address){
9305				angular.element('#zip').val("");
9306				angular.element('#zip').trigger('change');
9307				vm.accountModel.contactInfoRQ.address.address1 = "";
9308				vm.accountModel.contactInfoRQ.address.address2 = "";
9309				vm.accountModel.contactInfoRQ.address.address3 = "";
9310				vm.accountModel.contactInfoRQ.address.suburb = "";
9311			}
9312			vm.accountModel.contactInfoRQ.address.zipCode = "";
9313			vm.accountModel.contactInfoRQ.address.city = "";
9314			vm.accountModel.contactInfoRQ.address.state = null;
9315		}
9316
9317		// Loading country list from sightly component.
9318		function loadCountryList(data) {
9319			vm.countryData = accountUtilityService.getCountryList(data);
9320			vm.accountModel.contactInfoRQ.address.country = ($filter('filter')(vm.countryData, {code : vm.country}, true)[0]).code;
9321			getState(vm.accountModel.contactInfoRQ.address.country);     
9322			$rootScope.requestInProgress = false;
9323		}
9324		//To display terms condition links for COR CA
9325		function getEmailReceipt(countryCode) {
9326			if(countryCode == carRentalConstant.countryCodeCA){
9327				vm.showEmailReceipt = true;
9328			}else{
9329				vm.showEmailReceipt = false;
9330			}
9331		}
9332
9333		$rootScope.$on("publishCbpInfo", function(event, cbpInfo) {
9334			vm.country = cbpInfo.country;
9335		});
9336
9337		//Action need to be done on init call
9338		function _onCallOfDisplayControl(data, countryCode){
9339			vm.customerData = data;
9340			vm.nonEditEReceipt = false;
9341			if(data && data.displayControl && data.displayControl.displayElementMap){
9342				vm.initializeDisplayElementMap = data.displayControl.displayElementMap; //authenticationService.getDisplayControlModel(); // after profile/init call get value
9343				if(vm.initializeDisplayElementMap.password.visible){
9344					showInlineErrorMsg = Dictionary.I18n.get('msg.profile.password.reenter');
9345				}
9346			}
9347			//To hide username checkbox
9348			if(vm.customerData){
9349				vm.accountModel = signupService.getAccountData(vm.customerData);
9350				if(vm.accountModel.profPersonalInfoRQ.userName && vm.accountModel.profPersonalInfoRQ.userName != "" ){
9351					vm.emailAddressAsUsername = false;
9352					vm.showUniquenessCheckbox = false;
9353				}
9354			}
9355			//If concur/CBP flow
9356			//TODO: Line 163-166 needs to be looked over for handling multiple countries
9357			var cbpInfo = getDataService.getCBPInfoData();
9358			if(angular.isDefined(cbpInfo) && angular.isDefined(cbpInfo.country) && cbpInfo.country != '' && cbpInfo.country.length != 0){
9359				var residency = angular.isDefined(cbpInfo.country[0]) ? cbpInfo.country[0].toUpperCase() : 'US';
9360				vm.country = ((residency.indexOf("US") == -1) && (residency.indexOf("CA") != -1)) ? 'CA' : 'US';
9361			}else if(angular.isDefined(data) && angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.partnerType)){
9362				if(angular.isDefined(data.partnerCustomerInfo.address) && angular.isDefined(data.partnerCustomerInfo.address.country) && data.partnerCustomerInfo.address.country != ''){
9363					vm.country = data.partnerCustomerInfo.address.country;
9364				}
9365				if(data.partnerCustomerInfo.partnerType == "PARTNER_CBP"){
9366					$rootScope.$broadcast("CBPImageName", data.partnerCustomerInfo); // To set the image and header/footer in case of CBP
9367				}
9368				if(data.partnerCustomerInfo.partnerType == carRentalConstant.partnerTypeConcur){
9369					vm.nonEditEReceipt = true;
9370				}
9371				_mapPartnerCustomerInfo(data);    			
9372			}else if(angular.isDefined(data.oneClickEnrollmentInfo)){
9373				if(angular.isDefined(data.oneClickEnrollmentInfo.country) && data.oneClickEnrollmentInfo.country != "" && data.oneClickEnrollmentInfo.country != null){
9374					vm.country = data.oneClickEnrollmentInfo.country;
9375				}
9376				vm.accountModel.preferenceRQ.discountNumber = data.oneClickEnrollmentInfo.discountNumber
9377			} 
9378			if(angular.isDefined(data) && angular.isDefined(data.partnerCustomerInfo) ){
9379				_UpdateCostControlfield(data.partnerCustomerInfo);
9380			}
9381			vm.getPartnerType = authenticationService.getPartnerInfoModel();
9382			if(angular.isDefined(vm.getPartnerType) && (vm.getPartnerType == carRentalConstant.partnerTypeCBP || 
9383					vm.getPartnerType == carRentalConstant.partnerTypeConcur)) {
9384				vm.cbpconcurCustomerInfo = signupService.getConcurCustomerInfo();
9385				if(angular.isDefined(vm.cbpconcurCustomerInfo) && angular.isDefined(vm.cbpconcurCustomerInfo.customerInfo)) {
9386					vm.accountModel.contactInfoRQ.emailAddress = angular.isDefined(vm.cbpconcurCustomerInfo.partnerCustomerInfo.email) ? vm.cbpconcurCustomerInfo.partnerCustomerInfo.email : '';
9387					vm.accountModel.preferenceRQ.discountNumber = angular.isDefined(vm.cbpconcurCustomerInfo.partnerCustomerInfo.discountNumber) ? vm.cbpconcurCustomerInfo.partnerCustomerInfo.discountNumber : '';
9388					vm.accountModel.preferenceRQ.costControlNumber = angular.isDefined(vm.cbpconcurCustomerInfo.partnerCustomerInfo.costControlNumber) ? vm.cbpconcurCustomerInfo.partnerCustomerInfo.costControlNumber : '';
9389				}
9390			} else {
9391				vm.saveIdentityModel.emailAddress = angular.isDefined(vm.customerData.contacts)?vm.customerData.contacts.email:"";
9392			}
9393			var eOffersResult = signupService.geteOffersSupportedCountry(countryCode);
9394			//to display e-offers
9395			vm.eOffersDisplay = eOffersResult.supported;  
9396			//Default behaviour of e-offers checkbox
9397			if(vm.eOffersDisplay){
9398				if(angular.isUndefined(vm.accountModel.identityPwdRQ.promotionalEmailOptin))
9399					vm.accountModel.identityPwdRQ.promotionalEmailOptin = eOffersResult.optin;
9400			}
9401			var eReceiptResult = signupService.geteReceiptSupportedCountry(countryCode);
9402			//to display e-receipt
9403			//vm.eReceiptDisplay = eReceiptResult.supported;
9404			vm.eReceiptDisplay = false;
9405			//Default behaviour of e-receipt checkbox
9406			if(vm.eReceiptDisplay){
9407				if(angular.isUndefined(vm.accountModel.identityPwdRQ.eRecieptEmailOptin))
9408					vm.accountModel.identityPwdRQ.eRecieptEmailOptin = eReceiptResult.optin;
9409			}
9410			//Hiding the E-receipt opt-in toggle option as per ARD1-827:  setting the value as false by default
9411			// if(countryCode == carRentalConstant.countryCodeUS || countryCode == carRentalConstant.countryCodeCA){
9412			// 	vm.eReceiptDisplay = false;
9413			// 	//Setting the value for e-receipt opt-in as true by default
9414			// 	if(!vm.eReceiptDisplay){
9415			// 		vm.accountModel.identityPwdRQ.eRecieptEmailOptin = true;
9416			// 	}
9417			// }
9418			//Setting the value for e-receipt opt-in as true by default
9419			if(!vm.eReceiptDisplay){
9420				vm.accountModel.identityPwdRQ.eRecieptEmailOptin = true;
9421 			}
9422			getEmailReceipt(countryCode);
9423			// Show SMS opt-in only for US/CA COR
9424			if (countryCode == "US" || countryCode == "CA") {
9425				vm.showSmsOptIn = true;
9426			} else {
9427				vm.showSmsOptIn = false;
9428				vm.accountModel.contactInfoRQ.smsOptin = false;
9429			}
9430			setTimeout(function() {
9431				if(angular.isDefined(vm.customerData) && angular.isDefined(vm.customerData.userState) && angular.equals(vm.customerData.userState,carRentalConstant.userStatePartnerAuthenticated)){
9432					checkUsernameUniqueness(true);
9433				}
9434			}, 1500);
9435		}
9436
9437		//It will process the display control response
9438		function _processDisplayControl(countryCode) {
9439			$rootScope.requestInProgress = true;
9440			authenticationService.displayControlProfile(countryCode).then(function(data) {
9441				vm.instruction = $scope.processErrorMessage(data);
9442				_onCallOfDisplayControl(data,countryCode);
9443				vm.accountModel.contactInfoRQ.address.country = ($filter('filter')(vm.countryData,  {code : countryCode},  true)[0]).code;
9444				$rootScope.$broadcast("Profile.inProfileEnrollFlow", true);
9445				$rootScope.requestInProgress = false;
9446			},function(error){
9447				$rootScope.requestInProgress = false;
9448				if(angular.isDefined(error.errorList) && error.errorList.length > 0){
9449					vm.enrollmentPageError = error.errorList[0].message;
9450					vm.accountFormValidation = true;
9451					$("body").animate({
9452						"scrollTop": 0
9453					}, "slow");
9454				}
9455			});
9456		}
9457
9458		// Load states depending on domain and on change of country drop down
9459		function getState(countryCode, onChangeCountry) {
9460			if (vm.countryData && countryCode != undefined && countryCode != '' && (countryCode === carRentalConstant.countryCodeAU || countryCode === carRentalConstant.countryCodeCA || countryCode === carRentalConstant.countryCodeUS)) {
9461				var index = vm.countryData.indexOf($filter('filter')(
9462						vm.countryData,
9463						function(d) {
9464							return d.code === countryCode;
9465						})[0]);
9466				vm.statesForCountry = vm.countryData[index].stateList;
9467			}
9468			if(onChangeCountry){
9469				vm.hideStateTextBox = vm.hideStateFunction(countryCode);
9470				vm.accountModel.contactInfoRQ.address.address1 = "";
9471				vm.accountModel.contactInfoRQ.address.zipCode = "";
9472				vm.accountModel.contactInfoRQ.address.city = "";
9473				_processDisplayControl(countryCode);
9474				angular.element('#addressline1').val("");
9475				angular.element('#addressline1').trigger('change'); 
9476				angular.element('#zip').val("");
9477				angular.element('#zip').trigger('change');
9478			}
9479             
9480		//set default state value:
9481			if(vm.accountModel.contactInfoRQ.address.state == "" && vm.statesForCountry.length > 1){
9482				vm.accountModel.contactInfoRQ.address.state = null;
9483			}
9484		}
9485
9486		// defined in extension controller
9487		function hideStateFunction() {
9488			return false;
9489		}
9490
9491		// checking for username uniqueness
9492		function checkUsernameUniqueness(unchecked,signupForm){
9493			vm.userName = "";
9494			vm.bindErrTo = ""; //in case of error using the variable to find which field to bind error
9495			vm.showUniquenessError = false;
9496			// check if user wants email Id as username
9497			if(vm.emailAddressAsUsername == true){
9498				vm.userName = vm.accountModel.contactInfoRQ.emailAddress;
9499				vm.bindErrTo = "vm.accountModel.contactInfoRQ.emailAddress";
9500				vm.accountModel.profPersonalInfoRQ.userName = "";
9501			}else if(vm.emailAddressAsUsername == false && unchecked == true){
9502				setTimeout(function() {
9503					angular.element('#email').blur();
9504				}, 5);
9505			}
9506			//ABGTTT-170 changes to include captcha on the sign-up page
9507			if(vm.userName != ""){
9508				if(enableCaptcha == 'true'){
9509					grecaptcha.execute();
9510					$rootScope.calledFrom = "checkUserName";
9511				}
9512				else{
9513					validateUsernameApiCall();
9514				}
9515			}
9516			if (unchecked == false) {
9517				vm.createAccount(signupForm);
9518			}
9519		}
9520		
9521		//added new method to make the API Call as part of ABGTTT-170
9522		function validateUsernameApiCall(){
9523			if(angular.isDefined(vm.userName)){
9524				signupService.validateUserName(vm.userName,vm.recaptcha).then(function(data) {
9525					vm.usernameLookupCalled = true;
9526					vm.prod = data;
9527					if(angular.isDefined(data.customerInfo) && data.customerInfo.uniqueEmail == false && vm.emailAddressAsUsername == true){
9528						// show field level error when username is not unique
9529						if(vm.emailAddressAsUsername == true){
9530							$validationProvider.displayServiceError(vm.bindErrTo);
9531							vm.showUniquenessError = true;
9532						}
9533					}else{
9534						vm.showUniquenessError = false;
9535					}
9536					if(enableCaptcha == 'true') {
9537						ABG.resetCaptcha(true);
9538					}
9539				}, function(error) {
9540					$rootScope.requestInProgress = false;
9541					if(enableCaptcha == 'true') {
9542						ABG.resetCaptcha(true);
9543					}
9544				});
9545			}
9546		}
9547
9548		// Form submission to create account
9549		function createAccount(signupForm) {
9550			$validationProvider.validate(signupForm).success(_validationSuccess).error(_validationError);
9551			reservationModelService.addGTMScript();
9552		}
9553
9554		//on validation success
9555		function _validationSuccess() {
9556			$rootScope.requestInProgress = true;
9557			var expressEnrollmentDataModel = false; // accountModel will be build depending upon this
9558			var saveIdentityData = {};
9559			//Forming the request model object
9560			if(brand == carRentalConstant.brandName.PAYLESS && vm.accountModel.contactInfoRQ.address.country != '' && (vm.accountModel.contactInfoRQ.address.country != carRentalConstant.countryCodeAU && vm.accountModel.contactInfoRQ.address.country != carRentalConstant.countryCodeCA && vm.accountModel.contactInfoRQ.address.country != carRentalConstant.countryCodeUS)){
9561				vm.accountModel.contactInfoRQ.address.state = "Others";
9562			}
9563			var accountModel = signupService.getAccountModel(vm.accountModel);
9564			vm.accountFormValidation = false;
9565			if(vm.showUniquenessError == true){
9566				vm.accountModel.password = '';
9567				vm.enrollmentPageError = Dictionary.I18n.get('err.prof.username.exists') + '</br>'+ showInlineErrorMsg;
9568				vm.accountFormValidation = true;
9569				$validationProvider.displayServiceError(vm.bindErrTo);
9570				$rootScope.requestInProgress = false;
9571				window.scrollTo({top: 0, behavior: 'smooth'});
9572			} else{
9573				//Changes done as part of ABGTTT-170
9574				if((enableCaptcha == 'true' && vm.captchaExecuted == false ) && (brand != carRentalConstant.brandName.PAYLESS)){
9575						grecaptcha.execute();
9576						$rootScope.calledFrom = "createProfile";
9577				}else{
9578					vm.recaptcha = "";
9579					createProfileApiCall();
9580				}
9581				
9582			}
9583		};
9584		
9585		//added new method to make the API Call as part of ABGTTT-170
9586		function createProfileApiCall(){
9587			var accountModel = signupService.getAccountModel(vm.accountModel);
9588			signupService.createProfile(accountModel,vm.recaptcha).then(function(data) {
9589				data = $scope.processErrorMessage(data);
9590				vm.prod = data;
9591				if (!(angular.isDefined(vm.prod.errorList) && vm.prod.errorList.length > 0) || (angular.isDefined(vm.prod.warningList) && vm.prod.warningList.length > 0)) {
9592					//checks partner customer data
9593					vm.getPartnerType = authenticationService.getPartnerInfoModel();
9594					// User creating account from vehicle selection page will be redirected back to the same page after successfull account creation.
9595					if ($window.displayMemberRatesandBanner == "true" && angular.element(document).injector().get('storageService').getStorageData('isSignUpFromStep2') === true) {
9596						var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + "/" + "reservation" + htmlExtension + "#/vehicles";
9597						$window.location.href = redirectPath;
9598					}
9599					//TODO:Review- remove the partnerType check --> check the partner type and redirect accordingly
9600					else if(angular.isDefined(vm.prod.partnerCustomerInfo) && angular.isDefined(vm.prod.partnerCustomerInfo.partnerType)){
9601						var redirectPath = signupService.rulesToRedirect(vm.prod.displayControl);
9602						$window.location.href = redirectPath;
9603					}else{
9604							//Added condition only to redirect US customers to member rates page
9605							if(($window.brand == carRentalConstant.brandName.AVIS || $window.brand == carRentalConstant.brandName.BUDGET) && $window.location.pathname==="/en/loyalty-profile/member-rates-enrollment" && angular.isDefined(vm.prod) && angular.isDefined(vm.prod.customerInfo) && angular.isDefined(vm.prod.customerInfo.cor) && vm.prod.customerInfo.cor == "US" && (angular.isDefined(vm.accountModel) && angular.isDefined(vm.accountModel.preferenceRQ) && angular.isDefined(vm.accountModel.preferenceRQ.discountNumber) && (vm.accountModel.preferenceRQ.discountNumber == '' || vm.accountModel.preferenceRQ.discountNumber == vm.prod.customerInfo.memberShipDiscountNumber))){
9606								//ARD2-2964
9607								$('.show-generic-modal').hide();
9608								$('.modal-backdrop').hide();
9609								sessionStorage.setItem("genericmodaldisplay",'yes');
9610								sessionStorage.setItem("benefitsmodaldisplay",'false');
9611							
9612								if($window.brand == carRentalConstant.brandName.AVIS){
9613									var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + vm.avisMemberRedirect ;
9614									$window.location.href = redirectPath;
9615								}
9616								else if($window.brand == carRentalConstant.brandName.BUDGET){
9617									var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + vm.memberRedirect ;
9618									$window.location.href = redirectPath;
9619								}													
9620							}												
9621							else if($window.brand == carRentalConstant.brandName.AVIS){
9622								var redirectPath = signupService.rulesToRedirect(vm.prod.displayControl);
9623								$window.location.href = redirectPath;
9624							}						
9625							else{
9626								var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot + vm.redirectionPage + htmlExtension+"?signup=true";
9627								$window.location.href = redirectPath;
9628							}
9629						}
9630				} else {
9631					// Error code is not getting from webapi and its coming from services 
9632					//Based on it mapping the error message to display the field level error for email
9633					if(angular.isDefined(vm.prod) && angular.isDefined(vm.prod.errorList) && vm.prod.errorList[0].code === "06012"){
9634						$validationProvider.displayServiceError(vm.bindErrTo);
9635						vm.showUniquenessError = true;
9636					}
9637					if(angular.isDefined(vm.prod) && angular.isDefined(vm.prod.errorList) && vm.prod.errorList[0].code === "13002"){
9638						vm.prod.errorList[0].message = Dictionary.I18n.get('err.res.checkout.firstname.minAlphabets');
9639						$validationProvider.displayServiceError("vm.accountModel.profPersonalInfoRQ.firstName","invalid");
9640					}
9641					if(angular.isDefined(vm.prod) && angular.isDefined(vm.prod.errorList) && angular.isDefined(vm.prod.errorList[0].message)){
9642						vm.prod.errorList[0].message = vm.prod.errorList[0].message + '</br>'+ showInlineErrorMsg;
9643						angular.element(document).injector().get('anchorSmoothScroll').scrollTo('signUp');
9644					}
9645
9646					vm.accountModel.password = '';
9647					$validationProvider.displayServiceError("vm.accountModel.password",'required');
9648					$("body").animate({
9649						"scrollTop": 0
9650					}, "slow");
9651				}
9652				$rootScope.requestInProgress = false;
9653				if(enableCaptcha == 'true' && vm.captchaExecuted == false) {
9654					ABG.resetCaptcha(true);
9655				}
9656			}, function(error) {
9657				$rootScope.requestInProgress = false;
9658				if(angular.isDefined(error.errorList) && error.errorList.length > 0){
9659					vm.accountModel.password = '';
9660					vm.enrollmentPageError = error.errorList[0].message + '</br>'+ Dictionary.I18n.get('msg.profile.password.reenter');
9661					vm.accountFormValidation = true;
9662					$("body").animate({
9663						"scrollTop": 0
9664					}, "slow");
9665				}
9666				if(enableCaptcha == 'true' && vm.captchaExecuted == false) {
9667					ABG.resetCaptcha(true);
9668				}
9669			});
9670		}
9671		function _validationError(response) {
9672			$rootScope.requestInProgress = false;
9673			vm.prod = {};
9674			//TODO Make both common and remove condition
9675			var errCount = response.errorCount;
9676			if(errCount == 2 && response.MSG[0] === response.MSG[1]){
9677				errCount = 1;
9678			}
9679			// TODO - just use response.MSG[0] object directly.	
9680			if (1 === errCount) {
9681				vm.enrollmentPageError = response.MSG[0] + '</br>' + showInlineErrorMsg;
9682				vm.accountFormValidation = true;
9683				vm.accountModel.password = '';
9684				$validationProvider.displayServiceError("vm.accountModel.password",'required');
9685			} else if (1 < errCount) {
9686				//	call the message from the i18n ======= AEM
9687				vm.enrollmentPageError = Dictionary.I18n.get('err.global.multi.errorMessage') + '</br>' + showInlineErrorMsg;
9688				vm.accountFormValidation = true;
9689				vm.accountModel.password = '';
9690				$validationProvider.displayServiceError("vm.accountModel.password",'required');
9691			}
9692			$("body").animate({
9693				"scrollTop": 0
9694			}, "slow");
9695		};
9696		
9697		function _mapPartnerCustomerInfo(data){ 
9698			vm.accountModel = signupService.getAccountData(data);
9699			if(angular.isDefined(vm.customerData.partnerCustomerInfo) && angular.isDefined(vm.customerData.partnerCustomerInfo.costControlNumber)){
9700				_UpdateCostControlfield(vm.customerData.partnerCustomerInfo);
9701			}
9702			if(angular.isDefined(vm.accountModel.contactInfoRQ) && angular.isDefined(vm.accountModel.contactInfoRQ.address)){
9703				setTimeout(function() {
9704					angular.element('#addressline1').val(vm.accountModel.contactInfoRQ.address.address1);
9705					angular.element('#addressline1').trigger('change');              
9706					angular.element('#zip').val(vm.accountModel.contactInfoRQ.address.zipCode);
9707					angular.element('#zip').trigger('change');
9708				}, 5);
9709			}                       
9710		}
9711
9712
9713		var isValidXSRF=true;
9714		// Function will be called on page load
9715		function onPageLoad() {
9716
9717			$rootScope.requestInProgress = true;
9718			if(brand == carRentalConstant.brandName.PAYLESS){
9719				_loadCalendarDropdown();
9720			}	
9721			if(angular.isDefined(authenticationService.getXsrfToken())){
9722				isValidXSRF  = false;
9723				initialize();
9724			}
9725			
9726		}
9727
9728		$rootScope.$on('initSuccess', function(event, arg) {
9729			if(isValidXSRF){
9730				initialize();
9731			}
9732		});
9733
9734		function initialize(){
9735			authenticationService.displayControlProfile('').then(function(data) {
9736				/*  JAG-5203
9737				 *  On click of "Start Earning Today" in avis-preferred page 
9738				 *  user should be redirected to rewards page. Its handled by reading 
9739				 *  previous page URL and checked with exact URL of avis-preferred page and if preferred user than
9740				 *  based on the condition redirecting to rewards page.
9741				 *  Also have a condition check for avis as its applicable only for it.
9742				 */
9743				if($window.brand === carRentalConstant.brandName.AVIS){
9744					var previousPageURL = document.referrer.substring(document.referrer.lastIndexOf('/'),61);
9745					var avisPreferredURL = "/avis-preferred";
9746					if(angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.preferred) && data.customerInfo.preferred && previousPageURL === avisPreferredURL){
9747						ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot+"/dashboard/rewards" + htmlExtension);
9748					}
9749				}
9750
9751				//unauthorized access goes to login page
9752				if(angular.isDefined(data.customerInfo) && (angular.equals(data.customerInfo.userState,carRentalConstant.userStateRecognized) || (angular.equals(data.customerInfo.userState,carRentalConstant.userStateRememberMe)))){
9753					if(data.customerInfo.onlineStatus){
9754						$window.location.href = $window.contextPath + "/" + $window.locale + $window.contentRoot + "/login" + htmlExtension;
9755					}
9756
9757				} 
9758				if(angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.cor)){
9759					_onCallOfDisplayControl(data,data.customerInfo.cor);
9760				}else{
9761					_onCallOfDisplayControl(data,vm.country);
9762				}
9763
9764				loadCountryList(data);       
9765				$rootScope.$broadcast("Profile.inProfileEnrollFlow", true);
9766				$rootScope.requestInProgress = false;
9767				setTimeout(function() {
9768					jQuery('.hide-on-load-profile').removeClass('hide-on-load-profile');
9769				}, 1000);
9770			},function(error){
9771				$rootScope.requestInProgress = false;
9772				if(angular.isDefined(error.errorList) && error.errorList.length > 0){
9773					//Fix for NFR issue when Profile Service is down
9774					vm.enrollmentPageError=error.errorList[0].message;
9775
9776					vm.accountFormValidation = true;
9777					$("body").animate({
9778						"scrollTop": 0
9779					}, "slow");
9780				}
9781				setTimeout(function() {
9782					jQuery('.hide-on-load-profile').removeClass('hide-on-load-profile');
9783				}, 1000);
9784			});
9785		}
9786
9787
9788//		GTM FUNCTION
9789		function gtmBlur(string, string1, inputType) {
9790			//	hardcoded strings in this function need not be I18N as these won't be displayed in UI.
9791			var inputAction;
9792			if (inputType == 'text') {
9793				inputAction = string ? 'Filled In' : 'Skipped';
9794			} else if (inputType == 'checkbox') {
9795				inputAction = string ? 'Selected as Y' : 'Selected as N';
9796			} else if (inputType == 'dropdown') {
9797				inputAction = string ? 'Selected' : 'Not Selected';
9798			} 
9799			dataLayer.push({ 
9800				'event': 'trackEvent',
9801				'eventCategory': 'Tracking Form: ' + 'Enrollment-Form',
9802				'eventLabel': string1,
9803				'eventAction': inputAction
9804			});
9805		}
9806
9807		function _loadCalendarDropdown() {
9808			var lowerAgeLimit = vm.hasPartnerInfo ? ( angular.isDefined(vm.customerData.partnerCustomerInfo.minAge) ? vm.customerData.partnerCustomerInfo.minAge : carRentalConstant.ageLimit.lower )  : carRentalConstant.ageLimit.lower;
9809			var CalendarDetails = accountUtilityService.loadCalendarDropdown(lowerAgeLimit);
9810			vm.monthsList = CalendarDetails.monthsList;
9811			vm.yearsList = CalendarDetails.yearsList;
9812			vm.datesList = CalendarDetails.datesList;
9813		}
9814
9815		onPageLoad();
9816
9817		var extendedController = $controller('SignupExnController', {
9818			$scope: $scope
9819		});
9820		angular.extend(this, extendedController);
9821		
9822		//Changes done as part of ABGTTT-170
9823        $rootScope.$on("recaptcha", function(event, response){
9824       	 vm.recaptcha=response;
9825   			if(angular.isDefined(response) && response != '' && event.currentScope.calledFrom == "checkUserName"){
9826   				validateUsernameApiCall();
9827   				vm.captchaExecuted = true;
9828   			}else if(angular.isDefined(response) && response != '' && event.currentScope.calledFrom == "createProfile"){
9829   				createProfileApiCall();
9830   			}
9831        });
9832	}
9833})();
9834(function() {
9835	'use strict';
9836
9837	angular
9838	.module('account')
9839	.controller('DashboardWrapperController', DashboardWrapperController);
9840
9841	DashboardWrapperController.$inject = ['$controller', '$window', '$scope', '$rootScope', 'authenticationService','storageService','anchorSmoothScroll'];
9842
9843	function DashboardWrapperController($controller, $window, $scope, $rootScope, authenticationService, storageService, anchorSmoothScroll) {
9844
9845
9846		$controller('ExceptionHandlerController', {
9847			$scope: $scope
9848		});
9849
9850		// View Model.....
9851		var vmw = this;
9852		var isValidXSRF = true;
9853		vmw.isProfileComplete = false; 
9854		$rootScope.requestInProgress = true;
9855
9856		// Function will be called on page load
9857		function onPageLoad() {
9858			if(angular.isDefined(authenticationService.getXsrfToken())){
9859				isValidXSRF  = false;
9860				initialize();
9861			}
9862		}
9863
9864		$rootScope.$on('initSuccess', function(event, arg) {
9865			if(isValidXSRF){
9866				initialize();
9867			}
9868		});
9869		
9870		$rootScope.$on('Profile.Enrollmentstep', function(event, data) {
9871			if(data && (data == 'profile-completed' || data == 'enroll-rewards-section')){
9872				vmw.isProfileComplete = true;
9873			}
9874		});
9875        
9876	    //To handle amazon click on home profile dashboard
9877	    
9878	    jQuery(document).ready(function() {
9879	    	 ABG.amazonRedirect();
9880	    });
9881
9882		
9883		function initialize(){
9884			authenticationService.getCustomerAdditionalInfo().then(function(data){
9885				setTimeout(function() {
9886			    	  jQuery('.hide-on-load-profile').removeClass('hide-on-load-profile');
9887			    	  $rootScope.requestInProgress = false;
9888			    }, 1000);
9889			},function(error){
9890				storageService.deleteAllStorageData();
9891				var loginDelayedRedirect = setInterval(function(){
9892                    if(window.sessionStorage.getItem('ngStorage-xsrf') == null){
9893                    	clearInterval(loginDelayedRedirect);
9894                    	ABG.redirectPage($window.contextPath + "/" + $window.locale + $window.contentRoot + "/login" + htmlExtension + "#/" + error.errorList[0].code);
9895                    }
9896				},5);		
9897				
9898			});
9899			setTimeout(function(){
9900				var addNewDiscountCode = storageService.getStorageData('addNewDisount');
9901				if(angular.isDefined(addNewDiscountCode) && addNewDiscountCode){
9902					if($window.brand=='avis'){
9903					   angular.element('#addNewDiscountNumber').click();
9904					}
9905					if($window.brand=='budget'){
9906						angular.element('#edit-travel').click();	
9907					}
9908					storageService.deleteStorageData('addNewDisount');
9909					anchorSmoothScroll.scrollTo('profileUpgradeWrapper');
9910				}
9911			},3000);	
9912		}
9913
9914		// Page Init...
9915		onPageLoad();
9916	}
9917})();
9918(function() {
9919  'use strict';
9920
9921  angular
9922    .module('account')
9923    .controller('DivisionController', DivisionController);
9924
9925  DivisionController.$inject = ['$scope', '$state', '$rootScope', '$window', 'authenticationService', '$filter', 'carRentalConstant', 'signupService', '$validation', '$controller', 'accountModelService', '$location', 'corporateService','reservationModelService','getVehicles'];
9926
9927  function DivisionController($scope, $state, $rootScope, $window, authenticationService, $filter, carRentalConstant, signupService, $validationProvider, $controller, accountModelService, $location, corporateService,reservationModelService ,getVehicles) {
9928
9929    $controller('ExceptionHandlerController', {
9930      $scope: $scope
9931    });
9932
9933    // View Model.....
9934    var vm = this;
9935    var promise = {};
9936    var isValidXSRF = true;
9937    vm.formValidated = false;
9938    // View Callable.....
9939    vm.callChildSegment = callChildSegment;
9940    
9941    // View Model.....
9942    
9943    
9944    $rootScope.requestInProgress = true;
9945
9946
9947    // To display the division available for the segments.
9948    function onPageLoad() {
9949    	if(angular.isDefined(authenticationService.getXsrfToken())){
9950			isValidXSRF  = false;
9951			initialize();
9952		}
9953    }
9954    
9955    $rootScope.$on('initSuccess', function(event, arg) {
9956		if(isValidXSRF){
9957			initialize();
9958		}
9959	});
9960    
9961    function initialize(){
9962    	getVehicles.accountSummaryload('ACCOUNT_DIVISIONS_URL').then(function(data) {    		
9963    		$rootScope.requestInProgress = false;
9964    		if($window.brand == carRentalConstant.brandName.BUDGET) {
9965				var cbpFlag = reservationModelService.cbpFlag;
9966				cbpFlag.cbpFlow = true;
9967				reservationModelService.setCbpFlag(cbpFlag);
9968			}
9969    		vm.segments = angular.isDefined(data) && angular.isDefined(data.partnerCustomerInfo) && angular.isDefined(data.partnerCustomerInfo.childSegments) ? data.partnerCustomerInfo.childSegments : "";
9970    		$rootScope.$broadcast("CBPImageName", data.partnerCustomerInfo);	
9971    			
9972  	  	},function(error){
9973  	  		$rootScope.requestInProgress = false;
9974    	});    	
9975    }
9976    
9977    //onClick it makes an api call to inform back-end system of what awd user selected
9978    function callChildSegment(childAwd){
9979    	corporateService.getChildSegmentInfo(childAwd).then(function(data){
9980    		$rootScope.requestInProgress = true;
9981        	var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale +$window.contentRoot+ "/enrollment" + htmlExtension;
9982        	$window.location.href = redirectPath;        	
9983    	},function(error){
9984    		if(angular.isDefined(error.errorList[0]) && error.errorList.length > 0){
9985        		vm.formError = error.errorList[0].message;
9986                vm.formValidated = true;
9987    		}
9988    		$rootScope.requestInProgress = false;
9989    	});    	
9990    }
9991
9992    onPageLoad();
9993    
9994  }
9995})();
9996
9997(function() {
9998  'use strict';
9999
10000  angular
10001    .module('account')
10002    .controller('ActivationController', ActivationController);
10003
10004  ActivationController.$inject = ['$controller', '$scope', '$rootScope', 'signupService', 'authenticationService','$validation', 'accountgaService'];
10005
10006  function ActivationController($controller, $scope, $rootScope, signupService, authenticationService,$validationProvider, accountgaService) {
10007
10008    $controller('ExceptionHandlerController', {
10009      $scope: $scope
10010    });
10011
10012    // View Model.....
10013    var vm = this;
10014    vm.resendEmailSuccess = false;
10015    vm.resendEmailError = false;
10016    vm.disableLeftNavLink = false;
10017    vm.customerData = {};
10018    $rootScope.requestInProgress = true;
10019    
10020    // View Callable.....
10021    vm.resendActivationEmail = resendActivationEmail;
10022    	
10023
10024    $rootScope.$on('Profile.CustomerAdditionalInfo',function(event, response){
10025    	vm.customerData = response;
10026    	accountgaService.analyticsDimension(vm.customerData, '');
10027		vm.disableLeftNavLink = true;
10028		$rootScope.requestInProgress = false;
10029    });
10030    
10031    // Method is used to re-send the activation link
10032    function resendActivationEmail() {
10033    	      signupService.resendActivationEmail().then(function(data) { //service call to webApi
10034    	    	  data = $scope.processErrorMessage(data);
10035		          vm.prod = data;
10036    	        if (data && !((angular.isDefined(data.errorList) && data.errorList.length > 0) || (angular.isDefined(data.warningList) && data.warningList.length > 0))) {
10037    	          vm.resendEmailSuccess = true;
10038    	        }else{
10039    	        	vm.resendEmailSuccess = false;
10040    	        }
10041    	      }, function(error) {
10042    	    	  vm.prod = $scope.processErrorMessage(error);
10043			       $rootScope.requestInProgress = false;
10044    	      });
10045    	}
10046  }
10047})();
10048
10049(function() {
10050  'use strict';
10051
10052  angular
10053    .module('account')
10054    .controller('VerifyIdentityController', VerifyIdentityController);
10055
10056  VerifyIdentityController.$inject = ['$controller', '$scope', '$rootScope', '$state', 'signupService', '$validation', 'accountModelService', 'getDataService', 'carRentalConstant', '$window', 'authenticationService', 'getVehicles'];
10057
10058  function VerifyIdentityController($controller, $scope, $rootScope, $state, signupService, $validationProvider, accountModelService, getDataService, carRentalConstant, $window, authenticationService, getVehicles) {
10059
10060    $controller('ExceptionHandlerController', {
10061      $scope: $scope
10062    });
10063
10064    // View Model.....
10065    var vm = this;
10066    vm.expressEnrollmentPageError = "";
10067    vm.expressEnrollmentFormValidated = false;
10068    vm.validateOfflineProfileModel = accountModelService.validateOfflineProfileModel;
10069    vm.domain = $window.domain.toUpperCase();
10070    
10071    // View Callable.....
10072    vm.verifyIdentity = verifyIdentity;
10073    vm.gtmBlur = gtmBlur;
10074    vm.forgotWizard = forgotWizard;
10075
10076    // Private Methods.....
10077    vm._onPageLoad = onPageLoad;
10078    vm._checkForCbpUser = _checkForCbpUser;
10079    vm._validationSuccess = _validationSuccess;
10080    vm._validationError = _validationError;
10081    
10082    //On page load
10083    function onPageLoad(){
10084    	getVehicles.accountSummaryload('preferredFlow').then(function(response){
10085			vm.customerResponce = response;
10086			_checkForCbpUser();
10087			setTimeout(function() {
10088		    	  jQuery('.hide-on-load-profile').removeClass('hide-on-load-profile');
10089		    	  $rootScope.requestInProgress = false;
10090		    });
10091			$rootScope.requestInProgress = false;
10092		},function(){
10093			setTimeout(function() {
10094		    	  jQuery('.hide-on-load-profile').removeClass('hide-on-load-profile');
10095		    	  $rootScope.requestInProgress = false;
10096		    });
10097			$rootScope.requestInProgress = false;
10098    	});
10099    }
10100    //will check whether CBP flow and change the header/footer
10101    function _checkForCbpUser(){
10102    	if(angular.isDefined(vm.customerResponce) && angular.isDefined(vm.customerResponce.partnerCustomerInfo) && !angular.equals({}, vm.customerResponce.partnerCustomerInfo)
10103    			 && vm.customerResponce.partnerCustomerInfo.partnerType == "PARTNER_CBP"){
10104    		$rootScope.$broadcast("CBPImageName", vm.customerResponce.partnerCustomerInfo);	    		
10105    	}
10106    }
10107    
10108    // To verify identity based on form values
10109    function verifyIdentity(verifyIdentity) {
10110      $validationProvider.validate(verifyIdentity).success(vm._validationSuccess).error(vm._validationError); // field and from level validation
10111    }
10112
10113    function _validationSuccess() {
10114    	$rootScope.requestInProgress = true;
10115    	signupService.validateIdentity(vm.validateOfflineProfileModel).then(function(data) {
10116    		data = $scope.processErrorMessage(data);
10117    		signupService.setConcurCustomerInfo(data);
10118    		vm.prod = data;
10119    		if (!(angular.isDefined(data.errorList) && data.errorList.length > 0) && !(angular.isDefined(data.warningList) && data.warningList.length > 0) && !(angular.isDefined(data.instructionList) && data.instructionList.length > 0)) {
10120    			
10121    				ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot +  "/enrollment" + htmlExtension);
10122    		} 
10123    		
10124    		else  {
10125    			if(angular.isDefined(data.instructionList) && angular.isDefined(data.instructionList[0])){
10126	    			if(angular.equals(data.instructionList[0].code,'06041')){
10127	    	    		// last name mismatch, take to another page
10128	    	    		ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot +  "/concur
10128-already-linked-denied" + htmlExtension);
10129	    	  		}else if(angular.isDefined(data.instructionList) && angular.equals(data.instructionList[0].code,'06038')){
10130	    	  			// Already an online profile, take the user to login page
10131	    	    		ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot +  "/login" + htmlExtension + '#/06038');
10132	    	  		}
10133	    		}else if(angular.isDefined(data.errorList) && angular.isDefined(data.errorList[0])){
10134	    			if(angular.isDefined(vm.customerResponce) && 
10135	    					angular.isDefined(vm.customerResponce.partnerCustomerInfo) && 
10136	    					!angular.equals({}, vm.customerResponce.partnerCustomerInfo) &&
10137	    	    			vm.customerResponce.partnerCustomerInfo.partnerType == "PARTNER_CBP" &&
10138	    	    			angular.equals(data.errorList[0].code,'06012')){
10139	    				// Already an online profile, take the user to login page
10140	    				ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot +  "/login" + htmlExtension + '#/06012');
10141	    				return;
10142	    	  		}
10143	    		}
10144    			
10145    			$("body").animate({
10146    				"scrollTop": 0
10147    			}, "slow");
10148    		}
10149    		$rootScope.requestInProgress = false;
10150    	}, function(error) {
10151    		$rootScope.requestInProgress = false;
10152			vm.prod = $scope.processErrorMessage(error);
10153        	vm.accountFormValidation = true;
10154       	 	$("body").animate({
10155          	"scrollTop": 0
10156        	}, "slow");
10157    	});
10158    };
10159
10160    function _validationError(response) {
10161    	$rootScope.requestInProgress = false;
10162      var errCount = response.errorCount;
10163      if(angular.isDefined(vm.prod) && angular.isDefined(vm.prod.errorList)){
10164    	  vm.prod.errorList.length = 0;
10165      }      
10166      if (1 === errCount) {
10167        vm.expressEnrollmentPageError = response.MSG[0];
10168        vm.expressEnrollmentFormValidated = true;
10169      } else if (1 < errCount) {
10170        //	call the message from the i18n ======= AEM
10171        vm.expressEnrollmentPageError = Dictionary.I18n.get('err.global.multi.errorMessage');
10172        vm.expressEnrollmentFormValidated = true;
10173      }
10174
10175    };
10176    
10177    function forgotWizard() {
10178    	ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot +  "/forgot-username" + htmlExtension);
10179    }
10180    
10181    //TODO move logic to GTM service - GTM FUNCTION 
10182    function gtmBlur(string, string1, inputType, wizardKey) {
10183      //	hardcoded strings in this function need not be I18N as these won't be displayed in UI.
10184      if(wizardKey != null && ($window.brand == carRentalConstant.brandName.BUDGET || $window.brand == carRentalConstant.brandName.AVIS)) {
10185    	  string1 = Dictionary.I18n.get('lbl.global.wizardNumber,'+brand);
10186      }
10187      if (inputType == 'text') {
10188        var inputAction = string ? 'Filled In' : 'Skipped';
10189      } else if (inputType == 'check') {
10190        var inputAction = string ? 'Checked In' : 'Skipped';
10191      } else if (inputType == 'drop') {
10192        var inputAction = string ? 'Selected' : 'Not Selected';
10193      }
10194      dataLayer.push({
10195        'event': 'trackEvent',
10196        'eventCategory': 'Tracking Form: ' + 'express-enrollmentForm',
10197        'eventLabel': string1,
10198        'eventAction': inputAction
10199      });
10200    }
10201    onPageLoad();
10202    
10203  }
10204})();
10205
10206(function() {
10207	'use strict';
10208	
10209	angular
10210		.module('account')
10211		.controller('NavigationController', NavigationController);
10212	
10213	NavigationController.$inject = ['$controller', '$scope','carRentalConstant', '$rootScope', '$window', 'storageService', '$validation', 'myProfileService', 'authenticationService'];
10214
10215	function NavigationController($controller, $scope,carRentalConstant, $rootScope, $window, storageService, $validationProvider, myProfileService, authenticationService) {
10216
10217		$controller('ExceptionHandlerController', {
10218			$scope: $scope
10219		});
10220		
10221		// View Model.....
10222		var vm = this;
10223		var token = authenticationService.getXsrfToken();
10224		if(!token){
10225           $rootScope.requestInProgress = true;
10226		}
10227		
10228		vm.disableLink = false;
10229		vm.displayLoyaltyProgressBar = false;
10230		
10231		// View Callable.....
10232		vm.editSection = editSection;
10233		vm.currentPage = "";
10234		vm.disableLink = false;
10235		vm.amazonUserStatus = "";
10236		vm.hideModalBackdrop = hideModalBackdrop;
10237		vm.showPreferredPlusMsg = false;
10238		var preferredPlusDiscNum = ["A8885", "B8885", "C8885", "M8885"];
10239		
10240		// Private Methods.....
10241		vm._expandSubNavigation = _expandSubNavigation;
10242		vm.setPassword = setPassword;
10243		
10244		function setPassword() {
10245		    jQuery('html,body').animate({
10246		       scrollTop: $("#identityPasswordSection").offset().top + 150},
10247	      'slow');
10248		}
10249
10250		$rootScope.$on('Profile.CustomerAdditionalInfo',function(event, data){
10251			vm.customerData = data;
10252			if(angular.isDefined(vm.customerData.loyaltyDetails) && angular.isDefined(vm.customerData.loyaltyDetails.nextTierName) && vm.customerData.loyaltyDetails.nextTierName != ''){
10253				vm.displayLoyaltyProgressBar = true;
10254			}
10255			if(angular.isDefined(vm.customerData.secDiscNumber) && angular.isDefined(vm.customerData.membershipStatus) && angular.isDefined(vm.customerData.loyaltyDetails) && angular.isDefined(vm.customerData.loyaltyDetails.totalRentals) && angular.isDefined(vm.customerData.loyaltyDetails.totalSpend) && vm.customerData.loyaltyDetails.totalRentals>=25 && vm.customerData.loyaltyDetails.totalSpend>=7000 && (vm.customerData.membershipStatus == 'Preferred Plus Premium' || vm.customerData.membershipStatus == 'Preferred Plus')){
10256				preferredPlusDiscNum.forEach(function(entry){
10257					if(vm.customerData.secDiscNumber.indexOf(entry) != -1){
10258						vm.showPreferredPlusMsg = true;
10259					}
10260				});
10261			}
10262			vm.domain=$window.domain.toUpperCase();
10263			myProfileService.setEditMode(false);
10264			
10265			_expandSubNavigation();
10266			vm.amazonUserStatus = authenticationService.amazonLoginStatus(); 
10267			$rootScope.requestInProgress = false;
10268		});
10269		
10270		$rootScope.$on("updateMemberStatus", function(event, data){
10271			vm.customerData = angular.copy(data.customerInfo);
10272			vm.customerData.wizardNumber = data.customerInfo.wizardNumberMasked;
10273		});
10274		//to update amazon login status
10275		$rootScope.$on("Partner.partnerInfo", function(event, data){
10276			if(angular.isDefined(data)){
10277				vm.amazonUserStatus = authenticationService.amazonLoginStatus();
10278			}
10279		})
10280		
10281		function hideModalBackdrop(){
10282			$('.modal-backdrop').remove();
10283		}
10284
10285		// To check if any section on dash board is in edit mode
10286		function editSection(url){			
10287			var isInEdit = myProfileService.getEditMode().editMode;
10288			if(!isInEdit){
10289				$rootScope.requestInProgress = true;
10290				$window.location.href =  url;
10291				//ABG.redirectPage(url);
10292			}else{
10293				if(isInEdit){
10294					var currentSection = myProfileService.getEditMode().editSection;
10295                	myProfileService.anchorToMsg(currentSection);
10296                	vm.showSectionMessage = true;
10297                	$rootScope.$broadcast('Profile.ShowSaveCancelMsg', vm.showSectionMessage);
10298					//$(".profile-edit-progress-alert").modal("show");
10299				}
10300			}
10301		}
10302		
10303		// To expand sub navigation 
10304		function _expandSubNavigation(){
10305			$("[data-toggle='custom-dropdown']").on("click", function(){
10306				var tgt = $(this);
10307				var parent = tgt.closest(".dropdown");
10308				var isInEdit = myProfileService.getEditMode().editMode;
10309				if (!isInEdit) {
10310					tgt.dropdown("toggle");
10311				}
10312			});
10313		}
10314		
10315       
10316
10317		// Left Navigation menu close icon
10318		$(".left-sidebar").on("click tap", ".navbar-toggle", function () {
10319			$(".navbar-toggle span").toggleClass("wrap-dropdown-close");
10320		});
10321		
10322		
10323	}
10324})();
10325(function() {
10326	'use strict';
10327	
10328	angular
10329		.module('account')
10330		.controller('StaticPageController', StaticPageController);
10331	
10332	StaticPageController.$inject = ['$controller', '$scope', '$rootScope', 'getVehicles'];
10333
10334	function StaticPageController($controller, $scope, $rootScope, getVehicles) {
10335
10336		$controller('ExceptionHandlerController', {
10337			$scope: $scope
10338		});
10339		
10340		// View Model.....
10341		var vm = this;
10342		
10343		// View Callable.....
10344		vm.loadHelpModal = loadHelpModal;
10345		
10346		// Private Methods.....
10347
10348		// Function will be called on page load
10349		function onPageLoad() {
10350		}
10351		
10352		$rootScope.$on('Profile.CustomerAdditionalInfo',function(event, response){
10353	    	vm.customerData = response;
10354	    });		
10355		
10356		//loads help modal based on country
10357		function loadHelpModal(currentEle) {
10358			var target = currentEle.target.parentElement;
10359			var country = 'US'; // TODO Why hard coded?
10360			vm.helpURL = getVehicles.getUrl(target, country);
10361		}
10362		
10363		// Page Init...
10364		onPageLoad();
10365	}
10366})();
10367(function() {
10368    'use strict';
10369    angular
10370        .module('account')
10371        .controller('MyProfileController', MyProfileController);
10372    MyProfileController.$inject = ['$controller', '$scope', '$window', '$cookies', 'signupService', 'myProfileService', '$validation', 'carRentalConstant', '$filter', 'authenticationService', '$rootScope', 'getVehicles', 'datePickerInit', '$locale', 'rewardsProgramService', 'locationService', 'anchorSmoothScroll', '$compile', 'accountUtilityService', 'accountgaService', 'reservationModelService', 'securityService', 'storageService','gaService'];
10373
10374    function MyProfileController($controller, $scope, $window, $cookies, signupService, myProfileService, $validationProvider, carRentalConstant, $filter, authenticationService, $rootScope, getVehicles, datePickerInit, $locale, rewardsProgramService, locationService, anchorSmoothScroll, $compile, accountUtilityService, accountgaService, reservationModelService, securityService, storageService,gaService) {
10375        $controller('ExceptionHandlerController', {
10376            $scope: $scope
10377        });
10378
10379        $rootScope.requestInProgress = true;
10380        // View Model.....
10381        var vm = this;
10382        var promise = {};
10383        var loyaltyOptIn = "";
10384        var ftpOptIn = "";
10385        var optOut = "";
10386        vm.captchaFlag = false;
10387        vm.showSmsOptIn = true;
10388        vm.makeList=[];
10389        //vm.car = {};
10390        vm.modelList = [];
10391        //vm.favouriteCars = [];
10392        vm.primaryCheckbox='';
10393        vm.sectionInEdit = ""; 
10394        vm.invalidPhoneNumber = false;
10395        vm.credtiCardSectionToDisplay = false;
10396        vm.dlSectionDisplay = false;
10397        vm.creditCardType = "";
10398        vm.customerData = {};
10399        vm.accountModel = {};
10400        vm.tempAccountModel={};
10401        vm.cityDisplay = false;
10402        vm.amazonPrimaryValue = false;
10403        vm.creditCardExpired = false;
10404        vm.profilePageLevelError = false;
10405        vm.emailReceiptPreferenceHidden = true; 
10406        vm.emailOffersPreferenceHidden = true; 
10407        vm.isFtpEnrollmentFlow = false;
10408        vm.displayPromoField = false;
10409        vm.enableCaptcha = enableCaptcha; 
10410        vm.maskedDlNumber = "";
10411        vm.profilePageLevelErrorMsg = "";
10412        vm.expMonths = [];
10413        vm.countryList = [];
10414        vm.expMonthPreviewMode = "";
10415        vm.expYearPreviewMode = "";
10416        vm.hideCVV = true; //TODO Check if we can get from webapi
10417        vm.hideExpMonthYear = true; //TODO Check if we can get from webapi
10418        vm.displayFTPSection = false;
10419        vm.siteLanguage = "";
10420        vm.siteCountry = "";
10421        vm.ccDetailList = [];
10422        vm.declineTermsCondition = "";
10423        vm.termsConditionSectionDisplay = "";
10424        vm.carGroupPreferenceList = [];
10425        vm.carModelList = [];
10426        vm.titleList = myProfileService.getTitleList();
10427        vm.carGroupPreferredName = "";
10428        vm.travelPreferences = {
10429            getFrequentPickUpLocation: ""
10430        };
10431        vm.partnerDetails = "";
10432        vm.sectionDeleted = "";
10433        vm.displayLoyaltyMessage = false; //TODO: check with Sai
10434        vm.displayFTPMessage = false; //TODO: check with Sai
10435        vm.displayOptoutMessage = false; //TODO: check with Sai
10436        vm.insuranceOpted = false;
10437        vm.showUpdateMsg = false;
10438        vm.protectionCoverageSectionDisplay = false;
10439        vm.timeFormatToDisplay = "";
10440        vm.showSuccessMsg = false;
10441        vm.showErrorMsg = false;
10442        vm.formValidated = false;
10443        vm.deleteFail = false;
10444        vm.domain = $window.domain.toUpperCase();
10445        vm.brand= $window.brand;
10446        vm.getTnCCountryList = $window.termsandconditionsMap;
10447        vm.getAvisPreferredTermsList = $window.termsandconditionsRewardsMap;
10448        vm.hasPartnerInfo = false;
10449        vm.showFTPDeclinedMsg = false;
10450        vm.showFTPSuccessMsg = false;
10451        vm.rewardPreferredTnC = false;
10452        vm.conflictedSection = "";
10453        vm.summaryError = {};
10454        vm.primaryChecked = false;
10455        vm.sectionDeleted = '';
10456        vm.displayRewardsSection = true;
10457        vm.signUpFlow = false;
10458        vm.resetPasswordFlow = false;
10459        vm.profileOtp ='';
10460        vm.resendOtpSuccess = false;
10461        vm.resendOtpError = false;
10462        vm.tdCheck = true;
10463        vm.showProminentForm = false;
10464        vm.collapseProminentForm = false;
10465		vm.alexaSuccessMessage = "";
10466		
10467        vm.displaySuccessMsg = false;
10468        vm.multiValuesEnable = false;
10469        vm.showDelete = false;
10470        vm.hideDLState = false;
10471        
10472        vm.showMessage = false;
10473        vm.ccpresent = false;
10474		vm.amazonUserStatus = "";
10475		vm.showSectionMessage = false;
10476		vm.showExpressConsent = angular.isDefined(storageService.getStorageData('showExpressConsent'))?true:false;
10477		vm.retriveCallSuccess = angular.isDefined(storageService.getStorageData('retriveCallSuccess'))?true:false;
10478		vm.isEnterManual = false;
10479		vm.showBiometricScan = false;
10480		vm.goToCounterMsgForCC = false;
10481		vm.goToCounterMsgForDL = false;
10482
10483        
10484        // View Callable.....
10485        vm.saveProfileDetail = saveProfileDetail;
10486        vm.saveDetails = saveDetails;
10487        vm.getStateBasedOnCounty = getStateBasedOnCounty;
10488        vm.selectAddress = selectAddress;
10489        vm.updatePassword = updatePassword;
10490        vm.editSection = editSection;
10491        vm.cancelEdit = cancelEdit;
10492        vm.clearError = clearError;
10493        vm.carEdit = carEdit;
10494        vm.getSuggestions = getSuggestions;
10495        vm.validatePhoneNumber = validatePhoneNumber;
10496        vm.onChangeCreditCardType = onChangeCreditCardType; //TODO Check if we can get from webapi
10497        vm.modifyTempList = modifyTempList;
10498        vm.validatecurrentPasswordField = validatecurrentPasswordField;
10499        vm.validatenewPasswordField = validatenewPasswordField;
10500        vm.cancelTempListModifications = cancelTempListModifications;
10501        vm.declineProfileTermsCondition = declineProfileTermsCondition;
10502        vm.clearFtpDetails = clearFtpDetails;
10503        vm.setFtpEnrollment = setFtpEnrollment;
10504        vm.gtmBlur = gtmBlur;
10505        vm.clearAddress = clearAddress;
10506        vm.acceptConnectedCarTnC = acceptConnectedCarTnC;
10507        vm.closeConnectedCarTnc = closeConnectedCarTnc;
10508        vm.validatePromoCode = validatePromoCode;
10509        vm.loadHelpModal = loadHelpModal;
10510        vm.verifyProfileOtp = verifyProfileOtp;
10511        vm.resendOtp = resendOtp;
10512        vm.unlinkAmazonProfile = unlinkAmazonProfile;
10513        vm.deleteConfirm = deleteConfirm;
10514        vm.loadGetStateBasedOnCounty = loadGetStateBasedOnCounty;
10515        vm.displayCarClass = displayCarClass;
10516        vm.updateCdhUnAvailable = updateCdhUnAvailable;
10517        vm.displayModel = displayModel;
10518        //vm.displayCarClass = displayCarClass;
10519        // Private Methods.....     
10520        vm._loadCountry = _loadCountry;
10521        vm._loadDefaultCountry = _loadDefaultCountry;
10522        vm._setCreditCardSection = _setCreditCardSection;
10523        vm._setDlSection = _setDlSection;
10524        vm._loadMnthYrDropdown = _loadMnthYrDropdown;
10525        vm._loadLanguagePreference = _loadLanguagePreference;
10526        vm._dateTimeFormatDropDown = _dateTimeFormatDropDown;
10527        vm._setProtectionCoverageSection = _setProtectionCoverageSection;
10528        vm._setTermsConditionSection = _setTermsConditionSection;
10529        vm._loadCarPreferenceList = _loadCarPreferenceList;
10530        vm._setEnrollRewardsSection = _setEnrollRewardsSection;
10531        vm._getPartnerDetails = _getPartnerDetails;
10532        vm._initPopoverOnModal = _initPopoverOnModal;
10533        vm._loadCalendarDropdown = _loadCalendarDropdown;
10534        vm._loadEditSection = _loadEditSection;
10535        vm._setFreqPickUpLoc = _setFreqPickUpLoc;
10536        vm._getSectionInEdit = _getSectionInEdit;
10537        vm._checkForConnectedCarTnCModalDisplay = _checkForConnectedCarTnCModalDisplay;
10538        vm._checkForPartnerCustomerInfo = _checkForPartnerCustomerInfo;
10539        vm._checkForExpiredCC = _checkForExpiredCC;
10540        vm._clearPasswordFields = _clearPasswordFields;
10541        vm._setValueForPromoEmails = _setValueForPromoEmails;
10542        vm._setAddressDetails = _setAddressDetails;
10543        vm._setTnCLink = _setTnCLink;
10544        vm._loadEmail = _loadEmail;
10545        vm.saveProfile = saveProfile;
10546        vm.setPassword = setPassword;
10547        vm.custDetailsUpdate = custDetailsUpdate;
10548        vm.clearEmailPhoneError = clearEmailPhoneError;
10549        vm.reloadPage = reloadPage;
10550        vm.validateEmailPhoneNo = false;
10551		vm.initiateMitekVerification = initiateMitekVerification;
10552		vm.showManualDlForm = showManualDlForm;
10553
10554
10555        
10556        var frMonth = [{key: "01", desc: "janvier"},{key: "02", desc: "f\u00e9vrier"},{key: "03", desc: "mars"},{key: "04", desc: "avril"},{key: "05", desc: "mai"},{key: "06", desc: "juin"},{key: "07", desc: "juillet"},{key: "08", desc: "ao\u00fbt"},{key: "09", desc: "septembre"},{key: "10", desc: "octobre"},{key: "11", desc: "novembre"},{key: "12", desc: "d\u00e9cembre"}];
10557        
10558		$rootScope.$on('Profile.CustomerAdditionalInfo',function(event, response){
10559			vm.customerData = response;
10560			if(vm.customerData.cor == "US" || vm.customerData.cor == "CA"){
10561				vm.showBiometricScan = true;
10562			}
10563			vm.showPrefilled = storageService.getStorageData('dlVerifiedWithMitek');
10564			if (vm.showPrefilled && vm.customerData.dlSummary) {
10565				console.log(JSON.stringify(vm.customerData.dlSummary));
10566				vm.countryListForBiometricDl = accountUtilityService.getCountryList(vm.customerData, $window.countryListForDriverLicense);
10567				if(angular.isDefined(vm.countryListForBiometricDl) && vm.countryListForBiometricDl.length){
10568					var index = vm.countryListForBiometricDl.indexOf(
10569						$filter('filter')(vm.countryListForBiometricDl, function (d) {
10570							return d.code === vm.customerData.dlSummary.country;
10571						})[0]
10572					);
10573	
10574					vm.dlCountryName = vm.countryListForBiometricDl[index].name;
10575				}
10576				gaService.trackMitekVerEventsDuringProfileEnroll('PREFILLED_DL', 'Success', vm.customerData);
10577			} else if (vm.showPrefilled && !angular.isDefined(vm.customerData.dlSummary)) {
10578				gaService.trackMitekVerEventsDuringProfileEnroll('PREFILLED_DL', 'Failure', vm.customerData);
10579			}
10580			var session = authenticationService.getSessionModel();
10581			if(angular.isDefined(session) && angular.isDefined(session.tdCheck)){
10582				vm.tdCheck = session.tdCheck;
10583			}
10584			
10585			if(angular.isDefined(vm.customerData.cor) && ((vm.customerData.cor).toLowerCase() == 'us' || (vm.customerData.cor).toLowerCase() == 'ca') && $window.brand == carRentalConstant.brandName.AVIS && angular.isDefined(vm.customerData.userState) && vm.customerData.userState == 'AUTHENTICATED'){
10586				vm.multiValuesEnable = true;
10587			}
10588			onPageLoad();
10589		});
10590		
10591		$rootScope.$on('Profile.SelfInvoke',function(event, response){
10592			vm.customerData = response;
10593			onPageLoad();
10594		});
10595		
10596		function setPassword() {
10597		    jQuery('html,body').animate({
10598		       scrollTop: $("#identityPasswordSection").offset().top + 150},
10599		    'slow');
10600		}
10601
10602		
10603		//called whenever the page is refreshed
10604		function onPageLoad(){
10605			var captchaForm = $("#profileCreditCardForm");
10606	        if(angular.isDefined(vm.captchaFlag) && captchaForm.length == 1){
10607	        	vm.captchaFlag=true;
10608	        }
10609				if(storageService.getStorageData('displayAlexaSuccessMsg')){
10610				vm.displaySuccessMsg = true;
10611        		vm.alexaSuccessMessage = Dictionary.I18n.get('lbl.amazonBenefits.alexaSuccessMessage');
10612        		storageService.deleteStorageData('displayAlexaSuccessMsg');
10613			}
10614			$window.scrollTo(0,0);
10615			if(vm.customerData.enrollmentStep == 'credit-card-section'){
10616				vm.accountModel.cardType = vm.customerData.ccSummary.type;
10617				onChangeCreditCardType();
10618			}
10619			if(reservationModelService.getUrlParameter("signup") == "true"){
10620				vm.signUpFlow = true;
10621			}
10622			if (angular.isDefined(vm.customerData) && !angular.equals({}, vm.customerData)) {
10623				if (angular.isDefined(vm.customerData.webCustomer) && !angular.equals({}, vm.customerData.webCustomer) && vm.customerData.webCustomer.activationStatus === "0" && $window.brand != carRentalConstant.brandName.AVIS) {
10624	    			var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot + "/activation" + htmlExtension;
10625	    			$window.location.href = redirectPath;
10626	    		}
10627				vm.accountModel = myProfileService.getAccountData(vm.customerData);
10628				if($window.brand === carRentalConstant.brandName.PAYLESS && vm.customerData.iscreateProfileFlow) {
10629					accountgaService.paylessDimension(vm.customerData, '');
10630				} else if(($window.brand === carRentalConstant.brandName.AVIS || $window.brand === carRentalConstant.brandName.BUDGET)) {
10631					accountgaService.analyticsDimension(vm.customerData, '');	
10632				}
10633				vm.amazonUserStatus = authenticationService.amazonLoginStatus(); 
10634				_checkForConnectedCarTnCModalDisplay();
10635				onSectionUpdate();
10636				if (angular.isDefined(vm.customerData.errorList)){
10637					vm.summaryError = $scope.processErrorMessage(vm.customerData);
10638				}
10639				if($window.brand == carRentalConstant.brandName.AVIS && vm.customerData.resetPasswordFlow) {					
10640					vm.resetPasswordFlow = vm.customerData.resetPasswordFlow;
10641					vm.sectionInEdit = "password-section";					
10642					myProfileService.anchorToMsg(vm.sectionInEdit);
10643				}
10644				if(vm.customerData.enrollmentStep != 'profile-completed' && vm.customerData.enrollmentStep !='enroll-rewards-section'){
10645					vm.showProminentForm = true;
10646				} else {
10647					vm.showProminentForm = false;
10648				}
10649				$rootScope.$broadcast('Profile.Enrollmentstep', vm.customerData.enrollmentStep);
10650				// ARD3-1264 changes for Budget
10651				if($window.brand === carRentalConstant.brandName.BUDGET && (angular.isDefined(vm.accountModel) && vm.accountModel != '')){
10652					vm.tempAccountModel = angular.copy(vm.accountModel);
10653				}	
10654			}
10655			vm.updateCdhUnAvailable();
10656		}
10657		function updateCdhUnAvailable(data){
10658			if(angular.isDefined(vm.customerData.cdhUnAvailable) && vm.customerData.cdhUnAvailable == true){
10659				vm.cdhErrors = storageService.getStorageData('epCdhDownErrorList');
10660				if(vm.cdhErrors == undefined && angular.isDefined(data) &&  angular.isDefined(data.instructionList && data.instructionList.length>1)){
10661						angular.forEach(data.instructionList,function(error){
10662							if(error.code == '17435' && error.type == 'INSTRUCTION'){
10663								vm.cdhDownError = error.message;
10664						}
10665						})
10666						storageService.setStorageData('epCdhDownErrorList', vm.cdhDownError);
10667					}
10668			}
10669					
10670					/*vm.emailCdhError = vm.cdhErrors.emailCdhError;
10671					vm.addressCdhError = vm.cdhErrors.addressCdhError;
10672					vm.phoneCdhError = vm.cdhErrors.phoneCdhError;
10673					vm.ccCdhError = vm.cdhErrors.ccCdhError;
10674					vm.carCdhError = vm.cdhErrors.carCdhError;
10675					vm.discountCdhError = vm.cdhErrors.discountCdhError;*/
10676			
10677		}
10678		
10679		function carEdit(){
10680
10681			myProfileService.getCarPreferenceListFromServlet(vm.customerData.cor).then(function(carGroupPreference){
10682
10683				vm.favouriteCars = carGroupPreference;
10684				angular.forEach(vm.favouriteCars,function(carGroup){
10685					vm.makeList.push(carGroup.make);
10686				});
10687				var makesList = [];
10688				angular.forEach(vm.makeList, function(make) {
10689					if (angular.isDefined(make)) {
10690						makesList.push(make);
10691					}
10692				});
10693				vm.makeList = $filter('unique')(makesList, 'make');
10694				vm.addProperty.Car.make = vm.favouriteCars[0].make;
10695				if(vm.accountModel.carPreference){
10696					angular.forEach(vm.accountModel.carPreference,function(car){
10697						angular.forEach(vm.favouriteCars,function(carObj){
10698							if(car.makeModelCd == carObj.makeModelCd){
10699								car.make = carObj.make;
10700								car.description = carObj.model;
10701								car.carClass = carObj.carGroup; 
10702							}
10703						})
10704
10705					});
10706					angular.forEach(vm.accountModel.carPreference,function(car){
10707						if(car.carModelList != []){
10708							car.carModelList=[];
10709						angular.forEach(vm.favouriteCars,function(carObj){
10710					
10711						if(car.make == carObj.make){
10712							var modelRes={
10713									"makeModelCd" : carObj.makeModelCd,
10714									"modelName" :carObj.model
10715								}
10716							car.carModelList.push(modelRes);
10717							var modelList = [];
10718							angular.forEach(car.carModelList, function(model) {
10719								if (angular.isDefined(model)) {
10720									modelList.push(model);
10721								}
10722							});
10723							car.carModelList = $filter('unique')(modelList, 'modelName');
10724						}
10725						});
10726					}
10727						
10728					});
10729				}
10730				if(vm.addProperty.Car){
10731						vm.addProperty.Car.carModelList=[];
10732					angular.forEach(vm.favouriteCars,function(carObj){
10733						if(vm.addProperty.Car.make == carObj.make){
10734							var modelRes={
10735									"makeModelCd" : carObj.makeModelCd,
10736									"modelName" :carObj.model
10737								}
10738							vm.addProperty.Car.carModelList.push(modelRes);
10739							var modelList = [];
10740							angular.forEach(vm.addProperty.Car.carModelList, function(model) {
10741								if (angular.isDefined(model)) {
10742									modelList.push(model);
10743								}
10744							});
10745							vm.addProperty.Car.carModelList = $filter('unique')(modelList, 'modelName');
10746						}
10747					})
10748					vm.addProperty.Car.makeModelCd = vm.addProperty.Car.carModelList[0].makeModelCd;
10749					angular.forEach(vm.favouriteCars,function(carObj){
10750						if(vm.addProperty.Car.makeModelCd == carObj.makeModelCd){
10751							vm.addProperty.Car.carClass = carObj.carGroup;
10752						}
10753					});
10754					
10755				}
10756			});
10757
10758
10759
10760
10761		}
10762		function displayModel(make,objId){
10763		if(angular.isDefined(vm.addProperty.Car)){
10764				vm.addProperty.Car.carModelList = [];
10765				angular.forEach(vm.favouriteCars,function(favCar){
10766					//var makeName = favCar.description.split(" ");
10767					//favCar.make = makeName[0];
10768					if(favCar.make == make){
10769						var modelRes = {
10770								"makeModelCd" : favCar.makeModelCd,
10771								"modelName" : favCar.model
10772							}
10773						vm.addProperty.Car.carModelList.push(modelRes);
10774						var modelList = [];
10775					      angular.forEach(vm.addProperty.Car.carModelList, function(model) {
10776					        if (angular.isDefined(model)) {
10777					        	modelList.push(model);
10778					        }
10779					      });
10780					      vm.addProperty.Car.carModelList = $filter('unique')(modelList, 'modelName');
10781					      //vm.car.model = 'select a Model' ;
10782					      vm.addProperty.Car.makeModelCd = vm.addProperty.Car.carModelList[0].makeModelCd
10783					      if(vm.addProperty.Car.makeModelCd == favCar.makeModelCd){
10784					    	  vm.addProperty.Car.carClass= favCar.carGroup;
10785							
10786					}
10787					//vm.car.model = vm.car.carModelList[0];
10788					}
10789				})
10790			}
10791		
10792		if(vm.accountModel.carPreference){
10793			angular.forEach(vm.accountModel.carPreference,function(car){
10794				if(objId==car.maskId){
10795					car.carModelList=[];
10796					angular.forEach(vm.favouriteCars,function(favCar){
10797						if(favCar.make == make){
10798							var modelRes = {
10799									"makeModelCd" : favCar.makeModelCd,
10800									"modelName" : favCar.model
10801								}
10802							car.carModelList.push(modelRes);
10803							var modelList = [];
10804						      angular.forEach(car.carModelList, function(model) {
10805						        if (angular.isDefined(model)) {
10806						        	modelList.push(model);
10807						        }
10808						      });
10809						      car.carModelList = $filter('unique')(modelList, 'modelName');
10810							car.makeModelCd = car.carModelList[0].makeModelCd;
10811							if(car.makeModelCd == favCar.makeModelCd){
10812								car.carClass= favCar.carGroup;
10813							}
10814						}
10815						
10816						
10817					})
10818					
10819				}
10820			});
10821		}
10822		//console.log(vm.accountModel.carPreference);
10823			
10824			
10825			
10826		}
10827		function displayCarClass(modelName,objId){
10828			if(vm.accountModel.carPreference){
10829				angular.forEach(vm.accountModel.carPreference,function(car){
10830					if(objId==car.maskId){
10831						angular.forEach(vm.favouriteCars,function(CarObj){
10832							if(modelName == CarObj.makeModelCd){
10833								car.carClass= CarObj.carGroup;
10834							}
10835						})
10836						
10837					}
10838				});
10839			}
10840			if(vm.addProperty.Car){
10841				angular.forEach(vm.favouriteCars,function(model){
10842					if(modelName == model.makeModelCd){
10843						vm.addProperty.Car.carClass= model.carGroup;
10844					}
10845				})
10846			}
10847			
10848		}
10849		
10850		//called whenever a section is updated
10851		function onSectionUpdate(){
10852    		if (angular.isDefined(vm.customerData) && !angular.equals({}, vm.customerData)) {
10853    			_checkForPartnerCustomerInfo();
10854    			loyaltyOptIn = angular.isDefined(authenticationService.getLoyaltyDetails()) ? authenticationService.getLoyaltyDetails().loyaltyOptIn : "";
10855    			ftpOptIn = angular.isDefined(vm.customerData.ftpPartnerDetails) ? vm.customerData.ftpPartnerDetails.ftpOptIn : "";
10856    			optOut = angular.isDefined(vm.customerData.optOut) ? vm.customerData.optOut : "";
10857    			_setValueForPromoEmails();
10858    			_setTnCLink();
10859    			vm.customerData.enrollmentMonth = myProfileService.getMonths(vm.customerData.enrollmentMonth);
10860    			vm.customerData.pwdLastUpdatedMonth = myProfileService.getMonths(vm.customerData.pwdLastUpdatedMonth);    			
10861    			vm.accountModel = myProfileService.getAccountData(vm.customerData);
10862    			if((vm.customerData.enrollmentStep == 'protections-coverages-section') || ($window.location.href.indexOf("preferences") != -1)){
10863    				var supportedInsurances;
10864        			if(vm.hasPartnerInfo && angular.isDefined(vm.customerData.partnerCustomerInfo.insuranceMap)){
10865    					supportedInsurances = vm.customerData.partnerCustomerInfo.insuranceMap;
10866    				}
10867    				myProfileService.loadSupportedExtras(vm.customerData,supportedInsurances).then(function(extrasData) {
10868        				vm.accountModel.extrasData = extrasData;
10869        				vm.accountModel.tempList = angular.copy(vm.accountModel.extrasData);
10870        			});
10871    			} 
10872    			vm.accountModel.tempAwdList = angular.copy(vm.customerData.awd);
10873    			_loadEditSection();
10874    			_setAddressDetails();
10875    		if(vm.accountModel.contactAddress.address){
10876    			_loadCountry();
10877    		}	
10878    		vm._loadEmail();
10879    			vm._loadCarPreferenceList();
10880    			myProfileService.setEditMode(false);
10881    			vm._checkForExpiredCC();
10882    			vm._setCreditCardSection();
10883    			vm._setDlSection();
10884    			_loadMnthYrDropdown();
10885    			_loadLanguagePreference();
10886    			_dateTimeFormatDropDown();
10887    			vm._setProtectionCoverageSection();
10888    			_setTermsConditionSection();
10889    			vm._setEnrollRewardsSection();
10890    			_initPopoverOnModal();
10891    			_loadCalendarDropdown();
10892    			_setFreqPickUpLoc();
10893    			if(vm.multiValuesEnable){
10894         		   vm.carEdit();
10895         	   }
10896    		}
10897    		$rootScope.requestInProgress = false;		
10898		}
10899		
10900		function _setTnCLink(){
10901			if(angular.isDefined(vm.getTnCCountryList) && (vm.getTnCCountryList != '') && ((angular.isDefined(vm.accountModel) && vm.accountModel.showConnectedCarTncModal) || (vm.customerData.enrollmentStep == 'tnc-section'))){
10902				vm.showTnCPage = getVehicles.gettermsMapURL(vm.getTnCCountryList, vm.domain)+'.partial.html';
10903			}
10904		}
10905		
10906		function _checkForExpiredCC(){
10907			if (angular.isDefined(vm.customerData.ccSummary) 
10908					&& angular.isDefined(vm.customerData.ccSummary.expiryMsg) 
10909					&& angular.isDefined(vm.customerData.ccSummary.expiryMsg.code) 
10910					&& vm.customerData.ccSummary.expiryMsg.code === "06015") {
10911				vm.creditCardExpired = true;
10912				vm.profilePageLevelError = true;
10913				vm.profilePageLevelErrorMsg = vm.customerData.ccSummary.expiryMsg.fieldLevelMessage;
10914				vm.formValidated = true;
10915				vm.sectionInEdit = 'credit-card-section';
10916				vm.formError = vm.customerData.ccSummary.expiryMsg.fieldLevelMessage;
10917			} else {
10918				vm.creditCardExpired = false;
10919				vm.profilePageLevelError = false;
10920				vm.profilePageLevelErrorMsg = "";
10921				vm.formValidated = false;
10922				vm.formError = "";
10923			}
10924		}
10925		
10926		function _setAddressDetails(){
10927			angular.forEach(vm.customerData.contacts.address,function(address){
10928				if(angular.isDefined(address)){            	
10929	            	if(angular.isDefined(address.address1) && address.address1!=""){
10930	            		angular.element('#addressline1'+address.maskId).val(address.address1);
10931	                    angular.element('#addressline1'+address.maskId).trigger('change');
10932	            	}
10933					if(angular.isDefined(address.address2) && address.address2!=""){
10934	            		angular.element('#addressline2'+address.maskId).val(address.address2);
10935	                    angular.element('#addressline2'+address.maskId).trigger('change');
10936	            	}
10937	            	if(address.zipCode!=""){
10938	            		angular.element('#zip'+address.maskId).val(address.zipCode);
10939	                    angular.element('#zip'+address.maskId).trigger('change');
10940	            	}
10941	            }
10942			})
10943			if(angular.isDefined(vm.addProperty.Address)){
10944				if(angular.isDefined(vm.addProperty.Address.address1) && vm.addProperty.Address.address1!=""){
10945            		angular.element('#addressline').val(vm.addProperty.Address.address1);
10946                    angular.element('#addressline').trigger('change');
10947            	}
10948            	if(vm.addProperty.Address.zipCode!=""){
10949            		angular.element('#addZip').val(vm.addProperty.Address.zipCode);
10950                    angular.element('#addZip').trigger('change');
10951            	}
10952            }
10953		}
10954		
10955		function _setValueForPromoEmails(){
10956			// Sets the value for promo-emails and e-receipts specific to the country.
10957			if (angular.isDefined(vm.customerData.cor)) {
10958    			var eOffersResult = signupService.geteOffersSupportedCountry(vm.customerData.cor);
10959			    //to display e-offers
10960		    	vm.eOffersDisplay = eOffersResult.supported;  
10961		    	//Default behaviour of e-offers checkbox
10962		    	if(vm.eOffersDisplay){
10963		    		if(angular.isDefined(vm.accountModel.profileIdentity) && angular.isDefined(vm.accountModel.profileIdentity.promotionalEmailOptin)){
10964		    			vm.accountModel.profileIdentity.promotionalEmailOptin = eOffersResult.optin;
10965		    		}
10966		    			
10967		    	}
10968		    	var eReceiptResult = signupService.geteReceiptSupportedCountry(vm.customerData.cor);
10969		    	//to display e-receipt
10970		    	vm.eReceiptDisplay = eReceiptResult.supported;
10971		    	
10972		    	//Default behaviour of e-receipt checkbox
10973		    	if(vm.eReceiptDisplay){
10974		    		if(angular.isDefined(vm.accountModel.profileIdentity) && angular.isDefined(vm.accountModel.profileIdentity.eRecieptEmailOptin)){
10975		    			vm.accountModel.profileIdentity.eRecieptEmailOptin = eReceiptResult.optin;
10976		    		}
10977		    		
10978		    	}
10979    		}
10980		}
10981		
10982		//checks for conflict and caches partnerCustomerInfo
10983        function _checkForPartnerCustomerInfo(){
10984        	vm.conflictedSection = "";
10985        	if(angular.isDefined(vm.customerData.partnerCustomerInfo) && !angular.equals({}, vm.customerData.partnerCustomerInfo)){
10986        		vm.hasPartnerInfo = true;
10987        		if(angular.isDefined(vm.customerData.enrollmentStep) && vm.customerData.enrollmentStep != "" && vm.customerData.conflictCDBPartnerFlag){
10988        			vm.conflictedSection = vm.customerData.enrollmentStep;
10989        			//when CC section is conflicted, drop the existing CC details
10990        			if(vm.conflictedSection == "credit-card-section"){
10991        				vm.customerData.ccSummary.expDate = '';
10992        				vm.customerData.ccSummary.number = '';
10993        				vm.customerData.ccSummary.type = '';
10994        			}
10995        		}        		
10996        	}else{
10997        		vm.hasPartnerInfo = false;
10998        	}
10999        }
11000        
11001        function getSuggestions(callbackInput, timeoutPromise, getListFromSession) {
11002            if (getListFromSession && vm.session && (vm.session.status === carRentalConstant.userStateAuthenticated || vm.session.status === carRentalConstant.userStateRecognized)) {
11003                var deferred = $q.defer();
11004                // Get List from session
11005                vm.suggestions = authenticationService.getPreviousRateShopModel();
11006                deferred.resolve(vm.suggestions);
11007                return deferred.promise;
11008            } else {
11009                if (callbackInput) {
11010                    if (callbackInput.userInputString.length > 83) {
11011                        callbackInput.userInputString = callbackInput.userInputString
11012                            .slice(0, 80);
11013                    }
11014                    var obj = {
11015                        userInputString: callbackInput.userInputString
11016                    };
11017                    if (angular.isDefined(callbackInput.lat) && angular.isDefined(callbackInput.lon)) {
11018                        obj["lat"] = callbackInput.lat;
11019                        obj["lon"] = callbackInput.lon;
11020                    }
11021
11022                    vm.suggestions = [];
11023                    var resultValue = locationService.loadLocation(obj);
11024                    resultValue.then(function(dataSet) {
11025                        if (dataSet && dataSet.data) {
11026                            vm.suggestions = dataSet.data.suggestions;
11027
11028                        }
11029                    });
11030                    return resultValue;
11031                } else {
11032                    var deferred = $q.defer();
11033                    deferred.reject({});
11034                    return deferred.promise;
11035                }
11036            }
11037        }
11038        
11039        function _loadCalendarDropdown() {
11040        	var lowerAgeLimit = vm.hasPartnerInfo ? ( angular.isDefined(vm.customerData.partnerCustomerInfo.minAge) ? vm.customerData.partnerCustomerInfo.minAge : carRentalConstant.ageLimit.lower )  : carRentalConstant.ageLimit.lower;
11041        	var CalendarDetails = accountUtilityService.loadCalendarDropdown(lowerAgeLimit);
11042            vm.monthsList = CalendarDetails.monthsList;
11043            vm.yearsList = CalendarDetails.yearsList;
11044            vm.datesList = CalendarDetails.datesList;
11045        }
11046
11047        function _loadEditSection(){
11048//come under one property
11049        	vm.addProperty= {
11050        			"awd":{},
11051        			"ccSummary":{},
11052        			"email":{},
11053        			"phone":{},
11054        			"Address":{},
11055        			"Car":{}
11056        	};
11057        	vm.phone = {};
11058        }
11059        //prefilling angucomplete in edit mode for frequent pickup location
11060        function _setFreqPickUpLoc() {
11061            if (vm.customerData && vm.customerData.freqPickUpLocation) {
11062                vm.travelPreferences.freqPickUpLocationDisp = "";
11063                var index = vm.customerData.freqPickUpLocation.indexOf(':');
11064                vm.travelPreferences.freqPickUpLocationDisp = vm.customerData.freqPickUpLocation.substring(index + 1, vm.customerData.freqPickUpLocation.length);
11065                vm.travelPreferences.frequentPickUpLocationInitial = vm.travelPreferences.freqPickUpLocationDisp
11066            }
11067        }
11068
11069        function _loadCarPreferenceList() {
11070        	if($window.location.href.indexOf("preferences") != -1){
11071        		var carGroupPreference;
11072            	var supportedCarList = angular.isDefined(vm.hasPartnerInfo) && angular.isDefined(vm.customerData.partnerCustomerInfo.carGroupPreferences) ? vm.customerData.partnerCustomerInfo.carGroupPreferences : "";
11073            	myProfileService.getCarPreferenceList(vm.customerData.cor,vm.customerData.carPreference,supportedCarList).then(function(carGroupPreference){
11074        			vm.carGroupPreferenceList = carGroupPreference.carList;
11075                    vm.carGroupPreferredName = carGroupPreference.selectedCar;
11076        		});
11077        	}
11078        }
11079        
11080        function saveProfile(phoneNumberModelName,phoneNumber,smsOptin,section,profileForm,Obj,e,index){
11081        	if(angular.isDefined(smsOptin) && (smsOptin==true || smsOptin=='T') && angular.isDefined(phoneNumber) && (vm.customerData.cor == "US" || vm.customerData.cor == "CA")){
11082        		vm.validatePhoneNumber(phoneNumberModelName,phoneNumber,smsOptin,section,profileForm,Obj,e,index);
11083        	}
11084        	else{
11085        		if(section == 'dl-section'){
11086        			vm.saveProfileDetail(profileForm,e);	
11087        		}
11088        		if(section == 'telephone-section' || section == 'address-telephone-section'){
11089        			if(vm.domain === 'AU' || vm.domain === 'NZ'){
11090        				if(angular.isDefined(phoneNumber)){
11091        					if(phoneNumber.startsWith('0000')){
11092        						vm.invalidPhoneNumber = true;
11093        						$rootScope.requestInProgress = false;
11094        						anchorSmoothScroll.scrollTo('profileAddressForm');
11095        					}
11096        					else{
11097        						vm.invalidPhoneNumber = false;
11098        						$rootScope.requestInProgress = true;
11099        					}
11100        				}
11101        				if(!vm.invalidPhoneNumber){
11102        					vm.saveDetails(profileForm,Obj,e,index);        				
11103        				}
11104        			}
11105        			else{
11106        				vm.saveDetails(profileForm,Obj,e,index);
11107        			}
11108        		}	
11109        	}
11110        	
11111        }
11112        
11113        function validatePhoneNumber(phoneNumberModelName,phoneNumber,smsOptin,section,profileForm,Obj,e,index) {
11114        		$rootScope.requestInProgress=true;
11115            	myProfileService.validatePhoneNumber(phoneNumberModelName,phoneNumber,smsOptin,section,vm.accountModel).then(function(data){
11116            		if ((angular.isDefined(data.errorList) && data.errorList.length > 0) || (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0)) {
11117                        $rootScope.requestInProgress = false;
11118                        if(section == 'dl-section'){
11119                        	 anchorSmoothScroll.scrollTo('email-offers');}
11120                        if(section == 'telephone-section' || section == 'address-telephone-section'){
11121                        	anchorSmoothScroll.scrollTo('profileAddressForm');
11122                        		
11123                        }
11124                    }
11125                    else{
11126                    	if(section == 'dl-section'){
11127                    		vm.saveProfileDetail(profileForm,e);
11128                				
11129                		}
11130                    	if(section == 'telephone-section' || section == 'address-telephone-section'){
11131                    		vm.saveDetails(profileForm,Obj,e,index);
11132                		}
11133                    	}
11134            	}, function(error) {
11135            		if(angular.isDefined(error.errorList) && error.errorList.length > 0){
11136            			vm.formError = error.errorList[0].message;
11137    	                vm.formValidated = true;
11138            		}
11139            		$rootScope.requestInProgress = false;
11140            	});      	
11141		}
11142
11143        function validatecurrentPasswordField(enableMask) {
11144            if (enableMask) {
11145                setTimeout(function() {
11146                    angular.element('#currentPasswordHide').blur();
11147                }, 5);
11148            } else {
11149                setTimeout(function() {
11150                    angular.element('#currentPasswordShow').blur();
11151                }, 5);
11152            }
11153        }
11154
11155        function validatenewPasswordField(enableMaskNpwd) {
11156            if (enableMaskNpwd) {
11157                setTimeout(function() {
11158                    angular.element('#newPasswordHide').blur();
11159                }, 5);
11160            } else {
11161                setTimeout(function() {
11162                    angular.element('#newPasswordShow').blur();
11163                }, 5);
11164            }
11165        }
11166
11167
11168        // To load the language list on site preference
11169        // TODO Should get this from AEM config
11170        function _loadLanguagePreference() {
11171            vm.siteLanguageDropDown = carRentalConstant.sitePreferenceLanguageList;
11172            if(vm.hasPartnerInfo && angular.isDefined(vm.customerData.partnerCustomerInfo.supportedLanguages) && (vm.customerData.partnerCustomerInfo.supportedLanguages.length > 0)){
11173            	var supportedLangList = vm.customerData.partnerCustomerInfo.supportedLanguages;
11174            	vm.siteLanguageDropDown = myProfileService.getSupportedLanguageList(vm.siteLanguageDropDown,supportedLangList)
11175            }
11176
11177            if (angular.isDefined(vm.customerData) && angular.isDefined(vm.customerData.preferences) && angular.isDefined(vm.customerData.preferences.siteLanguage)) {
11178                for (var i = 0; i < vm.siteLanguageDropDown.length; i++) {
11179                    if (vm.siteLanguageDropDown[i].code.toUpperCase() == vm.customerData.webCustomer.siteLanguage.toUpperCase()) {
11180                        vm.accountModel.siteLanguage = vm.siteLanguageDropDown[i].code;
11181                        vm.siteLanguage = vm.siteLanguageDropDown[i].value;
11182                    }
11183                }
11184
11185            }
11186            for (var i = 0; i < vm.countryList.length; i++) {
11187                if (vm.countryList[i].code.toUpperCase() == vm.customerData.webCustomer.siteCountry.toUpperCase()) {
11188                    vm.siteCountry = vm.countryList[i].name;
11189                }
11190            }
11191        }
11192
11193        // To load date and time drop down
11194        function _dateTimeFormatDropDown() {
11195            var dateTimeFormat = accountUtilityService.getDateTimeFormat();
11196            vm.dateFormat = dateTimeFormat.dateFormat;
11197            vm.timeFormat = dateTimeFormat.timeFormat;
11198            if (angular.isDefined(vm.customerData.preferences) && angular.isDefined(vm.customerData.preferences.timeFmt)) {
11199                for (var i = 0; i < vm.timeFormat.length; i++) {
11200                    if (vm.customerData.preferences.timeFmt == vm.timeFormat[i].code) {
11201                        vm.timeFormatToDisplay = vm.timeFormat[i].value;
11202                    }
11203                }
11204            }
11205        }
11206
11207        // To load month year drop down for CC section
11208        function _loadMnthYrDropdown() {
11209        	var expMonthYearList = accountUtilityService.loadMnthYrDropdown();
11210            vm.expMonths = expMonthYearList.expMonths;
11211            vm.expYears = expMonthYearList.expYears;
11212            var expDates = [{
11213            	"expMonth" : "",
11214            	"expMonthPreviewMode":"",
11215            	"expYear":"",
11216            	"expYearPreviewMode":""
11217            }]
11218            
11219            //TODO
11220          if(angular.isDefined(vm.accountModel.creditCardList) && vm.accountModel.creditCardList.length>=1){
11221        	  angular.forEach(vm.accountModel.creditCardList,function(ccSummary,key){
11222                  if (angular.isDefined(ccSummary) && angular.isDefined(ccSummary.expDate)) {
11223                  
11224                  		var expDate = ccSummary.expDate.split("/");
11225                          var index = vm.expMonths.indexOf($filter('filter')(vm.expMonths, function(d) {
11226                              return d.key == expDate[0];
11227                          })[0]);
11228                          if (index != -1) {
11229                        	// French Months object's Array is assigned to vm.expMonths for French Language
11230                          	if((window.locale=='fr_US' || window.locale=='fr_CA' || window.locale=='fr') && (window.brand === 'budget' || window.brand === 'avis')){
11231                          		vm.expMonths = frMonth;
11232                          	}         
11233                          	ccSummary.expMonth = vm.expMonths[index].key;
11234                          	ccSummary.expMonthPreviewMode = vm.expMonths[index].desc; // getting month in words to display in preview mode
11235                          }
11236                          ccSummary.expYear = expDate[2];
11237                          ccSummary.expYearPreviewMode = expDate[2]; // getting year to display in preview mode
11238                  	
11239                      
11240                  }
11241                  if(angular.isDefined(ccSummary) && angular.isDefined(ccSummary.creditCardToken)){
11242                  	ccSummary.creditCardToken = ccSummary.creditCardToken;
11243                  }
11244                  
11245                 })
11246          }
11247            if (angular.isDefined(vm.customerData.ccSummary) && angular.isDefined(vm.customerData.ccSummary.expDate)) {
11248                var expDate = vm.customerData.ccSummary.expDate.split("/");
11249                var index = vm.expMonths.indexOf($filter('filter')(vm.expMonths, function(d) {
11250                    return d.key == expDate[0];
11251                })[0]);
11252                if (index != -1) {
11253                	// French Months object's Array is assigned to vm.expMonths for French Language
11254                	if((window.locale=='fr_US' || window.locale=='fr_CA' || window.locale=='fr') && (window.brand === 'budget' || window.brand === 'avis')){
11255                		vm.expMonths = frMonth;
11256                	}         	
11257                	vm.customerData.ccSummary.expMonth = vm.expMonths[index].key;
11258                    vm.customerData.ccSummary.expMonthPreviewMode = vm.expMonths[index].desc; // getting month in words to display in preview mode       	   	
11259                }
11260                vm.customerData.ccSummary.expYear = expDate[2];
11261                vm.customerData.ccSummary.expYearPreviewMode = expDate[2]; // getting year to display in preview mode
11262            } 
11263          
11264        }
11265
11266
11267        // Based on the CC type show and hide CVV and ExpMonthYear field
11268        function onChangeCreditCardType(type) {
11269        if(angular.isDefined(vm.accountModel) && angular.isDefined(vm.accountModel.ccSummary) && angular.isDefined(vm.accountModel.credit
11269CardList) && vm.accountModel.creditCardList.length==1){
11270       		 if (vm.accountModel.ccSummary.type == 'AV') {
11271       	                vm.hideCVV = false;
11272       	            } else {
11273       	                vm.hideCVV = true;
11274       	            }
11275       	            if (vm.accountModel.ccSummary.type == 'AV') {
11276       	                vm.hideExpMonthYear = false;
11277       	            } else {
11278       	                vm.hideExpMonthYear = true;
11279       	            }
11280				    if (vm.accountModel.ccSummary.type == 'CX' || vm.accountModel.ccSummary.type == 'CM'
11281								|| vm.accountModel.ccSummary.type == 'CA' || vm.accountModel.ccSummary.type == 'CS'
11282								|| vm.accountModel.ccSummary.type == 'CJ' || vm.accountModel.ccSummary.type == 'CD') {
11283				    	vm.isCVVMandatory = true;
11284				    	
11285				    } else {
11286				    	vm.isCVVMandatory = false;
11287				    }
11288       	
11289        }
11290        if(angular.isDefined(vm.accountModel) && angular.isDefined(vm.accountModel.creditCardList) && vm.accountModel.creditCardList.length>=1){
11291        		angular.forEach(vm.accountModel.creditCardList,function(cards){
11292        			cards.hideCVV = true;
11293        			cards.hideExpMonthYear = true;
11294        			if (cards.type == 'AV') {
11295        	                cards.hideCVV = false;
11296        	            } else {
11297        	                cards.hideCVV = true;
11298        	            }
11299        	            if (cards.type == 'AV') {
11300        	                cards.hideExpMonthYear = false;
11301        	            } else {
11302        	                cards.hideExpMonthYear = true;
11303        	            }
11304        	            if (cards.type == 'CX' || cards.type == 'CM'	|| cards.type == 'CA' || cards.type == 'CS'
11305        	            	|| cards.type == 'CJ' || cards.type == 'CD') {
11306        	            	cards.isCVVMandatory = true;
11307        	            } else {
11308        	            	cards.isCVVMandatory = false;
11309        	            }
11310        		})
11311        	}
11312        if(angular.isDefined(type) && angular.isDefined(vm.addProperty) && angular.isDefined(vm.addProperty.ccSummary) && angular.isDefined(vm.addProperty.ccSummary.type)){
11313        	if (vm.addProperty.ccSummary.type == 'AV') {
11314	                vm.hideCVV = false;
11315	            } else {
11316	                vm.hideCVV = true;
11317	            }
11318	            if (vm.addProperty.ccSummary.type == 'AV') {
11319	                vm.hideExpMonthYear = false;
11320	            } else {
11321	                vm.hideExpMonthYear = true;
11322	            }
11323	            if(vm.addProperty.ccSummary.type == 'CX' || vm.addProperty.ccSummary.type == 'CM' || vm.addProperty.ccSummary.type == 'CA' || vm.addProperty.ccSummary.type == 'CS'
11324	            	|| vm.addProperty.ccSummary.type == 'CJ' || vm.addProperty.ccSummary.type == 'CD'){
11325	            	vm.isCVVMandatory = true;
11326	            }else{
11327	            	 vm.isCVVMandatory = false;
11328	            }
11329        }
11330           
11331        }
11332
11333        // Checking the condition to display credit card section
11334        function _setCreditCardSection() {
11335        	var result;
11336    		if(angular.isDefined(vm.customerData.ccSummary) && angular.isDefined(vm.customerData.ccSummary.supportedCctypes) && (vm.customerData.ccSummary.supportedCctypes.length > 0)){
11337    			result = myProfileService.getCreditCardDetails(vm.customerData.ccSummary);
11338        	}else if(angular.isDefined(vm.customerData.partnerCustomerInfo) && angular.isDefined(vm.customerData.partnerCustomerInfo.ccSummary) && angular.isDefined(vm.customerData.partnerCustomerInfo.ccSummary.supportedCctypes) && (vm.customerData.partnerCustomerInfo.ccSummary.supportedCctypes.length > 0)){
11339        		if(angular.isDefined(vm.customerData.ccSummary) && angular.isDefined(vm.customerData.ccSummary.type) && vm.customerData.ccSummary.type.length > 0){
11340        			vm.customerData.partnerCustomerInfo.ccSummary.type = vm.customerData.ccSummary.type;
11341        		}        		
11342        		result = myProfileService.getCreditCardDetails(vm.customerData.partnerCustomerInfo.ccSummary);
11343        	}else{
11344        		result = myProfileService.getCreditCardDetails()
11345        	}
11346    		vm.ccDetailList = result.masterListForCC;
11347        	if(angular.isDefined(result.customerCcDetails)){
11348        		vm.credtiCardSectionToDisplay = true;
11349        		vm.customerData.ccSummary.cardTypeValue= result.customerCcDetails.value;
11350        		vm.customerData.ccSummary.type = result.customerCcDetails.code;
11351        		vm.creditCardType = result.customerCcDetails.value;
11352            	vm.accountModel.type = result.customerCcDetails.code;
11353        	}
11354        	if(angular.isDefined(vm.accountModel.creditCardList)){        		
11355        		angular.forEach(vm.accountModel.creditCardList,function(ccSummary,key){
11356        			ccSummary.supportedCctypes = vm.customerData.ccSummary.supportedCctypes;
11357        			result = myProfileService.getCreditCardDetails(ccSummary);
11358        			if(angular.isDefined(result.customerCcDetails)){
11359        				vm.credtiCardSectionToDisplay = true;
11360        				ccSummary.cardTypeValue= result.customerCcDetails.value;
11361        				ccSummary.type = result.customerCcDetails.code;
11362        			}
11363                	
11364        		})
11365        	}
11366        	
11367    		
11368    		
11369    		
11370
11371
11372            /*Credit card section to be displayed in edit mode if user not updated yet*/
11373            if (!vm.credtiCardSectionToDisplay) {
11374                _showSectionInExpendedMode('credit-card-section');
11375            }
11376            //For Conflict Scenario - CC conflicted
11377            if(vm.customerData.conflictCDBPartnerFlag && (vm.conflictedSection == "credit-card-section")){
11378            	vm.credtiCardSectionToDisplay = false;
11379            	_showSectionInExpendedMode('credit-card-section');
11380            	vm.formValidated = true;
11381				vm.sectionInEdit = 'credit-card-section';
11382//				vm.formError = Granite.I18n.get('err.profile.ccConflictMsg');
11383				vm.formError = vm.customerData.errorList[0].message;
11384        	}
11385
11386        }
11387
11388        // To Set DL section to display
11389          function _setDlSection() {
11390        	vm.countryListForDriverLicense = accountUtilityService.getCountryList(vm.customerData, $window.countryListForDriverLicense);
11391            /*country/state code converted to name for DL Info with masked dl number*/
11392            if (angular.isDefined(vm.countryListForDriverLicense) && (vm.countryListForDriverLicense.length>0) && angular.isDefined(vm.customerData) && angular.isDefined(vm.customerData.dlSummary) && angular.isDefined(vm.customerData.dlSummary.dlNumber) && vm.customerData.dlSummary.dlNumber !== '') {
11393                ////&& angular.isDefined(vm.customerData.dlSummary.country) && angular.isDefined(vm.customerData.dlSummary.state) //TODO need to check for c
11393ountry and state
11394                vm.showDOBField = false;
11395            	vm.dlSectionDisplay = true;
11396                for (var i = 0; i < vm.countryListForDriverLicense.length; i++) {
11397                    if (vm.countryListForDriverLicense[i].code == vm.customerData.dlSummary.country) {
11398                        vm.dlCountryName = vm.countryListForDriverLicense[i].name;
11399                        var state = vm.countryListForDriverLicense[i].stateList;
11400                        for (var j = 0; j < state.length; j++) {
11401                            if (state[j].stateCode == vm.customerData.dlSummary.state) {
11402                                vm.dlStateName = state[j].stateName;
11403                            }
11404                        }
11405                    }
11406                }
11407            }else{
11408            	vm.showDOBField = true;
11409            }
11410            if(angular.isDefined(vm.customerData) && angular.isDefined(vm.customerData.dlSummary) && angular.isDefined(vm.customerData.dlSummary.country)){
11411            	vm.statesForDL = accountUtilityService.getStateListBasedOnCounty(vm.customerData.dlSummary.country, vm.countryListForDriverLicense).statesForDL;
11412            }else if(angular.isDefined(vm.accountModel.dlSummary.country)){
11413            	vm.statesForDL = accountUtilityService.getStateListBasedOnCounty(vm.accountModel.dlSummary.country,vm.countryListForDriverLicense).statesForDL;
11414            }
11415          //GRY-3012,hiding the state field if the selected country is not having states in DL section.
11416            vm.hideDLState= (angular.isUndefined(vm.statesForDL)|| vm.statesForDL[0].stateCode == "Not Applicable")?true:false;
11417            if(vm.hideDLState== true){
11418               vm.accountModel.dlSummary.state = "Not Applicable";
11419         	}
11420            /*DL section to be displayed in edit mode if user not yet updated DL details, but updated CC details*/
11421            if (vm.customerData.enrollmentStep == 'dl-section') {
11422                _showSectionInExpendedMode('dl-section');
11423                accountgaService.analyticsDimension(vm.customerData, 'driver-license');
11424            }
11425        }
11426        // Setting Protection and coverage section to display
11427        function _setProtectionCoverageSection() {
11428            var protectionStatus = angular.isDefined(myProfileService.getCreateStatus()) ? myProfileService.getCreateStatus().protectionStatus : "";
11429            if (!protectionStatus) {
11430                if (angular.isDefined(vm.customerData.insuranceMap)) {
11431                    angular.forEach(vm.customerData.insuranceMap, function(insurance) {
11432                        if (angular.equals(insurance.value, true)) {
11433                            vm.insuranceOpted = true;
11434                        }
11435                    });
11436                    if (vm.dlSectionDisplay && !vm.customerData.preferred && !vm.insuranceOpted) {
11437                        _showSectionInExpendedMode('protections-coverages-section'); // will be shown in expanded mode
11438                        vm.protectionCoverageSectionDisplay = false;
11439                        if(angular.isDefined(vm.customerData.profileCompletionPercentage) && vm.customerData.profileCompletionPercentage >= 50 && vm.customerData.profileCompletionPercentage <= 70) {
11440                          accountgaService.analyticsDimension(vm.customerData, 'protections-coverages');                        	
11441                        }
11442                    } else {
11443                        vm.protectionCoverageSectionDisplay = true;
11444                    }
11445                }
11446            } else {
11447                vm.protectionCoverageSectionDisplay = true;
11448            }
11449            //For Conflict Scenario - PnC conflicted
11450        	if(vm.customerData.conflictCDBPartnerFlag && (vm.conflictedSection == "protections-coverages-section")){
11451        		_showSectionInExpendedMode('protections-coverages-section');
11452                vm.protectionCoverageSectionDisplay = false;
11453                vm.formValidated = true;
11454				vm.sectionInEdit = 'protections-coverages-section';
11455//				vm.formError = Granite.I18n.get('err.profile.insuranceConflictMsg');
11456				vm.formError = vm.customerData.errorList[0].message;
11457        	}
11458        }
11459        // Setting Terms and Conditions section to display
11460        function _setTermsConditionSection() {
11461            var protectionStatus = angular.isDefined(myProfileService.getCreateStatus()) ? myProfileService.getCreateStatus().protectionStatus : "";
11462            if ((protectionStatus || vm.insuranceOpted) && vm.customerData.preferred == false && vm.dlSectionDisplay && vm.credtiCardSectionToDisplay && (vm.conflictedSection != "protections-coverages-section")) {
11463                vm.termsConditionSectionDisplay = true;
11464                accountgaService.analyticsDimension(vm.customerData, 'terms-and-condition');
11465            } else {
11466                vm.termsConditionSectionDisplay = false;
11467                if(angular.isDefined(vm.customerData.profileCompletionPercentage) && vm.customerData.profileCompletionPercentage == 80) {
11468                  accountgaService.analyticsDimension(vm.customerData, 'terms-and-condition');
11469                }
11470            }
11471        }
11472
11473        /*will return all partner details*/
11474        function _getPartnerDetails() {
11475            myProfileService.getPartnerDetails().then(function(data) {
11476                if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0 &&
11477                    angular.isDefined(data.errorList) && data.errorList.length > 0) {
11478                    data = $scope.processErrorMessage(data);
11479                } else {
11480                    vm.partnerDetails = data;
11481                }
11482                if (vm.customerData.preferred == true && vm.customerData.enrollmentStep == 'enroll-rewards-section' && vm.customerData.loyaltyEligible.visible) {
11483                	vm.accountModel.program.pointsProgram = true;
11484                	vm.accountModel.program.partnerProgram = false;
11485                }
11486            }, function(error) {
11487            	if (vm.customerData.preferred == true && vm.customerData.enrollmentStep == 'enroll-rewards-section' && vm.customerData.loyaltyEligible.visible) {
11488            		vm.accountModel.program.pointsProgram = true;
11489            		vm.accountModel.program.partnerProgram = false;
11490                }
11491            });
11492        }
11493
11494        /*will set enrolment section on create flow*/
11495        function _setEnrollRewardsSection() {
11496            /*if user not selected yet*/
11497            if (vm.customerData.preferred == true && vm.customerData.enrollmentStep == 'enroll-rewards-section' && vm.customerData.loyaltyEligible.visible) {
11498                vm.displayFTPSection = true;
11499                _getPartnerDetails();
11500                _showSectionInExpendedMode('enroll-rewards-section');
11501                accountgaService.analyticsDimension(vm.customerData, '');
11502                vm.rewardsSectionDisplay = true;
11503                if(angular.isDefined(vm.getAvisPreferredTermsList) && vm.getAvisPreferredTermsList != ''){
11504                	if(!vm.customerData.expressConsentTerms){
11505                		vm.rewardPreferredTnC = false;
11506                	}else{
11507                		vm.showTnCModal = getVehicles.gettermsMapURL(vm.getAvisPreferredTermsList, vm.domain)+'.partial.html';
11508                    	vm.rewardPreferredTnC = true;
11509                    	vm.accountModel.showConnectedCarTncModal = true;   
11510                	}
11511                }
11512            } else {
11513            	if(!vm.customerData.loyaltyEligible.visible){
11514            		_getPartnerDetails();
11515            	}
11516            	if(angular.isDefined(vm.customerData.profileCompletionPercentage) && vm.customerData.profileCompletionPercentage == 100) {
11517            		accountgaService.analyticsDimension(vm.customerData, '');
11518            	}
11519                vm.rewardsSectionDisplay = false;
11520            }
11521        }
11522        
11523        // Setting zipcode, city and state fields after making selection from address suggestions
11524        function selectAddress(suggestion, suggestionType) {
11525        	if(angular.isDefined(vm.addProperty.Address.address1)||angular.isDefined(vm.addProperty.Address.zipCode)){
11526        		if (suggestionType === carRentalConstant.address) {
11527                    if (angular.isDefined(suggestion.address.postalCode)) {
11528                    	vm.addProperty.Address.zipCode = suggestion.address.postalCode;
11529                        angular.element('#addZip').val(suggestion.address.postalCode);
11530                        angular.element('#addZip').trigger('change');
11531                        setTimeout(function() {
11532    		    	          angular.element('#addZip').blur();
11533    		    	        }, 5);
11534                    }
11535                }
11536        		if (angular.isDefined(suggestion.address.locality)) {
11537        			vm.addProperty.Address.city = suggestion.address.locality;
11538        			vm.cityDisplay = true;
11539                }
11540                if (angular.isDefined(suggestion.address.adminDistrict)) {
11541                    var selectedState = $filter('filter')(vm.statesForCountry, {
11542                        stateCode: suggestion.address.adminDistrict
11543                    }, true)[0];
11544                    var index = vm.statesForCountry.indexOf(selectedState);
11545                    if (index > -1) {
11546                        vm.addProperty.Address.state = vm.statesForCountry[index].stateCode
11547                    }
11548                }
11549                if (angular.isDefined(suggestion.address3) && suggestion.address3.length > 0) {
11550                    vm.displayAddressLine3 = true;
11551                } else {
11552                    vm.displayAddressLine3 = false;
11553                }
11554                
11555        		
11556        	}
11557        	angular.forEach(vm.accountModel.contactAddress.address,function(address){
11558        	if((/^[a-zA-Z0-9 ]*$/.test(address.address1))|| (/^[a-zA-Z0-9 ]*$/.test(address.zipCode))){
11559        	    if (suggestionType === carRentalConstant.address) {
11560                    if (angular.isDefined(suggestion.address.postalCode)) {
11561                        address.zipCode = suggestion.address.postalCode;
11562                        angular.element('#zip'+address.maskId).val(suggestion.address.postalCode);
11563                        angular.element('#zip'+address.maskId).trigger('change');
11564                        setTimeout(function() {
11565    		    	          angular.element('#zip'+address.maskId).blur();
11566    		    	        }, 5);
11567                    }
11568                }
11569                if (angular.isDefined(suggestion.address.locality)) {
11570                    address.city = suggestion.address.locality;
11571                }
11572                if (angular.isDefined(suggestion.address.adminDistrict)) {
11573                    var selectedState = $filter('filter')(address.statesForCountry, {
11574                        stateCode: suggestion.address.adminDistrict
11575                    }, true)[0];
11576                    var index = address.statesForCountry.indexOf(selectedState);
11577                    if (index > -1) {
11578                        address.state = address.statesForCountry[index].stateCode
11579                    }
11580                }
11581                if (angular.isDefined(suggestion.address3) && suggestion.address3.length > 0) {
11582                    vm.displayAddressLine3 = true;
11583                } else {
11584                    vm.displayAddressLine3 = false;
11585                }
11586        	}
11587        	})
11588        	
11589        }
11590        
11591        function clearAddress(suggestionType){
11592        	if(suggestionType === carRentalConstant.address){
11593      			angular.element('#zip').val("");
11594      			angular.element('#zip').trigger('change');
11595      			vm.accountModel.contactAddress.address.address1 = "";
11596      			vm.accountModel.contactAddress.address.address2 = "";
11597      			vm.accountModel.contactAddress.address.address3 = "";
11598      			vm.accountModel.contactAddress.address.suburb = "";
11599      		}
11600        	vm.accountModel.contactAddress.address.zipCode = "";
11601        	vm.accountModel.contactAddress.address.city = "";
11602        	vm.accountModel.contactAddress.address.state = "";
11603        }
11604        
11605        // Loading country list from sightly component.
11606        function _loadCountry() {
11607        	vm.countryList = accountUtilityService.getCountryList(vm.customerData);
11608        	vm.accountModel.dlSummary.country = (angular.isDefined(vm.customerData.dlSummary) && angular.isDefined(vm.customerData.dlSummary.country)) ? vm.customerData.dlSummary.country : vm.customerData.cor;
11609        	angular.forEach(vm.accountModel.contactAddress.address,function(address){
11610        		getStateBasedOnCounty(address,'',true);
11611               
11612        	});
11613        	 if (vm.customerData.cor == "US" || vm.customerData.cor == "CA") {
11614                 vm.showSmsOptIn = true;
11615             } else {
11616                 vm.showSmsOptIn = false;
11617             }
11618            
11619        }
11620        function _loadDefaultCountry(e){
11621        	//vm.Address.country = vm.accountModel.contactAddress.address[0].adrTelCountryName;
11622        	vm.countryList = accountUtilityService.getCountryList(vm.customerData);
11623        	if(angular.isDefined(vm.countryList)){
11624				var index = vm.countryList.indexOf($filter('filter')(
11625						vm.countryList,
11626						function(d) {
11627							return d.code === vm.accountModel.contactAddress.address[0].country;
11628						})[0]);
11629				if(index > -1){
11630					vm.addProperty.Address.country = vm.countryList[index].code;
11631				}
11632			}
11633        	var editSection = myProfileService.getSectionInEdit(e);
11634        	if(angular.isDefined(vm.customerData) && angular.isDefined(vm.customerData.dlSummary) && angular.isDefined(vm.customerData.dlSummary.country) && editSection == "dl-section"){
11635                vm.sectionInEdit ="dl-section"; 
11636                loadGetStateBasedOnCounty(vm.accountModel.dlSummary.country);
11637        	}
11638        	else{
11639  	   		loadGetStateBasedOnCounty(vm.accountModel.contactAddress.address[0].country);
11640        	}
11641       
11642            }
11643
11644
11645        // Load states depending on domain and on change of country drop down
11646        function loadGetStateBasedOnCounty(countryCode, countryListForDriverLicense) {
11647            var countryAndState = {};
11648            if(angular.isDefined(countryListForDriverLicense) && countryListForDriverLicense.length > 0){
11649				countryAndState = accountUtilityService.getStateListBasedOnCounty(countryCode, countryListForDriverLicense);
11650            }else{
11651				countryAndState = accountUtilityService.getStateListBasedOnCounty(countryCode, vm.countryList);
11652            }
11653            vm.adrTelCountryName = countryAndState.countryName;
11654            vm.statesForCountry = countryAndState.statesForCountry;
11655            vm.statesForDL = countryAndState.statesForDL;
11656          //GRY-3012,hiding the state field if the selected country is not having states in DL section.
11657            vm.hideDLState = ((angular.isUndefined(vm.statesForDL) || vm.statesForDL[0].stateCode == "Not Applicable") && (vm.customerData.enrollmentStep == "dl-section" || vm.sectionInEdit =="dl-section"))? true:false;
11658            if(vm.hideDLState== true){
11659           		vm.accountModel.dlSummary.state = "Not Applicable";
11660           		}
11661            	
11662            showZipCode(countryCode);
11663            
11664          //set default state dropdown value:
11665            if(angular.isDefined(vm.accountModel.dlSummary.state)&& angular.isDefined(vm.statesForDL) && (vm.accountModel.dlSummary.state == "Not Applicable" && vm.statesForDL.length >1)){
11666				vm.accountModel.dlSummary.state = null;
11667			}
11668        }
11669        function showZipCode(countryCode) {
11670            // check for city - show for CA, PR, US and VI (CX and CV)
11671            if (countryCode == carRentalConstant.countryCodeCA || countryCode == carRentalConstant.countryCodePR ||
11672                countryCode == carRentalConstant.countryCodeUS || countryCode == carRentalConstant.countryCodeCX ||
11673                countryCode == carRentalConstant.countryCodeCV || countryCode == carRentalConstant.countryCodeVI) {
11674                vm.showCity = true;
11675            } else {
11676                vm.showCity = false;
11677            }
11678
11679            // check for state - show for AU, CA, US and NZ
11680            if (countryCode == carRentalConstant.countryCodeAU || countryCode == carRentalConstant.countryCodeCA ||
11681                countryCode == carRentalConstant.countryCodeUS) {
11682                vm.showState = true;
11683            } else {
11684                vm.showState = false;
11685            }
11686            if (countryCode == carRentalConstant.countryCodeNZ) {
11687                vm.showCity = true;
11688            }
11689            // check for suburb - show for AU and NZ
11690            if (countryCode == carRentalConstant.countryCodeAU || countryCode == carRentalConstant.countryCodeNZ) {
11691                vm.showSuburb = true;
11692            } else {
11693                vm.showSuburb = false;
11694            }
11695
11696            // check for zipcode - show for AU, CA, NZ, PR, US and VI (CX CV)
11697            if (vm.showSuburb || vm.showCity) {
11698                vm.showZipcode = true;
11699            } else {
11700                vm.showZipcode = false;
11701            }
11702        }
11703
11704
11705        // Load states depending on domain and on change of country drop down
11706        // Need to refactor this duplicate code getStateBasedOnCounty &  loadGetStateBasedOnCounty
11707        function getStateBasedOnCounty(address,countryList,flagOnLoad) {
11708        	if(flagOnLoad){
11709        		var countryAndState = accountUtilityService.getStateListBasedOnCounty(address.country, vm.countryList);
11710            	address.adrTelCountryName= countryAndState.countryName;
11711                address.statesForCountry = countryAndState.statesForCountry;
11712                address.statesForDL = countryAndState.statesForDL;
11713            	displayZipCityState(address);
11714            	//GRY-3012,hiding the state field if the selected country is not having states in DL section.
11715            	vm.hideDLState = ((angular.isUndefined(address.statesForDL) || address.statesForDL[0].stateCode == "Not Applicable") && (vm.customerData.enrollmentStep == "dl-section" || vm.sectionInEdit =="dl-section"))? true:false;
11716                if(vm.hideDLState== true){
11717                 vm.accountModel.dlSummary.state = "Not Applicable";
11718                }
11719            	//set default state and country dropdown value:
11720                if(angular.isDefined(vm.accountModel.dlSummary.state)&& angular.isDefined(address.statesForDL) && (vm.accountModel.dlSummary.state == "" && address.statesForDL.length >1)){
11721    				vm.accountModel.dlSummary.state = null;
11722    			}
11723                
11724        	} else {
11725        		loadGetStateBasedOnCounty(address)
11726        	}
11727        }
11728
11729        //TODO Get this from webapi
11730        // Based on county show n=and hide city, sate and suburb
11731        function displayZipCityState(address) {
11732            // check for city - show for CA, PR, US and VI (CX and CV)
11733            if (address.country == carRentalConstant.countryCodeCA || address.country == carRentalConstant.countryPR ||
11734            		address.country == carRentalConstant.countryCodeUS || address.country == carRentalConstant.countryCodeCX ||
11735            		address.country == carRentalConstant.countryCodeCV || address.country == carRentalConstant.countryCodeVI) {
11736            	address.showCity = true;
11737            } else {
11738            	address.showCity = false;
11739            }
11740
11741            // check for state - show for AU, CA, US and NZ
11742            if (address.country == carRentalConstant.countryCodeAU || address.country == carRentalConstant.countryCodeCA ||
11743            		address.country == carRentalConstant.countryCodeUS) {
11744            	address.showState = true;
11745            } else {
11746            	address.showState = false;
11747            }
11748            if (address.country == carRentalConstant.countryCodeNZ) {
11749            	address.showCity = true;
11750            }
11751            // check for suburb - show for AU and NZ
11752            if (address.country == carRentalConstant.countryCodeAU || address.country == carRentalConstant.countryCodeNZ) {
11753            	address.showSuburb = true;
11754            } else {
11755            	address.showSuburb = false;
11756            }
11757
11758            // check for zipcode - show for AU, CA, NZ, PR, US and VI (CX CV)
11759            if (address.showSuburb || address.showCity) {
11760            	address.showZipcode = true;
11761            } else {
11762            	address.showZipcode = false;
11763            }
11764        }
11765        /*clears all the ftp fields*/
11766        function clearFtpDetails(partner) {
11767        	vm.accountModel = rewardsProgramService.clearFtpDetails(vm.accountModel,partner);
11768            vm.formValidated = false;
11769        }
11770        
11771        function setFtpEnrollment(){
11772        	vm.accountModel.program.partnerProgram = true;
11773        	vm.accountModel.program.pointsProgram = false;
11774        	vm.isFtpEnrollmentFlow = true;
11775        	vm.rewardsSectionDisplay = false;
11776        	//check this condition
11777            if (vm.customerData.cor == carRentalConstant.countryCodeAU || vm.customerData.cor == carRentalConstant.countryCodeNZ) {
11778                vm.displayPromoField = true;
11779            }
11780        }
11781       /* Pre-otp changes starts*/
11782        function custDetailsUpdate(){
11783        	var customerData = vm.customerData;
11784        	var accountModel = vm.accountModel;
11785        	vm.reqField = false;
11786        	vm.sectionInEdit = 'customer-details-section';
11787        	if(vm.sectionInEdit =='customer-details-section'){
11788        			if(customerData.contacts.email[0]  != undefined && angular.isDefined(customerData.contacts.phoneNumbers)){
11789        				accountModel.enteredEmail = vm.custDetailsUpdateEmail;
11790          				accountModel.emailMaskId = '1';
11791          				accountModel.primaryEmail = 'true';
11792          				accountModel.emailOperation ='update'
11793          				accountModel.enteredPhone = customerData.contacts.cellPhone;
11794          				accountModel.primaryPhoneNo = 'true';
11795          				accountModel.phoneMaskId = '1';
11796          				accountModel.phoneOperation ='update' 	
11797              		}
11798        			else if(customerData.contacts.email[0] != undefined && !(angular.isDefined(customerData.contacts.phoneNumbers))) {
11799        				accountModel.enteredEmail = customerData.contacts.email[0].email;
11800        				accountModel.emailMaskId = '1';
11801        				accountModel.primaryEmail = 'true';
11802        				accountModel.emailOperation ='update'
11803        				if(angular.isDefined(vm.modelPhoneNumber) && vm.modelPhoneNumber != ""){
11804        					accountModel.enteredPhone = vm.modelPhoneNumber;
11805        				}else{
11806        					vm.reqField = true;  				
11807            				jQuery('#phoneReqError')[0].innerHTML="<span class='error'>" + Dictionary.I18n.get('117') + " </span>";
11808            				if(vm.reqField && (jQuery('#phoneReqError')[0].innerText) != ''){
11809            					jQuery('.platform-error-message').hide();
11810            				}	
11811        				}
11812        				accountModel.primaryPhoneNo = 'true';
11813        				accountModel.phoneMaskId = ' ';
11814        				accountModel.phoneOperation ='add';	
11815              		}
11816        			else if(customerData.contacts.email[0] == undefined && angular.isDefined(customerData.contacts.phoneNumbers)) {
11817        				if(angular.isDefined(vm.modelEmailAddress) && vm.modelEmailAddress != ""){
11818        					accountModel.enteredEmail = vm.modelEmailAddress;
11819        				}else{
11820        					vm.reqField = true;	
11821        					jQuery('#emailAddErr')[0].innerHTML="<span class='error'>" +Dictionary.I18n.get('err.res.checkout.email.required') + "</span>";
11822            				if(vm.reqField && (jQuery('#emailAddErr')[0].innerText) != ''){
11823            					jQuery('.platform-error-message').hide();
11824            				}
11825        				}
11826        				accountModel.emailMaskId = ' ';
11827        				accountModel.primaryEmail = 'true';
11828        				accountModel.emailOperation ='add'
11829        				accountModel.enteredPhone = customerData.contacts.cellPhone;
11830        				accountModel.primaryPhoneNo = 'true';
11831        				accountModel.phoneMaskId = '1';
11832        				accountModel.phoneOperation ='update'	
11833        			}
11834        			else{
11835        				if(angular.isDefined(vm.modelEmailAddress) && vm.modelEmailAddress != ""){
11836            				accountModel.enteredEmail = vm.modelEmailAddress;
11837            				}else{
11838            					vm.reqField = true;
11839            					jQuery('#emailAddErr')[0].innerHTML="<span class='error'>" +Dictionary.I18n.get('err.res.checkout.email.required') + "</span>";
11840                				if(vm.reqField && (jQuery('#emailAddErr')[0].innerText) != ''){
11841                					jQuery('.platform-error-message').hide();
11842                				}		
11843            				}
11844        				accountModel.emailMaskId = ' ';
11845        				accountModel.primaryEmail = 'true';
11846        				accountModel.emailOperation ='add'
11847        				if(angular.isDefined(vm.modelPhoneNumber) && vm.modelPhoneNumber != ""){
11848        					accountModel.enteredPhone =  vm.modelPhoneNumber;
11849                			}else
11849{
11850                				vm.reqField = true;    				
11851                				jQuery('#phoneReqError')[0].innerHTML="<span class='error'>" + Dictionary.I18n.get('117') + " </span>";
11852                				if(vm.reqField && (jQuery('#phoneReqError')[0].innerText) != ''){
11853                					jQuery('.platform-error-message').hide();
11854                				}		
11855                			}
11856        				accountModel.primaryPhoneNo = 'true';
11857        				accountModel.phoneMaskId = ' ';
11858        				accountModel.phoneOperation ='add'
11859        			}
11860        	       	   	setTimeout(function() {
11861        	       	   		myProfileService.updateProfile(customerData,accountModel,vm.sectionInEdit).then(function(data){ 
11862        	       	   			data = $scope.processErrorMessage(data);
11863        	       	   			if ((angular.isDefined(data.errorList) && data.errorList.length > 0)) {
11864        	       	   				if(angular.isDefined(data.fieldErrors) && data.fieldErrors[0].classifier == "invalid"){
11865        	       	   					jQuery('#invalidEmailMessage')[0].innerHTML = "<span class='error'>" +Dictionary.I18n.get('err.res.checkout.email.invalid') +"</span>";
11866        	       	   			}
11867        	       	   				$rootScope.requestInProgress = false;    	                   	
11868        	       	   			}else{
11869        	       	   				vm.customerData = data;
11870        	       	   				$rootScope.requestInProgress = false;
11871        	       	   				jQuery('.customer-details-modal').modal('hide');
11872        	       	   				$('.modal-backdrop').remove();
11873        	            			jQuery('.confirmed-modal').modal('show');
11874        	       	   			}
11875        	       	   		}, 	function(error) {
11876        	       	   				$rootScope.requestInProgress = false;
11877        	       	   		});
11878        	           	},100);
11879        			}      
11880        		}
11881        function reloadPage(){
11882        	$window.location.reload(true);
11883        }
11884        function clearEmailPhoneError(){
11885       	 $("#phoneReqError").find('span').remove();
11886       	 $("#emailAddErr").find('span').remove();
11887       	 $("#invalidEmailMessage").find('span').remove();
11888       }
11889        /* Pre-otp changes ends*/
11890        
11891        /*save details in my profile and preferences section */
11892        function saveDetails(profileForm,Obj,e,index){
11893      	  _getSectionInEdit(e);
11894      	  // EP Change Start
11895      	  vm.showDelete=false;
11896      	  var tempaccountModel = vm.accountModel;
11897             if(angular.isDefined(vm.accountModel.awd)&&  (vm.accountModel.awd.length>0)){
11898                 var tempdiscountnumber = vm.accountModel.awd[0].discountNumber;
11899
11900            }
11901      	  if(angular.isDefined(Obj.number))
11902      	{
11903      		  if(Obj.number.indexOf("*") == -1)
11904      			  {
11905  		  	vm.showMessage = true;
11906  		  }
11907  	  else
11908  		  {
11909  		  vm.showMessage = false;
11910  		  }
11911      	}
11912        	
11913        	// EP change end
11914      	if(angular.isDefined(Obj.maskId) && Obj.maskId!="" && vm.sectionInEdit!='address-telephone-section' && vm.sectionInEdit != 'amazon-discount-section'){
11915      		Obj.operation ='update';
11916      	}else if(vm.sectionInEdit != 'amazon-discount-section'){
11917      		Obj.operation ='add';
11918      		Obj.maskId = "";
11919      	}
11920		if(vm.sectionInEdit == 'discount-number-section' && angular.isDefined(vm.accountModel.tempAwdList) && vm.accountModel.tempAwdList.length>0  && vm.accountModel.tempAwdList[0].discountNumber === '' && angular.isDefined(vm.accountModel.awd)&&  (vm.accountModel.awd.length>0)){
11921			Obj.operation ='delete';
11922			  Obj.maskId = 1;
11923			Obj.discountNumber = tempdiscountnumber;
11924			Obj.primary = true;
11925
11926		}
11927      	if(vm.sectionInEdit =='address-telephone-section'){
11928      		if(angular.isDefined(Obj.address[0].maskId) && Obj.address[0].maskId!=""){
11929      			Obj.address[0].operation ='update';
11930      		}else{
11931      			Obj.address[0].operation ='add';
11932      			Obj.address[0].maskId="";
11933      		}
11934      		if(angular.isDefined(Obj.telephone) && Obj.telephone!=""  && angular.isDefined(Obj.telephone[0].maskId) && Obj.telephone[0].maskId!=""){
11935      			Obj.telephone[0].operation ='update';
11936      			Obj.telephone[0].smsOptIn=(angular.isDefined(Obj.telephone[0].smsOptIn)&& Obj.telephone[0].smsOptIn== true)?"T":"N";
11937      		}else if(angular.isDefined(Obj.telephone) && Obj.telephone!=""){
11938      			Obj.telephone[0].operation ='add';
11939      			Obj.telephone[0].maskId="";
11940      			Obj.telephone[0].smsOptIn=(angular.isDefined(Obj.telephone[0].smsOptIn)&& Obj.telephone[0].smsOptIn== true)?"T":"N";
11941      			Obj.telephone[0].primary = true;
11942      		}
11943      	}
11944      	if(vm.sectionInEdit == 'amazon-discount-section'){
11945      		angular.forEach(vm.accountModel.awd,function(awdList){
11946      			if(awdList.maskId=='-1'){
11947      				awdList.primary = vm.amazonPrimaryValue;
11948      				awdList.operation = 'update';
11949      				 var Objlist = [];
11950             		  	Objlist.push(awdList);
11951             		  	Obj= Objlist;
11952      			}
11953      		})
11954      	}
11955      	  if(vm.sectionInEdit=='identity-password-section'){
11956      		Obj.promoMails=(angular.isDefined(Obj.promoMails)&& Obj.promoMails== true)?"Y":"N";
11957      		Obj.eRecieptEmailOptin = ((vm.customerData.cor == carRentalConstant.countryCodeUS || vm.customerData.cor == carRentalConstant.countryCodeCA) || (angular.isDefined(Obj.eRecieptEmailOptin) && Obj.eRecieptEmailOptin==true)) ? "Y" : "N";
11958      	  }
11959      	  if(vm.sectionInEdit=='discount-number-section' && !(angular.isDefined(Obj.primary)) && vm.accountModel.awd.length>=1 ){
11960      		  Obj.primary = false;
11961      	  }
11962      	  if(vm.sectionInEdit=='car-preference-section' && !(angular.isDefined(Obj.primary)) && vm.accountModel.carPreference.length>=1 ){
11963      		  Obj.primary = false;
11964      	  }
11965      	  if(vm.sectionInEdit=='telephone-section'){
11966        		Obj.smsOptIn=(angular.isDefined(Obj.smsOptIn)&& Obj.smsOptIn== true)?"T":"N";
11967        	  }
11968      	  if(vm.sectionInEdit=='telephone-section' && angular.isUndefined(Obj.primary) &&  (vm.customerData.contacts.phoneNumbers=='' ||vm.customerData.contacts.phoneNumbers == undefined) ){
11969      		  Obj.primary = true;
11970      	  }
11971      	  if(vm.sectionInEdit=='discount-number-section' && Obj.operation == 'add' && vm.accountModel.awd.length<1){
11972      		  Obj.primary = true;
11973      	  }
11974      	  if(vm.sectionInEdit=='car-preference-section' && Obj.operation == 'add' && vm.accountModel.carPreference.length<1){
11975      		  Obj.primary = true;
11976      	  }
11977      	  if(vm.sectionInEdit=='discount-number-section'){
11978      		  var Objlist = [];
11979      		  Objlist.push(Obj);
11980      		  Obj= Objlist;
11981			  
11982			  if ($window.brand === carRentalConstant.brandName.AVIS && Obj[0].operation === 'add') {
11983				for (var i = 0; i < vm.customerData.awd.length; i++) {
11984				  if (vm.customerData.awd[i].discountNumber === "J328400") {
11985					var marketingAWDObj = vm.customerData.awd[i];
11986					marketingAWDObj.operation = "delete";
11987					// If Avis marketing AWD (J328400) is already present in the profile, adding new AWD will be considered as an update action (Updating marketing AWD with new AWD)
11988					Obj[0].operation = "update";
11989					// Assigning the properties of existing marketing AWD to new AWD
11990					Obj[0].genericPartnerAWD = marketingAWDObj.genericPartnerAWD;
11991					Obj[0].maskId = marketingAWDObj.maskId;
11992					Obj[0].selected = marketingAWDObj.selected;
11993					Obj.push(marketingAWDObj);
11994					break;
11995				  }
11996				}
11997			  }
11998      	  }
11999      	   if((vm.sectionInEdit == 'credit-card-section')){
12000					vm.updateProfileCC.submit(profileForm,Obj,e,index);
12001					if(angular.isDefined(vm.formError)){
12002 	                	document.getElementById('profileAvisCreditCardForm').scrollIntoView();
12003 	                }
12004			   }
12005			   if(!(vm.sectionInEdit == 'credit-card-section')){
12006      	  $validationProvider.validate(profileForm).success(function(){
12007             	$rootScope.requestInProgress = true;          
12008             	myProfileService.updateProfile(vm.customerData,Obj,vm.sectionInEdit).then(function(data){ 
12009                     data = $scope.processErrorMessage(data);
12010                     if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
12011                     	
12012                     	/*
12013                     	 * Error message for age limit in MPf flow varies depen
12013ding  on AWD rules.
12014                     	 * i18n for the error includes an angular expression to generate message dynamically.
12015                     	 * It needs $scope.$eval method to parse where other messages throw console error for $scope.$eval. 
12016                     	 * So added below condition check.
12017                     	 */
12018                     	if(data.errorList[0].code == '06042'){
12019                     		vm.formError = $scope.$eval(data.errorList[0].message);
12020                     	}else{
12021                     		vm.formError = data.errorList[0].message;
12022                     	}
12023                     	if(data.errorList[0].code == '17414'){
12024                     		vm.cdhError = 'Your details were not saved,please try again.';
12025                     	}
12026                         vm.formValidated = true;
12027                         vm.showUpdateMsg = false;
12028                         $rootScope.requestInProgress = false;
12029                         vm.updateCdhUnAvailable(data);
12030                         if(!vm.formValidated && vm.cdhError){
12031                         	myProfileService.anchorToMsg(vm.sectionInEdit,index);
12032                         }  
12033                     }else{
12034                         vm.customerData = data;
12035                         
12036                         vm.formValidated = false;
12037                         vm.showUpdateMsg = true;
12038                         vm.showSuccessMsg = true;
12039                         $rootScope.requestInProgress = false;
12040                         vm.updateCdhUnAvailable(data);
12041                         myProfileService.anchorToMsg(vm.sectionInEdit,index);
12042                         editSection(false);
12043                         onSectionUpdate();
12044                         $('.add-'+vm.sectionInEdit).modal("hide");
12045                         $('body').removeClass('modal-open');
12046                         //ALM-508 changes 
12047                         if(enableCaptcha == 'true'){
12048								ABG.resetCaptcha(true);
12049								}
12050                         }
12051             	}, function(error) {
12052             		if(angular.isDefined(error.errorList) && error.errorList.length > 0){
12053             			vm.formError = error.errorList[0].message;
12054             			vm.updateCdhUnAvailable(data);
12055     	                vm.formValidated = true;
12056     	                vm.showSuccessMsg = false;
12057             		}
12058             		Obj.secureCode ='';
12059             		if(!vm.formValidated && vm.cdhError){
12060                  	myProfileService.anchorToMsg(vm.sectionInEdit,index);
12061                  }  
12062             		$rootScope.requestInProgress = false;
12063             	});
12064             }).error(function(data){
12065            	 Obj.secureCode ='';
12066             	vm.formError = (data.errorCount >= 2) ? Dictionary.I18n.get('err.global.multi.errorMessage') : data.MSG[0];
12067             	vm.formValidated = true;
12068             	vm.showSuccessMsg = false;
12069              $rootScope.requestInProgress = false;
12070              vm.updateCdhUnAvailable(data);
12071                 if(data.errorCount>1 ||(!vm.formValidated && vm.cdhError)){
12072              myProfileService.anchorToMsg(vm.sectionInEdit);
12073              }
12074              else if(data.errorCount==1){
12075                  document.getElementsByName(data.fieldName)[0].focus();
12076              }
12077
12078             });
12079			   }
12080           
12081      	  
12082        }
12083       
12084        vm.updateProfileCC = {
12085				formObj: "",
12086				index : "",
12087				profileForm: "",
12088				submit: function(profileForm,Obj,e,index ) {
12089							vm.updateProfileCC.formObj = Obj;
12090							vm.updateProfileCC.index  = index ;
12091							vm.updateProfileCC.profileForm = profileForm; 
12092							if(profileForm.$name === 'addCreditCardForm' && angular.isDefined(vm.updateProfileCC.formObj.primary) && vm.updateProfileCC.formObj.primary == true)
12093							{
12094								vm.showMessage=true;
12095							}
12096							if(profileForm.$name === 'creditCardFieldForm' && angular.isDefined(vm.updateProfileCC.formObj.primary) && vm.updateProfileCC.formObj.primary == true && vm.updateProfileCC.index  !=0)
12097							{
12098								vm.showMessage=false;
12099							}
12100							if(vm.sectionInEdit =='credit-card-section' && vm.accountModel.showDCC == true && (vm.updateProfileCC.formObj.type == carRentalConstant.credit
12100CardTypeVisaId || vm.updateProfileCC.formObj.type === carRentalConstant.creditCardTypeMasterId)){
12101								vm.updateProfileCC.formObj.dccPreference = vm.accountModel.dccPreference;
12102							}
12103							if(vm.sectionInEdit=='credit-card-section' && vm.updateProfileCC.formObj.type=='AV'){
12104								vm.updateProfileCC.formObj.expMonth = "";
12105								vm.updateProfileCC.formObj.expYear = "";
12106							}
12107							$validationProvider.validate(profileForm).success(function(){
12108										$rootScope.requestInProgress = true;
12109										vm.updateProfileCC.validationSuccess();
12110									
12111									
12112            	
12113							}).error(function(data){
12114								vm.updateProfileCC.formObj.secureCode ='';
12115								vm.formError = (data.errorCount >= 2) ? Dictionary.I18n.get('err.global.multi.errorMessage') : data.MSG[0];
12116								vm.formValidated = true;
12117								vm.showSuccessMsg = false;
12118								$rootScope.requestInProgress = false;
12119								vm.updateCdhUnAvailable(data);
12120								   if(data.errorCount>1 ||(!vm.formValidated && vm.cdhError)){
12121								myProfileService.anchorToMsg(vm.sectionInEdit);
12122								}
12123								else if(data.errorCount==1){
12124									document.getElementsByName(data.fieldName)[0].focus();
12125								}
12126
12127							});
12128					},
12129				validationSuccess: function() {
12130					if(enableCaptcha == 'true'){
12131						grecaptcha.execute();
12132					}
12133					else{
12134						vm.updateProfileCC.successCreditCardUpdate();
12135					}
12136	     		},
12137				successCreditCardUpdate: function() {
12138					// ARD2-4238 | Go to counter message is conditioned on the below variable vm.goToCounterMsgForCC for cc update
12139					vm.goToCounterMsgForCC = (angular.isDefined(vm.updateProfileCC.formObj.operation) && vm.updateProfileCC.formObj.operation == 'update' &&
12140												angular.isDefined(vm.domain) && vm.domain.toLowerCase() == 'us' &&
12141												angular.isDefined(vm.customerData.cor) && vm.customerData.cor.toLowerCase() == 'us' &&
12142												angular.isDefined(vm.customerData.membershipStatus) && vm.customerData.membershipStatus !== "My Avis Member" &&
12143												angular.isDefined(vm.customerData.ftpreferred) && vm.customerData.ftpreferred == false)
12144					myProfileService.updateProfile(vm.customerData,vm.updateProfileCC.formObj,vm.sectionInEdit,vm.recaptcha).then(function(data){ 
12145							   data = $scope.processErrorMessage(data);
12146							   if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
12147								
12148								/*
12149								 * Error message for age limit in MPf flow varies depending  on AWD rules.
12150								 * i18n for the error includes an angular expression to generate message dynamically.
12151								 * It needs $scope.$eval method to parse where other messages throw console error for $scope.$eval. 
12152								 * So added below condition check.
12153								 */
12154								if(data.errorList[0].code == '06042'){
12155									vm.formError = $scope.$eval(data.errorList[0].message);
12156								}else{
12157									vm.formError = data.errorList[0].message;
12158								}
12159								if(data.errorList[0].code == '17414'){
12160									vm.cdhError = 'Your details were not saved,please try again.';
12161								}
12162								   vm.formValidated = true;
12163								   vm.showUpdateMsg = false;
12164								   $rootScope.requestInProgress = false;
12165								   vm.updateCdhUnAvailable(data);
12166								   if(!vm.formValidated && vm.cdhError){
12167									myProfileService.anchorToMsg(vm.sectionInEdit,vm.updateProfileCC.index );
12168								   }  
12169								   ABG.resetCaptcha(true);
12170							   }else{
12171								   vm.customerData = data;
12172								   
12173								   vm.formValidated = false;
12174								   vm.showUpdateMsg = true;
12175								   vm.showSuccessMsg = true;
12176								   $rootScope.requestInProgress = false;
12177								   vm.updateCdhUnAvailable(data);
12178								   myProfileService.anchorToMsg(vm.sectionInEdit,vm.updateProfileCC.index );
12179								   editSection(false);
12180								   onSectionUpdate();
12181								   $('.add-'+vm.sectionInEdit).modal("hide");
12182								   $('body').removeClass('modal-open');
12183								 //ALM-508 changes
12184									if(enableCaptcha == 'true'){
12185									ABG.resetCaptcha(true);
12186									}
12187
12188
12189							   }
12190								}, function(error) {
12191								if(angular.isDefined(error.errorList) && error.errorList.length > 0){
12192									vm.formError = error.errorList[0].message;
12193									vm.updateCdhUnAvailable(data);
12194									vm.formValidated = true;
12195									vm.showSuccessMsg = false;
12196								}
12197								vm.updateProfileCC.formObj.secureCode ='';
12198								if(!vm.formValidated && vm.cdhError){
12199									myProfileService.anchorToMsg(vm.sectionInEdit,vm.updateProfileCC.index );
12200									
12201								}  
12202								$rootScope.requestInProgress = false;
12203								ABG.resetCaptcha(true);
12204							});
12205								
12206						}
12207						
12208						
12209						
12210				};
12211        
12212        
12213        
12214        
12215        
12216        // To update sectional details
12217        function saveProfileDetail(profileForm, e) { //TODO check for the form values
12218             _getSectionInEdit(e);
12219             var accountModel = vm.accountModel;
12220             if(angular.isDefined(vm.accountModel.awd)&&  (vm.accountModel.awd.length>0)){
12221                 var tempdiscountnumber = vm.accountModel.awd[0].discountNumber;
12222
12223            }
12224             if(vm.sectionInEdit == 'credit-card-section'){
12225            	 vm.saveProfileCC.submit(profileForm);
12226            	 
12227             }
12228             if(vm.sectionInEdit == 'name-section' && $window.brand == "payless" && angular.isDefined(accountModel.profileIdentity.emails)){
12229            	 accountModel.profileIdentity.emails[0].operation = "update";
12230             }
12231			
12232             if(vm.sectionInEdit == 'travel-preferences-section' && angular.isDefined(accountModel.travelPreferences) && angular.isDefined(accountModel.travelPreferences.awd) && vm.multiValuesEnable == false && $window.brand != carRentalConstant.brandName.BUDGET){
12233            	 if(angular.isDefined(accountModel.travelPreferences.awd[0])&& angular.isDefined(accountModel.travelPreferences.awd[0].maskId) && accountModel.travelPreferences.awd[0].maskId!="" && !($.isEmptyObject(vm.accountModel.tempAwdList))&& angular.isDefined(vm.accountModel.tempAwdList) && vm.accountModel.tempAwdList[0].discountNumber !=''){
12234            		 accountModel.travelPreferences.awd[0].operation = "update";
12235            		 accountModel.travelPreferences.awd[0].discountNumber = vm.accountModel.tempAwdList[0].discountNumber;
12236            	 }else if(angular.isDefined(vm.accountModel.tempAwdList) && !($.isEmptyObject(vm.accountModel.tempAwdList)) && angular.isDefined(vm.accountModel.tempAwdList[0].discountNumber) && angular.isDefined(vm.accountModel.tempAwdList[0].discountNumber) && vm.accountModel.tempAwdList[0].discountNumber !=''){
12237            		 accountModel.travelPreferences.awd = [{
12238            			 "discountNumber" : vm.accountModel.tempAwdList[0].discountNumber,
12239            			 "operation" : "add",
12240            			 "maskId" : "",
12241            			 "primary":true,
12242            			 "nickName":""
12243            		 }
12243]
12244            	 }else if(angular.isDefined(vm.accountModel.tempAwdList) && !($.isEmptyObject(vm.accountModel.tempAwdList)) && vm.accountModel.tempAwdList[0].discountNumber === '' && angular.isDefined(vm.accountModel.awd)&&  (vm.accountModel.awd.length>0)){
12245            		 accountModel.travelPreferences.companyName = " ";
12246            		 accountModel.travelPreferences.awd = [{
12247            			 "discountNumber" : tempdiscountnumber,
12248            			 "operation" : "delete",
12249            			 "maskId" : 1,
12250            			 "primary":true,
12251            			 "nickName":""
12252            		 }]
12253
12254				}
12255             }
12256             if(vm.sectionInEdit == 'travel-preferences-section' && angular.isDefined(accountModel.travelPreferences) && angular.isDefined(accountModel.travelPreferences.awd) && (vm.multiValuesEnable == true || $window.brand === carRentalConstant.brandName.BUDGET)){
12257            	 vm.accountModel.travelPreferences.awd = [];
12258             }
12259             if(vm.sectionInEdit == 'dl-section' && angular.isDefined(accountModel.dlSummary.telephone) && angular.isDefined(accountModel.contactAddress) && angular.isDefined(accountModel.contactAddress.telep
12259hone) && accountModel.contactAddress.telephone!=""){
12260            	 accountModel.dlSummary.maskId = accountModel.contactAddress.telephone[0].maskId;
12261            	 accountModel.dlSummary.primary = accountModel.contactAddress.telephone[0].primary;
12262            	 accountModel.dlSummary.operation = 'update';
12263             }
12264             if(!(vm.sectionInEdit == 'credit-card-section')){
12265            $validationProvider.validate(profileForm).success(function(){
12266            	$rootScope.requestInProgress = true;
12267				vm.customerData.costControlCode = vm.accountModel.costControlCode;
12268				if (vm.sectionInEdit == 'dl-section') {
12269					// ARD2-4238 | Go to counter message is conditioned on the below variable vm.goToCounterMsgForDL for dl update
12270					vm.goToCounterMsgForDL = (angular.isDefined(vm.domain) && vm.domain.toLowerCase() == 'us' &&
12271												angular.isDefined(vm.customerData.cor) && vm.customerData.cor.toLowerCase() == 'us' &&
12272												angular.isDefined(vm.customerData.membershipStatus) && vm.customerData.membershipStatus !== "My Avis Member" &&
12273												angular.isDefined(vm.customerData.ftpreferred) && vm.customerData.ftpreferred == false)
12274				}
12275            	myProfileService.updateProfile(vm.customerData,accountModel,vm.sectionInEdit).then(function(data){ 
12276                    data = $scope.processErrorMessage(data);
12277                    if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
12278						if(vm.showPrefilled && vm.sectionInEdit == 'dl-section'){
12279							reservationModelService.addGTMScript();
12280							gaService.trackMitekVerEventsDuringProfileEnroll('DL_UPDATED', 'Failure', vm.customerData);
12281						}
12282                    	vm.accountModel.secureCode ='';
12283                    	/*
12284                    	 * Error message for age limit in MPf flow varies depen
12284ding  on AWD rules.
12285                    	 * i18n for the error includes an angular expression to generate message dynamically.
12286                    	 * It needs $scope.$eval method to parse where other messages throw console error for $scope.$eval. 
12287                    	 * So added below condition check.
12288                    	 */
12289                    	if(data.errorList[0].code == '06042'){
12290                    		vm.formError = $scope.$eval(data.errorList[0].message);
12291                    	}else{
12292                    		vm.formError = data.errorList[0].message;
12293                    	}
12294                    	vm.updateCdhUnAvailable(data);
12295                        vm.formValidated = true;
12296                        vm.showSuccessMsg = false;
12297                        $rootScope.requestInProgress = false;
12298                        myProfileService.anchorToMsg(vm.sectionInEdit);
12299                    }else{
12300                        vm.customerData = data;
12301						if(vm.showPrefilled && vm.sectionInEdit == 'dl-section'){
12302							reservationModelService.addGTMScript();
12303							gaService.trackMitekVerEventsDuringProfileEnroll('DL_UPDATED', 'Success', vm.customerData);
12304						}
12305                        if($window.brand == carRentalConstant.brandName.AVIS && vm.customerData.enrollmentStep != 'profile-completed'){
12306                        	$rootScope.$broadcast('Profile.SelfInvoke',data);	
12307                        } 
12308                        var reservationModel = reservationModelService.getReservationModel();
12309                       if(angular.isDefined(reservationModel) && angular.isDefined(reservationModel.coupon)&& angular.isDefined(reservationModel.coupon.discountNumber) && angular.isDefined(vm.customerData.awd) && vm.customerData.awd!=''){
12310                    	   reservationModel.coupon.discountNumber = vm.customerData.awd[0].discountNumber;
12311                       }
12312                        
12313                        vm.formValidated = false;
12314                        vm.showSuccessMsg = true;
12315                        vm.updateCdhUnAvailable(data);
12316                        $rootScope.requestInProgress = false;
12317                        myProfileService.anchorToMsg(vm.sectionInEdit);
12318                        editSection(false);
12319                        onSectionUpdate();                                               
12320                    }
12321            	}, function(error) {
12322            		if(angular.isDefined(error.errorList) && error.errorList.length > 0){
12323            			vm.formError = error.errorList[0].message;
12324    	                vm.formValidated = true;
12325    	                vm.showSuccessMsg = false;
12326            		}
12327					if(vm.showPrefilled && vm.sectionInEdit == 'dl-section'){
12328						reservationModelService.addGTMScript();
12329						gaService.trackMitekVerEventsDuringProfileEnroll('DL_UPDATED', 'Failure', vm.customerData);
12330					}
12331            		vm.accountModel.secureCode ='';
12332            		//myProfileService.anchorToMsg(vm.sectionInEdit);
12333            		$rootScope.requestInProgress = false;
12334            	})
12335            }).error(function(data){
12336				if(vm.showPrefilled && vm.sectionInEdit == 'dl-section'){
12337					reservationModelService.addGTMScript();
12338					gaService.trackMitekVerEventsDuringProfileEnroll('DL_UPDATED', 'Failure', vm.customerData);
12339				}
12340            	vm.accountModel.secureCode ='';
12341            	vm.formError = ABG.getFormValidationError(data,false)[0].message;
12342            	vm.formValidated = true;
12343            	vm.showSuccessMsg = false;
12344                $rootScope.requestInProgress = false;
12345                if(data.errorCount>1){
12346                    myProfileService.anchorToMsg(vm.sectionInEdit);
12347                    }
12348                    else if(data.errorCount==1){
12349                    	 document.getElementsByName(data.fieldName)[0].focus();
12350                    }
12351
12352            });
12353        }
12354		// If discount-codes-section [bcd code + amazon link/unlink] is in edit mode
12355		if(vm.sectionInEdit == 'discount-codes-section' && angular.isDefined(accountModel.travelPreferences) && angular.isDefined(accountModel.travelPreferences.awd) && $window.brand == carRentalConstant.brandName.BUDGET){
12356			if(angular.isDefined(accountModel.travelPreferences.awd[0])&& angular.isDefined(accountModel.travelPreferences.awd[0].maskId) && accountModel.travelPreferences.awd[0].maskId!="" && !($.isEmptyObject(vm.accountModel.tempAwdList))&& angular.isDefined(vm.accountModel.tempAwdList) && vm.accountModel.tempAwdList[0].discountNumber !=''){
12357				accountModel.travelPreferences.awd[0].operation = "update";
12358				accountModel.travelPreferences.awd[0].discountNumber = vm.accountModel.tempAwdList[0].discountNumber;
12359			}else if(angular.isDefined(vm.accountModel.tempAwdList) && !($.isEmptyObject(vm.accountModel.tempAwdList)) && angular.isDefined(vm.accountModel.tempAwdList[0].discountNumber) && vm.accountModel.tempAwdList[0].discountNumber !=''){
12360				accountModel.travelPreferences.awd = [{
12361					"discountNumber" : vm.accountModel.tempAwdList[0].discountNumber,
12362					"operation" : "add",
12363					"maskId" : "",
12364					"primary":true,
12365					"nickName":""
12366				}]
12367			}else if(angular.isDefined(vm.accountModel.tempAwdList) && !($.isEmptyObject(vm.accountModel.tempAwdList)) && vm.accountModel.tempAwdList[0].discountNumber === '' && angular.isDefined(vm.accountModel.awd)&&  (vm.accountModel.awd.length>0)){
12368				accountModel.travelPreferences.companyName = " "; 
12369				accountModel.travelPreferences.awd = [{
12370					"discountNumber" : tempdiscountnumber,
12371					"operation" : "delete",
12372					"maskId" : 1,
12373					"primary":true,
12374					"nickName":""
12375				}]
12376
12377		   }
12378		}
12379
12380        }
12381       
12382        
12383        vm.saveProfileCC = {
12384        		profileForm: "",
12385				submit: function(profileForm) {
12386					vm.saveProfileCC.profileForm = profileForm;	
12387							$validationProvider.validate(profileForm).success(function(){
12388										$rootScope.requestInProgress = true;
12389										vm.saveProfileCC.validationSuccess();
12390									
12391									
12392            	
12393							}).error(function(data){
12394								vm.accountModel.secureCode ='';
12395								vm.formError = ABG.getFormValidationError(data,false)[0].message;
12396								vm.formValidated = true;
12397								vm.showSuccessMsg = false;
12398								$rootScope.requestInProgress = false;
12399								if(data.errorCount>1){
12400									myProfileService.anchorToMsg(vm.sectionInEdit);
12401									}
12402									else if(data.errorCount==1){
12403										 document.getElementsByName(data.fieldName)[0].focus();
12404									}
12405
12406							});
12407					},
12408				validationSuccess: function() {
12409					if(enableCaptcha == 'true'){
12410						grecaptcha.execute();
12411					}
12412					else{
12413						vm.saveProfileCC.successCreditCardUpdate();
12414					}
12415	     		},
12416				successCreditCardUpdate: function() {
12417					//credit session update
12418					var accountModel = vm.accountModel;
12419						 if(vm.sectionInEdit == 'credit-card-section' && (!(angular.isDefined(vm.accountModel.ccSummary.maskId)) || (angular.isDefined(vm.accountModel.ccSummary.maskId) && vm.accountModel.ccSummary.maskId==""))){
12420								accountModel = vm.accountModel.ccSummary;
12421								accountModel.primary = true;
12422							}else if(vm.sectionInEdit == 'credit-card-section'){
12423								 accountModel = vm.accountModel.ccSummary;
12424								 accountModel.operation = "update";
12425								 accountModel.dccPreference = vm.accountModel.dccPreference;					 
12426							}
12427							myProfileService.updateProfile(vm.customerData,accountModel,vm.sectionInEdit,vm.recaptcha).then(function(data){ 
12428								data = $scope.processErrorMessage(data);
12429								if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
12430									vm.accountModel.secureCode ='';
12431									/*
12432									 * Error message for age limit in MPf flow varies depen
12432ding  on AWD rules.
12433									 * i18n for the error includes an angular expression to generate message dynamically.
12434									 * It needs $scope.$eval method to parse where other messages throw console error for $scope.$eval. 
12435									 * So added below condition check.
12436									 */
12437									if(data.errorList[0].code == '06042'){
12438										vm.formError = $scope.$eval(data.errorList[0].message);
12439									}else{
12440										vm.formError = data.errorList[0].message;
12441									}
12442									vm.updateCdhUnAvailable(data);
12443									vm.formValidated = true;
12444									vm.showSuccessMsg = false;
12445									$rootScope.requestInProgress = false;
12446									myProfileService.anchorToMsg(vm.sectionInEdit);
12447									ABG.resetCaptcha(true);
12448								}else{
12449									vm.customerData = data;
12450									if($window.brand == carRentalConstant.brandName.AVIS && vm.customerData.enrollmentStep != 'profile-completed'){
12451										$rootScope.$broadcast('Profile.SelfInvoke',data);	
12452									} 
12453									var reservationModel = reservationModelService.getReservationModel();
12454								   if(angular.isDefined(reservationModel) && angular.isDefined(reservationModel.coupon)&& angular.isDefined(reservationModel.coupon.discountNumber) && angular.isDefined(vm.customerData.awd) && vm.customerData.awd!=''){
12455									   reservationModel.coupon.discountNumber = vm.customerData.awd[0].discountNumber;
12456								   }
12457									
12458									vm.formValidated = false;
12459									vm.showSuccessMsg = true;
12460									vm.updateCdhUnAvailable(data);
12461									$rootScope.requestInProgress = false;
12462									myProfileService.anchorToMsg(vm.sectionInEdit);
12463									editSection(false);
12464									onSectionUpdate(); 
12465									//ALM-508 changes
12466									if(enableCaptcha == 'true'){
12467									ABG.resetCaptcha(true);
12468									}
12469								}
12470							}, function(error) {
12471								if(angular.isDefined(error.errorList) && error.errorList.length > 0){
12472									vm.formError = error.errorList[0].message;
12473									vm.formValidated = true;
12474									vm.showSuccessMsg = false;
12475								}
12476								vm.accountModel.secureCode ='';
12477								//myProfileService.anchorToMsg(vm.sectionInEdit);
12478								$rootScope.requestInProgress = false;
12479								ABG.resetCaptcha(true);
12480							});
12481										 
12482						}	
12483				};
12484        
12485        
12486        
12487        // This function is used to save the updated password
12488        function updatePassword(changePasswordForm, e) {
12489            _getSectionInEdit(e);
12490             var redirectURL;
12491            if (vm.accountModel.updatePassword.currentPassword == vm.accountModel.updatePassword.newPassword && vm.accountModel.updatePassword.currentPassword != "" && vm.accountModel.updatePassword.newPassword != "") {
12492            	vm.formError = Dictionary.I18n.get('error.profile.common.samepassword,' + brand) + '</br>' + Dictionary.I18n.get('msg.profile.password.reenter');
12493				vm.formValidated = true;
12494                _clearPasswordFields();
12495                myProfileService.anchorToMsg(vm.sectionInEdit);
12496            } else if (vm.accountModel.updatePassword.currentPassword == "" && vm.accountModel.updatePassword.newPassword != "") {
12497            	vm.formError = Dictionary.I18n.get('error.profile.oldPassword.required,' + brand) + '</br>' + Dictionary.I18n.get('msg.profile.password.reenter');
12498				vm.formValidated = true;
12499                _clearPasswordFields();
12500                myProfileService.anchorToMsg(vm.sectionInEdit);
12501            } else {
12502                $validationProvider.validate(changePasswordForm).success(function(){
12503                	$rootScope.requestInProgress = true;
12504                	myProfileService.updatePassword(vm.customerData,vm.accountModel,vm.sectionInEdit).then(function(data) {
12505                		data = $scope.processErrorMessage(data);
12506                		if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
12507                			if (angular.equals(data.errorList[0].code, '30033')) 
12508                				{   
12509                    			//vm.summaryError = $scope.processErrorMessage(data);
12510                   				//getLogout();
12511                				vm.summaryError = $scope.processErrorMessage(data);
12512                				authenticationService.deleteAllStorageData();
12513                				storageService.setStorageData('authMsg',vm.summaryError.errorList[0].message);
12514                				ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot + "/login" + htmlExtension);
12515                				
12516                         		}
12517                			else
12518                			{
12519                				vm.formError = data.errorList[0].message;
12520                			   vm.formValidated = true;
12521                				_clearPasswordFields();
12522                			}
12523                		}
12524                		else {
12525                			vm.customerData = data;
12526                			vm.formValidated = false;
12527                			vm.showSuccessMsg = true;
12528                			onSectionUpdate();
12529                			editSection(false);
12530                			setTimeout(function(){
12531                				angular.element('#cancel-password').click();
12532                		        myProfileService.anchorToMsg(vm.sectionInEdit);  
12533
12534                			},10); 
12535
12536                		}
12537                		$rootScope.requestInProgress = false;
12538                		myProfileService.anchorToMsg(vm.sectionInEdit);
12539                	}, function(error) {
12540                		if(angular.isDefined(error.errorList) && error.errorList.length > 0){
12541                			vm.formError = error.errorList[0].message;
12542        	                vm.formValidated = true;
12543        	                vm.showSuccessMsg = false;
12544                		}
12545                		myProfileService.anchorToMsg(vm.sectionInEdit);
12546                		_clearPasswordFields();
12547                		$rootScope.requestInProgress = false;
12548                	});
12549                }).error(function(data){
12550                	vm.formError = (data.errorCount >= 2) ? (Dictionary.I18n.get('err.global.multi.errorMessage') + '</br>' + Dictionary.I18n.get('msg.profile.password.reenter')) : (data.MSG[0] + '</br>' + Dictionary.I18n.get('msg.profile.password.reenter'));
12551                	vm.formValidated = true;
12552                	 _clearPasswordFields();
12553                    $rootScope.requestInProgress = false;
12554                    myProfileService.anchorToMsg(vm.sectionInEdit);
12555                });
12556            }
12557        }
12558
12559
12560
12561        /*Save terms and condition whether accepted or not*/
12562        function declineProfileTermsCondition(e) {
12563            _getSectionInEdit(e);
12564            vm.declineTermsCondition = true; 
12565        }
12566
12567        function _getSectionInEdit(e) {
12568            vm.sectionInEdit = myProfileService.getSectionInEdit(e);
12569        }
12570
12571        function _clearPasswordFields(){
12572        	vm.accountModel.updatePassword.newPassword = '';
12573            vm.accountModel.updatePassword.currentPassword = '';
12574        }
12575      
12576
12577        /* To edit section in profile dash board page
12578         *  - this function is triggered on click of edit, save and cancel of each section
12579         *  - it stores the edit value and the section which is in edit to session storage
12580         *  - @param toEdit {boolean} - holds the value true if section is in edit mode
12581         *  - @param section {string} - holds HTML class name of section in edit
12582         *  - @param event {event} - holds the JS event 
12583         *  - @return void*/
12584        function editSection(toEdit, $event) {
12585        	// read TD flag from customer info obj  
12586        	if(toEdit){
12587        		vm.showSuccessMsg = false;
12588                var isInEdit = myProfileService.checkEditMode();
12589                if (isInEdit) {
12590               	var currentSection = myProfileService.getSectionInEdit($event);
12591               	if(vm.sectionInEdit == "telephone-section"){
12592               		vm.sectionInEdit = "address-section";
12593               	}
12594                	myProfileService.anchorToMsg(vm.sectionInEdit);
12595                	if(vm.customerData.passwordGraceWindow){
12596                		vm.showSectionMessage = false;
12597                	}else{
12598                		vm.showSectionMessage = true;
12599                	}
12600                    //$(".profile-edit-progress-alert").modal("show");             	
12601                   
12602                } else {
12603                	var editSection = myProfileService.getSectionInEdit($event);
12604                	if(vm.tdCheck || editSection == 'dl-section') {
12605                		editSectionHandler(toEdit, $event);
12606                	} else {
12607                		$rootScope.requestInProgress = true;
12608                		securityService.generateOtp().then(function(data){
12609                			if(data.promptOtpFlag){
12610                				editSectionHandler(toEdit, $event);	
12611                			} else if(!data.promptOtpFlag && angular.isUndefined(data.errorList)){
12612                				vm.tdCheck = true;
12613                    			//setTimeout(function(){_setAddressDetail
12613s()},5);            			
12614                    			var session = authenticationService.getSessionModel();           
12615                    			session.tdCheck = true            			
12616                    			authenticationService.setSessionModel(session);
12617                				editSectionHandler(toEdit, $event);
12618                			} else {
12619                				$(".profile-edit-error").modal("show");
12620                			}        			
12621                			$rootScope.requestInProgress = false;
12622                		}, function(error){
12623                			$(".profile-edit-error").modal("show");
12624                			$rootScope.requestInProgress = false;
12625                		})
12626                	}
12627                }
12628        	} else {
12629        		vm.resendOtpSuccess = false;
12630        		vm.resendOtpError = false;
12631        		vm.showSectionMessage= false;
12632        		editSectionHandler(toEdit, $event);
12633        	}
12634        }
12635        
12636        function editSectionHandler(toEdit, $event) {
12637        	if($window.brand == carRentalConstant.brandName.AVIS && vm.resetPasswordFlow){
12638        		vm.resetPasswordFlow = false
12639        	}
12640        	vm.formValidated = false;
12641        	var tempData = {
12642        		tempList : {},
12643        		extrasData : {}
12644        	}
12645        	tempData.tempList = angular.copy(vm.accountModel.tempList);
12646        	tempData.extrasData = angular.copy(vm.accountModel.extrasData);
12647        	if(toEdit){
12648        		vm.tempAccountModel = angular.copy(vm.accountModel);
12649        	}
12650            //vm.accountModel = myProfileService.getAccountData(vm.customerData);
12651            vm.accountModel.tempList = tempData.tempList; 
12652            vm.accountModel.extrasData = tempData.extrasData;
12653            _loadMnthYrDropdown();
12654            _loadCalendarDropdown();
12655            _loadEditSection();
12656            _loadDefaultCountry($event);
12657            vm._loadCarPreferenceList();
12658        	   vm.onChangeCreditCardType(); //  show/hide CVV and Year filed based on card type.
12659           //Resetting the field Errors
12660        	   var elem = angular.element('.wrap-auto-sugg #addressline1');
12661    		   $validationProvider.removeError(elem);
12662        	   $validationProvider.resetError('vm.addProperty.Address.address2');
12663        	   if(vm.multiValuesEnable){
12664        		   vm.carEdit();
12665        	   }
12666            
12667            _clearErrorMsg();
12668           if(!toEdit){
12669        	   vm.accountModel = angular.copy(vm.tempAccountModel);
12670           }
12671           setTimeout(function(){_setAddressDetails()},5);
12672            if (toEdit) {
12673                vm.showSuccessMsg = false;
12674                vm.showUpdateMsg= false;
12675                var isInEdit = myProfileService.checkEditMode();
12676                // TODO remove this check
12677                if (isInEdit) {
12678                    $(".profile-edit-progress-alert").modal("show");
12679                } else {
12680                    _getSectionInEdit($event);
12681                    if (vm.sectionInEdit == "protections-coverages-section" || vm.sectionInEdit == "travel-preferences-section") {
12682                        vm.accountModel.extrasData = angular.copy(vm.accountModel.tempList);
12683                    }
12684                    //for displaying the non editable message for DL section
12685                    /*else if (vm.sectionInEdit == "dl-section") {
12686                    	vm.formError = Dictionary.I18n.get('msg.profile.nonEditableDriversLicense,'+brand);
12687                        vm.formValidated = true;
12688                    }*/
12689                    myProfileService.setEditMode(true, vm.sectionInEdit);
12690                    myProfileService.triggerEditMode($event, toEdit, vm.sectionInEdit);
12691                }
12692            } else {
12693                myProfileService.setEditMode(false);
12694                myProfileService.triggerEditMode($event, toEdit, vm.sectionInEdit);
12695            }
12696        }
12697        
12698        function resendOtp(){
12699        	vm.resendOtpSuccess = false;
12700        	vm.resendOtpError = false;
12701        	$rootScope.requestInProgress = true;
12702    		securityService.generateOtp().then(function(data){
12703    			$rootScope.requestInProgress = false;
12704    			if(data.errorList && data.errorList.length > 0){
12705        			data = $scope.processErrorMessage(data);
12706        			vm.resendOtpError = true;        			
12707        		} else if(data.promptOtpFlag){
12708        			vm.resendOtpSuccess = true;
12709        		} else if(!data.promptOtpFlag && angular.isUndefined(data.errorList)){
12710        			vm.tdCheck = true;
12711        			//setTimeout(function(){_setAddressDetails()},5);
12712        			var session = authenticationService.getSessionModel();
12713        			session.tdCheck = true;
12714        			authenticationService.setSessionModel(session);
12715        		}
12716    		}, function(error){
12717    			$rootScope.requestInProgress = false;
12718    			vm.resendOtpError = true;    			  			
12719    		})
12720        }
12721        
12722        function verifyProfileOtp(event){    		
12723        	vm.resendOtpSuccess = false;
12724        	vm.resendOtpError = false; 
12725    		var formName = angular.element(event.target)[0].form.name;
12726    		var formCtrl = angular.element("[name='"+formName+"']").controller("form");
12727    		$validationProvider.validate(formCtrl).success(function(){
12728            	var otpReqObj ={"otpNumber": vm.profileOtp} 
12729            	$rootScope.requestInProgress = true;
12730            	securityService.validateOtp(otpReqObj).then(function(data){
12731            		if(data.errorList){
12732            			data = $scope.processErrorMessage(data);
12733            		}
12734            		if(data.errorList && data.errorList.length > 0){
12735            			if(data.errorList.length==1){
12736            				if(data.errorList[0].code=="110033"){
12737            					$validationProvider.displayServiceError('vm.profileOtp', 'invalidotp', false, formName)
12738            				}            				
12739            				else if(data.errorList[0].code=="110034"){
12740            					$validationProvider.displayServiceError('vm.profileOtp', 'expiredotp', false, formName)
12741            				}
12742            				else if(data.errorList[0].code=="110023"){            					
12743            					getLogout();            					
12744            				}
12745            				else{
12746            					// generic message for all other scenarios
12747            					$validationProvider.displayServiceError('vm.profileOtp', 'genericotp', false, formName)
12748            				}
12749            			}            			          			
12750            		} else if(!data.promptOtpFlag) { 
12751            			vm.tdCheck = true;
12752            			setTimeout(function(){_setAddressDetails()},5); 
12753						// TODO: need to refactor below code
12754            			if(vm.sectionInEdit = 'enroll-rewards-section'){
12755            				setFtpEnrollment();
12756            			}
12757            			var session = authenticationService.getSessionModel();           
12758            			session.tdCheck = true            			
12759            			authenticationService.setSessionModel(session);                		
12760            		}
12761            		
12762            		$rootScope.requestInProgress = false;
12763            	},function(error){            		
12764            		$rootScope.requestInProgress = false;
12765            	})        		
12766            }).error(function(err){
12767            	
12768            });
12769    		
12770    		//  
12771    	}
12772        
12773        function getLogout() {
12774			var redirectURL;
12775			$rootScope.requestInProgress = true;
12776			var sessionStatus = authenticationService.getSessionModel();
12777			authenticationService.logout().then(function(data) {
12778				authenticationService.setLoginAuthenticate(false);				
12779				redirectURL = $rootScope.contextPath + "/" + $rootScope.locale + "/home" + htmlExtension;
12780				storageService.setStorageData('lockedUser', vm.customerData.contacts.email);				
12781				$cookies.remove('resModelDisplayControls');				
12782				setTimeout(function() {
12783					$window.location.href = redirectURL;
12784				}, 1);
12785			},
12786			function(error) {
12787				$rootScope.requestInProgress = false;
12788			});
12789		}
12790
12791        /* resets the form in address section when clicked on cancel*/
12792        function cancelEdit(form) {
12793            $validationProvider.reset(form);
12794        }
12795        /*will expand the section without storing into session storage*/
12796        function _showSectionInExpendedMode(section) {
12797        	
12798            setTimeout(function() {
12799                var cardOuter = $(".wrap-profile-progress").find(".card-outer-content:visible");
12800                cardOuter.find(".card-inner-content").addClass("editable-mode");
12801                cardOuter.find(".modal").modal("show");
12802            }, 1500);
12803        }
12804        
12805       //Resetting the CC field Errors
12806        function clearError(form) {
12807        	$(".error").empty();
12808        	$("input").removeClass("platform-element-error ng-invalid");
12809        }
12810        
12811        function _clearErrorMsg() {
12812            vm.formValidated = false;
12813            _checkForExpiredCC();
12814            $validationProvider.resetError('vm.addProperty.email.email', true);
12815            $validationProvider.resetError('vm.addProperty.phone.phoneNumber', true);
12816            $validationProvider.resetError('vm.addProperty.ccSummary.type', true);
12817            $validationProvider.resetError('vm.addProperty.ccSummary.number', true);
12818            $validationProvider.resetError('vm.addProperty.ccSummary.expMonth', true);
12819            $validationProvider.resetError('vm.addProperty.ccSummary.expYear', true);
12820            $validationProvider.resetError('vm.addProperty.ccSummary.secureCode', true);
12821            $validationProvider.resetError('vm.addProperty.awd.discountNumber', true);
12822            if(vm.sectionInEdit == 'dl-section'){
12823                $validationProvider.resetError('vm.accountModel.dlSummary.dlNumber');
12824            }
12825			if(vm.sectionInEdit == 'name-section'){
12826                $validationProvider.resetError('vm.accountModel.profileIdentity.firstName');
12827				$validationProvider.resetError('vm.accountModel.profileIdentity.lastName');
12828				$validationProvider.resetError('vm.accountModel.profileIdentity.userName');
12829            }
12830        }
12831
12832        /* this function is triggered when we either accept or reject any product or insurance
12833         * - iterates through each object in tempList (both ancillaries and insurances) to change its value based on selection 
12834         * - vm.accountModel.tempList is a nested json which holds the list of products and protections which is displayed to the user
12835         * - @param product {json} - current object
12836         * - @param value {boolean} - to set the value of current object
12837         * - @param type {string} - indicates if we are manipulating "products" list or "protections" list 
12838         * - @return void*/
12839        function modifyTempList(product, value, type) {
12840            for (var i = 0; i < vm.accountModel.tempList[type].length; i++) {
12841                if (product.code === vm.accountModel.tempList[type][i].code) {
12842                	vm.accountModel.tempList[type][i].value = value;
12843                    break;
12844                }
12845            }
12846        }
12847
12848        /* code added by UI team - for tablet mode - view more functionality*/
12849        $(".wrap-dashboard").on("click", ".wrap-toggle-link", function(e) {
12850            var $this = $(this),
12851                toggleText = $this.parent().find(".wrap-toggle-text");
12852
12853            if ($this.hasClass("view-more")) {
12854                $this.text($this.data("viewlesslabel")).addClass("view-less").removeClass("view-more");
12855                toggleText.removeClass("hidden-xs");
12856            } else {
12857                $this.text($this.data("viewmorelabel")).addClass("view-more").removeClass("view-less");
12858                toggleText.addClass("hidden-xs");
12859            }
12860        });
12861
12862        /* triggered on cancelling modifications in Protections and Travel Preferences section
12863         * sets tempList to its original state as was before edit*/
12864        function cancelTempListModifications() {
12865        	vm.accountModel.tempList = angular.copy(vm.accountModel.extrasData);
12866        }
12867
12868        // initializing the modal for Info icons in protection and coverage , travel preference sections 
12869        function _initPopoverOnModal() {
12870            $(".modal").on("shown.bs.modal", function() {
12871                $("[data-toggle=popover]").popover();
12872            });
12873        }
12874        /* GTM tracking purpose listener added */
12875        $scope.$on("AugCompleteBlurEvent",function(event, data){
12876        	gtmBlur((angular.isDefined(data.userInput) && !angular.equals(data.userInput, "")), 'frequentLocation', 'text');
12877        });
12878        
12879        $scope.$on("Profile.ShowSaveCancelMsg",function(event, data){
12880        	vm.showSectionMessage = data;
12881        });
12882
12883        //	GTM FUNCTION
12884        function gtmBlur(string, string1, inputType, wizardKey) {
12885            //	hardcoded strings in this function need not be I18N as these won't be displayed in UI.
12886        	if(wizardKey != null && ($window.brand == carRentalConstant.brandName.BUDGET || $window.brand == carRentalConstant.brandName.AVIS)) {
12887          	  string1 = Dictionary.I18n.get('lbl.global.wizardNumber,'+brand);
12888            }
12889            if (inputType == 'text') {
12890                var inputAction = string ? 'Filled In' : 'Skipped';
12891            } else if (inputType == 'checkbox') {
12892                var inputAction = string ? 'Selected as Y' : 'Selected as N';
12893            } else if (inputType == 'dropdown') {
12894                var inputAction = string ? 'Selected' : 'Not Selected';
12895            }
12896            dataLayer.push({
12897                'event': 'trackEvent',
12898                'eventCategory': 'Tracking Form: ' + 'Profile-Form',
12899                'eventLabel': string1,
12900                'eventAction': inputAction
12901            });
12902        }
12903        
12904        /*function _checkForConnectedCarTnCModalDisplay(){
12905        	if(angular.isDefined(vm.accountModel) && vm.accountModel.showConnectedCarTncModal){
12906        		setTimeout(function(){
12907					$("#temporary-modalTnC .modal.connected-car-tnc").modal("show");
12908				}, 2000);
12909        	}
12910        }*/
12911		
12912		function _checkForConnectedCarTnCModalDisplay(){
12913        	if(angular.isDefined(vm.accountModel) && vm.accountModel.retrieveExpressConsentInd && angular.isDefined(vm.retriveCallSuccess) && !vm.retriveCallSuccess){
12914        		myProfileService.retrieveExpressConsentTerms().then(function(data){
12915        			storageService.setStorageData('showExpressConsent', !data.customerInfo.expressConsentTerms);
12916        			storageService.setStorageData('retriveCallSuccess', true);
12917        			if(angular.isDefined(data) && angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.expressConsentTerms) && !data.customerInfo.expressConsentTerms && angular.isDefined(data.customerInfo.preferred) && data.customerInfo.preferred){
12918        				vm.accountModel.showConnectedCarTncModal = true;
12919        				vm.rewardPreferredTnC = false;
12920        				vm.showTnCPage = getVehicles.gettermsMapURL(vm.getTnCCountryList, vm.domain)+'.partial.html';
12921        			setTimeout(function(){
12922    					$("#temporary-modalTnC .modal.connected-car-tnc").modal("show");
12923    				}, 2000);
12924        			}
12925        		});        		
12926        	}
12927        	vm.showExpressConsent = storageService.getStorageData('showExpressConsent');
12928        	if(angular.isDefined(vm.showExpressConsent) && vm.showExpressConsent){
12929        		vm.accountModel.showConnectedCarTncModal = true;
12930				vm.rewardPreferredTnC = false;
12931				vm.showTnCPage = getVehicles.gettermsMapURL(vm.getTnCCountryList, vm.domain)+'.partial.html';
12932    			setTimeout(function(){
12933					$("#temporary-modalTnC .modal.connected-car-tnc").modal("show");
12934				}, 2000);
12935    		}
12936        }
12937		
12938    	function acceptConnectedCarTnC(e){
12939    		 vm.sectionInEdit = "tnc-section";
12940    		 $("#temporary-modalTnC .modal.connected-car-tnc").modal("hide");
12941    		 vm.customerData.expressConsentTerms = true;
12942    		 vm.accountModel.acceptTermsConditions = true;
12943    		 myProfileService.updateProfile(vm.customerData,vm.accountModel,vm.sectionInEdit).then(function(data){
12944    			 data = $scope.processErrorMessage(data);
12945                 if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
12946                     $rootScope.requestInProgress = false;
12947                 }else{
12948                     vm.customerData = data;
12949                     $rootScope.requestInProgress = false;
12950                     storageService.setStorageData('showExpressConsent', false);
12951                     onSectionUpdate();
12952                 }
12953    		 }, function(error) {
12954         		$rootScope.requestInProgress = false;
12955         	 });
12956		}	
12957    	
12958    	function closeConnectedCarTnc(){
12959    		$("#temporary-modalTnC .modal.connected-car-tnc").modal("hide");
12960    	} 
12961    	
12962    	function validatePromoCode() {
12963            var expression = {
12964                        "promocode": carRentalConstant.validatePromoCode['pc']
12965            };
12966            $validationProvider.setExpression(expression);  		
12967    	}
12968    	/*load the T&C content for SMS opt-in*/
12969    	function loadHelpModal(currentEle) {
12970    		vm.country = $window.countrySelect?$window.countrySelect:'US';
12971			var target = currentEle.target.parentElement;
12972			vm.helpURL = getVehicles.getUrl(target, country);
12973		}
12974			//[AMAZONPRIME]
12975    	function unlinkAmazonProfile(){
12976    		vm.sectionInEdit = 'unlink-amazon-profile';
12977    		angular.element('.unlink-prime-modal').modal('show');
12978    	}
12979    	
12980    	//to update amazon login status
12981		$rootScope.$on("Partner.partnerInfo", function(event, data){
12982			if(angular.isDefined(data)){
12983				vm.amazonUserStatus = authenticationService.amazonLoginStatus();
12984			}
12985		})
12986		
12987    	   /*To display optins in email section */
12988        function _loadEmail(){
12989        	angular.forEach(vm.accountModel.profileIdentity.emails,function(email){
12990        		email.promoMails=(angular.isDefined(email.promoMails)&& (email.promoMails=="Y"|| email.promoMails == true))?true:false;
12991        		email.eRecieptEmailOptin = (angular.isDefined(email.eRecieptEmailOptin)&& (email.eRecieptEmailOptin=="Y" || email.eRecieptEmailOptin==true))?true:false;
12992        		email.prefilledemail = email.email;
12993        	});
12994        	angular.forEach(vm.accountModel.contactAddress.telephone,function(phone){
12995        		if(angular.isDefined(phone.smsOptIn)){
12996        		phone.smsOptIn= (angular.isDefined(phone.smsOptIn)&& (phone.smsOptIn=="T" || phone.smsOptIn==true))?true:false;
12997        		}
12998        		
12999        	})
13000        	angular.forEach(vm.accountModel.contactAddress.address,function(address){
13001        		address.prefilledZipCode = address.zipCode;
13002        	})
13003        	 if(angular.isUndefined(vm.customerData.contacts.phoneNumbers) || vm.customerData.contacts.phoneNumbers==''){
13004        		 vm.addProperty.phone = {
13005        				 "primary" : false
13006        		 }
13007        		 vm.primaryPhone = true;
13008        	 }else{
13009        		 vm.addProperty.phone = {
13010        				 "primary" : false
13011        		 }
13012        		vm.primaryPhone = false;
13013        	}
13014        	if(vm.amazonUserStatus == carRentalConstant.amazonLinked){
13015		        	for (var i = 0; i < vm.accountModel.tempAwdList.length; i++) {
13016						if (vm.accountModel.tempAwdList[i].maskId=='-1') {
13017							vm.amazonPrimaryValue = vm.accountModel.tempAwdList[i].primary;
13018							vm.accountModel.tempAwdList.splice(i,1);
13019						}
13020					}
13021			}
13022        	if(vm.accountModel.awd.length<2){
13023        		if(vm.accountModel.awd.length<1){
13024        			vm.primaryAwd = true;
13025        		}
13026        		else if(vm.accountModel.awd.length==1){
13027        			if(vm.amazonUserStatus == carRentalConstant.amazonLinked && vm.amazonPrimaryValue==false){
13028            			vm.primaryAwd = true;
13029            		} 
13030        		}
13031        		else
13032        			vm.primaryAwd = false;
13033        	}        	
13034        }
13035       /*585672 to delete the entries in my profile and preferences section */
13036 	   function deleteConfirm(sectionDeleted,Obj,radioCheck,index){
13037 		  vm.showUpdateMsg = false;
13038 		   vm.sectionDeleted = sectionDeleted;
13039 		  vm.sectionInEdit = sectionDeleted;
13040 		   vm.tempAccountModel = angular.copy(vm.accountModel);
13041	        if(sectionDeleted == 'discount-number-section'){
13042	        if(Obj.length>2){
13043	        	angular.forEach(Obj, function(Obj1,key) {
13044	        		if(key!=radioCheck && Obj1.primary== true){
13045	        			Obj1.primary= false;
13046	        			Obj1.operation = 'delete';
13047	        		}else if(key == radioCheck){
13048	        			Obj1.primary = true;
13049	        			Obj1.operation='update';
13050	        		}else{
13051	        			Obj1.operation = '';
13052	        		}
13053	        	});
13054	        	
13055	        var removeIndex=[];
13056	        	for (var i = 0; i < Obj.length; i++) {
13057					if (Obj[i].operation=='') {
13058						removeIndex.push(i);
13059						//Obj.splice(i, 1);
13060					}
13061				}
13062	        	for(var i=removeIndex.length-1; i>=0; i--){
13063	        		Obj.splice(removeIndex[i],1);
13064	        	}
13065	        }else if(Obj.length == 2){
13066	        	angular.forEach(Obj, function (discount){
13067	        		if(discount.primary == true){
13068	        			discount.operation = 'delete';
13069	        			discount.primary =false;
13070	        		}else{
13071	        			discount.operation = 'update';
13072	        			discount.primary =true;
13073	        		}
13074	        	})
13075	        }else if(Obj.length == 1){
13076	        	angular.forEach(Obj,function(discount){
13077	        		discount.operation= 'delete';
13078	        	})
13079	        }
13080	        else{
13081	        	Obj.operation = 'delete';
13082	        	var Objlist = [];
13083	        	Objlist.push(Obj);
13084	        	Obj = Objlist;
13085	        }
13086	        
13087	        $(".delete-"+sectionDeleted).modal("hide");
13088	        $('body').removeClass('modal-open');
13089	        $('.modal-backdrop').remove();
13090        	$rootScope.requestInProgress = true;
13091	        	
13092	        }else if(sectionDeleted == 'identity-password-section'){
13093	        	Obj.promoMails=(angular.isDefined(Obj.promoMails)&& Obj.promoMails== true)?"Y":"N";
13094        		Obj.eRecieptEmailOptin = (angular.isDefined(Obj.eRecieptEmailOptin) && Obj.eRecieptEmailOptin==true)?"Y":"N";
13095	        }else if(sectionDeleted=='telephone-section'){
13096          		Obj.smsOptIn=(angular.isDefined(Obj.smsOptIn)&& Obj.smsOptIn== true)?"T":"N";
13097        	  } else if(sectionDeleted == 'unlink-amazon-section'){
13098			    	angular.forEach(Obj, function(Obj1,key) {
13099			    		if(Obj1.maskId!=radioCheck && Obj1.primary== true){
13100		        			Obj1.primary= false;
13101		        			Obj1.operation = 'delete';
13102		        		}else if(Obj1.maskId == radioCheck){
13103		        			Obj1.primary = true;
13104		        			Obj1.operation='update';
13105		        		}else{
13106		        			Obj1.operation = '';
13107		        		}
13108		        	});
13109			    	var removeIndex=[];
13110		        	for (var i = 0; i < Obj.length; i++) {
13111						if (Obj[i].operation=='') {
13112							removeIndex.push(i);
13113							//Obj.splice(i, 1);
13114						}
13115					}
13116		        	for(var i=removeIndex.length-1; i>=0; i--){
13117		        		Obj.splice(removeIndex[i],1);
13118		        	}
13119		        	$(".delete-"+sectionDeleted).modal("hide");
13120		        	$('body').removeClass('modal-open');
13121			        $('.modal-backdrop').remove();
13122			        $rootScope.requestInProgress = true;
13123			    }
13124	        if(sectionDeleted != 'discount-number-section' && sectionDeleted != 'unlink-amazon-section'){
13125			    	 Obj.operation = 'delete';
13126			    	$(".delete-"+sectionDeleted+"-"+Obj.maskId).modal("hide");
13127		        	$('body').removeClass('modal-open');
13128			        $('.modal-backdrop').remove();
13129			        $rootScope.requestInProgress = true;
13130			    }else{
13131			    	$rootScope.requestInProgress = true;
13132			    }
13133			    if(vm.sectionInEdit =='credit-card-section' && vm.accountModel.showDCC == true && (Obj.type == carRentalConstant.creditCardTypeVisaId || Obj.type === carRentalConstant.creditCardTypeMasterId)){
13134	        		Obj.dccPreference = vm.accountModel.dccPreference;
13135	        	}
13136		        	
13137	        	myProfileService.updateProfile(vm.customerData,Obj,sectionDeleted).then(function(data){
13138	        		$rootScope.requestInProgress = true;
13139	                data = $scope.processErrorMessage(data);
13140	                if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
13141	                
13142	                	/*
13143	                	 * Error message for age limit in MPf flow varies depen
13143ding  on AWD rules.
13144	                	 * i18n for the error includes an angular expression to generate message dynamically.
13145	                	 * It needs $scope.$eval method to parse where other messages throw console error for $scope.$eval. 
13146	                	 * So added below condition check.
13147	                	 */
13148	                	vm.accountModel = angular.copy(vm.tempAccountModel);
13149	                 	if(data.errorList[0].code == '17414'){
13150                       		vm.cdhError = 'Your details were not saved,please try again.';
13151                       	}
13152	                 	vm.updateCdhUnAvailable(data);
13153                       vm.formError = data.errorList[0].message;
13154                       vm.deleteFail = true;
13155	                    vm.showUpdateMsg = false;
13156	                    $rootScope.requestInProgress = false;
13157	                    myProfileService.anchorToMsg(sectionDeleted,index);
13158	                    /*if((sectionDeleted != 'address-section') && (sectionDeleted != 'telephone-section')){
13159	                	  myProfileService.anchorToMsg(sectionDeleted);
13160	                  }*/
13161	                   
13162	                }else{
13163	                    vm.customerData = data;
13164	                    
13165	                    vm.showDelete=true;
13166	                    vm.showUpdateMsg = true;
13167	                    vm.deleteFail = false;
13168	                    vm.updateCdhUnAvailable(data);
13169	                    $rootScope.requestInProgress = false;
13170	                    myProfileService.anchorToMsg(sectionDeleted,index);
13171	                    editSection(false);
13172	                    onSectionUpdate();                                               
13173	                }
13174	        	}, function(error) {
13175	        		if(angular.isDefined(error.errorList) && error.errorList.length > 0){
13176	        			vm.formError = error.errorList[0].message;
13177	        			vm.updateCdhUnAvailable(data);
13178		                vm.formValidated = true;
13179		                vm.showSuccessMsg = false;
13180		                vm.deleteFail = true;
13181	        		}
13182	        		$rootScope.requestInProgress = false;
13183	        	})
13184	        	
13185	        }
13186
13187			
13188		function initiateMitekVerification() {
13189			reservationModelService.addGTMScript();
13190			gaService.trackMitekVerEventsDuringProfileEnroll('START_SCAN_CTA', 'Click', vm.customerData.customerInfo);
13191			$window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot + "/biometric-validation/mitek-validation" + htmlExtension + "#/front-scan";
13192		}
13193		function showManualDlForm(){
13194			reservationModelService.addGTMScript();
13195			gaService.trackMitekVerEventsDuringProfileEnroll('ENTER_MANUAL_CTA', 'Click', vm.customerData.customerInfo);
13196			vm.isEnterManual = true;
13197		}
13198        
13199    	var extendedController = $controller('MyProfileExnController', {
13200        	$scope: $scope
13201        });
13202    	setTimeout(function() {
13203            var cardOuter = $(".wrap-profile-progress").find(".card-outer-content:visible");
13204            cardOuter.find(".card-inner-content").addClass("editable-mode");
13205            cardOuter.find(".modal").modal("show");
13206        }, 1500);
13207        angular.extend(this, extendedController);
13208        $rootScope.$on("recaptcha", function(event, response){
13209    	 vm.recaptcha=response;
13210			if(angular.isDefined(response) && response != ''){
13211				if(vm.updateProfileCC.profileForm.$name === 'creditCardFieldForm' || vm.updateProfileCC.profileForm.$name === 'addCreditCardForm'){
13212					vm.updateProfileCC.successCreditCardUpdate();
13213				}
13214				else if(vm.saveProfileCC.profileForm.$name === 'profileCreditCardForm' ){
13215					vm.saveProfileCC.successCreditCardUpdate();
13216				}
13217				
13218			}			
13219    	 				
13220     });
13221        
13222     angular.element(document).ready(function () {
13223    	 setTimeout(function() {
13224         	if(angular.isDefined(vm.customerData) && vm.customerData.passwordGraceWindow){
13225 				anchorSmoothScroll.scrollTo('changePasswordForm');
13226 				angular.element('#edit-password').click();
13227 				vm.resetPwdMsg = Dictionary.I18n.get('err.msg.profile.resetPassword');
13228 			}
13229         	// ABGDIMT 812 changes        	
13230         	if(angular.isDefined(vm.customerData) && angular.isDefined(vm.customerData.creditCardList) && vm.customerData.creditCardList.length >= 1) {        		
13231         		if((angular.isDefined(vm.customerData.creditCardList[0]) && angular.isDefined(vm.customerData.creditCardList[0].badCard) && vm.customerData.creditCardList[0].badCard == true) || 
13232         		   (angular.isDefined(vm.customerData.creditCardList[1]) && angular.isDefined(vm.customerData.creditCardList[1].badCard) && vm.customerData.creditCardList[1].badCard == true) || 
13233         		   (angular.isDefined(vm.customerData.creditCardList[2]) && angular.isDefined(vm.customerData.creditCardList[2].badCard) && vm.customerData.creditCardList[2].badCard == true) || 
13234         		   (angular.isDefined(vm.customerData.creditCardList[3]) && angular.isDefined(vm.customerData.creditCardList[3].badCard) && vm.customerData.creditCardList[3].badCard == true)){
13235     				vm.showAlertIcon = true;
13236     			}
13237     			else{
13238     				vm.showAlertIcon = false;
13239     			}	
13240           	}
13241         	/*Pre-OTP changes*/
13242         	vm.session = authenticationService.getSessionModel(); 
13243            if(angular.isDefined(vm.session) && vm.session.status == carRentalConstant.userStateAuthenticated && angular.isDefined(vm.customerData) && angular.isDefined(vm.customerData.webCustomer) && 
13244            (vm.customerData.contacts.email == '' || vm.customerData.contacts.phoneNumbers == undefined || vm.customerData.webCustomer.promptContactInfoValidation)){
13245            	angular.element('.customer-details-modal').modal('show');
13246            	if(!(angular.isDefined(vm.customerData.contacts.phoneNumbers))) {
13247            	angular.element('#phoneNum').addClass("platform-element-error");
13248            	}
13249            	if(vm.customerData.contacts.email == '') {
13250            	angular.element('#emailAddr').addClass("platform-element-error");
13251            }
13252            	if(angular.isDefined(vm.customerData.contacts.email[0]) && angular.isDefined(vm.customerData.contacts.email[0].email )){
13253            		vm.custDetailsUpdateEmail = vm.customerData.contacts.email[0].email;
13254            	}        		
13255            	}
13256         	
13257         }, 2000);        
13258	 });
13259        
13260		
13261    }
13262})();
13263(function() {
13264	'use strict';
13265	
13266	angular
13267		.module('account')
13268		.controller('PreferredCreditCardController', PreferredCreditCardController);
13269	
13270	PreferredCreditCardController.$inject = ['$controller', '$scope', 'carRentalConstant', '$rootScope', '$window', 'authenticationService', 'myProfileService','datePickerInit', '$locale', '$filter', '$validation', 'rewardsProgramService', 'accountUtilityService', 'signupService','getVehicles','reservationModelService'];
13271
13272	function PreferredCreditCardController($controller, $scope, carRentalConstant, $rootScope, $window, authenticationService, myProfileService,datePickerInit, $locale, $filter, $validationProvider, rewardsProgramService, accountUtilityService, signupService,getVehicles, reservationModelService) {
13273
13274		$controller('ExceptionHandlerController', {
13275			$scope: $scope
13276		});
13277		
13278		
13279		// View Model.....
13280		var vm = this;
13281		var isValidXSRF = true;
13282		vm.hideExpMonthYear = true;
13283		vm.hasPartnerInfo = false;
13284		vm.captchaFlag = false;
13285		vm.enableCaptcha = enableCaptcha;
13286		vm.customerData = {};
13287		vm.customerData.preferred = true;
13288		vm.hideCVV = true;
13289		vm.tdCheck = true;
13290		vm.formValidated = false;
13291		vm.domain = $window.domain.toUpperCase();
13292		// View Callable.....
13293		//vm.saveProfileDetail = saveProfileDetail;
13294		//vm.saveProfileDetailforCC = saveProfileDetailforCC;
13295		vm.onChangeCreditCardType = onChangeCreditCardType;
13296		
13297		// Private Methods.....
13298		vm._setCreditCardSection = _setCreditCardSection;
13299		vm._loadMnthYrDropdown = _loadMnthYrDropdown;
13300        
13301        function _checkForPartnerCustomerInfo(){
13302        	if(angular.isDefined(vm.customerResponce) && angular.isDefined(vm.customerResponce.partnerCustomerInfo) && !angular.equals({}, vm.customerResponce.partnerCustomerInfo)){
13303        		vm.hasPartnerInfo = true;       		
13304        	}else{
13305        		vm.hasPartnerInfo = false;
13306        	}
13307        }
13308        
13309      //TODO: need to move to service file
13310        function onChangeCreditCardType(type) {
13311            if (type == 'AV') {
13312                vm.hideCVV = false;
13313            } else {
13314                vm.hideCVV = true;
13315            }
13316            if (type == 'AV') {
13317                vm.hideExpMonthYear = false;
13318            } else {
13319                vm.hideExpMonthYear = true;
13320            }
13321            if (type == 'CX' || type  == 'CM'
13322				|| type  == 'CA' || type  == 'CS' || type == 'CD' || type == 'CJ') {
13323            		vm.isCVVMandatory = true;
13324            } else {
13325            		vm.isCVVMandatory = false;
13326            }
13327        }
13328        function _loadMnthYrDropdown() {
13329        	var expMonthYearList = accountUtilityService.loadMnthYrDropdown();
13330            vm.expMonths = expMonthYearList.expMonths;
13331            vm.expYears = expMonthYearList.expYears;
13332            var expDate = [];
13333            //TODO
13334            if (angular.isDefined(vm.customerResponce.customerInfo) && angular.isDefined(vm.customerResponce.customerInfo.ccSummary) && angular.isDefined(vm.customerResponce.customerInfo.ccSummary.expDate)) {
13335                expDate = vm.customerResponce.customerInfo.ccSummary.expDate.split("/");
13336            }else if(angular.isDefined(vm.customerResponce.partnerCustomerInfo) && angular.isDefined(vm.customerResponce.partnerCustomerInfo.ccSummary) && angular.isDefined(vm.customerResponce.partnerCustomerInfo.ccSummary.expDate)){
13337            	expDate = vm.customerResponce.partnerCustomerInfo.ccSummary.expDate.split("/");
13338            }
13339            if(angular.isDefined(expDate.length) && expDate.length > 0){
13340            	 var index = vm.expMonths.indexOf($filter('filter')(vm.expMonths, function(d) {
13341                     return d.key == expDate[0];
13342                 })[0]);
13343                 if (index != -1) {
13344                     vm.accountModel.expMonth = vm.expMonths[index].key;
13345                 }
13346                 vm.accountModel.expYear = expDate[2];
13347            }
13348        }
13349        // Checking the condition to display credit card section
13350		function _setCreditCardSection() {
13351			var result;
13352            if(vm.domain == 'US'|| vm.domain == 'CA'){
13353             result = vm.hasPartnerInfo ? (angular.isDefined(vm.customerResponce.partnerCustomerInfo.ccSummary) ? myProfileService.getCreditCardDetails(vm.customerResponce.partnerCustomerInfo.ccSummary) : myProfileService.getCreditCardDetails()):myProfileService.getCreditCardDetails();
13354            }
13355            if(vm.domain == 'AU'|| vm.domain == 'NZ'){
13356 		    result = vm.hasPartnerInfo ? (angular.isDefined(vm.customerResponce.partnerCustomerInfo.ccSummary) ? myProfileService.getCreditCardDetails(vm.customerResponce.partnerCustomerInfo.ccSummary) : myProfileService.getCreditCardDetails()) : (angular.isDefined(vm.customerResponce.customerInfo.ccSummary) ? myProfileService.getCreditCardDetails(vm.customerResponce.customerInfo.ccSummary) : myProfileService.getCreditCardDetails());
13357            }
13358            vm.ccDetailList = result.masterListForCC;
13359            vm.ccDetailListAUNZ=result.masterListForCCAUNZ;
13360        	//If CC details in customer data - for backbutton
13361        	if(vm.customerResponce.customerInfo && angular.isDefined(vm.customerResponce.customerInfo.ccSummary) && angular.isDefined(vm.customerResponce.customerInfo.ccSummary.number)){
13362        		vm.creditCardType = vm.customerResponce.customerInfo.ccSummary.number;
13363            	vm.accountModel.cardType = vm.customerResponce.customerInfo.ccSummary.type;
13364            //If CC details in partner info- create for MPF flow	
13365        	}else if(angular.isDefined(result.customerCcDetails)){
13366        		vm.creditCardType = result.customerCcDetails.value;
13367            	vm.accountModel.cardType = result.customerCcDetails.code;
13368        	}
13369        }
13370
13371        function _getSectionInEdit(e) {
13372            vm.sectionInEdit = myProfileService.getSectionInEdit(e);
13373        }       
13374        
13375        
13376		// Function will be called on page load
13377		function onPageLoad() {
13378			reservationModelService.addGTMScript();
13379			var captchaForm = $("#profileCreditCardForm");
13380	        if(angular.isDefined(vm.captchaFlag) && captchaForm.length == 1){
13381	        	vm.captchaFlag=true;
13382	        }
13383			if(angular.isDefined(authenticationService.getXsrfToken())){
13384				isValidXSRF  = false;
13385				initialize();
13386			}
13387		}
13388		
13389		$rootScope.$on('initSuccess', function(event, arg) {
13390			if(isValidXSRF){
13391				initialize();
13392			}
13393		});
13394		
13395		
13396		function initialize(){
13397			getVehicles.accountSummaryload('preferredFlow').then(function(response){
13398				vm.customerResponce = response;
13399				if(angular.isDefined(vm.customerResponce.customerInfo)&&angular.isDefined(vm.customerResponce.customerInfo.profileCompletionPercentage)&&angular.isDefined(vm.customerResponce.customerInfo.profCompStep)){
13400					vm.customerData.profileCompletionPercentage = vm.customerResponce.customerInfo.profileCompletionPercentage;
13401					vm.customerData.profCompStep = vm.customerResponce.customerInfo.profCompStep;
13402				}
13403				_checkForPartnerCustomerInfo();
13404				if(vm.hasPartnerInfo && angular.isDefined(vm.customerResponce.partnerCustomerInfo.partnerType) && vm.customerResponce.partnerCustomerInfo.partnerType == "PARTNER_CBP"){
13405	    	    		$rootScope.$broadcast("CBPImageName", vm.customerResponce.partnerCustomerInfo);				
13406	    		}
13407				if((!angular.isDefined(vm.customerResponce.partnerCustomerInfo)) || (angular.isDefined(vm.customerResponce.customerInfo) && angular.isDefined(vm.customerResponce.customerInfo.ccSummary) && angular.isDefined(vm.customerResponce.customerInfo.ccSummary.number))){
13408					vm.accountModel = myProfileService.getAccountData(vm.customerResponce.customerInfo);
13409				}else{
13410					vm.accountModel = myProfileService.getAccountData(vm.customerResponce.partnerCustomerInfo);
13411				}
13412				
13413				if(angular.isDefined(vm.customerResponce.displayControl) && angular.isDefined(vm.customerResponce.displayControl.enrollmentStep)){
13414					var enrollmentStep = vm.customerResponce.displayControl.enrollmentStep;
13415					vm.customerData.enrollmentStep = enrollmentStep;
13416					myProfileService.triggerEditMode(undefined, true, enrollmentStep); //carRentalConstant.enrollmentStepToSectionModel[enrollmentStep]
13417				}
13418				_loadMnthYrDropdown();
13419				_setCreditCardSection();
13420				onChangeCreditCardType();
13421				
13422			}, function(error) {
13423				if(angular.isDefined(error.errorList) && error.errorList.length > 0){
13424        			vm.formError = error.errorList[0].message;
13425	                vm.formValidated = true;
13426        		}
13427				$rootScope.requestInProgress = false;
13428			});
13429		}
13430		//To save user details
13431		vm.saveCredit = {
13432				submit: function(profileForm, e) {
13433							$rootScope.requestInProgress = true;
13434							_getSectionInEdit(e);
13435							//var accountModel = vm.accountModel;
13436							$validationProvider.validate(profileForm).success(function(){
13437								vm.saveCredit.validationSuccess();
13438							}).error(function(data){
13439								vm.accountModel.secureCode ='';
13440								vm.formError = ABG.getFormValidationError(data,false)[0].message;
13441								vm.formValidated = true;
13442								$rootScope.requestInProgress = false;
13443								if(data.errorCount>1){
13444									myProfileService.anchorToMsg(vm.sectionInEdit);
13445									}
13446									else if(data.errorCount==1){
13447										 document.getElementsByName(data.fieldName)[0].focus();
13448									}
13449								
13450							});
13451					},
13452				validationSuccess: function() {
13453					if(enableCaptcha == 'true'){
13454						grecaptcha.execute();
13455					}
13456					else{
13457						vm.saveCredit.successCreditCardUpdate();
13458						}
13459	     		},
13460				successCreditCardUpdate: function() {
13461					//credit session update
13462					var accountModel = vm.accountModel;
13463						 if(vm.sectionInEdit == 'credit-card-section' && (!(angular.isDefined(vm.accountModel.ccSummary.maskId)) || (angular.isDefined(vm.accountModel.ccSummary.maskId) && vm.accountModel.ccSummary.maskId == ""))){
13464							accountModel = vm.accountModel.ccSummary;
13465								accountModel.primary = true;
13466									myProfileService.updateProfile(vm.customerResponce.customerInfo,accountModel,vm.sectionInEdit,vm.recaptcha).then(function(data){ 
13467										data = $scope.processErrorMessage(data);
13468										if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
13469											vm.accountModel.secureCode ='';
13470											vm.formError = data.errorList[0].message;
13471											vm.formValidated = true;
13472											$rootScope.requestInProgress = false;
13473											myProfileService.anchorToMsg(vm.sectionInEdit);
13474										}else{
13475											var redirectPath = signupService.rulesToRedirect(data);
13476											$window.location.href = redirectPath;                  
13477										}
13478									}, function(error) {
13479										if(angular.isDefined(error.errorList) && error.errorList.length > 0){
13480											vm.formError = error.errorList[0].message;
13481											vm.formValidated = true;
13482											myProfileService.anchorToMsg(vm.sectionInEdit);
13483											if(enableCaptcha == 'true') {
13484												ABG.resetCaptcha(true);
13485											}
13486										}
13487										vm.accountModel.secureCode ='';
13488										$rootScope.requestInProgress = false;
13489									});
13490						}
13491						if(enableCaptcha == 'true') {
13492												ABG.resetCaptcha(true);
13493											}
13494				}
13495		};		
13496		$(".enrollment-form").on("click", ".wrap-toggle-link", function(e) {
13497            var $this = $(this),
13498                toggleText = $this.parent().find(".wrap-toggle-text");
13499
13500            if ($this.hasClass("view-more")) {
13501                $this.text($this.data("viewlesslabel")).addClass("view-less").removeClass("view-more");
13502                toggleText.removeClass("hidden-xs");
13503            } else {
13504                $this.text($this.data("viewmorelabel")).addClass("view-more").removeClass("view-less");
13505                toggleText.addClass("hidden-xs");
13506            }
13507        });
13508		// Page Init...
13509		onPageLoad();
13510		$rootScope.$on("recaptcha", function(event, response){
13511    	 vm.recaptcha=response;
13512			if(angular.isDefined(response) && response != ''){
13513				//vm.loginInProgress = true;
13514				vm.saveCredit.successCreditCardUpdate();
13515			}			
13516    	 				
13517     });
13518		
13519	}
13520})();
13521(function () {
13522	'use strict';
13523
13524	angular
13525		.module('account')
13526		.controller('PreferredDriverLicenseController', PreferredDriverLicenseController);
13527
13528	PreferredDriverLicenseController.$inject = ['$controller', '$scope', 'carRentalConstant', '$rootScope', '$window', 'authenticationService', 'myProfileService', 'datePickerInit', '$locale', '$filter', '$validation', 'rewardsProgramService', 'accountUtilityService', 'signupService', 'accountgaService', 'getVehicles', 'anchorSmoothScroll', 'storageService', 'gaService', 'reservationModelService'];
13529
13530	function PreferredDriverLicenseController($controller, $scope, carRentalConstant, $rootScope, $window, authenticationService, myProfileService, datePickerInit, $locale, $filter, $validationProvider, rewardsProgramService, accountUtilityService, signupService, accountgaService, getVehicles, anchorSmoothScroll, storageService, gaService, reservationModelService) {
13531
13532		$controller('ExceptionHandlerController', {
13533			$scope: $scope
13534		});
13535
13536
13537		// View Model.....
13538		var vm = this;
13539		var isValidXSRF = true;
13540		vm.hideExpMonthYear = true;
13541		vm.hasPartnerInfo = false;
13542		vm.customerData = {};
13543		vm.customerData.preferred = true;
13544		vm.hideCVV = true;
13545		vm.disableDLState = false;
13546		vm.hideDLState = false;
13547		vm.domain = $window.domain.toUpperCase();
13548		vm.hideDLForm = false;
13549		vm.isEnterManual = false;
13550		vm.dlCountryName = '';
13551		vm.showBiometricScan = false;
13552		vm.brand= $window.brand;
13553
13554		// View Callable.....
13555		vm.saveProfileDetail = saveProfileDetail;
13556		vm.validatePhoneNumber = validatePhoneNumber;
13557		vm.getStateBasedOnCounty = getStateBasedOnCounty;
13558		vm.loadHelpModal = loadHelpModal;
13559		vm.saveProfile = saveProfile;
13560		vm.initiateMitekVerification = initiateMitekVerification;
13561		vm.showManualDlForm = showManualDlForm;
13562
13563		// Private Methods.....
13564		vm._setDlSection = _setDlSection;
13565		vm._loadCalendarDropdown = _loadCalendarDropdown;
13566		vm._loadCountry = _loadCountry;
13567
13568		function _checkForPartnerCustomerInfo() {
13569			if (angular.isDefined(vm.customerResponce) && angular.isDefined(vm.customerResponce.partnerCustomerInfo) && !angular.equals({}, vm.customerResponce.partnerCustomerInfo)) {
13570				vm.hasPartnerInfo = true;
13571			} else {
13572				vm.hasPartnerInfo = false;
13573			}
13574		}
13575
13576		function _loadCountry() {
13577			vm.countryList = accountUtilityService.getCountryList();
13578			vm.accountModel.dlSummary.country = (angular.isDefined(vm.customerResponce.customerInfo.dlSummary) && angular.isDefined(vm.customerResponce.customerInfo.dlSummary.country)) ? vm.customerResponce.customerInfo.dlSummary.country : vm.customerResponce.customerInfo.cor;
13579			getStateBasedOnCounty(vm.accountModel.dlSummary.country);
13580			if (vm.customerResponce.customerInfo.cor == "US" || vm.customerResponce.customerInfo.cor == "CA") {
13581				vm.showSmsOptIn = true;
13582			} else {
13583				vm.showSmsOptIn = false;
13584			}
13585		};
13586
13587		// Load states depending on domain and on change of country drop down
13588		function getStateBasedOnCounty(countryCode, countryListForDriverLicense) {
13589			var countryAndState = {};
13590			if (angular.isDefined(countryListForDriverLicense) && countryListForDriverLicense.length > 0) {
13591				countryAndState = accountUtilityService.getStateListBasedOnCounty(countryCode, countryListForDriverLicense);
13592			} else {
13593				countryAndState = accountUtilityService.getStateListBasedOnCounty(countryCode, vm.countryList);
13594			}
13595			vm.adrTelCountryName = countryAndState.countryName;
13596			vm.statesForDL = countryAndState.statesForDL;
13597			//GRY-3012,hiding the state field if the selected country is not having states in DL section.
13598
13599			vm.hideDLState = ((angular.isUndefined(vm.statesForDL) || vm.statesForDL[0].stateCode == "Not Applicable") && (angular.isDefined(vm.customerResponce.displayControl && vm.customerResponce.displayControl.enrollmentStep) && vm.customerResponce.displayControl.enrollmentStep == 'dl-section')) ? true : false;
13600			if (vm.hideDLState == true && angular.isDefined(vm.accountModel.dlSummary.state)) {
13601				vm.accountModel.dlSummary.state = "Not Applicable";
13602			}
13603			else if (angular.isDefined(vm.accountModel.dlSummary.state)) {
13604				vm.accountModel.dlSummary.state = null;
13605			}
13606
13607			/*
13608			 * disabling state field in concur flow only if the state value from partnerInfo is present in dropdown list and prefilled 
13609			 */
13610			if (angular.isDefined(vm.statesForDL)) {
13611				if ($filter('filter')(vm.statesForDL, { 'stateCode': vm.accountModel.dlSummary.state })[0]) {
13612					vm.disableDLState = true;
13613				}
13614			}
13615			//set default state dropdown value:
13616			if (angular.isDefined(vm.accountModel.dlSummary.state) && angular.isDefined(vm.statesForDL) && (vm.accountModel.dlSummary.state == "" && vm.statesForDL.length > 1)) {
13617				vm.accountModel.dlSummary.state = null;
13618			}
13619
13620		}
13621
13622		function saveProfile(phoneNumberModelName, phoneNumber, smsOptin, section, profileForm, Obj, e, index) {
13623			if (angular.isDefined(smsOptin) && smsOptin && angular.isDefined(phoneNumber) && (vm.customerResponce.customerInfo.cor == "US" || vm.customerResponce.customerInfo.cor == "CA")) {
13624				vm.validatePhoneNumber(phoneNumberModelName, phoneNumber, smsOptin, section, profileForm, Obj, e, index);
13625			}
13626			else {
13627				vm.saveProfileDetail(profileForm, e)
13628			}
13629		}
13630
13631
13632		function validatePhoneNumber(phoneNumberModelName, phoneNumber, smsOptin, section, profileForm, Obj, e, index) {
13633			$rootScope.requestInProgress = true;
13634			$validationProvider.validate(profileForm).success(function () {
13635				myProfileService.validatePhoneNumber(phoneNumberModelName, phoneNumber, smsOptin, section, vm.accountModel).then(function (data) {
13636					if ((angular.isDefined(data.errorList) && data.errorList.length > 0) || (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0)) {
13637						$rootScope.requestInProgress = false;
13638						anchorSmoothScroll.scrollTo('email-offers');
13639					}
13640					else {
13641						vm.saveProfileDetail(profileForm, e);
13642					}
13643				}, function (error) {
13644					if (angular.isDefined(error.errorList) && error.errorList.length > 0) {
13645						vm.formError = error.errorList[0].message;
13646						vm.formValidated = true;
13647					}
13648					$rootScope.requestInProgress = false;
13649				});
13650			}).error(function (data) {
13651				vm.formError = ABG.getFormValidationError(data, false)[0].message;
13652				vm.formValidated = true;
13653				$rootScope.requestInProgress = false;
13654				if (data.errorCount > 1) {
13655					myProfileService.anchorToMsg(vm.sectionInEdit);
13656				}
13657				else if (data.errorCount == 1) {
13658					document.getElementsByName(data.fieldName)[0].focus();
13659				}
13660			});
13661		}
13662
13663		function _loadCalendarDropdown() {
13664			var lowerAgeLimit = vm.hasPartnerInfo ? (angular.isDefined(vm.customerResponce.partnerCustomerInfo.minAge) ? vm.customerResponce.partnerCustomerInfo.minAge : carRentalConstant.ageLimit.lower) : carRentalConstant.ageLimit.lower;
13665			var CalendarDetails = accountUtilityService.loadCalendarDropdown(lowerAgeLimit);
13666			vm.monthsList = CalendarDetails.monthsList;
13667			vm.yearsList = CalendarDetails.yearsList;
13668			vm.datesList = CalendarDetails.datesList;
13669			//sets the dropdown if DOB is available
13670			if (angular.isDefined(vm.customerResponce.customerInfo) && angular.isDefined(vm.customerResponce.customerInfo.dlSummary) && angular.isUndefined(vm.customerResponce.customerInfo.dlSummary.dlNumber)) {
13671				if (angular.isDefined(vm.customerResponce.partnerCustomerInfo) && angular.isDefined(vm.customerResponce.partnerCustomerInfo.dob)
13672					&& angular.isDefined(vm.monthsList) && vm.monthsList != "" && vm.monthsList.length > 0 && angular.isDefined(vm.accountModel)) {
13673					var date = vm.customerResponce.customerInfo.dob.split("/");
13674					var index = vm.monthsList.indexOf($filter('filter')(vm.monthsList, function (d) {
13675						return d.key == date[0];
13676					})[0]);
13677					if (angular.isDefined(index) && index != -1) {
13678						vm.accountModel.dobMonth = vm.monthsList[index].key;
13679					}
13680					vm.accountModel.dobDate = date[1];
13681					vm.accountModel.dobYear = date[2];
13682				}
13683			}
13684		}
13685		// To Set DL section to display
13686		function _setDlSection() {
13687			/*
13688			 * As concur interface has free text field for DL state user can enter either state name or code.
13689			 * To pre-fill state dropdown mapping the state Name to state Code.
13690			 */
13691			//Pre-fill phone number if already entered in 1st step of profile flow.( ARD2-508 changes as part of pre-otp changes )
13692			vm.accountModel.dlSummary.telephone = vm.customerResponce.customerInfo.cellPhone;
13693			vm.countryListForDriverLicense = accountUtilityService.getCountryList(vm.customerResponce, $window.countryListForDriverLicense);
13694			if (angular.isDefined(vm.customerResponce) && angular.isDefined(vm.customerResponce.customerInfo) && angular.isDefined(vm.customerResponce.customerInfo.dlSummary) && angular.isDefined(vm.customerResponce.customerInfo.dlSummary.country)) {
13695				vm.statesForDL = accountUtilityService.getStateListBasedOnCounty(vm.customerResponce.customerInfo.dlSummary.country, vm.countryListForDriverLicense).statesForDL;
13696			}
13697			if (vm.statesForDL && angular.isDefined(vm.customerResponce.partnerCustomerInfo) && angular.isDefined(vm.customerResponce.partnerCustomerInfo.dlSummary) && angular.isDefined(vm.customerResponce.partnerCustomerInfo.dlSummary.state) && vm.customerResponce.customerInfo.dlSummary.state !== '') {
13698				var index = vm.statesForDL.indexOf($filter('filter')(
13699					vm.statesForDL,
13700					function (d) {
13701						return (d.stateCode.toUpperCase() === vm.customerResponce.partnerCustomerInfo.dlSummary.state.toUpperCase() || d.stateName.toUpperCase() === vm.customerResponce.partnerCustomerInfo.dlSummary.state.toUpperCase());
13702					})[0]);
13703				if (index > -1) {
13704					vm.disableDLState = true;
13705					vm.accountModel.dlSummary.state = vm.statesForDL[index].stateCode;
13706				}
13707			}
13708			if (vm.countryListForDriverLicense && angular.isDefined(vm.customerResponce.customerInfo) && angular.isDefined(vm.customerResponce.customerInfo.dlSummary) && angular.isDefined(vm.customerResponce.customerInfo.dlSummary.dlNumber) && vm.customerResponce.customerInfo.dlSummary.dlNumber !== '') {
13709				vm.showDOBField = false;
13710			} else {
13711				vm.showDOBField = true;
13712			}
13713
13714		}
13715
13716		function _getSectionInEdit(e) {
13717			vm.sectionInEdit = myProfileService.getSectionInEdit(e);
13718		}
13719		function _convertDataFormat(dobMonth, dobDate, dobYear) {
13720			if (angular.isDefined(dobMonth) && angular.isDefined(dobDate) && angular.isDefined(dobYear) &&
13721				dobMonth != "" && dobDate != "" && dobYear != "") {
13722				return dobMonth + "/" + dobDate + "/" + dobYear;
13723			}
13724		}
13725
13726		// Function will be called on page load
13727		function onPageLoad() {
13728			if (angular.isDefined(authenticationService.getXsrfToken())) {
13729				isValidXSRF = false;
13730				initialize();
13731			}
13732		}
13733
13734		$rootScope.$on('initSuccess', function (event, arg) {
13735			if (isValidXSRF) {
13736				initialize();
13737			}
13738		});
13739
13740		function initialize() {
13741			getVehicles.accountSummaryload('preferredFlow').then(function (response) {
13742				vm.customerResponce = response;
13743				if(vm.customerResponce.customerInfo.cor == "US" || vm.customerResponce.customerInfo.cor == "CA"){
13744					vm.showBiometricScan = true;
13745				}
13746				vm.showPrefilled = storageService.getStorageData('dlVerifiedWithMitek');
13747				reservationModelService.addGTMScript();
13748				if (vm.showPrefilled && vm.customerResponce.customerInfo.dlSummary) {
13749					console.log(JSON.stringify(vm.customerResponce.customerInfo.dlSummary));
13750					vm.countryListForBiometricDl = accountUtilityService.getCountryList(vm.customerResponce.customerInfo, $window.countryListForDriverLicense);
13751					if(angular.isDefined(vm.countryListForBiometricDl) && vm.countryListForBiometricDl.length){
13752						var index = vm.countryListForBiometricDl.indexOf(
13753							$filter('filter')(vm.countryListForBiometricDl, function (d) {
13754								return d.code === vm.customerResponce.customerInfo.dlSummary.country;
13755							})[0]
13756						);
13757		
13758						vm.dlCountryName = vm.countryListForBiometricDl[index].name;
13759					}
13760					gaService.trackMitekVerEventsDuringProfileEnroll('PREFILLED_DL', 'Success', vm.customerResponce.customerInfo);
13761				} else if (vm.showPrefilled && !angular.isDefined(vm.customerResponce.customerInfo.dlSummary)) {
13762					gaService.trackMitekVerEventsDuringProfileEnroll('PREFILLED_DL', 'Failure', vm.customerResponce.customerInfo);
13763				}
13764				if (angular.isDefined(vm.customerResponce.customerInfo) && angular.isDefined(vm.customerResponce.customerInfo.profileCompletionPercentage) && angular.isDefined(vm.customerResponce.customerInfo.profCompStep)) {
13765					vm.customerData.profileCompletionPercentage = vm.customerResponce.customerInfo.profileCompletionPercentage;
13766					vm.customerData.profCompStep = vm.customerResponce.customerInfo.profCompStep;
13767				}
13768				_checkForPartnerCustomerInfo();
13769				if (vm.hasPartnerInfo && angular.isDefined(vm.customerResponce.partnerCustomerInfo.partnerType) && vm.customerResponce.partnerCustomerInfo.partnerType == "PARTNER_CBP") {
13770					$rootScope.$broadcast("CBPImageName", vm.customerResponce.partnerCustomerInfo);
13771				}
13772				if ((!angular.isDefined(vm.customerResponce.partnerCustomerInfo)) || (angular.isDefined(vm.customerResponce.customerInfo) && angular.isDefined(vm.customerResponce.customerInfo.dlSummary) && angular.isDefined(vm.customerResponce.customerInfo.dlSummary.dlNumber))) {
13773					vm.accountModel = myProfileService.getAccountData(vm.customerResponce.customerInfo);
13774				} else {
13775					vm.accountModel = myProfileService.getAccountData(vm.customerResponce.partnerCustomerInfo);
13776				}
13777				if (angular.isDefined(vm.accountModel) && angular.isDefined(vm.accountModel.dlSummary) && angular.isDefined(vm.accountModel.dlSummary.telephone) && vm.accountModel.dlSummary.telephone != "") {
13778					vm.accountModel.dlSummary.maskId = "1"
13779					vm.accountModel.dlSummary.operation = 'update';
13780				}
13781				if (angular.isDefined(vm.customerResponce.displayControl) && angular.isDefined(vm.customerResponce.displayControl.enrollmentStep)) {
13782					var enrollmentStep = vm.customerResponce.displayControl.enrollmentStep;
13783					vm.customerData.enrollmentStep = enrollmentStep;
13784					myProfileService.triggerEditMode(undefined, true, enrollmentStep); //carRentalConstant.enrollmentStepToSectionModel[enrollmentStep]
13785				}
13786				accountgaService.analyticsDimension(vm.customerResponce, 'driver-license');
13787				_loadCountry();
13788				_setDlSection();
13789				_loadCalendarDropdown();
13790				if (angular.isDefined(vm.customerResponce.customerInfo) && vm.customerResponce.customerInfo.quickPassUpdateFlow) {
13791					vm.accountModel.dlSummary.state = vm.customerResponce.customerInfo.dlSummary.state;
13792				}
13793				/* disableSaveCTA based on T&C status */
13794				if (angular.isDefined(vm.customerResponce.customerInfo) && angular.isDefined(vm.customerResponce.customerInfo.preferred) && vm.customerResponce.customerInfo.preferred) {
13795					vm.disableSaveCTA = true;
13796				} else {
13797					vm.disableSaveCTA = false;
13798				}
13799
13800			}, function (error) {
13801				if (angular.isDefined(error.errorList) && error.errorList.length > 0) {
13802					vm.formError = error.errorList[0].message;
13803					vm.formValidated = true;
13804				}
13805				$rootScope.requestInProgress = false;
13806			});
13807		}
13808
13809		//To save user details
13810		function saveProfileDetail(profileForm, e) { //TODO check for the form values
13811			$rootScope.requestInProgress = true;
13812			if(vm.showPrefilled){
13813				reservationModelService.addGTMScript();
13814				gaService.trackMitekVerEventsDuringProfileEnroll('SAVE_DL_CTA', 'Click', vm.customerResponce.customerInfo);
13815			}
13816			_getSectionInEdit(e);
13817			if (vm.sectionInEdit == 'dl-section' && angular.isDefined(vm.accountModel.dlSummary.telephone) && angular.isDefined(vm.accountModel.contactAddress) && angular.isDefined(vm.accountModel.contactAddress.telep
13817hone) && vm.accountModel.contactAddress.telephone != "") {
13818				vm.accountModel.dlSummary.maskId = vm.accountModel.contactAddress.telephone[0].maskId;
13819				vm.accountModel.dlSummary.primary = vm.accountModel.contactAddress.telephone[0].primary;
13820				vm.accountModel.dlSummary.operation = 'update';
13821			}
13822			if (angular.isDefined(vm.accountModel.dlSummary.dlNumber)) {
13823				vm.accountModel.dlSummary.dlNumber = vm.accountModel.dlSummary.dlNumber.replace(/-|\s/g, "");
13824			}
13825			$validationProvider.validate(profileForm).success(function () {
13826				myProfileService.updateProfile(vm.customerResponce.customerInfo, vm.accountModel, vm.sectionInEdit).then(function (data) {
13827					data = $scope.processErrorMessage(data);
13828					if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
13829						/*
13830						 * Error message for age limit in MPf flow varies depending  on AWD rules.
13831						 * i18n for the error includes an angular expression to generate message dynamically.
13832						 * It needs $scope.$eval method to parse where other messages throw console error for $scope.$eval. 
13833						 * So added below condition check.
13834						 */
13835						if (data.errorList[0].code == '06042') {
13836							vm.formError = $scope.$eval(data.errorList[0].message);
13837						} else {
13838							vm.formError = data.errorList[0].message;
13839						}
13840						if(vm.showPrefilled){
13841							reservationModelService.addGTMScript();
13842							gaService.trackMitekVerEventsDuringProfileEnroll('DL_UPDATED', 'Failure', vm.customerResponce.customerInfo);
13843						}
13844						vm.formValidated = true;
13845						$rootScope.requestInProgress = false;
13846						myProfileService.anchorToMsg(vm.sectionInEdit);
13847					} else {
13848						if(vm.showPrefilled){
13849							reservationModelService.addGTMScript();
13850							gaService.trackMitekVerEventsDuringProfileEnroll('DL_UPDATED', 'Success', vm.customerResponce.customerInfo);
13851						}
13852						var redirectPath = signupService.rulesToRedirect(data);
13853						$window.location.href = redirectPath;
13854					}
13855				}, function (error) {
13856					if (angular.isDefined(error.errorList) && error.errorList.length > 0) {
13857						vm.formError = error.errorList[0].message;
13858						vm.formValidated = true;
13859						myProfileService.anchorToMsg(vm.sectionInEdit);
13860						if(vm.showPrefilled){
13861							reservationModelService.addGTMScript();
13862							gaService.trackMitekVerEventsDuringProfileEnroll('DL_UPDATED', 'Failure', vm.customerResponce.customerInfo);
13863						}
13864					}
13865					$rootScope.requestInProgress = false;
13866				});
13867			}).error(function (data) {
13868				vm.formError = ABG.getFormValidationError(data, false)[0].message;
13869				vm.formValidated = true;
13870				$rootScope.requestInProgress = false;
13871				if(vm.showPrefilled){
13872					reservationModelService.addGTMScript();
13873					gaService.trackMitekVerEventsDuringProfileEnroll('DL_UPDATED', 'Failure', vm.customerResponce.customerInfo);
13874				}
13875				if (data.errorCount > 1) {
13876					myProfileService.anchorToMsg(vm.sectionInEdit);
13877				}
13878				else if (data.errorCount == 1) {
13879					document.getElementsByName(data.fieldName)[0].focus();
13880				}
13881			});
13882		}
13883
13884		$(".enrollment-form").on("click", ".wrap-toggle-link", function (e) {
13885			var $this = $(this),
13886				toggleText = $this.parent().find(".wrap-toggle-text");
13887
13888			if ($this.hasClass("view-more")) {
13889				$this.text($this.data("viewlesslabel")).addClass("view-less").removeClass("view-more");
13890				toggleText.removeClass("hidden-xs");
13891			} else {
13892				$this.text($this.data("viewmorelabel")).addClass("view-more").removeClass("view-less");
13893				toggleText.addClass("hidden-xs");
13894			}
13895		});
13896
13897		function loadHelpModal(currentEle) {
13898			vm.country = $window.countrySelect ? $window.countrySelect : 'US';
13899			var target = currentEle.target.parentElement;
13900			vm.helpURL = getVehicles.getUrl(target, country);
13901		}
13902
13903		function initiateMitekVerification() {
13904			reservationModelService.addGTMScript();
13905			gaService.trackMitekVerEventsDuringProfileEnroll('START_SCAN_CTA', 'Click', vm.customerResponce.customerInfo);
13906			$window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot + "/biometric-validation/mitek-validation" + htmlExtension + "#/front-scan";
13907		}
13908		function showManualDlForm() {
13909			reservationModelService.addGTMScript();
13910			gaService.trackMitekVerEventsDuringProfileEnroll('ENTER_MANUAL_CTA', 'Click', vm.customerResponce.customerInfo);
13911			vm.isEnterManual = true;
13912		}
13913		// Page Init...
13914		onPageLoad();
13915
13916		$(document).on('DOMNodeInserted', function (e) {
13917			if (angular.element('.driver-info-success').length && !vm.successScroll) {
13918				setTimeout(function () {
13919					$('html, body').animate({
13920						scrollTop: $('.driver-info-success').offset().top - 90
13921					});
13922				}, 1000);
13923				vm.successScroll = true;
13924			}
13925		});
13926
13927	}
13928})();
13929(function() {
13930	'use strict';
13931	
13932	angular
13933		.module('account')
13934		.controller('PreferredProtectionCoverageController', PreferredProtectionCoverageController);
13935	
13936	PreferredProtectionCoverageController.$inject = ['$controller', '$scope', 'carRentalConstant', '$rootScope', '$window', 'authenticationService', 'myProfileService','datePickerInit', '$locale', '$filter', '$validation', 'rewardsProgramService', 'signupService', 'accountgaService','getVehicles'];
13937
13938	function PreferredProtectionCoverageController($controller, $scope, carRentalConstant, $rootScope, $window, authenticationService, myProfileService,datePickerInit, $locale, $filter, $validationProvider, rewardsProgramService, signupService, accountgaService,getVehicles) {
13939
13940		$controller('ExceptionHandlerController', {
13941			$scope: $scope
13942		});
13943		
13944		
13945		// View Model.....
13946		var vm = this;
13947		var isValidXSRF = true;
13948		vm.hideExpMonthYear = true;
13949		vm.hasPartnerInfo = false;
13950		vm.customerData = {};
13951		vm.customerData.preferred = true;
13952		vm.hideCVV = true;
13953		vm.tdCheck = true;
13954
13955		// View Callable.....
13956		vm.modifyTempList = modifyTempList;
13957		vm.cancelTempListModifications = cancelTempListModifications;
13958		vm.saveProfileDetail = saveProfileDetail;
13959		
13960		// Private Methods.....
13961        
13962        function _checkForPartnerCustomerInfo(){
13963        	if(angular.isDefined(vm.customerResponce) && angular.isDefined(vm.customerResponce.partnerCustomerInfo) && !angular.equals({}, vm.customerResponce.partnerCustomerInfo)){
13964        		vm.hasPartnerInfo = true;       		
13965        	}else{
13966        		vm.hasPartnerInfo = false;
13967        	}
13968        }
13969        
13970
13971        function _getSectionInEdit(e) {
13972            vm.sectionInEdit = myProfileService.getSectionInEdit(e);
13973        }       
13974        
13975		// Function will be called on page load
13976		function onPageLoad() {
13977			if(angular.isDefined(authenticationService.getXsrfToken())){
13978				isValidXSRF  = false;
13979				initialize();
13980			}
13981		}
13982		
13983		$rootScope.$on('initSuccess', function(event, arg) {
13984			if(isValidXSRF){
13985				initialize();
13986			}
13987		});
13988		
13989		function initialize(){
13990			getVehicles.accountSummaryload('preferredFlow').then(function(response){
13991				vm.customerResponce = response;				
13992				if(angular.isDefined(vm.customerResponce.customerInfo)&&angular.isDefined(vm.customerResponce.customerInfo.profileCompletionPercentage)&&angular.isDefined(vm.customerResponce.customerInfo.profCompStep)){
13993					vm.customerData.profileCompletionPercentage = vm.customerResponce.customerInfo.profileCompletionPercentage;
13994					vm.customerData.profCompStep = vm.customerResponce.customerInfo.profCompStep;
13995				}
13996				_checkForPartnerCustomerInfo();
13997				if(vm.hasPartnerInfo && angular.isDefined(vm.customerResponce.partnerCustomerInfo.partnerType) && vm.customerResponce.partnerCustomerInfo.partnerType == "PARTNER_CBP"){
13998	    	    		$rootScope.$broadcast("CBPImageName", vm.customerResponce.partnerCustomerInfo);				
13999	    		}
14000				vm.accountModel = myProfileService.getAccountData(vm.customerResponce.customerInfo);
14001				var supportedInsurances;
14002    			if(vm.hasPartnerInfo && angular.isDefined(vm.customerResponce.partnerCustomerInfo.insuranceMap)){
14003					supportedInsurances = vm.customerResponce.partnerCustomerInfo.insuranceMap;
14004				}
14005    			myProfileService.loadSupportedExtras(vm.customerResponce.customerInfo,supportedInsurances).then(function(extrasData) {
14006    				vm.accountModel.extrasData = extrasData;
14007    				vm.accountModel.tempList = angular.copy(vm.accountModel.extrasData);
14008    			});
14009				if(angular.isDefined(vm.customerResponce.displayControl) && angular.isDefined(vm.customerResponce.displayControl.enrollmentStep)){
14010					var enrollmentStep = vm.customerResponce.displayControl.enrollmentStep;
14011					vm.customerData.enrollmentStep = enrollmentStep;
14012					myProfileService.triggerEditMode(undefined, true, enrollmentStep);//carRentalConstant.enrollmentStepToSectionModel[enrollmentStep]
14013				}
14014				accountgaService.analyticsDimension(vm.customerResponce, 'protection-and-coverages');
14015				
14016			}, function(error) {
14017				if(angular.isDefined(error.errorList) && error.errorList.length > 0){
14018        			vm.formError = error.errorList[0].message;
14019	                vm.formValidated = true;
14020        		}
14021        		$rootScope.requestInProgress = false;
14022			});
14023		}
14024
14025		function modifyTempList(product, value, type) {
14026            for (var i = 0; i < vm.accountModel.tempList[type].length; i++) {
14027                if (product.code === vm.accountModel.tempList[type][i].code) {
14028                    vm.accountModel.tempList[type][i].value = value;
14029                    break;
14030                }
14031            }
14032        }
14033		function cancelTempListModifications() {
14034            vm.accountModel.tempList = angular.copy(vm.accountModel.extrasData);
14035        }
14036		
14037		//To save user details
14038		function saveProfileDetail(profileForm, e) { //TODO check for the form values
14039        	$rootScope.requestInProgress = true;
14040            _getSectionInEdit(e);
14041            $validationProvider.validate(profileForm).success(function(){
14042            	myProfileService.updateProfile(vm.customerResponce.customerInfo,vm.accountModel,vm.sectionInEdit).then(function(data){ 
14043                    data = $scope.processErrorMessage(data);
14044                    if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
14045                    	vm.formError = data.errorList[0].message;
14046                        vm.formValidated = true;
14047                        $rootScope.requestInProgress = false;
14048                        myProfileService.anchorToMsg(vm.sectionInEdit);
14049                    }else{
14050                    	var redirectPath = signupService.rulesToRedirect(data);
14051                		$window.location.href = redirectPath;                  
14052                    }
14053            	}, function(error) {
14054            		if(angular.isDefined(error.errorList) && error.errorList.length > 0){
14055            			vm.formError = error.errorList[0].message;
14056    	                vm.formValidated = true;
14057    	                myProfileService.anchorToMsg(vm.sectionInEdit);
14058            		}
14059            		$rootScope.requestInProgress = false;
14060            	});
14061            }).error(function(data){
14062            	vm.formError = ABG.getFormValidationError(data,false)[0].message;
14063            	vm.formValidated = true;
14064                $rootScope.requestInProgress = false;
14065                myProfileService.anchorToMsg(vm.sectionInEdit);
14066            });
14067        }
14068		
14069		$(".enrollment-form").on("click", ".wrap-toggle-link", function(e) {
14070            var $this = $(this),
14071                toggleText = $this.parent().find(".wrap-toggle-text");
14072
14073            if ($this.hasClass("view-more")) {
14074                $this.text($this.data("viewlesslabel")).addClass("view-less").removeClass("view-more");
14075                toggleText.removeClass("hidden-xs");
14076            } else {
14077                $this.text($this.data("viewmorelabel")).addClass("view-more").removeClass("view-less");
14078                toggleText.addClass("hidden-xs");
14079            }
14080        });
14081		
14082		// Page Init...
14083		onPageLoad();
14084		
14085		
14086	}
14087})();
14088(function() {
14089	'use strict';
14090	
14091	angular
14092		.module('account')
14093		.controller('PreferredTermsConditionController', PreferredTermsConditionController);
14094	
14095	PreferredTermsConditionController.$inject = ['$controller', '$scope', 'carRentalConstant', '$rootScope', '$window', 'authenticationService', 'myProfileService','datePickerInit', '$locale', '$filter', '$validation', 'rewardsProgramService', 'accountUtilityService', 'signupService', 'accountgaService','getVehicles'];
14096
14097	function PreferredTermsConditionController($controller, $scope, carRentalConstant, $rootScope, $window, authenticationService, myProfileService,datePickerInit, $locale, $filter, $validationProvider, rewardsProgramService, accountUtilityService, signupService, accountgaService,getVehicles) {
14098
14099		$controller('ExceptionHandlerController', {
14100			$scope: $scope
14101		});
14102		
14103		
14104		// View Model.....
14105		var vm = this;
14106		var isValidXSRF  = true;
14107		vm.hideExpMonthYear = true;
14108		vm.hasPartnerInfo = false;
14109		vm.customerData = {};
14110		vm.customerData.preferred = true;
14111		vm.hideCVV = true;
14112		// View Callable.....
14113		vm.saveProfileDetail = saveProfileDetail;
14114		vm.declineProfileTermsCondition = declineProfileTermsCondition;
14115		vm.getTnCCountryList = $window.termsandconditionsMap;
14116		vm.domain = $window.domain.toUpperCase();
14117		// Private Methods.....
14118        
14119        function _checkForPartnerCustomerInfo(){
14120        	if(angular.isDefined(vm.customerResponce) && angular.isDefined(vm.customerResponce.partnerCustomerInfo) && !angular.equals({}, vm.customerResponce.partnerCustomerInfo)){
14121        		vm.hasPartnerInfo = true;       		
14122        	}else{
14123        		vm.hasPartnerInfo = false;
14124        	}
14125        }
14126        
14127        /*TODO- COR check will be removed once T&C data gets fetched from AEM node based on COR*/
14128        function _checkForConnectedCarTnCDisplay(){
14129        	if(angular.isDefined(vm.customerResponce.customerInfo) && !vm.customerResponce.customerInfo.preferred){
14130        		if(carRentalConstant.showConnectedCarTncArray.includes( vm.customerResponce.customerInfo.cor.toUpperCase())){
14131        				vm.accountModel.showConnectedCarTnC = true;
14132        		}else{
14133        			vm.accountModel.showConnectedCarTnC = false;
14134        		}
14135        	}
14136        }
14137        function _setTermsConditionSection() {
14138        	if(vm.customerResponce.customerInfo.preferred){
14139        		vm.disableDeclineButton = true;
14140        	}else{
14141        		vm.disableDeclineButton = false;
14142        	}
14143             vm.termsConditionSectionDisplay = false;
14144         
14145        }
14146
14147        function _getSectionInEdit(e) {
14148            vm.sectionInEdit = myProfileService.getSectionInEdit(e);
14149        } 
14150		
14151		// Function will be called on page load
14152		function onPageLoad() {
14153			if(angular.isDefined(authenticationService.getXsrfToken())){
14154				isValidXSRF  = false;
14155				initialize();
14156			}
14157		}
14158		
14159		$rootScope.$on('initSuccess', function(event, arg) {
14160			if(isValidXSRF){
14161				initialize();
14162			}
14163		});
14164		
14165		function initialize(){
14166			getVehicles.accountSummaryload('preferredFlow').then(function(response){
14167				vm.customerResponce = response;
14168				
14169				if(angular.isDefined(vm.customerResponce.customerInfo)&&angular.isDefined(vm.customerResponce.customerInfo.profileCompletionPercentage)&&angular.isDefined(vm.customerResponce.customerInfo.profCompStep)){
14170					vm.customerData.profileCompletionPercentage = vm.customerResponce.customerInfo.profileCompletionPercentage;
14171					vm.customerData.profCompStep = vm.customerResponce.customerInfo.profCompStep;
14172				}
14173				_checkForPartnerCustomerInfo();
14174				if(vm.hasPartnerInfo && angular.isDefined(vm.customerResponce.partnerCustomerInfo.partnerType) && vm.customerResponce.partnerCustomerInfo.partnerType == "PARTNER_CBP"){
14175	    	    		$rootScope.$broadcast("CBPImageName", vm.customerResponce.partnerCustomerInfo);				
14176	    		}
14177				vm.accountModel = myProfileService.getAccountData(vm.customerResponce.customerInfo);
14178				vm.accountModel.showConnectedCarTnC = true;
14179				vm.accountModel.showConnectedCarTncModal = false;
14180				if(angular.isDefined(vm.customerResponce.displayControl) && angular.isDefined(vm.customerResponce.displayControl.enrollmentStep)){
14181					var enrollmentStep = vm.customerResponce.displayControl.enrollmentStep;
14182					myProfileService.triggerEditMode(undefined, true, enrollmentStep);//carRentalConstant.enrollmentStepToSectionModel[enrollmentStep]
14183				}
14184				if(angular.isDefined(vm.getTnCCountryList) && (vm.getTnCCountryList != '')){
14185					vm.showTnCPage = getVehicles.gettermsMapURL(vm.getTnCCountryList, vm.domain)+'.partial.html';
14186				}
14187				accountgaService.analyticsDimension(vm.customerResponce, 'terms-and-conditions');
14188				_checkForConnectedCarTnCDisplay();
14189				_setTermsConditionSection();
14190				
14191			}, function(error) {
14192				if(angular.isDefined(error.errorList) && error.errorList.length > 0){
14193        			vm.formError = error.errorList[0].message;
14194	                vm.formValidated = true;
14195        		}
14196        		$rootScope.requestInProgress = false;
14197			});
14198		}
14199		function declineProfileTermsCondition(e){
14200			signupService.resendActivationEmail().then(function(response){
14201				$window.location.href = $rootScope.contextPath + "/" + $rootScope.locale +$window.contentRoot+"/activation" + htmlExtension;
14202			},function(){
14203				$window.location.href = $rootScope.contextPath + "/" + $rootScope.locale +$window.contentRoot+"/activation" + htmlExtension;
14204        	});
14205		}	
14206		//To save user details
14207		function saveProfileDetail(profileForm, e) { 
14208        	$rootScope.requestInProgress = true;
14209            _getSectionInEdit(e);
14210            $validationProvider.validate(profileForm).success(function(){
14211            	myProfileService.updateProfile(vm.customerResponce.customerInfo,vm.accountModel,vm.sectionInEdit).then(function(data){ 
14212                    data = $scope.processErrorMessage(data);
14213                    if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
14214                    	vm.formError = data.errorList[0].message;
14215                        vm.formValidated = true;
14216                        $rootScope.requestInProgress = false;
14217                    }else{
14218                    	var redirectPath = signupService.rulesToRedirect(data);
14219                		$window.location.href = redirectPath;                  
14220                    }
14221                    myProfileService.anchorToMsg(vm.sectionInEdit);
14222            	}, function(error) {
14223            		if(angular.isDefined(error.errorList) && error.errorList.length > 0){
14224            			vm.formError = error.errorList[0].message;
14225    	                vm.formValidated = true;
14226    	                myProfileService.anchorToMsg(vm.sectionInEdit);
14227            		}
14228            		$rootScope.requestInProgress = false;
14229            	})
14230            }).error(function(data){
14231            	vm.formError = ABG.getFormValidationError(data,false)[0].message;
14232            	vm.formValidated = true;
14233                $rootScope.requestInProgress = false;
14234                myProfileService.anchorToMsg(vm.sectionInEdit);
14235            });
14236        }
14237		
14238		$(".enrollment-form").on("click", ".wrap-toggle-link", function(e) {
14239            var $this = $(this),
14240                toggleText = $this.parent().find(".wrap-toggle-text");
14241
14242            if ($this.hasClass("view-more")) {
14243                $this.text($this.data("viewlesslabel")).addClass("view-less").removeClass("view-more");
14244                toggleText.removeClass("hidden-xs");
14245            } else {
14246                $this.text($this.data("viewmorelabel")).addClass("view-more").removeClass("view-less");
14247                toggleText.addClass("hidden-xs");
14248            }
14249        });
14250		
14251		// Page Init...
14252		onPageLoad();
14253		
14254		
14255	}
14256})();
14257(function() {
14258	'use strict';
14259	
14260	angular
14261		.module('account')
14262		.controller('PreferredRewardsController', PreferredRewardsController);
14263	
14264	PreferredRewardsController.$inject = ['$controller', '$scope', 'carRentalConstant', '$rootScope', '$window', 'authenticationService', 'myProfileService','datePickerInit', '$locale', '$filter', '$validation', 'rewardsProgramService', 'accountgaService', 'accountUtilityService','getVehicles'];
14265
14266	function PreferredRewardsController($controller, $scope, carRentalConstant, $rootScope, $window, authenticationService, myProfileService,datePickerInit, $locale, $filter, $validationProvider, rewardsProgramService, accountgaService, accountUtilityService,getVehicles) {
14267
14268		$controller('ExceptionHandlerController', {
14269			$scope: $scope
14270		});
14271		
14272		
14273		// View Model.....
14274		var vm = this;
14275		var isValidXSRF = true;
14276		vm.hideExpMonthYear = true;
14277		vm.hasPartnerInfo = false;
14278		vm.customerData = {
14279				'loyaltyEligible':{
14280					'visible': false
14281				},
14282				'profileCompletionPercentage':'',
14283				'profCompStep':''
14284		};
14285		vm.customerData.preferred = true;
14286		vm.getAvisPreferredTermsList = $window.termsandconditionsRewardsMap;
14287		// View Callable.....
14288		vm.saveProfileDetail = saveProfileDetail
14289		vm.displayRewardsSection = true;
14290		vm.tdCheck = true;
14291		vm.showAmazonRewardsMsg = false;
14292		vm.amazonRewardsMessage = "";
14293		// Private Methods.....
14294		vm._checkForPartnerCustomerInfo = _checkForPartnerCustomerInfo;
14295		vm._setEnrollRewardsSection = _setEnrollRewardsSection;
14296		vm.clearFtpDetails = clearFtpDetails;
14297		vm._getPartnerDetails = _getPartnerDetails;
14298		vm._getSectionInEdit = _getSectionInEdit;
14299		vm.onChangeRewardPreference = onChangeRewardPreference;
14300        
14301        function _checkForPartnerCustomerInfo(){
14302        	if(angular.isDefined(vm.customerResponce) && angular.isDefined(vm.customerResponce.partnerCustomerInfo) && !angular.equals({}, vm.customerResponce.partnerCustomerInfo)){
14303        		vm.hasPartnerInfo = true;       		
14304        	}else{
14305        		vm.hasPartnerInfo = false;
14306        	}
14307        }
14308        
14309		function _setEnrollRewardsSection() {
14310            /*if user not selected yet*/
14311			vm.accountModel.program.pointsProgram = true;
14312			vm.accountModel.program.partnerProgram = false;
14313                _getPartnerDetails();
14314                vm.rewardsSectionDisplay = true;
14315                if(angular.isDefined(vm.getAvisPreferredTermsList) && vm.getAvisPreferredTermsList != ''){
14316                	vm.showTnCModal = getVehicles.gettermsMapURL(vm.getAvisPreferredTermsList, vm.domain)+'.partial.html';
14317                	vm.rewardPreferredTnC = true;
14318                	vm.accountModel.showConnectedCarTncModal = true;                	
14319                }
14320        }
14321		
14322		/*clears all the ftp fields*/
14323        function clearFtpDetails(partner) {
14324        	vm.accountModel = rewardsProgramService.clearFtpDetails(vm.accountModel,partner);
14325        	vm.accountModel = rewardsProgramService.setFTPSection(vm.customerData,vm.accountModel);
14326        }
14327		
14328        /*To set the Save CTA disable*/
14329		function onChangeRewardPreference(reward,id,partnerCode, membership, promotion) {
14330			//To clear partner details
14331			if(angular.isDefined(vm.formError) && vm.formError != ""){
14332        		vm.formValidated = false;
14333    			vm.formError = "";
14334    			vm.accountModel.airlineMembershipNumber = '';
14335    			vm.accountModel.otherMembershipNumber = '';
14336    			vm.accountModel.airlinePartner = '';
14337    			$scope.$broadcast("clearPartnerDetails");
14338        	}
14339			if(id == 'pointsPrgm'){
14340				//reward is the points selection accountModel value
14341				if(reward && vm.accountModel.program.partnerProgram){
14342					vm.accountModel.program.partnerProgram = false;
14343				}
14344				vm.disableSaveButton = false;
14345
14346			} else if(id == 'partnerPrgm'){
14347				//reward is the partner selection accountModel value
14348				if(reward && vm.accountModel.program.pointsProgram){
14349					vm.accountModel.program.pointsProgram = false;
14350				}
14351				vm.disableSaveButton = false;
14352			}
14353			else if (!vm.accountModel.program.pointsProgram && !vm.accountModel.program.partnerProgram) {
14354				vm.disableSaveButton = false;
14355			} 
14356		}
14357        
14358		function _getPartnerDetails() {
14359            myProfileService.getPartnerDetails().then(function(data) {
14360                if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0 &&
14361                    angular.isDefined(data.errorList) && data.errorList.length > 0) {
14362                    data = $scope.processErrorMessage(data);
14363                } else {
14364                    vm.partnerDetails = data;
14365                }
14366            }, function(error) {
14367            	$rootScope.requestInProgress = false;
14368            });
14369        }
14370        function _getSectionInEdit(e) {
14371            vm.sectionInEdit = myProfileService.getSectionInEdit(e);
14372        }       
14373        
14374		// Function will be called on page load
14375		function onPageLoad() {
14376			if(angular.isDefined(authenticationService.getXsrfToken())){
14377				isValidXSRF  = false;
14378				initialize();
14379			}
14380		}
14381		
14382		$rootScope.$on('initSuccess', function(event, arg) {
14383			if(isValidXSRF){
14384				initialize();
14385			}
14386		});
14387		
14388		function initialize(){
14389			getVehicles.accountSummaryload('preferredFlow').then(function(response){
14390				vm.customerResponce = response;
14391				vm.customerData.loyaltyEligible.visible = vm.customerResponce.displayControl.displayElementMap.loyaltyEligible.visible;
14392				if(angular.isDefined(vm.customerResponce.customerInfo)&&angular.isDefined(vm.customerResponce.customerInfo.profileCompletionPercentage)&&angular.isDefined(vm.customerResponce.customerInfo.profCompStep)){
14393					vm.customerData.profileCompletionPercentage = vm.customerResponce.customerInfo.profileCompletionPercentage;
14394					vm.customerData.profCompStep = vm.customerResponce.customerInfo.profCompStep;
14395				}
14396				_checkForPartnerCustomerInfo();
14397				if(vm.hasPartnerInfo && angular.isDefined(vm.customerResponce.partnerCustomerInfo.partnerType) && vm.customerResponce.partnerCustomerInfo.partnerType == "PARTNER_CBP"){
14398	    	    		$rootScope.$broadcast("CBPImageName", vm.customerResponce.partnerCustomerInfo);				
14399	    		}
14400				vm.accountModel = myProfileService.getAccountData(vm.customerResponce.customerInfo);
14401				if(angular.isDefined(vm.customerResponce.displayControl) && angular.isDefined(vm.customerResponce.displayControl.enrollmentStep)){
14402					var enrollmentStep = vm.customerResponce.displayControl.enrollmentStep;
14403					vm.customerData.enrollmentStep = enrollmentStep;
14404					myProfileService.triggerEditMode(undefined, true, enrollmentStep);//carRentalConstant.enrollmentStepToSectionModel[enrollmentStep]
14405				}
14406				if(angular.isDefined(vm.customerResponce.displayControl) && 
14407						angular.isDefined(vm.customerResponce.displayControl.enrollmentStep) && vm.hasPartnerInfo && angular.isDefined(vm.customerResponce.partnerCustomerInfo.partnerType) 
14408						&& angular.isDefined(vm.customerResponce.customerInfo) && angular.isDefined(vm.customerResponce.customerInfo.amazonLinked) && vm.customerResponce.customerInfo.amazonLinked
14409						&& vm.customerResponce.partnerCustomerInfo.partnerType == "PARTNER_AMAZON"
14410						&& vm.customerResponce.displayControl.enrollmentStep == "enroll-rewards-section"){
14411					vm.showAmazonRewardsMsg = true;
14412					vm.amazonRewardsMessage = Dictionary.I18n.get('lbl.amazonBenefits.rewardsSuccessMessage');
14413				}
14414				
14415				accountgaService.analyticsDimension(vm.customerResponce, '');
14416				_setEnrollRewardsSection();
14417				
14418			}, function(error) {
14419				if(angular.isDefined(error.errorList) && error.errorList.length > 0){
14420        			vm.formError = error.errorList[0].message;
14421	                vm.formValidated = true;
14422        		}
14423        		$rootScope.requestInProgress = false;
14424			});
14425		}
14426		//To save user details
14427		function saveProfileDetail(profileForm, e) { //TODO check for the form values
14428        	$rootScope.requestInProgress = true;
14429            _getSectionInEdit(e);
14430            $validationProvider.validate(profileForm).success(function(){
14431            	myProfileService.updateProfile(vm.customerResponce.customerInfo,vm.accountModel,vm.sectionInEdit).then(function(data){ 
14432                    data = $scope.processErrorMessage(data);
14433                    if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
14434                    	vm.formError = data.errorList[0].message;
14435                        vm.formValidated = true;
14436                        $rootScope.requestInProgress = false;
14437                        myProfileService.anchorToMsg(vm.sectionInEdit);
14438                    }else{
14439                    	var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot+"/activation" + htmlExtension;
14440                		$window.location.href = redirectPath;                  
14441                    }
14442            	}, function(error) {
14443            		if(angular.isDefined(error.errorList) && error.errorList.length > 0){
14444            			vm.formError = error.errorList[0].message;
14445    	                vm.formValidated = true;
14446    	                myProfileService.anchorToMsg(vm.sectionInEdit);
14447            		}
14448            		$rootScope.requestInProgress = false;
14449            	});
14450            }).error(function(data){
14451            	vm.formError = ABG.getFormValidationError(data,false)[0].message;
14452            	vm.formValidated = true;
14453                $rootScope.requestInProgress = false;
14454                myProfileService.anchorToMsg(vm.sectionInEdit);
14455            });
14456        }
14457		
14458		$(".enrollment-form").on("click", ".wrap-toggle-link", function(e) {
14459            var $this = $(this),
14460                toggleText = $this.parent().find(".wrap-toggle-text");
14461
14462            if ($this.hasClass("view-more")) {
14463                $this.text($this.data("viewlesslabel")).addClass("view-less").removeClass("view-more");
14464                toggleText.removeClass("hidden-xs");
14465            } else {
14466                $this.text($this.data("viewmorelabel")).addClass("view-more").removeClass("view-less");
14467                toggleText.addClass("hidden-xs");
14468            }
14469        });
14470		
14471		// Page Init...
14472		onPageLoad();
14473		
14474		
14475	}
14476})();
14477(function() {
14478	'use strict';
14479	angular
14480	.module('account')
14481	.controller('MyActivityController', MyActivityController);
14482
14483	MyActivityController.$inject = ['$controller', '$state','$filter', '$scope', 'getDataService','authenticationService','$window','carRentalConstant','storageService','$rootScope','$sce','reservationModelService','accountUtilityService','ReceiptLookupService','rentalService', 'gaService','lookupService','vehicleService', 'rentalVehicleService'];
14484
14485	function MyActivityController($controller, $state,$filter, $scope, getDataService,authenticationService, $window, carRentalConstant,storageService,$rootScope,$sce,reservationModelService,accountUtilityService,ReceiptLookupService,rentalService, gaService,lookupService,vehicleService, rentalVehicleService) {
14486		// ReceiptLookupService
14487		$controller('ExceptionHandlerController', {$scope: $scope});
14488
14489		var vm = this;
14490		vm.openRental = {
14491				detailsAvailable : false,
14492				detailsError : false,
14493				itineraries : null,
14494				inProgress : true,
14495				showCampaign :  false
14496		};
14497		vm.upcomingRes = {
14498				detailsAvailable : false,
14499				detailsError : false,
14500				itineraries : null,
14501				inProgress : true,
14502				showCampaign :  false
14503		};
14504		vm.pastRental = {
14505				detailsAvailable : false,
14506				detailsError : false,
14507				itineraries : null,
14508				inProgress : true,
14509				showCampaign : false
14510		};
14511		vm.cancelledRes = {
14512				detailsAvailable : false,
14513				detailsError : false,
14514				itineraries : null,
14515				inProgress : true,
14516				showCampaign : false
14517		};
14518		vm.showProminentForm = false;
14519        vm.profileUrl = $window.contextPath + "/" + $window.locale + '/loyalty-profile/avis-preferred/dashboard/profile' + htmlExtension;
14520		vm.receiptRequest = carRentalConstant.receiptRequest;
14521		vm.customerData = {};
14522		vm.prod = {};
14523		vm.brand = $window.brand;
14524		vm.rangeSelector = {};
14525		vm.Math = window.Math;
14526		vm.imageNotAvailable = true;
14527		vm.viewAll = false;
14528		vm.domain = $window.domain.toUpperCase();
14529		// Protected methods
14530		vm._processReservations = accountUtilityService.processItenaries;
14531		vm.viewReservationDetails = viewReservationDetails;
14532		// View callable
14533		vm.getPastRentalReceipt = getPastRentalReceipt;
14534		vm.toResDetailsPage = toResDetailsPage;
14535		vm.initRangeSelector = initRangeSelector;
14536		vm.dateRangeFilter = dateRangeFilter;
14537		vm.convertToDateTime = accountUtilityService.convertToDateTime;
14538		vm.dateFilterUtil = dateFilterUtil;
14539		vm.scrollUp = scrollUp;
14540		vm.profileDashboardImagePath = accountUtilityService.profileDashboardImagePath;
14541		vm.bookAgain = bookAgain;
14542		vm.getRentalExt = getRentalExt;
14543		vm.getVehicle = getVehicle;
14544		vm.getLocationAndRedirect = getLocationAndRedirect;
14545		vm.retrieveUpcomingRes = retrieveUpcomingRes;
14546		vm.selectVehicle = [];
14547		vm.errorList = null;
14548		vm.vehErrorList = null;
14549		vm.errorTrack = {};
14550		geolocFail = geolocFail;
14551
14552		angular.element(document).ready(function () {
14553			setTimeout(function(){
14554				$scope.$broadcast('reCalcViewDimensions');
14555			},2000);	        
14556	    });
14557
14558		function viewReservationDetails(confirmationNumber) {
14559			if (angular.isDefined(vm.customerData)) {
14560				$rootScope.$broadcast('viewReservationDetails', confirmationNumber);
14561			}
14562		}
14563
14564
14565		function retrieveUpcomingRes() {
14566			var upcoming = storageService.getStorageData('upcomingReservations');
14567			if(angular.isDefined(upcoming)){
14568				vm.upcomingRes = vm._processReservations(upcoming);
14569			}
14570			if (upcoming && upcoming.resSummaryList && upcoming.resSummaryList.length > 0 && upcoming.resSummaryList.filter(function (reservation) { return reservation.onAirportIndicator }).length > 0) {
14571				var tmpSelectVehicle = upcoming.resSummaryList.filter(function (reservation) { return reservation.onAirportIndicator });
14572				if (tmpSelectVehicle && tmpSelectVehicle.length > 0) {
14573					vm.selectVehicle.push(tmpSelectVehicle[0]);
14574				}
14575			}
14576		}
14577
14578		
14579		//TODO- move it to account.access.control.service
14580		$rootScope.$on('Profile.CustomerAdditionalInfo',function(event, data){
14581			$rootScope.requestInProgress = true;
14582			vm.customerData = data;
14583			if(vm.customerData.enrollmentStep != 'profile-completed' && vm.customerData.enrollmentStep !='enroll-rewards-section'){
14584				vm.showProminentForm = true;
14585			} else {
14586				vm.showProminentForm = false;
14587			}
14588				if(angular.isDefined(data) && angular.isDefined(data.userState) && angular.equals(data.userState,carRentalConstant.userStateRememberMe)){
14589					ABG.redirectPage($window.contextPath + "/" + $window.locale + $window.contentRoot +  "/login" + htmlExtension);
14590				}
14591				
14592				var session = authenticationService.getSessionModel();
14593				if (session && angular.isDefined(session) && angular.isDefined(session.status) && (session.status === "AUTHENTICATED" || session.status === "REMEMBER_ME")) {
14594					if(authenticationService.getOpenRentals() != undefined){
14595						vm.openRental = vm._processReservations(authenticationService.getOpenRentals());
14596						if(vm.openRental.itineraries!= null && angular.isDefined(vm.openRental.itineraries.errorList) && vm.openRental.itineraries.errorList.length > 0){
14597							vm.errorList = $scope.processErrorMessage(vm.openRental.itineraries).errorList;
14598						}
14599					} else {
14600						vm.openRental.inProgress = false;
14601						vm.openRental.showCampaign = true;
14602					}
14603					if(authenticationService.getUpcomingReservations() != undefined) {
14604						vm.upcomingRes = vm._processReservations(authenticationService.getUpcomingReservations());
14605					}
14606					if(authenticationService.getPastReservations() != undefined) {
14607						vm.pastRental = vm._processReservations(authenticationService.getPastReservations());
14608					}
14609					if(authenticationService.getCancelledReservations() != undefined) {
14610						vm.cancelledRes = vm._processReservations(authenticationService.getCancelledReservations());
14611					}
14612				}
14613				if (angular.equals($rootScope.deviceType, "handheld")) {
14614					// Details Page initializes range selector
14615					if (angular.isDefined(vm.rangeSelector.range) && vm.pageSize == 10)
14616						vm.pageSize = 5;
14617				}
14618				$rootScope.requestInProgress = false;
14619		});
14620    
14621        // Check for Location sharing and redirect to On Airport - Vehicle availability
14622		function getVehicle(confirmationNumber) {
14623			if (navigator.permissions) {
14624				navigator.permissions.query({ name: 'geolocation' }).then(function (geoLocResult) {
14625					if ((geoLocResult.state == "none" || geoLocResult.state == "granted") && navigator.geolocation) {
14626						getLocationAndRedirect(confirmationNumber);
14627					} else {
14628						// Another modal to be shown that says Browser doesn't support Location sharing
14629						$rootScope.requestInProgress = false;
14630						if (confirmationNumber) {
14631							getLocationAndRedirect(confirmationNumber);
14632						}
14633						angular.element('#locationDisabledWarning').modal('show');
14634						//ABG.switchContentBasedOnBrowser();
14635					}
14636				})
14637			} else {
14638				getLocationAndRedirect(confirmationNumber);
14639			}
14640		}
14641
14642		function getLocationAndRedirect(confirmationNumber) {
14643			if (navigator.userAgent.indexOf("msie") > -1 ||
14644				navigator.appVersion.indexOf('Trident/') > 0 ||
14645				navigator.userAgent.toLowerCase().indexOf('edge') ||
14646				navigator.userAgent.toLowerCase().indexOf('edg') ||
14647				(navigator.userAgent.toLowerCase().indexOf('safari') && !window.chrome)) {
14648				var location_timeout = setTimeout(function() { geolocFail() }, 2000);
14649			}
14650
14651			navigator.geolocation.getCurrentPosition(function (result) { // executes when user allows location sharing
14652				clearTimeout(location_timeout);
14653				angular.element('#locationDisabledWarning').modal('hide');
14654				$rootScope.requestInProgress = true;
14655				var selfServiceRequestObj = {
14656					"uniqueId": "",
14657					"geoCoordinate": {
14658						"longitude": result.coords.longitude,
14659						"latitude": result.coords.latitude
14660					},
14661					"confirmationNumber": confirmationNumber
14662				}
14663		
14664				rentalVehicleService.getVehicleDetails(selfServiceRequestObj).then(function (data) {
14665					if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
14666						$rootScope.requestInProgress = false;
14667						vm.vehErrorList = data.errorList;
14668						vm.errorTrack = $scope.processErrorMessage(data);
14669					}
14670					else {
14671						angular.element(document).injector().get('getDataService').setVehiclesResponse(data);
14672						gaService.analyticsSelfserviceClickEvents('my activity dashboard');
14673
14674						 if(data.vehicleSummaryList.length>=1 && !(angular.equals(data.vehicleSummaryList,{}))){
14675						var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + "/" + "rental" + htmlExtension + "#/select-vehicle";
14676						$window.location.href = redirectPath;
14677						 }else{
14678							 var genericErrorMessage = Dictionary.I18n.get('err.res.genericerrormsg,'+brand);
14679								var errorList = [];
14680								errorList.push({
14681									"message": genericErrorMessage
14682								})
14683								vm.vehErrorList = errorList;
14684								console.log('empty response');
14685						 }
14686
14687					}
14688				}, function (error) {
14689					var genericErrorMessage = Dictionary.I18n.get('err.res.genericerrormsg,'+brand);
14690					var errorList = [];
14691					errorList.push({
14692						"message": genericErrorMessage
14693					})
14694					$rootScope.requestInProgress = false;
14695					vm.errorTrack = $scope.processErrorMessage(errorList);
14696					vm.vehErrorList = errorList;
14697				});
14698			}, function (result) { // executes when user denies location sharing
14699				clearTimeout(location_timeout);
14700				geolocFail();				
14701			});
14702		}
14703
14704		function geolocFail() {
14705			$rootScope.requestInProgress = false;
14706			angular.element('#locationDisabledWarning').modal('show');
14707			//ABG.switchContentBasedOnBrowser();
14708		}
14709
14710		function getPastRentalReceipt(reservation){
14711			$rootScope.requestInProgress = true;
14712			vm.receiptRequest = {
14713					'rentalAgreementNum': reservation.rentalAgreementNumber
14714			};
14715
14716			var promise = ReceiptLookupService.load(vm.receiptRequest,true);
14717			// console.log(promise);
14718
14719			promise.then(function(data){
14720				vm.validateResponse = data;
14721				if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0 ||
14722						(angular.isDefined(data.warningList) && data.warningList.length > 0)) {
14723					vm.prod = $scope.processErrorMessage(data);
14724					$rootScope.requestInProgress = false;
14725				}else if(angular.isDefined(data.errorList) && data.errorList.length > 0){
14726					$rootScope.requestInProgress = false;
14727					vm.prod = $scope.processErrorMessage(data);
14728					vm.scrollUp();
14729				}else if(data.errorList==null || data.errorList == undefined){
14730					//TODO: need to look at the need of storage? 
14731					storageService.setStorageData('receiptRequest', vm.receiptRequest);
14732					storageService.setStorageData('receiptResponse', vm.validateResponse);
14733					$rootScope.requestInProgress = false; 
14734					ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + "/" +  "reservation/receipt-details" + htmlExtension);
14735				}
14736			}, function(error){
14737				$rootScope.requestInProgress = false;
14738				vm.prod = $scope.processErrorMessage(error);
14739				vm.scrollUp();
14740			});
14741		};
14742
14743		function scrollUp(){
14744			$("body").animate({
14745				"scrollTop": 0
14746			}, "slow");
14747		}
14748
14749		function toResDetailsPage(reservation,goToVMCPage) {
14750			// Can't use this OMEGA reservation object to populate the VMC page, hence doing lookup call
14751			$rootScope.requestInProgress = true;
14752			var lookupModel = {};
14753			lookupModel.lastName = authenticationService.getCustomerModel().lastName;
14754			lookupModel.confirmationNumber = reservation.confirmationNumber;
14755			reservationModelService.setLookUpModel(lookupModel);
14756			lookupService.load().then(function(data) {
14757				vm.prod = $scope.processErrorMessage(data);
14758				if (!(angular.isDefined(vm.prod.errorList) && vm.prod.errorList.length > 0)) {
14759					getDataService.addToReservationData(vm.prod);
14760					reservationModelService.load(vm.prod, false, true);
14761					getDataService.addToConfirmationData(vm.prod);
14762					if(goToVMCPage)
14763						ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + '/reservation/' + carRentalConstant.getReservationPage);
14764					else
14765						ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + '/reservation' + htmlExtension + '#/confirmation/lookup');
14766				}else{
14767					$('html, body').animate({
14768			               'scrollTop' : $(".my-activity").position().top
14769			           });
14770				}
14771				$rootScope.requestInProgress = false;
14772			}, function(error) {
14773				$rootScope.requestInProgress = false;
14774				vm.prod = $scope.processErrorMessage(error);
14775				vm.scrollUp();
14776			});
14777		}
14778		
14779		function route(redirectPath) {
14780		      if (redirectPath && !$state.current.name) {
14781		        setTimeout(function() {
14782		          //$window.location.href = redirectPath;
14783		          ABG.redirectPage(redirectPath);
14784		          //$state.go(redirectPath, {}, {reload: true});      
14785		        }, 1);
14786		      } else if (redirectPath) {
14787		        $state.go(redirectPath, {}, {
14788		          reload: true
14789		        });
14790		      }
14791		    }
14792		
14793		function getRentalExt(rentalAgreementNumber){
14794			$rootScope.requestInProgress = true;
14795	    	rentalService.fetchRentalDetails(rentalAgreementNumber).then(function(data){
14796	    		$rootScope.requestInProgress = true;
14797	    		if(angular.isDefined(data) && angular.isUndefined(data.errorList)){
14798	    			gaService.analyticsRentalClickEvents(data, 'rental lookup');
14799	    			
14800	    			var redirectPath= $rootScope.contextPath + "/" + $rootScope.locale + "/" + "rental/rental-dashboard" + htmlExtension;
14801	    	    	route(redirectPath);
14802	    		}
14803	    	},function(error){
14804	    		
14805	    		var redirectPath= $rootScope.contextPath + "/" + $rootScope.locale + "/" + "reservation/view-modify-cancel" + htmlExtension;
14806	    		route(redirectPath);
14807	    	});
14808	    }
14809		
14810		//[BOOKAGAIN] handling book again call from home page past rental section.
14811	    function bookAgain(rentalAgreementNumber){
14812	    	$rootScope.requestInProgress = true;
14813	    	var reservationModel = reservationModelService.bookingModel;
14814	    	reservationModel.rentalAgreementNumber = rentalAgreementNumber;
14815	    	//making book again flow true.
14816	    	reservationModel.bookAgain.bookAgainFlow = true;
14817	    	reservationModelService.setReservationModel(reservationModel);
14818	    	var redirectPath= $rootScope.contextPath + "/" + $rootScope.locale + "/" + "reservation/book-again" + htmlExtension + "#/book-again";           
14819	    	vehicleService.getBookAgainData(false).then(function(data) {    		
14820
14821	    		if (angular.isDefined(data.errorList) && (data.errorList.length > 0)) {
14822	    			data = $scope.processErrorMessage(data);
14823//	    			if (!$state.current.name) {
14824	    				redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + "/" + "reservation" + htmlExtension + "#/time-and-place";           
14825//	    			} else {
14826//	    				redirectPath = carRentalConstant.step1aPageName;
14827//	    			}
14828	    			reservationModel.bookAgain.bookAgainFlow=false;
14829	    			reservationModelService.setReservationModel(reservationModel);
14830//	    			route(redirectPath);
14831	    			ABG.redirectPage(redirectPath);
14832	    		}else{
14833	    			ABG.redirectPage(redirectPath);
14834	    		}
14835	    	},
14836	    	function(error) {
14837	    		vm.isAnonymous = true;
14838	    		$rootScope.requestInProgress = false;
14839	    	});
14840	    }
14841
14842		function initRangeSelector(type) {
14843			vm.rangeSelector = accountUtilityService.initRangeSelector(type)
14844
14845			if (angular.equals($rootScope.deviceType, "handheld")) {
14846				// Details Page initializes range selector
14847				if (angular.isDefined(vm.rangeSelector.range) && vm.pageSize == 10)
14848					vm.pageSize = 5;
14849			}
14850		}
14851
14852		// This filter is used for ordering the list ex: past rental in reverse chronological order
14853		function dateFilterUtil(){
14854			return function(res){
14855				if (res === null) 
14856					return false;
14857				return vm.convertToDateTime(res.pickDateTime).getTime();
14858			}
14859		}
14860
14861		// This filter is used to filter based on date range slider values
14862		function dateRangeFilter(minVal,maxValue) {
14863			var s = vm.convertToDateTime(vm.rangeSelector.minSelected);
14864			var e = vm.convertToDateTime(vm.rangeSelector.maxSelected);
14865
14866			return function(res){
14867				// console.log(res);
14868				if (res === null) 
14869					return false;
14870				var d = vm.convertToDateTime(res.pickDateTime);
14871				// console.log(d,s,e);
14872				if (d >= s && d <= e) 
14873					return true;
14874				return false;
14875			}
14876		}
14877		
14878		// past rentals on function
14879		$rootScope.$on('Profile.noshowCancelledRes', function(event, data) {
14880			vm.cancelledRes = vm._processReservations(data);
14881		});
14882
14883		// past rentals on function
14884		$rootScope.$on('Profile.pastRentals', function(event, data) {
14885			vm.pastRental = vm._processReservations(data);
14886		});
14887
14888		// upcoming reservation on function
14889		$rootScope.$on('Profile.upcomingReservation', function(event, data) {
14890			vm.upcomingRes = vm._processReservations(data);
14891		});
14892		
14893		/*// open rentals on function*/
14894		$rootScope.$on('Profile.openRentals', function(event, data) {
14895			vm.openRental = vm._processReservations(data);
14896		});
14897		
14898		$rootScope.$on('Profile.rentalHistory', function(event, data) {
14899			if(angular.isDefined(data) && !angular.equals(data,{})){
14900				angular.forEach(data, function(value,key){
14901					if(value.onAirportIndicator){
14902						vm.selectVehicle.push(value);
14903					}
14904				});
14905				vm.upcomingRes = vm._processReservations(authenticationService.getUpcomingReservations());
14906			}
14907			else{
14908				retrieveUpcomingRes();
14909			}
14910			if (storageService.getStorageData('getVehicleError')) {
14911				vm.vehErrorList = storageService.getStorageData('getVehicleError');
14912			}
14913			if(vm.selectVehicle.length == 0){
14914				vm.prod.errorList = vm.vehErrorList;
14915			}
14916			setTimeout(function(){
14917				storageService.deleteStorageData('getVehicleError');
14918			},3000);
14919		});
14920	}
14921})();
14922(function() {
14923	'use strict';
14924
14925	angular
14926	.module('account')
14927	.controller('EmailActivationController', EmailActivationController);
14928
14929	EmailActivationController.$inject = ['$controller', '$location', '$scope', 'carRentalConstant', 'authenticationService', '$rootScope', '$window', 'storageService'];
14930
14931	function EmailActivationController($controller, $location, $scope, carRentalConstant, authenticationService, $rootScope, $window, storageService) {
14932
14933		$controller('ExceptionHandlerController', {
14934			$scope: $scope
14935		});
14936
14937		// View Model.....
14938		var vm = this;
14939		storageService.deleteAllStorageData(); // Removes all session storage whenever the controller is loaded
14940		// Private Methods.....
14941		vm._activateProfileCall = _activateProfileCall;
14942
14943		// Function will be called on page load
14944		function onPageLoad() {
14945			var queryParams = "";
14946			// Reads the query string from URL and sets the query params to this variable.
14947			queryParams = $location.search();
14948
14949			var params = {};
14950			angular.forEach(queryParams, function(value, key) {
14951				params[key] = value;
14952			});
14953			
14954			var isNewRequest= true;
14955
14956			if($window.sessionStorage.profileKey && $window.sessionStorage.profileKey===params.WIZARD_NUMBER){
14957					//both wizard number are same. hence call summary end point service
14958					isNewRequest=false;
14959			}else{
14960				if(storageService.sessionStorageSupport()===true){
14961					//fresh request invoke profile/activate call.and store the key in sessionStoage.
14962					$window.sessionStorage.profileKey = params.WIZARD_NUMBER;
14963				} 
14964			}
14965			if(isNewRequest){
14966				setTimeout(function(){
14967					vm._activateProfileCall(params);
14968				},10);
14969			}else{
14970				authenticationService.init().then(function(){
14971					authenticationService.getCustomerAdditionalInfo().then(function(){
14972						//method triggered for invoking access control
14973					},function(error){
14974						ABG.redirectPage($window.contextPath + "/" + $window.locale + $window.contentRoot + "/login" + htmlExtension + "#/" + error.errorList[0].code);
14975					});
14976				}, function(error) {
14977					$rootScope.requestInProgress = false;
14978				});
14979			}
14980		}
14981
14982		// Calls webapi for profile activation
14983		function _activateProfileCall(params) {
14984			authenticationService.activateProfileInit(params).then(function(data) {
14985				data = $scope.processErrorMessage(data);
14986				if (angular.isDefined(data.instructionList && data.instructionList.length>1)){
14987					angular.forEach(data.instructionList,function(error){
14988						if(error.code == '17435' && error.type == 'INSTRUCTION'){
14989							vm.cdhDownError = error.message;
14990						}
14991					})
14992					storageService.setStorageData('epCdhDownErrorList', vm.cdhDownError);
14993				}
14994				// Logic for Redirection
14995				if (!(angular.isDefined(data.errorList) && data.errorList.length > 0) || (angular.isDefined(data.warningList) && data.warningList.length > 0)) {
14996					if(angular.isDefined(data.customerInfo.userState) && angular.equals(data.customerInfo.userState,carRentalConstant.userStateAuthenticated) && data.customerInfo.webCustomer.activationStatus === "1"){
14997						ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot+"/dashboard/profile" + htmlExtension);
14998					} else {
14999						ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale +$window.contentRoot+ "/login" + htmlExtension);
15000					}
15001				} else {
15002					//TODO:Review- must be redirect to login page with an error.  
15003					var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale +$window.contentRoot+ "/login" + htmlExtension;
15004					ABG.redirectPage(redirectPath + "#/" + data.errorList[0].code);
15005				}
15006			},
15007			function(error) {
15008				var errorCode = "";
15009				if(angular.isDefined(error.errorList[0]) && error.errorList.length > 0){
15010					errorCode = error.errorList[0].code;
15011				}
15012				//on rejection redirecting to login page
15013				ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale +$window.contentRoot+ "/login" + htmlExtension  + "#/" + errorCode);
15014			});
15015		}
15016
15017		// Call on page load
15018		onPageLoad();
15019	}
15020})();
15021
15022(function() {
15023    'use strict';
15024
15025    angular
15026        .module('account')
15027        .controller('RewardsProgramController', RewardsProgramController);
15028
15029    RewardsProgramController.$inject = ['$controller', '$rootScope', '$scope', '$window', '$cookies', 'myProfileService', 'authenticationService', '$validation', 'rewardsProgramService', 'carRentalConstant', '$sce', 'accountUtilityService', 'securityService', 'storageService','anchorSmoothScroll','$compile','getVehicles'];
15030
15031    function RewardsProgramController($controller, $rootScope, $scope, $window, $cookies, myProfileService, authenticationService, $validationProvider, rewardsProgramService, carRentalConstant, $sce, accountUtilityService, securityService, storageService,anchorSmoothScroll,$compile,getVehicles) {
15032
15033        $controller('ExceptionHandlerController', {
15034            $scope: $scope
15035        });
15036
15037        // View Model.....
15038        var vm = this;
15039
15040        vm.customerData = {};
15041        vm.accountModel = {};
15042        vm.tempAccountModel = {};
15043        vm.showLoyaltyOption = false;
15044        vm.showOptout = false;
15045        vm.hidePromoCampaign = false;
15046        vm.rewardsSectionDisplay = false;
15047        vm.rewardPreferredTnC = false;
15048        vm.prod = {};
15049        vm.rangeSelector = {};
15050        vm.Math = window.Math;
15051        vm.displayRewardsSection = true;
15052        vm.displayPromoField = false;
15053        vm.domain = $window.domain.toUpperCase();
15054        vm.getTnCCountryRewardsList = $window.termsandconditionsRewardsMap;
15055        vm.loyaltyPnts = {
15056				detailsAvailable : false,
15057				detailsError : false,
15058				itineraries : {},
15059				inProgress : true,
15060				showCampaign :  false
15061		};
15062        vm.resendOtpSuccess = false;
15063    	vm.resendOtpError = false;
15064    	vm.tdCheck = true;
15065		vm.digitalCardToken = "";
15066    	vm.digitalCardURL = $window.digitalCardURL;
15067        //view callables
15068        vm.editSection = editSection;
15069        vm.clearFtpDetails = clearFtpDetails;
15070        vm.enrollRewards = enrollRewards;
15071        vm.saveProfileDetail = saveProfileDetail;
15072        vm.initRangeSelector = initRangeSelector;
15073        vm.dateRangeFilter = dateRangeFilter;
15074        vm.convertToDateTime = accountUtilityService.convertToDateTime;
15075        vm.dateFilterUtil = dateFilterUtil;
15076        vm.initLoyaltyPoints = initLoyaltyPoints;
15077        vm.getMemberCardPDF = getMemberCardPDF;
15078        vm.onChangeRewardPreference = onChangeRewardPreference;
15079        vm.cancelEdit = cancelEdit;
15080        vm.gtmBlur = gtmBlur;
15081        vm.verifyProfileOtp = verifyProfileOtp;
15082        vm.resendOtp = resendOtp;
15083        vm.addToDigitalWallet = addToDigitalWallet;
15084        //private functions
15085        vm._setEnrollRewardsSection = _setEnrollRewardsSection;
15086        vm._showSectionInExpendedMode = _showSectionInExpendedMode;
15087        vm._getPartnerDetails = _getPartnerDetails;
15088
15089        vm._processLoyaltyPoints = accountUtilityService.processItenaries;
15090        vm._enableRewardsSection = _enableRewardsSection;
15091        angular.element(document).ready(function () {
15092			setTimeout(function(){
15093				$scope.$broadcast('reCalcViewDimensions');
15094			},2000);	        
15095	    });
15096        angular.element(document).ready(function () {
15097            if ($window.brand === "budget") {
15098              var checkFtpAndHidePromo = setInterval(function () {
15099                if (
15100                  angular.isDefined(vm.customerData) &&
15101                  !angular.equals({}, vm.customerData)
15102                ) {
15103                  clearInterval(checkFtpAndHidePromo); // Stop polling now
15104          
15105                  // Checking if ftp is already enrolled
15106                  if (
15107                    angular.isDefined(vm.customerData.ftpPartnerDetails) &&
15108                    !angular.equals({}, vm.customerData.ftpPartnerDetails) &&
15109                    vm.customerData.ftpPartnerDetails.ftpOptIn
15110                  ) {
15111                    vm.hidePromoCampaign = true;
15112                  }
15113                }
15114              }, 500);
15115            }
15116          });
15117        vm.enrollRewards=function(param){		  
15118  		  $rootScope.$emit("enrollRewards",{'param':param});
15119  	  	}
15120        
15121        $rootScope.$on("enrollRewards",function(event,response){        	
15122        	      	enrollRewards(response.param || "");
15123        	        });
15124        
15125        
15126        $rootScope.$on('Profile.CustomerAdditionalInfo',function(event, response){
15127        	vm.customerData = response;
15128
15129            /* ARD2-5046: Avis APAC digital card change starts */
15130            if (angular.isDefined(vm.customerData) && !angular.equals({}, vm.customerData)) {
15131            	if (!vm.digitalCardToken && $window.brand == carRentalConstant.brandName.AVIS) {
15132            		if ((vm.domain === 'AU' || vm.domain === 'NZ') && (vm.customerData.cor == 'AU' || vm.customerData.cor == 'NZ') && (vm.customerData.membershipStatus == 'My Avis Member' || vm.customerData.membershipStatus == 'Preferred' || vm.customerData.membershipStatus == 'President\'s Club')) {
15133            			vm.digitalCardToken = vm.customerData.digitalCardToken;
15134            		}
15135            	}
15136            }
15137            /* ARD2-5046: Avis APAC digital card change ends */
15138            
15139        	var session = authenticationService.getSessionModel();
15140			if(angular.isDefined(session) && angular.isDefined(session.tdCheck)){
15141				vm.tdCheck = session.tdCheck;
15142			}
15143        	vm.accountModel = myProfileService.getAccountData(vm.customerData);        	
15144        	if($window.brand == carRentalConstant.brandName.AVIS && angular.isDefined(vm.getTnCCountryRewardsList) && vm.getTnCCountryRewardsList != ''){
15145        		vm.showTnCModal = getVehicles.gettermsMapURL(vm.getTnCCountryRewardsList, vm.domain)+'.partial.html';
15146        	}
15147        	_setEnrollRewardsSection();
15148        });
15149        
15150        $rootScope.recompile = function() {
15151			  var element = angular.element('.checking');
15152			  if(element.length>0){
15153				  var teaserContainer = angular.element('checking');
15154				  //removing multiple div's injected by first time campaign resolution  
15155				  teaserContainer.each(function (idx, elem) {
15156
15157					  if (idx != 0) {
15158						  jQuery(elem).remove();
15159					  }
15160				  });
15161
15162				  $compile(element)($scope);
15163				  $scope.$apply();
15164				  angular.element('.checking').removeClass('checking');
15165				  jQuery('.hide-on-load').removeClass('hide-on-load');
15166			  }	       
15167		  };
15168		  
15169        /*Triggered on click of cancel*/
15170        function cancelEdit() {
15171        	vm.formValidated = false;
15172        	_enableRewardsSection();
15173        }
15174        
15175     // To update sectional details
15176        function saveProfileDetail(profileForm, e) { //TODO check for the form values
15177        	vm.sectionInEdit = myProfileService.getSectionInEdit(e);
15178        	$rootScope.requestInProgress = true;
15179            $validationProvider.validate(profileForm).success(function(){
15180            	myProfileService.updateProfile(vm.customerData,vm.accountModel,vm.sectionInEdit).then(function(data){ 
15181                    data = $scope.processErrorMessage(data);
15182                    if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
15183                    	vm.formError = data.errorList[0].message;
15184                        vm.formValidated = true;
15185                        $rootScope.requestInProgress = false;
15186                    }else{
15187                        vm.customerData = data;
15188                        vm.formValidated = false;
15189                        vm.showSuccessMsg = true;
15190                        editSection(false);     
15191                        location.reload();
15192                    }
15193                    myProfileService.anchorToMsg(vm.sectionInEdit);
15194            	}, function(error) {
15195            		if(angular.isDefined(error.errorList) && error.errorList.length > 0){
15196            			vm.formError = error.errorList[0].message;
15197    	                vm.formValidated = true;
15198    	                myProfileService.anchorToMsg(vm.sectionInEdit);
15199            		}
15200            		$rootScope.requestInProgress = false;
15201            	})
15202            }).error(function(data){
15203            	vm.formError = ABG.getFormValidationError(data,false)[0].message;
15204            	vm.formValidated = true;
15205                $rootScope.requestInProgress = false;
15206                myProfileService.anchorToMsg(vm.sectionInEdit);
15207            });
15208        }
15209        
15210        /*Enroll rewards campaign CTA*/
15211        function enrollRewards(rewards) {
15212            if (rewards == 'loyalty') {
15213            	if(vm.customerData.preferred){
15214                    _showSectionInExpendedMode('enroll-rewards-section');
15215                    vm.accountModel.program.pointsProgram = true;
15216                    vm.accountModel.program.partnerProgram = false;
15217            	}else{
15218            		var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot + htmlExtension;
15219            		$window.location.href = redirectPath;  
15220            	}
15221            } else if (rewards == 'ftp') {
15222                _showSectionInExpendedMode('enroll-rewards-section');
15223                vm.accountModel.program.partnerProgram = true;
15224                vm.accountModel.program.pointsProgram = false;
15225            }
15226            vm.displayRewardsSection = true;
15227            vm.hidePromoCampaign = true;
15228            vm.disableSaveButton = false;
15229            anchorSmoothScroll.scrollTo('enrollRewardsForm');
15230        }
15231
15232        /*Will expand the rewards section */
15233        function _showSectionInExpendedMode(section) {
15234            setTimeout(function() {
15235                var e;
15236              myProfileService.triggerEditMode(e, true, 'enroll-rewards-section');
15237          }, 10);
15238        }
15239
15240        /* To edit section in profile dash board page
15241         *  - this function is triggered on click of edit, save and cancel of each section
15242         *  - it stores the edit value and the section which is in edit to session storage
15243         *  - @param toEdit {boolean} - holds the value true if section is in edit mode
15244         *  - @param section {string} - holds HTML class name of section in edit
15245         *  - @param event {event} - holds the JS event 
15246         *  - @return void*/
15247        function editSection(toEdit, $event) {
15248            if (toEdit) {
15249                vm.sectionInEdit = myProfileService.getSectionInEdit($event);                
15250            	if(vm.tdCheck || vm.customerData.enrollmentStep == 'enroll-rewards-section'){            		
15251                    myProfileService.triggerEditMode($event, toEdit, vm.sectionInEdit);
15252                    vm.tempAccountModel = angular.copy(vm.accountModel);
15253            	} else {
15254            		$rootScope.requestInProgress = true;
15255            		securityService.generateOtp().then(function(data){
15256            			if(data.promptOtpFlag){
15257            				myProfileService.triggerEditMode($event, toEdit, vm.sectionInEdit);
15258                            vm.tempAccountModel = angular.copy(vm.accountModel);	
15259            			} else {
15260            				$(".profile-edit-error").modal("show");
15261            			}        			
15262            			$rootScope.requestInProgress = false;
15263            		}, function(error){
15264            			$(".profile-edit-error").modal("show");
15265            			$rootScope.requestInProgress = false;
15266            		})
15267            	}
15268            } else {
15269                if (angular.isDefined(vm.tempAccountModel) && (!angular.equals({}, vm.tempAccountModel))) {
15270                    vm.accountModel = angular.copy(vm.tempAccountModel);
15271                }
15272                myProfileService.triggerEditMode($event, toEdit, vm.sectionInEdit);
15273            }
15274            // Checking if ftp is already enrolled
15275            if (
15276                angular.isDefined(vm.customerData.ftpPartnerDetails) &&
15277                !angular.equals({}, vm.customerData.ftpPartnerDetails) &&
15278                vm.customerData.ftpPartnerDetails.ftpOptIn
15279              ) {
15280                vm.hidePromoCampaign = true;
15281              }
15282              else {
15283                vm.hidePromoCampaign = false;
15284              }
15285        }
15286
15287        /*will set enrollment section on create flow*/
15288        function _setEnrollRewardsSection() {
15289        	_enableRewardsSection();
15290        	var urlArray = $window.location.href.split("/");
15291        	if((urlArray.length != 0) && (urlArray[urlArray.length-1].indexOf('rewards') != -1)){
15292        		var defaultSelectionValue = rewardsProgramService.rewardsDefaultSelection(vm.customerData);
15293        		if(defaultSelectionValue == "pointsProgram"){
15294        			vm.accountModel.program.pointsProgram = true;
15295        			vm.accountModel.program.partnerProgram = false;
15296        		}else if(defaultSelectionValue == "partnerProgram"){
15297        			vm.accountModel.program.partnerProgram = true;
15298        			vm.accountModel.program.pointsProgram = false;
15299        		}else if(defaultSelectionValue == "optOutProgram"){
15300        			vm.accountModel.program.partnerProgram = false;
15301        			vm.accountModel.program.pointsProgram = false;
15302        		}
15303                if (vm.customerData.loyaltyEligible.visible && !vm.customerData.ftpPartnerDetails.ftpOptIn && !vm.customerData.optOut && !vm.customerData.loyaltyDetails.loyaltyOptIn) {
15304                   //TODO: Change the variable name
15305                	vm.rewardsSectionDisplay = true;
15306                }else{
15307                    vm.rewardsSectionDisplay = false;
15308                }
15309                /*To display promo field depending on cor*/
15310                //TODO:review- need to get it from api
15311                if (vm.customerData.cor == carRentalConstant.countryCodeAU || vm.customerData.cor == carRentalConstant.countryCodeNZ) {
15312                    vm.displayPromoField = true;
15313                } 
15314                //To display the rewards terms pop-up
15315                if(angular.isDefined(vm.showTnCModal)){
15316                	vm.rewardPreferredTnC = true;
15317                	vm.accountModel.showConnectedCarTncModal = true;
15318                } else{
15319                	vm.rewardPreferredTnC = false;
15320                }
15321                
15322                
15323                vm.accountModel = rewardsProgramService.setFTPSection(vm.customerData,vm.accountModel);
15324                vm.disableSaveButton = true;
15325                _getPartnerDetails();
15326        	}        	
15327        }
15328        
15329        /*To set the Save CTA disable*/
15330        function onChangeRewardPreference(reward,id,partnerCode, membership, promotion) {
15331        	//To clear partner details
15332        	if(angular.isDefined(vm.formError) && vm.formError != ""){
15333        		vm.formValidated = false;
15334    			vm.formError = "";
15335    			vm.accountModel.airlineMembershipNumber = '';
15336    			vm.accountModel.airlinePartner = '';
15337    			vm.accountModel.otherMembershipNumber = ''
15338    			$scope.$broadcast("clearPartnerDetails");
15339        	}
15340            if(id == 'pointsPrgm'){
15341            	//reward is the points selection accountModel value
15342            	if(reward && vm.accountModel.program.partnerProgram){
15343            		vm.accountModel.program.partnerProgram = false;
15344            	}
15345            	if (reward && vm.customerData.loyaltyDetails.loyaltyOptIn) {
15346                    vm.disableSaveButton = true;
15347                }else{
15348                	vm.disableSaveButton = false;
15349                }
15350             } else if(id == 'partnerPrgm'){
15351            	//reward is the partner selection accountModel value
15352        	    if(reward && vm.accountModel.program.pointsProgram){
15353        		vm.accountModel.program.pointsProgram = false;
15354        	     }
15355        	    //If partner opt in
15356                if (reward == true && vm.customerData.ftpPartnerDetails.ftpOptIn) {
15357                    //if partner code or membership number or promotional code not changed
15358                    if (!angular.isDefined(partnerCode) || (partnerCode == vm.customerData.ftpPartnerDetails.partnerCode &&
15359                            (!angular.isDefined(membership) ||
15360                                (angular.isDefined(membership) && membership == vm.customerData.ftpPartnerDetails.memebershipNumber)) &&
15361                            (!angular.isDefined(promotion) ||
15362                                (angular.isDefined(promotion) && promotion == vm.customerData.ftpPartnerDetails.promotionalCode)))) {
15363
15364                        vm.disableSaveButton = true;
15365                    } else {
15366                        vm.disableSaveButton = false;
15367                    }
15368
15369                } else{
15370                	vm.disableSaveButton = false;
15371                }
15372              }
15373             else if (vm.accountModel.program.pointsProgram == false && vm.accountModel.program.partnerProgram == false && !vm.customerData.loyaltyDetails.loyaltyOptIn && !vm.customerData.ftpPartnerDetails.ftpOptIn) {
15374                vm.disableSaveButton = true;
15375            } else {
15376                vm.disableSaveButton = false;
15377            }
15378        }
15379
15380
15381        /*will return all partner details*/
15382        function _getPartnerDetails() {
15383            myProfileService.getPartnerDetails().then(function(data) {
15384                if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0 &&
15385                    angular.isDefined(data.errorList) && data.errorList.length > 0) {
15386                    data = $scope.processErrorMessage(data);
15387                } else {
15388                    vm.partnerDetails = data;
15389                }
15390            }, function(error) {
15391            	$rootScope.requestInProgress = false;
15392            });
15393        }
15394
15395        /*clears all the ftp fields*/
15396        function clearFtpDetails(partner) {
15397        	vm.accountModel = rewardsProgramService.clearFtpDetails(vm.accountModel,partner);
15398        	vm.accountModel = rewardsProgramService.setFTPSection(vm.customerData,vm.accountModel);
15399        }
15400      
15401        function initRangeSelector(type) {
15402            vm.rangeSelector = accountUtilityService.initRangeSelector(type)
15403            
15404            if (angular.equals($rootScope.deviceType, "handheld")) {
15405                // Details Page initializes range selector
15406				if (angular.isDefined(vm.rangeSelector.range) && vm.pageSize == 10)
15407                    vm.pageSize = 5;
15408                }
15409            }
15410
15411     // This filter is used for ordering the list ex: past rental in reverse chronological order
15412        function dateFilterUtil() {
15413            return function(res) {
15414                if (res === null)
15415                    return false;
15416                return vm.convertToDateTime(res.interactionDate).getTime();
15417            }
15418        }
15419
15420     // This filter is used to filter based on date range slider values
15421        
15421function dateRangeFilter(minVal, maxValue) {
15422            var s = vm.convertToDateTime(vm.rangeSelector.minSelected);
15423            var e = vm.convertToDateTime(vm.rangeSelector.maxSelected);
15424
15425            return function(loyalPt) {
15426                if (loyalPt === null)
15427                    return false;
15428                if (angular.isUndefined(loyalPt.interactionType) && loyalPt.interactionType == '' &&
15429                    angular.isUndefined(loyalPt.actionType) && loyalPt.actionType == '')
15430                    return false;
15431                var d = vm.convertToDateTime(loyalPt.interactionDate);
15432                if (d >= s && d <= e)
15433                    return true;
15434                return false;
15435            }
15436        }
15437
15438        function initLoyaltyPoints() {
15439
15440            $rootScope.requestInProgress = true;
15441
15442            var promise = rewardsProgramService.getLoyaltyActivity();
15443
15444            promise.then(function(data) {
15445                $rootScope.requestInProgress = false;
15446                vm.prod = data;
15447                vm.loyaltyPnts = vm._processLoyaltyPoints(vm.prod);
15448            }, function(error) {
15449               	var data = {'errorList':[{'code':'timeout','message':'timedout / webapi error'}]}
15450                vm._processLoyaltyPoints(data);
15451                $rootScope.requestInProgress = false;
15452            });
15453
15454        }
15455
15456        function _processLoyaltyPoints(data) {
15457            var dataSet;
15458            if (angular.isDefined(data.errorList) && (data.errorList.length > 0)) {
15459                vm.loyaltyPointsDetails = data;
15460                vm._processLoyaltyPointsDetails(data);
15461            } else {
15462
15463                 dataSet = {
15464                    'flag': true,
15465                    'data': data.loyaltySummaryList
15466                };
15467
15468                vm._processLoyaltyPointsDetails(dataSet);
15469            }
15470            vm.loyaltyPointsInProgress = false;
15471        }
15472        //TODO review : check to not use different variables for showing errors
15473        function _processLoyaltyPointsDetails(dataSet) {
15474            if (angular.isDefined(dataSet.data) == false) {
15475                vm.loyaltyPointsDetailsError = true;
15476                vm.loyaltyPointsInProgress = false;
15477            } else {
15478                vm.loyaltyPointsDetails = dataSet.data;
15479                if (vm.loyaltyPointsDetails == undefined && !dataSet.flag) {
15480                    vm.loyaltyPointsDetailsError = true;
15481                } else {
15482                    if (vm.loyaltyPointsDetails && vm.loyaltyPointsDetails[0].interactionDate && vm.loyaltyPointsDetails.errorList == undefined) {
15483                        vm.loyaltyPointsDetailsAvailable = true;
15484                        vm.loyaltyPointsDetailsError = false;
15485                    } else {
15486                        if (vm.loyaltyPointsDetails && vm.loyaltyPointsDetails.errorList) {
15487                            vm.loyaltyPointsDetailsError = true;
15488                        } else {
15489                            vm.loyaltyPointsDetailsError = false;
15490                        }
15491                    }
15492                }
15493            }
15494        }
15495
15496        function getMemberCardPDF() {
15497        	var url = apiurl + "/print/fetch-membercard";
15498            $window.open(url, '_blank');
15499        }
15500        
15501        function addToDigitalWallet() {
15502            var url = vm.digitalCardURL + vm.digitalCardToken;
15503            $window.open(url, '_blank');
15504        }
15505        //    	GTM FUNCTION
15506        function gtmBlur(string, string1, inputType) {
15507            //	hardcoded strings in this function need not be I18N as these won't be displayed in UI.
15508            if (inputType == 'text') {
15509                var inputAction = string ? 'Filled In' : 'Skipped';
15510            } else if (inputType == 'checkbox') {
15511                var inputAction = string ? 'Selected as Y' : 'Selected as N';
15512            } else if (inputType == 'dropdown') {
15513                var inputAction = string ? 'Selected' : 'Not Selected';
15514            }
15515            dataLayer.push({
15516                'event': 'trackEvent', 
15517                'eventCategory': 'Tracking Form: ' + 'Profile-Form',
15518                'eventLabel': string1,
15519                'eventAction': inputAction
15520            });
15521        }
15522        function _enableRewardsSection() {
15523        	var isSafariClient=false;
15524        	isSafariClient = navigator.vendor && navigator.vendor.indexOf('Apple') > -1 && navigator.userAgent && !navigator.userAgent.match('CriOS');
15525        	if(!vm.customerData.ftpPartnerDetails.ftpOptIn && !vm.customerData.loyaltyEligible.visible && !isSafariClient){
15526        		vm.displayRewardsSection = false;
15527        	}
15528        	if(vm.customerData.cor =='AU' || vm.customerData.cor =='NZ') {
15529        		vm.displayRewardsSection = true;
15530        	}
15531        }
15532        
15533        function resendOtp(){     
15534        	vm.resendOtpSuccess = false;
15535        	vm.resendOtpError = false;
15536        	$rootScope.requestInProgress = true;
15537    		securityService.generateOtp().then(function(data){
15538    			$rootScope.requestInProgress = false;
15539    			if(data.errorList && data.errorList.length > 0){
15540        			data = $scope.processErrorMessage(data);
15541        			vm.resendOtpError = true;        			
15542        		} else {
15543        			vm.resendOtpSuccess = true;
15544        		}    			
15545    		}, function(error){
15546    			$rootScope.requestInProgress = false;
15547    			vm.resendOtpError =true;    			  			
15548    		})
15549        }
15550        
15551        function verifyProfileOtp(event){    		
15552        	vm.resendOtpSuccess = false;
15553        	vm.resendOtpError = false; 
15554    		var formName = angular.element(event.target)[0].form.name;
15555    		var formCtrl = angular.element("[name='"+formName+"']").controller("form");
15556    		$validationProvider.validate(formCtrl).success(function(){
15557            	var otpReqObj ={"otpNumber": vm.profileOtp} 
15558            	$rootScope.requestInProgress = true;
15559            	securityService.validateOtp(otpReqObj).then(function(data){
15560            		if(data.errorList){
15561            			data = $scope.processErrorMessage(data);
15562            		}
15563            		if(data.errorList && data.errorList.length > 0){
15564            			if(data.errorList.length==1){
15565            				if(data.errorList[0].code=="110033"){
15566            					$validationProvider.displayServiceError('vm.profileOtp', 'invalidotp', false, formName)
15567            				}            				
15568            				else if(data.errorList[0].code=="110034"){
15569            					$validationProvider.displayServiceError('vm.profileOtp', 'expiredotp', false, formName)
15570            				}
15571            				else if(data.errorList[0].code=="110023"){            					
15572            					getLogout();            					
15573            				}
15574            				else{
15575            					// generic message for all other scenarios
15576            					$validationProvider.displayServiceError('vm.profileOtp', 'genericotp', false, formName)
15577            				}
15578            			}            			          			
15579            		} else if(!data.promptOtpFlag) { 
15580            			var session = authenticationService.getSessionModel();           
15581            			session.tdCheck = true
15582            			vm.tdCheck = true;
15583            			authenticationService.setSessionModel(session);                		
15584            		}
15585            		
15586            		$rootScope.requestInProgress = false;
15587            	},function(error){            		
15588            		$rootScope.requestInProgress = false;
15589            	})        		
15590            }).error(function(err){
15591            	
15592            });
15593    		
15594    		//  
15595    	}
15596        
15597        function getLogout() {
15598        	var redirectURL;
15599			$rootScope.requestInProgress = true;
15600			var sessionStatus = authenticationService.getSessionModel();
15601			authenticationService.logout().then(function(data) {
15602				authenticationService.setLoginAuthenticate(false);				
15603				redirectURL = $rootScope.contextPath + "/" + $rootScope.locale + "/home" + htmlExtension;
15604				storageService.setStorageData('lockedUser', vm.customerData.contacts.email);				
15605				$cookies.remove('resModelDisplayControls');				
15606				setTimeout(function() {
15607					$window.location.href = redirectURL;
15608				}, 1);
15609			},
15610			function(error) {
15611				$rootScope.requestInProgress = false;
15612			});
15613		}
15614
15615    }
15616})();
15617(function () {
15618    'use strict';
15619
15620    angular
15621        .module('account')
15622        .controller('BiometricValidationController', BiometricValidationController);
15623
15624    BiometricValidationController.$inject = ['$controller', '$scope', '$rootScope', '$state', '$validation', '$window', 'biometricService', 'reservationModelService', 'MiTek', 'clearMe', '$location', 'storageService', 'gaService'];
15625
15626    function BiometricValidationController($controller, $scope, $rootScope, $state, $validationProvider, $window, biometricService, reservationModelService, MiTek, clearMe, $location, storageService, gaService) {
15627
15628        $controller('ExceptionHandlerController', {
15629            $scope: $scope
15630        });
15631
15632        // View Model.....
15633        var vm = this;
15634        $rootScope.requestInProgress = true;
15635        $rootScope.isIntrerimProfile = true;
15636        vm.blockType = 'St';
15637
15638
15639        vm.domain = $window.domain.toUpperCase();
15640        // Private Methods.....
15641        vm._onPageLoad = onPageLoad;
15642        vm.closeErrorPage = closeErrorPage;
15643        vm.redirectToLoginPage = redirectToLoginPage;
15644        //On page load
15645        function onPageLoad() {
15646            reservationModelService.addGTMScript();
15647            if ($state.current.name == 'errors') {
15648                vm.errorMessage = storageService.getStorageData('sessionErrMsg');
15649                vm.blockType = 'Err';
15650                $rootScope.requestInProgress = false;
15651
15652            }
15653            else if ($state.current.name == 'success') {
15654                vm.blockType = 'Scs';
15655                $rootScope.requestInProgress = false;
15656            } else {
15657                var encryptedToken = reservationModelService.getUrlParameter("id");
15658                var utmSource = reservationModelService.getUrlParameter('utm_content');
15659                var utmMedium = reservationModelService.getUrlParameter('utm_medium');
15660                if (!encryptedToken) {
15661                    ABG.redirectPage($window.contextPath + "/" + $window.locale + $window.contentRoot + "/login" + htmlExtension);
15662                }
15663                biometricService.getProfileSummary(encryptedToken, utmSource, utmMedium).then(function (response) {
15664                    if (angular.isDefined(response.errorList) && response.errorList.length) {
15665                        response = $scope.processErrorMessage(response);
15666                        storageService.setStorageData('sessionErrMsg', response.errorList[0].message)
15667                        setTimeout(function () {
15668                            ABG.redirectPage($window.contextPath + "/" + $window.locale + $window.contentRoot + "/login" + htmlExtension + "#/" + response.errorList[0].code);
15669                        }, 200);
15670
15671                    }
15672                    else if (response.customerInfo) {
15673                        vm.customerResponce = response.customerInfo;
15674                        gaService.trackBiometricVerificationEvents('VERIFICATION_INITIATED', 'Success', vm.customerResponce);
15675                        if (vm.customerResponce && vm.customerResponce.wizardNumberMasked)
15676                            gaService.dataLayerOfBiometricFlow(vm.customerResponce.wizardNumberMasked);
15677                        // jQuery('.video').removeClass('video');
15678                        if (vm.customerResponce.ftpreferred) {
15679                            gaService.trackBiometricVerificationEvents('CLEAR_PROMO', 'Loaded', vm.customerResponce);
15680                            $window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot + "/biometric-validation" + htmlExtension + "#/clear-me";
15681
15682                        } else if (!vm.customerResponce.ftpreferred && vm.customerResponce.preferred) {
15683                            gaService.trackBiometricVerificationEvents('CLEAR_PROMO', 'AlreadyVerified', vm.customerResponce);
15684                            $window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot + "/biometric-validation" + htmlExtension + "#/success";
15685                        } else {
15686                            ABG.redirectPage($window.contextPath + "/" + $window.locale + $window.contentRoot + "/login" + htmlExtension);
15687                        }
15688                    } else {
15689                        ABG.redirectPage($window.contextPath + "/" + $window.locale + $window.contentRoot + "/login" + htmlExtension);
15690                    }
15691                }, function (error) {
15692                    gaService.trackBiometricVerificationEvents('VERIFICATION_INITIATED', 'Failure', '');
15693                    $rootScope.requestInProgress = false;
15694                    ABG.redirectPage($window.contextPath + "/" + $window.locale + $window.contentRoot + "/login" + htmlExtension + "#/" + error.errorList[0].code);
15695
15696                });
15697            }
15698        }
15699
15700        function redirectToLoginPage() {
15701            ABG.redirectPage($window.contextPath + "/" + $window.locale + $window.contentRoot + "/login" + htmlExtension);
15702        }
15703        function closeErrorPage() {
15704            ABG.redirectPage($window.contextPath + "/" + $window.locale + $window.contentRoot + "/login" + htmlExtension);
15705        }
15706
15707        onPageLoad();
15708
15709    }
15710})();
15711
15712(function () {
15713  "use strict";
15714
15715  angular
15716    .module("account")
15717    .controller("BiometricController", BiometricController);
15718
15719  BiometricController.$inject = [
15720    "$controller",
15721    "$scope",
15722    "$rootScope",
15723    "$sce",
15724    "$validation",
15725    "biometricService",
15726    "$window",
15727    "storageService",
15728    "clearMe",
15729    "$state",
15730    "reservationModelService",
15731    "gaService",
15732    "carRentalConstant",
15733  ];
15734
15735  function BiometricController(
15736    $controller,
15737    $scope,
15738    $rootScope,
15739    $sce,
15740    $validationProvider,
15741    biometricService,
15742    $window,
15743    storageService,
15744    clearMe,
15745    $state,
15746    reservationModelService,
15747    gaService,
15748    carRentalConstant,
15749  ) {
15750    $controller("ExceptionHandlerController", {
15751      $scope: $scope,
15752    });
15753    $rootScope.requestInProgress = true;
15754
15755    // View Model.....
15756    var vm = this;
15757
15758    vm.customerResponce = {};
15759    vm.loadClearpromo = false;
15760    vm.domain = $window.domain.toUpperCase();
15761    vm.apiErrMsg = "";
15762    vm.smsRes = {
15763      showLinkSent: false,
15764      currAttempt: 0,
15765    };
15766    vm.isValidated = false;
15767
15768    // View Callable.....
15769    vm.trigerSms = trigerSms;
15770
15771    // Private Methods.....
15772    vm._onPageLoad = onPageLoad;
15773    vm.addVideoClass = addVideoClass;
15774    vm._setVM = _setVM;
15775    vm.initiateMitekScan = initiateMitekScan;
15776    vm.updateProfileStatus = updateProfileStatus;
15777    vm.enableEnterpriseCaptcha = enableEnterpriseCaptcha;
15778
15779    function triggerAuditUpdate(wizardNumber, flow, device, promoName) {
15780      var promise = biometricService.triggerBiometricAudit(
15781        wizardNumber,
15782        flow,
15783        device,
15784        promoName,
15785      );
15786      // Do nothing with the response
15787      promise.then(
15788        function (_response) {},
15789        function (error) {
15790          console.error("Unable to do biometric audit update: ", error);
15791        },
15792      );
15793    }
15794
15795    //On page load
15796    function onPageLoad() {
15797      reservationModelService.addGTMScript();
15798      var biometricPerformed =
15799        storageService.getStorageData("biometricPerformed");
15800      biometricService.getCustomerDataData().then(function (result) {
15801        vm.customerResponce = result.customerInfo;
15802        if (vm.customerResponce && vm.customerResponce.wizardNumberMasked)
15803          gaService.dataLayerOfBiometricFlow(
15804            vm.customerResponce.wizardNumberMasked,
15805          );
15806        if (!vm.customerResponce) {
15807          ABG.redirectPage(
15808            $window.contextPath +
15809              "/" +
15810              $window.locale +
15811              $window.contentRoot +
15812              "/login" +
15813              htmlExtension,
15814          );
15815        }
15816        if (!vm.customerResponce.ftpreferred && !biometricPerformed) {
15817          $window.location.href =
15818            $rootScope.contextPath +
15819            "/" +
15820            $rootScope.locale +
15821            $window.contentRoot +
15822            "/biometric-validation" +
15823            htmlExtension +
15824            "#/success";
15825        }
15826        if (
15827          $rootScope.deviceType === "handheld" &&
15828          $state.current.name == "clear-me"
15829        ) {
15830          setTimeout(function () {
15831            clearMe.initiate(
15832              "clear-button",
15833              "self-checkout",
15834              "verify",
15835              "profile-enrollment",
15836            );
15837          });
15838          var btnEle = document.getElementById("clear-button");
15839          if (btnEle) {
15840            btnEle.addEventListener("click", function (_event) {
15841              setTimeout(function () {
15842                triggerAuditUpdate(
15843                  vm.customerResponce.wizardNumberMasked,
15844                  "POST_PROFILE_ENROLLMENT",
15845                  "MOBILE",
15846                  "CLEAR_ME_BTN_CLICKED",
15847                  null,
15848                  null,
15849                );
15850              }, 1000);
15851            });
15852          }
15853        }
15854        if (
15855          $state.current.name === "success" &&
15856          biometricPerformed !== undefined
15857        ) {
15858          storageService.deleteStorageData("biometricPerformed"); // we do not need this session val anymore
15859        }
15860
15861        $rootScope.requestInProgress = false;
15862      });
15863    }
15864
15865    function _setVM(extendVM) {
15866      vm = extendVM;
15867    }
15868
15869    function addVideoClass() {
15870      jQuery(".rmvdo").addClass("video");
15871    }
15872    /**
15873     * This function is triggered when the user clicks on the send button on the campaign modal window and it takes the form object from the HTML
15874     * @param formName: Form Object - The form that is present in the d2m Promo HTML
15875     */
15876    function trigerSms(formName) {
15877      vm.isValidated = false;
15878      if (
15879        $window.brand == carRentalConstant.brandName.PAYLESS ||
15880        (enableEnterpriseCaptcha == "true" &&
15881          ($window.brand == carRentalConstant.brandName.AVIS ||
15882            $window.brand == carRentalConstant.brandName.BUDGET))
15883      ) {
15884        grecaptcha.enterprise
15885          .execute(enterpriseCaptchaSiteKey, {
15886            action: "triggerSms",
15887            twofactor: true,
15888          })
15889          .then(function (token) {
15890            vm.recaptcha = token;
15891            _sendSms(formName);
15892          });
15893      } else {
15894        _sendSms(formName);
15895      }
15896    }
15897
15898    function _sendSms(formName) {
15899      /**
15900       * Call the service and pass the wizard number
15901       * If the API is success then we have show the message
15902       * If the API is error, handle it
15903       */
15904      // validate the submitted form
15905      $validationProvider
15906        .validate(formName)
15907        .success(function (succ) {
15908          $rootScope.requestInProgress = true; // need to make it true
15909          biometricService
15910            .sendSms(vm.customerResponce.wizardNumberMasked, vm.recaptcha)
15911            .then(
15912              function (result) {
15913                if (result != null) {
15914                  vm.smsRes.result = result;
15915                  if (
15916                    angular.isDefined(result.fieldErrors) &&
15917                    result.fieldErrors !== null &&
15918                    result.fieldErrors.length > 0
15919                  ) {
15920                    var element = result.fieldErrors[0];
15921                    var errorElement = {
15922                      message: $validationProvider.displayServiceError(
15923                        element.field,
15924                        element.classifier,
15925                      ),
15926                    };
15927                    vm.isValidated = true;
15928                    vm.apiErrMsg = errorElement.message;
15929                  } else if (
15930                    angular.isDefined(result.errorList) &&
15931                    result.errorList !== null &&
15932                    result.errorList.length > 0
15933                  ) {
15934                    gaService.trackBiometricVerificationEvents(
15935                      "D2M_SMS",
15936                      "Failed",
15937                      vm.customerResponce,
15938                    );
15939                    var errElement = result.errorList[0];
15940                    vm.isValidated = true;
15941                    vm.apiErrMsg = errElement.message;
15942                  } else {
15943                    gaService.trackBiometricVerificationEvents(
15944                      "D2M_SMS",
15945                      "Sent",
15946                      vm.customerResponce,
15947                    );
15948                    vm.smsRes.showLinkSent = true;
15949                    vm.smsRes.currAttempt++;
15950                  }
15951                  $rootScope.requestInProgress = false;
15952                }
15953              },
15954              function (e) {
15955                if (
15956                  angular.isDefined(e.fieldErrors) &&
15957                  e !== null &&
15958                  e.fieldErrors !== null &&
15959                  e.fieldErrors.length > 0
15960                ) {
15961                  var element = e.fieldErrors[0];
15962                  var errorElement = {
15963                    message: $validationProvider.displayServiceError(
15964                      element.field,
15965                      element.classifier,
15966                    ),
15967                  };
15968                  vm.isValidated = true;
15969                  vm.apiErrMsg = errorElement.message;
15970                }
15971                if (
15972                  angular.isDefined(e.errorList) &&
15973                  e.errorList !== null &&
15974                  e.errorList.length > 0
15975                ) {
15976                  vm.isValidated = true;
15977                  vm.apiErrMsg = e.errorList[0].message;
15978                }
15979                $rootScope.requestInProgress = false;
15980              },
15981            );
15982        })
15983        .error(function (err) {
15984          // handling error from form not successfully validated
15985          vm.isValidated = true;
15986          vm.apiErrMsg = $scope.processErrorMessage(err.MSG[0]);
15987          angular.element(".ng-invalid").focus();
15988        });
15989    }
15990
15991    function initiateMitekScan() {
15992      $window.location.href =
15993        $rootScope.contextPath +
15994        "/" +
15995        $rootScope.locale +
15996        $window.contentRoot +
15997        "/biometric" +
15998        htmlExtension +
15999        "#/front-dl-scan";
16000    }
16001    function updateProfileStatus() {
16002      $rootScope.requestInProgress = true;
16003      biometricService
16004        .convertProfile(vm.customerResponce.wizardNumberMasked)
16005        .then(
16006          function (response) {
16007            if (
16008              angular.isDefined(response.errorList) &&
16009              response.errorList.length
16010            ) {
16011              gaService.trackBiometricVerificationEvents(
16012                "VERIFICATION",
16013                "Failed",
16014                vm.customerResponce,
16015              );
16016              response = $scope.processErrorMessage(response);
16017              storageService.setStorageData(
16018                "sessionErrMsg",
16019                response.errorList[0].message,
16020              );
16021              $window.location.href =
16022                $rootScope.contextPath +
16023                "/" +
16024                $rootScope.locale +
16025                $window.contentRoot +
16026                "/biometric-validation" +
16027                htmlExtension +
16028                "#/errors";
16029            } else if (response.customerInfo) {
16030              vm.customerResponce = response.customerInfo;
16031              gaService.trackBiometricVerificationEvents(
16032                "VERIFICATION",
16033                "Completed",
16034                vm.customerResponce,
16035              );
16036              $window.location.href =
16037                $rootScope.contextPath +
16038                "/" +
16039                $rootScope.locale +
16040                $window.contentRoot +
16041                "/biometric-validation" +
16042                htmlExtension +
16043                "#/success";
16044              $rootScope.requestInProgress = false;
16045            } else {
16046              ABG.redirectPage(
16047                $window.contextPath +
16048                  "/" +
16049                  $window.locale +
16050                  $window.contentRoot +
16051                  "/login" +
16052                  htmlExtension,
16053              );
16054            }
16055            $rootScope.requestInProgress = false;
16056          },
16057          function (error) {
16058            gaService.trackBiometricVerificationEvents(
16059              "VERIFICATION",
16060              "Failed",
16061              vm.customerResponce,
16062            );
16063            $rootScope.requestInProgress = false;
16064            storageService.setStorageData(
16065              "sessionErrMsg",
16066              error.errorList[0].message,
16067            );
16068            $window.location.href =
16069              $rootScope.contextPath +
16070              "/" +
16071              $rootScope.locale +
16072              $window.contentRoot +
16073              "/biometric-validation" +
16074              htmlExtension +
16075              "#/errors";
16076          },
16077        );
16078    }
16079
16080    onPageLoad();
16081  }
16082})();
16083
16084(function () {
16085    'use strict';
16086
16087    angular
16088        .module('account')
16089        .controller('VerifyIdentityWithMitekController', VerifyIdentityWithMitekController);
16090
16091    VerifyIdentityWithMitekController.$inject = ['$controller', '$scope', '$rootScope', '$state', '$validation', '$window', 'biometricService', 'reservationModelService', 'MiTek', '$location', 'storageService', 'authenticationService', 'gaService'];
16092
16093    function VerifyIdentityWithMitekController($controller, $scope, $rootScope, $state, $validationProvider, $window, biometricService, reservationModelService, MiTek, $location, storageService, authenticationService, gaService) {
16094
16095        $controller('ExceptionHandlerController', {
16096            $scope: $scope
16097        });
16098
16099        // View Model.....
16100        var vm = this;
16101        $rootScope.requestInProgress = true;
16102        $rootScope.isIntrerimProfile = true;
16103        vm.showCameraOverlay = false;
16104        /*This object controls what processing <div> to render throughout the process*/
16105        vm.captureLoading = {
16106            dlf: false,
16107            dlb: false,
16108            selfiVerify: false,
16109            idVerified: false
16110        };
16111        /*Type of the documents used in the scan*/
16112        var typeOfDoc = {
16113            driverLicenseFront: 'DL_FRONT',
16114            driverLicenseBack: "PDF417_BARCODE",
16115            usersSelfie: "SELFIE"
16116        };
16117        /*Type of encoding used in MiTek*/
16118        var encodingType = {
16119            baseSixtyFour: 'base64',
16120            barcode: 'PDF417',
16121            selfie: 'Selfie'
16122        };
16123        /*whichName Reference*/
16124        vm.docName = {
16125            front: 'DL FRONT',
16126            back: 'DL BACK',
16127            selfie: 'SELFIE'
16128        };
16129        vm.delay = { timeoutDelay: 100000, verifyDelay: 2000, successDelay: 2000, lazyDelay: 30000 };
16130        vm.manualCapture = { dlf: false, dlb: false };
16131        vm.customerResponce = {};
16132        vm.errorOnWhichStep = { dlf: false, selfie: false };
16133
16134
16135        vm.domain = $window.domain.toUpperCase();
16136        vm.resSummary = {};
16137        vm.documents = [];
16138        vm.miteKError = '';
16139        vm.isShowLazyLoadCTA = false;
16140        // Private Methods.....
16141        vm._onPageLoad = onPageLoad;
16142        vm.autoCapture = autoCapture;
16143        vm.manualUpload = manualUpload;
16144        vm._resultStore = _resultStore;
16145        vm.goToFacialScan = goToFacialScan;
16146        vm.verifyDocuments = verifyDocuments;
16147        vm.goToBack = goToBack;
16148        vm.goToDlPage = goToDlPage;
16149        //On page load
16150        function onPageLoad() {
16151            reservationModelService.addGTMScript();
16152            vm.customerResponce = authenticationService.getCustomerModel();
16153            if (!vm.customerResponce) {
16154                ABG.redirectPage($window.contextPath + "/" + $window.locale + $window.contentRoot + "/login" + htmlExtension);
16155            }
16156            vm.documents = storageService.getStorageData('mitekDocuments') || [];
16157            if ($state.current.name == 'front-scan' || $location.absUrl().includes('front-scan')) {
16158                vm.scanType = 'front-scan';
16159                vm.whichCapture = typeOfDoc.driverLicenseFront;
16160                vm.whichName = vm.docName.front;
16161                vm.isShowLazyLoadCTA = true;
16162                gaService.trackMitekVerEventsDuringProfileEnroll('DL_FRONT_SCAN', 'Intiate', vm.customerResponce);
16163                vm.autoCapture();
16164            } else if ($state.current.name == 'back-scan' || $location.absUrl().includes('back-scan')) {
16165                vm.scanType = 'back-scan';
16166                vm.whichCapture = typeOfDoc.driverLicenseBack;
16167                vm.whichName = vm.docName.back;
16168                vm.isShowLazyLoadCTA = true;
16169                gaService.trackMitekVerEventsDuringProfileEnroll('DL_BACK_SCAN', 'Intiate', vm.customerResponce);
16170                vm.autoCapture();
16171            } else if ($state.current.name == 'facial-scan' || $location.absUrl().includes('facial-scan')) {
16172                vm.scanType = 'facial-scan';
16173                vm.whichCapture = typeOfDoc.usersSelfie;
16174                vm.whichName = vm.docName.selfie;
16175                gaService.trackMitekVerEventsDuringProfileEnroll('SELFIE_SCAN', 'Intiate', vm.customerResponce);
16176                vm.autoCapture();
16177            } else if ($state.current.name == 'facial-instruction' || $location.absUrl().includes('facial-instruction')) {
16178                vm.scanType = 'facial-instruction';
16179                gaService.trackMitekVerEventsDuringProfileEnroll('FACIAL_SCAN_GUIDE', 'Intiate', vm.customerResponce);
16180                $rootScope.requestInProgress = false;
16181            }
16182        }
16183
16184        function autoCapture() {
16185            MiTek.autoCapture(vm.whichCapture, vm, $scope).then(
16186                function (result) {
16187                    if (result) {
16188                        loadVerifyScreen();
16189                        _resultStore(result);
16190                    }
16191                });
16192
16193
16194        }
16195
16196        function manualUpload() {
16197            /* To scroll the screen top */
16198            $(window).scrollTop(0);
16199            vm.captureLoading.dlf = false;
16200            vm.captureLoading.dlb = false;
16201
16202            vm.lazyLoad = false;
16203            vm.showCameraOverlay = false;
16204            clearTimeout(vm.attemptTimer);
16205            mitekScienceSDK.cmd('SDK_STOP');
16206            setTimeout(function () {
16207                MiTek.manualCapture(vm, $scope).then(
16208                    function (result) {
16209                        if (result) {
16210                            loadVerifyScreen();
16211                            _resultStore(result);
16212                        }
16213                    });
16214            }, 10);
16215        }
16216
16217
16218        /**
16219         * This method used for showing captured div on dl scan success case
16220         */
16221        function loadVerifyScreen() {
16222            // Screen should go to the top to avoid user to do the manual scrolling
16223            $(window).scrollTop(0);
16224            if (vm.whichName === vm.docName.front) {
16225                vm.captureLoading.dlf = true;
16226            } else if (vm.whichName == vm.docName.back) {
16227                vm.captureLoading.dlb = true;
16228            }
16229            $scope.$apply();
16230        }
16231        /**
16232     * remove same type document if duplicate in request array
16233     */
16234        function removeDuplicateImageIfExist(typeOfDoc) {
16235            var index = vm.documents.findIndex(function (item) {
16236                return item.typeOfDoc == typeOfDoc;
16237            });
16238            if (index !== -1) {
16239                vm.documents.splice(index, 1);
16240            }
16241        }
16242        function _resultStore(result) {
16243            vm.showCameraOverlay = false;
16244            vm.lazyLoad = false;
16245            $scope.$apply();
16246            removeDuplicateImageIfExist(vm.whichName);
16247            switch (result.response.docType) {
16248                case typeOfDoc.usersSelfie:
16249                    {
16250                        vm.documents.push({
16251                            image: result.response.imageData.split(',')[1],
16252                            encodingType: encodingType.selfie,
16253                            imageType: result.response.docType,
16254                            typeOfDoc: vm.whichName
16255                        });
16256                    }
16257                    break;
16258                case typeOfDoc.driverLicenseFront:
16259                    {
16260                        vm.documents.push({
16261                            image: result.response.imageData.split(',')[1],
16262                            encodingType: encodingType.baseSixtyFour,
16263                            imageType: result.response.docType,
16264                            typeOfDoc: vm.whichName
16265                        });
16266                    }
16267                    break;
16268
16269                case typeOfDoc.driverLicenseBack:
16270                    {
16271                        vm.documents.push({
16272                            image: angular.isDefined(result.response.code)
16273                                ? result.response.code
16274                                : result.response.imageData.split(',')[1],
16275                            encodingType: angular.isDefined(result.response.code)
16276                                ? encodingType.barcode
16277                                : encodingType.baseSixtyFour,
16278                            imageType: result.response.docType,
16279                            typeOfDoc: vm.whichName
16280                        });
16281                    }
16282                    break;
16283            }
16284            if (vm.whichName == vm.docName.front) {
16285                storageService.setStorageData('mitekDocuments', vm.documents);
16286                setTimeout(function () {
16287                    vm.whichCapture = typeOfDoc.driverLicenseBack;
16288                    vm.whichName = vm.docName.back;
16289                    $state.go('back-scan', {});
16290                }, vm.delay.verifyDelay);
16291            } else if (vm.whichName == vm.docName.back) {
16292                storageService.setStorageData('mitekDocuments', vm.documents);
16293                setTimeout(function () {
16294                    $state.go('facial-instruction', {});
16295
16296                }, vm.delay.verifyDelay);
16297            }
16298
16299            // when all the image strings are captured then only we will call the service
16300            if (vm.documents.length == 3 && vm.whichName == vm.docName.selfie) {
16301                storageService.setStorageData('mitekDocuments', vm.documents);
16302                vm.captureLoading.selfiVerify = true;
16303                // to send the image strings to WEBAPI
16304                vm.verifyDocuments();
16305            }
16306        }
16307        function goToFacialScan() {
16308            gaService.trackMitekVerEventsDuringProfileEnroll('SELFIE_TERMS_ACCEPT', 'Click', vm.customerResponce);
16309            $state.go('facial-scan');
16310            // vm.pageInit();
16311        }
16312        function goToBack() {
16313            $window.history.back();
16314        }
16315
16316        function goToDlPage() {
16317            ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot + "/driving-licence" + htmlExtension);
16318
16319        }
16320
16321        /**
16322         * It's sending documents to webapi for verification
16323         */
16324        function verifyDocuments() {
16325            var tobeSend = JSON.parse(JSON.stringify(vm.documents));
16326            angular.forEach(tobeSend, function (item) {
16327                delete item.typeOfDoc;
16328            });
16329            biometricService
16330                .verifyDlDetails(
16331                    tobeSend,
16332                    vm.customerResponce.wizardNumberMasked
16333                )
16334                .then(
16335                    function (data) {
16336                        vm.captureLoading.selfiVerify = false;
16337                        vm.captureLoading.idVerified = true;
16338                        gaService.trackMitekVerEventsDuringProfileEnroll('DL_VERIFIED', 'Success', vm.customerResponce);
16339                        setTimeout(function () {
16340                            if (angular.isDefined(data.customerInfo) && angular.isDefined(data.customerInfo.webCustomer)
16341                                && angular.isDefined(data.customerInfo.webCustomer.activationStatus) && data.customerInfo.webCustomer.activationStatus == "1") {
16342                                    ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot +  "/dashboard/profile" + htmlExtension);
16343                            } else {
16344                                ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot + "/driving-licence" + htmlExtension);
16345                            }
16346                        }, vm.delay.successDelay);
16347                    },
16348                    function (error) {
16349                        gaService.trackMitekVerEventsDuringProfileEnroll('DL_VERIFIED', 'Failure', vm.customerResponce);
16350                        if (error && error.fieldErrors) {
16351                            var fieldError = $scpe.processErrorMessage(error);
16352                            vm.errorDisplayList = fieldError;
16353                        } else {
16354                            if (error && error.errorList) {
16355                                error = $scope.processErrorMessage(error);
16356                                vm.errorDisplayList = error.errorList;
16357                                if (error.errorList[0].code == '90050') {
16358                                    removeDuplicateImageIfExist(vm.docName.back);
16359                                    vm.captureLoading.selfiVerify = false;
16360                                    vm.whichCapture = typeOfDoc.driverLicenseFront;
16361                                    vm.whichName = vm.docName.front;
16362                                    vm.errorOnWhichStep.dlf = true;
16363                                    vm.mitekValidation = true;
16364                                    vm.miteKError = error.errorList[0].message;
16365                                } else if (
16366                                    error.errorList[0].code == '90055' ||
16367                                    error.errorList[0].code == '90056' ||
16368                                    error.errorList[0].code == '90057'
16369                                ) {
16370                                    vm.captureLoading.selfiVerify = false;
16371                                    vm.errorOnWhichStep.selfie = true;
16372                                    vm.errorOnWhichStep.dlf = false;
16373                                    vm.mitekValidation = true;
16374                                    vm.miteKError = error.errorList[0].message;
16375
16376                                } else {
16377                                    vm.captureLoading.selfiVerify = false;
16378                                    vm.errorOnWhichStep.dlf = true;
16379                                    vm.mitekValidation = true;
16380                                    vm.miteKError = error.errorList[0].message;
16381                                }
16382                            }
16383                        }
16384                    }
16385                );
16386        }
16387        // dynamic classes for MiTek UI thingy
16388        $(document).on('DOMNodeInserted', function (e) {
16389            if (
16390                $('#mitekOuterContainer').length &&
16391                vm.whichCapture == typeOfDoc.driverLicenseBack
16392            ) {
16393                $('#mitekOuterContainer').addClass('DL_BACK_PDF');
16394                if ($('#mitekOuterContainer').hasClass('DL_SELFIE_SCAN')) {
16395                    $('#mitekOuterContainer').removeClass('DL_SELFIE_SCAN');
16396                }
16397                if ($('#mitekOuterContainer').hasClass('DL_FRONT_SCAN')) {
16398                    $('#mitekOuterContainer').removeClass('DL_FRONT_SCAN');
16399                }
16400            } else if (
16401                $('#mitekOuterContainer').length &&
16402                vm.whichCapture == typeOfDoc.usersSelfie
16403            ) {
16404                if ($('#mitekOuterContainer').hasClass('DL_BACK_PDF')) {
16405                    $('#mitekOuterContainer').removeClass('DL_BACK_PDF');
16406                }
16407                if ($('#mitekOuterContainer').hasClass('DL_FRONT_SCAN')) {
16408                    $('#mitekOuterContainer').removeClass('DL_FRONT_SCAN');
16409                }
16410                $('#mitekOuterContainer').addClass('DL_SELFIE_SCAN');
16411            } else if (
16412                $('#mitekOuterContainer').length &&
16413                vm.whichCapture == typeOfDoc.driverLicenseFront
16414            ) {
16415                if ($('#mitekOuterContainer').hasClass('DL_BACK_PDF')) {
16416                    $('#mitekOuterContainer').removeClass('DL_BACK_PDF');
16417                }
16418                if ($('#mitekOuterContainer').hasClass('DL_SELFIE_SCAN')) {
16419                    $('#mitekOuterContainer').removeClass('DL_SELFIE_SCAN');
16420                }
16421                $('#mitekOuterContainer').addClass('DL_FRONT_SCAN');
16422            } else {
16423                // no condition no class required
16424                if ($('#mitekOuterContainer').hasClass('DL_BACK_PDF')) {
16425                    $('#mitekOuterContainer').removeClass('DL_BACK_PDF');
16426                }
16427            }
16428            if (
16429                vm.whichCapture == typeOfDoc.usersSelfie &&
16430                $('.FACE_IN_GUIDE').length > 0
16431            ) {
16432                $('#mitekOuterContainer').addClass('mitek_selfie_green'); // adding it beside the existing one
16433            } else if ($('.FACE_IN_GUIDE').length == 0) {
16434                if ($('#mitekOuterContainer').hasClass('mitek_selfie_green')) {
16435                    $('#mitekOuterContainer').removeClass('mitek_selfie_green');
16436                }
16437            }
16438        });
16439        onPageLoad();
16440
16441    }
16442})();
16443
16444(function() {
16445  'use strict';
16446
16447  angular
16448    .module('account')
16449    .controller('CredentialController', CredentialController);
16450  
16451  CredentialController.$inject = ['$rootScope','$state', '$controller', '$scope', '$window', 'credentialService', '$validation', '$sce', 'authenticationService', 'accessControlService', 'carRentalConstant', 'accountModelService', '$location','accountUtilityService', 'utilityService', 'myProfileService', 'storageService'];
16452
16453  function CredentialController($rootScope,$state, $controller, $scope, $window, credentialService, $validationProvider, $sce, authenticationService, accessControlService, carRentalConstant,accountModelService, $location, accountUtilityService, utilityService, myProfileService, storageService) {
16454
16455    // View Model.....
16456	$controller('ExceptionHandlerController', {$scope: $scope});
16457    var vm = this;
16458    var isValidXSRF = true;
16459    vm._validationError=_validationError;
16460    vm._validationErrorExpire= _validationErrorExpire;
16461    vm.forgotUserNameSubmit = forgotUserNameSubmit;
16462    vm.country = $window.domain.toUpperCase();
16463    vm.forgotPasswordSubmit = forgotPasswordSubmit;
16464	vm.forgotPasswordNewSubmit = forgotPasswordNewSubmit;
16465    vm.resetPasswordSubmit = resetPasswordSubmit;
16466    vm.resetExpirePasswordSubmit = resetExpirePasswordSubmit;
16467    vm.dispalyOnloadError = dispalyOnloadError;
16468    vm.gtmBlur = gtmBlur;
16469    vm.errorDisplayList = [];
16470    vm.enableCaptcha = enableCaptcha;
16471    vm.domain = $window.domain.toUpperCase();
16472	vm._loadCalendarDropdown = _loadCalendarDropdown;
16473	vm._recaptcha = _recaptcha;
16474	var pageName=$window.location.pathname;
16475	$rootScope.requestInProgress = true;
16476	var url = $location.$$absUrl;	
16477	var sessionwizard = storageService.getStorageData('expiredUser');
16478	var errorCode = url ? url.split('#/')[1] : window.location.search.slice(1); // Read query parameter from URL
16479	vm.disableLookUp = false;
16480	vm.formName = $window.formName;
16481	vm.brand = $window.brand;
16482
16483	if(errorCode){
16484		dispalyOnloadError(errorCode);
16485	}
16486	vm.isLoginModelOpen = false;
16487	vm.forgotPasswordCall=false;
16488	vm.forgotUsernameCall=false;
16489	var defaultValue = '';
16490
16491    function onPageLoad() {
16492    	if(brand == carRentalConstant.brandName.PAYLESS || ((brand == carRentalConstant.brandName.AVIS || brand == carRentalConstant.brandName.BUDGET) && (domain == carRentalConstant.countryCodeAU.toLowerCase() || domain == carRentalConstant.countryCodeNZ.toLowerCase()))){
16493	    	 _loadCalendarDropdown();
16494	    }
16495    	if(angular.isDefined(authenticationService.getXsrfToken())){
16496			isValidXSRF  = false;
16497			initialize();
16498		}
16499			
16500    	vm.isLoginModelOpen = true; 	
16501    }
16502    
16503    function initialize(){
16504    	var session = authenticationService.getSessionModel();  
16505    	vm.credentialModal = accountModelService.credentialModal;    	
16506    	if(angular.isDefined(session) && angular.isDefined(session.status) && session.status===carRentalConstant.userStateAuthenticated){
16507    		authenticationService.getCustomerAdditionalInfo().then(function(data){
16508        		accessControlService.validatePage(data);
16509        		$rootScope.requestInProgress = false;
16510    		},function(error){
16511    			ABG.redirectPage($window.contextPath + "/" + $window.locale + $window.contentRoot + "/login" + htmlExtension + "#/" + error.errorList[0].code);
16512    		});
16513    	}
16514    	else{
16515    		$rootScope.requestInProgress = false;
16516    		if(passwordExpireValue == carRentalConstant.passwordExpirePage){
16517    		credentialService.getPasswordExpireLogin().then(function(data){
16518    			$("#expired-user").show();
16519    			vm.credentialModal.wizard = data.userLogin; 	//Populate Expired userName/wizard 
16520    			//storageService.deleteStorageData('reservationModel');
16521    			//storageService.deleteStorageData('customer');	
16522    		},function(error){
16523    			ABG.redirectPage($window.contextPath + "/" + $window.locale + "/home" + htmlExtension);
16524    		});		
16525    		}
16526    		
16527        	//set default values for Payless forgot-password/username scenarios post AJS_1.7 upgrade
16528        	vm.credentialModal.dobMonth = null;
16529        	vm.credentialModal.dobDate = null;
16530        	vm.credentialModal.dobYear = null;
16531    	}  	
16532    }
16533    
16534    $rootScope.$on('initSuccess', function(event, arg) {
16535		if(isValidXSRF){
16536			initialize();
16537		}
16538	});
16539    
16540    function forgotUserName() {
16541    	vm.successMessage = null;
16542    	vm.forgotUsernameCall=true;
16543    	if(enableCaptcha == 'true'){
16544    		grecaptcha.execute();  		
16545    	}else{
16546    		forgotUserNameCaptcha();
16547    	}
16548    }
16549  //calling the method on captcha value is true or false.
16550    function forgotUserNameCaptcha() {
16551    	$rootScope.requestInProgress = true;
16552		var promise = credentialService.forgotUserName(vm.credentialModal,vm.recaptcha);
16553		promise.then(function(data) {
16554			$rootScope.requestInProgress = false;
16555			if(angular.isDefined(data)){
16556				if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0 ||
16557						(angular.isDefined(data.errorList) && data.errorList.length > 0)) {
16558					data =  $scope.processErrorMessage(data);
16559					ABG.resetCaptcha(); 
16560					vm.errorDisplayList =data.errorList;
16561				} else {
16562					ABG.resetCaptcha();						
16563					vm.successMessage = Dictionary.I18n.get('msg.profile.wizardMailSent,'+brand)+vm.credentialModal.emailAddress;
16564				}
16565				$window.scrollTo(0, 0);
16566			}
16567		}, function(error) {
16568			vm.errorDisplayList =  $scope.processErrorMessage(error).errorList;
16569			$rootScope.requestInProgress = false;
16570			ABG.resetCaptcha();
16571			$("body").animate({
16572	              "scrollTop": 0
16573	            }, "slow");
16574		});
16575    }
16576    
16577   
16578    
16579    function userResetPassword() {
16580    	$rootScope.requestInProgress = true;
16581    	 var promise = authenticationService.resetPassword(vm.credentialModal.password);
16582         promise.then(function(data) {
16583           $rootScope.requestInProgress = false;
16584           if(angular.isDefined(data)){
16585        	   if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0 ||
16586        			   (angular.isDefined(data.errorList) && data.errorList.length > 0)) {
16587						   ABG.resetCaptcha();
16588        		   data = $scope.processErrorMessage(data);
16589        		   ABG.resetCaptcha(); 
16590        		   vm.errorDisplayList =data.errorList;
16591        	    } else {  
16592        	        var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot+"/dashboard/profile" + htmlExtension;
16593        	        $window.location.href = redirectPath;
16594        	    } 
16595           }
16596         }, function(error) {
16597        	vm.errorDisplayList =  $scope.processErrorMessage(error).errorList;
16598 			$rootScope.requestInProgress = false;
16599			ABG.resetCaptcha();
16600 			$("body").animate({
16601	              "scrollTop": 0
16602	            }, "slow");
16603         });
16604    }
16605    
16606    function userForgotPassword() {
16607    	vm.forgotPasswordSuccessMessage = null;
16608    	vm.forgotPasswordCall=true;
16609    	if(enableCaptcha == 'true'){
16610    		grecaptcha.execute();  		
16611    	}else{
16612    		userForgotPasswordCaptcha();
16613    	}   	
16614    }
16615    //calling the method on captcha value is true or false.
16616    function userForgotPasswordCaptcha(){
16617    	$rootScope.requestInProgress = true;
16618		var promise = credentialService.forgotPassword(vm.credentialModal,vm.recaptcha);
16619		promise.then(function(data) {
16620			$rootScope.requestInProgress = false;
16621			if(angular.isDefined(data)){
16622				if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0 ||
16623						(angular.isDefined(data.errorList) && data.errorList.length > 0)) {
16624					data = $scope.processErrorMessage(data);
16625					ABG.resetCaptcha(); 
16626					vm.errorDisplayList =data.errorList;
16627				} else { 
16628					ABG.resetCaptcha();
16629					vm.forgotPasswordSuccessMessage = Dictionary.I18n.get('msg.profile.passwordMailSent')+vm.credentialModal.emailAddress; 
16630					vm.disableLookUp = true;
16631				}
16632				$window.scrollTo(0, 0);
16633			}
16634		}, function(error) {
16635			vm.errorDisplayList =  $scope.processErrorMessage(error).errorList;
16636			$rootScope.requestInProgress = false;
16637			$("body").animate({
16638	              "scrollTop": 0
16639	            }, "slow");
16640		});
16641    }
16642	
16643    //Forgot Password New
16644    function userForgotPasswordNew() {
16645    	vm.forgotPasswordSuccessMessage = null;
16646    	vm.forgotPasswordCallNew=true;
16647    	if(enableCaptcha == 'true'){
16648    		grecaptcha.execute();  		
16649    	}else{
16650    		userForgotPasswordCaptchaNew();
16651    	}   	
16652    }
16653	function userForgotPasswordCaptchaNew(){
16654    	$rootScope.requestInProgress = true;
16655		var promise = credentialService.forgotPasswordNew(vm.credentialModal,vm.recaptcha);
16656		promise.then(function(data) {
16657			$rootScope.requestInProgress = false;
16658			if(angular.isDefined(data)){
16659				if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0 ||
16660						(angular.isDefined(data.errorList) && data.errorList.length > 0)) {
16661					data = $scope.processErrorMessage(data);
16662					ABG.resetCaptcha(); 
16663					vm.errorDisplayList =data.errorList;
16664				} else { 
16665					ABG.resetCaptcha();
16666					vm.forgotPasswordSuccessMessage = Dictionary.I18n.get('msg.profile.passwordMailSent')+ Dictionary.I18n.get('msg.profile.registeredEmail');  
16667					vm.disableLookUp = true;
16668				}
16669				$window.scrollTo(0, 0);
16670			}
16671		}, function(error) {
16672			vm.errorDisplayList =  $scope.processErrorMessage(error).errorList;
16673			$rootScope.requestInProgress = false;
16674			$("body").animate({
16675	              "scrollTop": 0
16676	            }, "slow");
16677		});
16678    }
16679
16680	function _validationError(response) {
16681		vm.errorDisplayList = ABG.getFormValidationError(response,true);
16682	}
16683	function dispalyOnloadError(errorCode) {
16684		utilityService.getErrorMessageByCode(errorCode).then(function(data){
16685			vm.errorDisplayList=data;
16686			 $window.scrollTo(0, 0);
16687		},function(){});
16688	}
16689	
16690	function resetPasswordSubmit(resetPasswordForm) {
16691		$validationProvider.validate(resetPasswordForm).success(userResetPassword).error(vm._validationError);
16692	}
16693	
16694	function forgotPasswordSubmit(forgetUserNameForm) {
16695		vm.errorDisplayList = [];
16696		$validationProvider.validate(forgetUserNameForm).success(userForgotPassword).error(vm._validationError);
16697	}
16698	
16699	function forgotPasswordNewSubmit(forgotPasswordNewForm) {
16700		vm.errorDisplayList = [];
16701		$validationProvider.validate(forgotPasswordNewForm).success(userForgotPasswordNew).error(vm._validationError);
16702	}
16703
16704	function forgotUserNameSubmit(forgetPasswordForm) {
16705		vm.errorDisplayList = [];
16706		$validationProvider.validate(forgetPasswordForm).success(forgotUserName).error(vm._validationError);
16707	}
16708		
16709	function resetExpirePasswordSubmit(expirePasswordForm) {
16710		vm.errorDisplayList = [];
16711		if (vm.credentialModal.updatePassword.currentPassword == vm.credentialModal.updatePassword.newPassword && vm.credentialModal.updatePassword.currentPassword != "" && vm.credentialModal.updatePassword.newPassword != "") {
16712			vm.errorDisplayList = Dictionary.I18n.get('error.profile.common.samepassword,' + brand) + '</br>' + Dictionary.I18n.get('msg.profile.password.reenter');
16713			vm.formValidated = true;
16714            _clearPasswordFields();
16715        } else if (vm.credentialModal.updatePassword.currentPassword == "" && vm.credentialModal.updatePassword.newPassword != "") {
16716        	vm.errorDisplayList = Dictionary.I18n.get('error.profile.oldPassword.required,' + brand) + '</br>' + Dictionary.I18n.get('msg.profile.password.reenter');
16717			vm.formValidated = true;
16718            _clearPasswordFields();            
16719        }else{
16720        	$validationProvider.validate(expirePasswordForm).success(forgotExpire).error(vm._validationErrorExpire);
16721        }		
16722	}
16723	function forgotExpire() {
16724            	$rootScope.requestInProgress = true;
16725            	var sectionedit = 'password-section';
16726            	myProfileService.updatePassword(vm.customerData,vm.credentialModal,sectionedit).then(function(data) {
16727            		data = $scope.processErrorMessage(data);
16728            		if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0) {
16729            			vm.errorDisplayList = data.errorList[0].message;
16730            				vm.formValidated = true;
16731            				_clearPasswordFields();
16732            		} else if (angular.isDefined(data.errorList) && data.errorList.length > 0) {
16733            			vm.errorDisplayList = data.errorList[0].message;
16734            				vm.formValidated = true;
16735            				_clearPasswordFields();
16736            		} else {
16737            			vm.formValidated = false;
16738            			ABG.redirectPage($rootScope.contextPath + "/" + $rootScope.locale +$window.contentRoot+"/dashboard/profile" + htmlExtension);
16739            		}
16740            		//$rootScope.requestInProgress = false;                	
16741            	}, function(error) {
16742            		if(angular.isDefined(error.errorList) && error.errorList.length > 0){
16743            			vm.errorDisplayList = error.errorList[0].message;
16744    	                vm.formValidated = true;
16745    	                vm.showSuccessMsg = false;
16746    	                $window.scrollTo(0, 0);
16747            		}
16748            		_clearPasswordFields();
16749            		$rootScope.requestInProgress = false;
16750            	})           
16751		}
16752		function _validationErrorExpire(data) {
16753	        //.error(function(data){
16754	            	vm.errorDisplayList = (data.errorCount >= 2) ? (Dictionary.I18n.get('err.global.multi.errorMessage') + '</br>' + Dictionary.I18n.get('msg.profile.password.reenter')) : (data.MSG[0] + '</br>' + Dictionary.I18n.get('msg.profile.password.reenter'));
16755	            	vm.formValidated = true;
16756	            	 //_clearPasswordFields();
16757	                $rootScope.requestInProgress = false;
16758	                $window.scrollTo(0, 0);	           
16759	           // });
16760	     }			
16761	
16762	function _clearPasswordFields(){
16763		vm.credentialModal.currentPassword = defaultValue;
16764		vm.credentialModal.newPassword = defaultValue;
16765    }
16766	function _loadCalendarDropdown() {
16767		var lowerAgeLimit = vm.hasPartnerInfo ? ( angular.isDefined(vm.customerData.partnerCustomerInfo.minAge) ? vm.customerData.partnerCustomerInfo.minAge : carRentalConstant.ageLimit.lower )  : carRentalConstant.ageLimit.lower;
16768    	var CalendarDetails = accountUtilityService.loadCalendarDropdown(lowerAgeLimit);
16769    	vm.monthsList = CalendarDetails.monthsList;
16770        vm.yearsList = CalendarDetails.yearsList;
16771        vm.datesList = CalendarDetails.datesList;
16772    }
16773	
16774//	GTM FUNCTION
16775	function gtmBlur(string, string1, inputType) {
16776		//	hardcoded strings in this function need not be I18N as these won't be displayed in UI.
16777		var inputAction;
16778		if (inputType == 'text') {
16779			inputAction = string ? 'Filled In' : 'Skipped';
16780		} else if (inputType == 'checkbox') {
16781			inputAction = string ? 'Selected as Y' : 'Selected as N';
16782		} else if (inputType == 'dropdown') {
16783			inputAction = string ? 'Selected' : 'Not Selected';
16784		} 
16785		dataLayer.push({ 
16786			'event': 'trackEvent',
16787			'eventCategory': 'Tracking Form: ' + 'Forgot-Reset-Password-form',
16788			'eventLabel': string1,
16789			'eventAction': inputAction
16790		});
16791	}
16792	 onPageLoad();
16793	 
16794	 //Overridden in Ext Controller
16795	 function _recaptcha(){
16796	 }
16797	 
16798	 var extendedController = $controller('CredentialExnController', {
16799     	$scope: $scope
16800     });
16801     angular.extend(this, extendedController);
16802     
16803	//broadcasting recaptcha 
16804     $rootScope.$on("recaptcha", function(event, response){
16805    	 vm.recaptcha=response;
16806    	 if(angular.isDefined(response) && response != ''){
16807    		 if(vm.forgotPasswordCall){
16808    			 userForgotPasswordCaptcha();
16809    			 vm.forgotPasswordCall=false;
16810    		 }else if(vm.forgotPasswordCallNew){
16811				userForgotPasswordCaptchaNew();
16812				vm.forgotPasswordCallNew=false;
16813			}else if(vm.forgotUsernameCall){
16814    		 	 forgotUserNameCaptcha();
16815    			 vm.forgotUsernameCall=false;
16816    			 
16817    		 }			
16818    	 }				
16819     });
16820  }
16821})();
16822
16823(function() {
16824  'use strict';
16825
16826  angular
16827    .module('account')
16828    .controller('EmailCredentialController', EmailCredentialController);
16829
16830  EmailCredentialController.$inject = ['$controller', '$location', '$scope', 'authenticationService', '$rootScope', '$window'];
16831
16832  function EmailCredentialController($controller, $location, $scope, authenticationService, $rootScope, $window) {
16833
16834    $controller('ExceptionHandlerController', {
16835      $scope: $scope
16836    });
16837
16838    // View Model.....
16839    var vm = this;
16840    vm.processActivation = true;
16841    vm.prod = {}; //TODO change it to relevant name
16842    
16843    // Private Methods.....
16844    vm._validateEmailLinkCall = _validateEmailLinkCall;
16845
16846    // Function will be called on page load
16847    function onPageLoad() {
16848    	//console.log('EmailCredentialController');
16849      var queryParams = "";
16850      // Reads the query string from URL and sets the query params to this variable.
16851      queryParams = $location.search();
16852
16853      var params = {};
16854      angular.forEach(queryParams, function(value, key) {
16855        params[key] = value;
16856      });
16857      // To check if XSRF token present
16858      if (authenticationService.getXsrfToken()) {
16859        vm.processActivation = false;
16860        _validateEmailLinkCall(params);
16861      }
16862      // Call only on init call success
16863      var onInitSuccess = $rootScope.$on('initSuccess', function(event, arg) {
16864        if (vm.processActivation) {
16865          _validateEmailLinkCall(params);
16866        }
16867      });
16868    }
16869    
16870    // Calls webapi for validating email Link
16871    function _validateEmailLinkCall(params) {
16872    	authenticationService.passwordResetMailValidate(params).then(function(data) {
16873    		if(angular.isDefined(data)){
16874    			data = $scope.processErrorMessage(data);
16875    			if ((angular.isDefined(data.errorList) && data.errorList.length > 0) || (angular.isDefined(data.warningList) && data.warningList.length > 0)) {
16876    				var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale +$window.contentRoot+"/forgot-password" + htmlExtension;
16877    				ABG.redirectPage(redirectPath + "#/" + data.errorList[0].code);
16878    			} else {
16879    				var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale +$window.contentRoot+"/reset-password" + htmlExtension;
16880    				$window.location.href = redirectPath;
16881    				//ABG.redirectPage(redirectPath);
16882    			}
16883    		}else{
16884    			var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot+"/forgot-password" + htmlExtension;
16885    			$window.location.href = redirectPath;
16886    			//ABG.redirectPage(redirectPath);
16887    		}
16888    	},
16889    	function(error) {
16890    		var redirectPath = $rootScope.contextPath + "/" + $rootScope.locale + $window.contentRoot+"/forgot-password" + htmlExtension  + "#/" + error.errorList[0].code;
16891    		$window.location.href = redirectPath;
16892    		//ABG.redirectPage(redirectPath);
16893    	});
16894    }
16895   
16896    // Call on page load
16897    onPageLoad();
16898  }
16899})();
16900
16901(function () {
16902  "use strict";
16903
16904  angular
16905    .module("accountServices")
16906    .service("biometricService", biometricService);
16907  biometricService.$inject = [
16908    "$http",
16909    "$q",
16910    "exceptionHandler",
16911    "authenticationService",
16912    "$window",
16913    "carRentalConstant",
16914    "reservationModelService",
16915    "storageService",
16916  ];
16917
16918  function biometricService(
16919    $http,
16920    $q,
16921    exceptionHandler,
16922    authenticationService,
16923    $window,
16924    carRentalConstant,
16925    reservationModelService,
16926    storageService,
16927  ) {
16928    var result = {
16929      getCustomerDataData: getCustomerDataData,
16930      sendSms: sendSms,
16931      getProfileSummary: getProfileSummary,
16932      convertProfile: convertProfile,
16933      verifyDlDetails: verifyDlDetails,
16934      triggerBiometricAudit: triggerBiometricAudit,
16935    };
16936
16937    /**
16938     * Returns the data from front-end cache if present, otherwise loads by calling api
16939     */
16940    function getCustomerDataData() {
16941      var deferred = $q.defer();
16942      var url =
16943        apiurl + "/summary/profile?url=/account/my-profile/biometricSummary";
16944      $http({
16945        method: "GET",
16946        url: url,
16947      })
16948        .then(function onSuccess(response) {
16949          if (
16950            angular.isUndefined(reservationModelService.getReservationModel())
16951          ) {
16952            reservationModelService.load("", true);
16953          }
16954          var data = response.data;
16955          deferred.resolve(data);
16956        })
16957        .catch(function onError(response) {
16958          var data = response.data;
16959          deferred.reject(data);
16960        });
16961
16962      return deferred.promise;
16963    }
16964
16965    /**
16966     *
16967     * @param {*} wizardNumber
16968     * @returns we are getting wizard number from profile retrive endpoint and triggering the sms endpoint,it's sending sms to user
16969     */
16970
16971    function sendSms(wizardNumber, recaptcha) {
16972      var deferred = $q.defer();
16973      var url = apiurl + "/profile/send-sms";
16974      $http({
16975        method: "POST",
16976        url: url,
16977        data: { wizardNumber: wizardNumber },
16978        headers: {
16979          "g-recaptcha-response": recaptcha ? recaptcha : "",
16980        },
16981      })
16982        .then(function onSuccess(response) {
16983          var data = response.data;
16984          deferred.resolve(data);
16985        })
16986        .catch(function onError(response) {
16987          var data = response.data;
16988          deferred.reject(ABG.evaluateError(data));
16989        });
16990      return deferred.promise;
16991    }
16992
16993    /**
16994     *
16995     * @param {*} token
16996     * @returns we are getting token from the sms url and passing to web API and from there we are getting cdb Summary.
16997     */
16998    function getProfileSummary(encryptedToken, utmSource, utmMedium) {
16999      //check if the xsrf token in present, if not call the init and then call profile login
17000      var token = authenticationService.getXsrfToken();
17001      if (!token) {
17002        var deferred = $q.defer();
17003        var initApiCall = authenticationService.init();
17004        $q.all([initApiCall]).then(function (initApiData) {
17005          _loadProfileSummary(encryptedToken, utmSource, utmMedium).then(
17006            function (data) {
17007              deferred.resolve(data);
17008            },
17009          );
17010        });
17011        return deferred.promise;
17012      } else {
17013        return _loadProfileSummary(encryptedToken, utmSource, utmMedium);
17014      }
17015
17016      function _loadProfileSummary(encryptedToken, utmSource, utmMedium) {
17017        var deferred = $q.defer();
17018        var url = apiurl + "/profile/retrieve";
17019        $http({
17020          method: "POST",
17021          url: url,
17022          data: {
17023            encryptedToken: encryptedToken,
17024            utmSource: utmSource,
17025            utmMedium: utmMedium,
17026          },
17027        })
17028          .then(function onSuccess(response) {
17029            var data = response.data;
17030            if (
17031              angular.isDefined(data) &&
17032              angular.isUndefined(data.errorList)
17033            ) {
17034              storageService.setStorageData("profile-data", data.customerInfo);
17035              deferred.resolve(data);
17036            } else {
17037              deferred.resolve(data);
17038            }
17039          })
17040          .catch(function onError(response) {
17041            var data = response.data;
17042            deferred.reject(ABG.evaluateError(data));
17043          });
17044        return deferred.promise;
17045      }
17046    }
17047    /**
17048     *
17049     * @param {*} wizardNumber
17050     * @returns we are getting wizard number from profile retrive endpoint and triggering the updateFtpDl endpoint,it's updating  the profile
17051     */
17052
17053    function convertProfile(wizardNumber) {
17054      var deferred = $q.defer();
17055      var url = apiurl + "/profile/convert";
17056      $http({
17057        method: "POST",
17058        url: url,
17059        data: { wizardNumber: wizardNumber },
17060      })
17061        .then(function onSuccess(response) {
17062          var data = response.data;
17063          deferred.resolve(data);
17064        })
17065        .catch(function onError(response) {
17066          var data = response.data;
17067          deferred.reject(ABG.evaluateError(data));
17068        });
17069      return deferred.promise;
17070    }
17071    /**
17072     * This is invoked when we capture the dl and selfie data
17073     */
17074    function verifyDlDetails(documents, wizardNumber) {
17075      var reqObj = {
17076        documents: documents,
17077        wizardNumber: wizardNumber,
17078      };
17079      var deferred = $q.defer();
17080      var url = apiurl + "/profile/verifyDriversLicense";
17081      $http({
17082        method: "POST",
17083        url: url,
17084        data: reqObj,
17085      })
17086        .then(function onSuccess(response) {
17087          var data = response.data;
17088          if (!($window.brand == carRentalConstant.brandName.PAYLESS)) {
17089            ABG.updateContextStores();
17090          }
17091          data = exceptionHandler.processError(
17092            data,
17093            reservationModelService.modelMap,
17094          );
17095          if (angular.isDefined(data) && angular.isUndefined(data.errorList)) {
17096            storageService.setStorageData("dlVerifiedWithMitek", true);
17097            deferred.resolve(data);
17098          } else {
17099            storageService.setStorageData("dlVerifiedWithMitek", false);
17100            deferred.reject(data);
17101          }
17102        })
17103        .catch(function onError(response) {
17104          storageService.setStorageData("dlVerifiedWithMitek", false);
17105          var data = response.data;
17106          deferred.reject(data);
17107        });
17108      return deferred.promise;
17109    }
17110    function triggerBiometricAudit(
17111      wizardNumber,
17112      flow,
17113      device,
17114      promoName,
17115      utmMedium,
17116      utmSource,
17117    ) {
17118      var reqObj = {
17119        wizardNumber: wizardNumber,
17120        flow: flow,
17121        transactionType:
17122          device.length && promoName.length
17123            ? device.toUpperCase() + "_" + promoName.toUpperCase()
17124            : "UNKNOWN",
17125        utmMedium:
17126          utmMedium === undefined || utmMedium === null ? "" : utmMedium,
17127        utmSource:
17128          utmSource === undefined || utmSource === null ? "" : utmMedium,
17129      };
17130      var deferred = $q.defer();
17131      var url = apiurl + "/bio-metric-report/update-audit";
17132      $http({
17133        method: "POST",
17134        url: url,
17135        data: reqObj,
17136      })
17137        .then(function onSuccess(response) {
17138          var data = response.data;
17139          if (!($window.brand == carRentalConstant.brandName.PAYLESS)) {
17140            ABG.updateContextStores();
17141          }
17142          data = exceptionHandler.processError(
17143            data,
17144            reservationModelService.modelMap,
17145          );
17146          if (angular.isDefined(data) && angular.isUndefined(data.errorList)) {
17147            deferred.resolve(data);
17148          } else {
17149            deferred.reject(data);
17150          }
17151        })
17152        .catch(function onError(response) {
17153          var data = response.data;
17154          deferred.reject(data);
17155        });
17156      return deferred.promise;
17157    }
17158    return result;
17159  }
17160})();
17161
17162(function () {
17163  'use strict';
17164  angular.module('account').config(bioMetricRouting);
17165  bioMetricRouting.$inject = ['$stateProvider'];
17166
17167  function bioMetricRouting($stateProvider) {
17168    $stateProvider.state('clear-me', {
17169      url: '/clear-me',
17170      templateUrl:
17171        rootpath + contentRoot + '/biometric-validation/clear-me.partial' + htmlExtension,
17172      controller: 'BiometricController',
17173      controllerAs: 'vm'
17174    });
17175    $stateProvider.state('profile-details', {
17176      url: '/profile-details',
17177      templateUrl:
17178        rootpath + contentRoot + '/biometric-validation/profile-details.partial' + htmlExtension,
17179      controller: 'BiometricController',
17180      controllerAs: 'vm'
17181    });
17182    $stateProvider.state('errors', {
17183      url: '/errors',
17184      templateUrl:
17185        rootpath + contentRoot + '/biometric-validation/errors.partial' + htmlExtension,
17186      controller: 'BiometricValidationController',
17187      controllerAs: 'vm'
17188    });
17189    $stateProvider.state('success', {
17190      url: '/success',
17191      templateUrl:
17192        rootpath + contentRoot + '/biometric-validation/success.partial' + htmlExtension,
17193      controller: 'BiometricValidationController',
17194      controllerAs: 'vm'
17195    });
17196    $stateProvider.state('mitek', {
17197      url: '/mitek',
17198      templateUrl:
17199        rootpath + contentRoot + '/biometric-validation/mitek.partial' + htmlExtension,
17200      controller: 'BiometricController',
17201      controllerAs: 'vm'
17202    });
17203    $stateProvider.state('front-scan', {
17204      url: '/front-scan',
17205      templateUrl: rootpath + contentRoot + '/biometric-validation/mitek-validation/front-scan.partial' + htmlExtension,
17206      controller: 'VerifyIdentityWithMitekController',
17207      controllerAs: 'vm'
17208    });
17209    $stateProvider.state('back-scan', {
17210      url: '/back-scan',
17211      templateUrl:
17212        rootpath + contentRoot + '/biometric-validation/mitek-validation/back-scan.partial' + htmlExtension,
17213      controller: 'VerifyIdentityWithMitekController',
17214      controllerAs: 'vm'
17215    });
17216    $stateProvider.state('facial-scan', {
17217      url: '/facial-scan',
17218      templateUrl:
17219        rootpath + contentRoot + '/biometric-validation/mitek-validation/facial-scan.partial' + htmlExtension,
17220      controller: 'VerifyIdentityWithMitekController',
17221      controllerAs: 'vm'
17222    });
17223    $stateProvider.state('facial-instruction', {
17224      url: '/facial-instruction',
17225      templateUrl:
17226        rootpath + contentRoot + '/biometric-validation/mitek-validation/facial-instruction.partial' + htmlExtension,
17227      controller: 'VerifyIdentityWithMitekController',
17228      controllerAs: 'vm'
17229    });
17230
17231  }
17232})();
17233
17234(function() {
17235	'use strict';
17236
17237	angular
17238		.module('partner', []);
17239})();
17240(function() {
17241	'use strict';
17242	
17243	angular
17244		.module('partner')
17245		.controller('PartnerController', PartnerController);
17246	
17247	PartnerController.$inject = ['$scope', '$window', '$compile', '$timeout', '$rootScope', 'authenticationService','getDataService','bridgeService', 'reservationModelService', '$controller', 'carRentalConstant'];
17248
17249	function PartnerController($scope, $window, $compile, $timeout, $rootScope, authenticationService, getDataService,bridgeService, reservationModelService, $controller, carRentalConstant) {
17250
17251		
17252		// View Model.....
17253		var vm = this;
17254        var DashboardController = $controller('DashboardController', {
17255		$scope: $scope
17256	});
17257        angular.extend(this, DashboardController);
17258        DashboardController._setVM(vm);
17259		// View Callable.....
17260		vm.callPartnerReservation = callPartnerReservation;
17261		vm.setUrl = setUrl;
17262		vm.memberToDisplay = "";
17263		vm.parentAwd = $window.parentAwd;
17264		vm.segmentName = $window.segmentName;
17265		vm.member = $window.member;
17266		var linkUrl = "";
17267        var count = 0;
17268        var callPartnerReservationCount = 0;
17269		var trackingId = "";
17270		var segmentDetails = {
17271				"segmentName" : vm.segmentName,
17272				"memberToDisplay" : "",
17273				"awdNumber" : "",
17274				"country" : "",
17275				"requiresMemberID" : false,
17276				"partnerName" : ""	
17277		}
17278		
17279		// Private Methods.....
17280		vm._onPageLoad = _onPageLoad;
17281		vm._getMemberDetails = _getMemberDetails;
17282		
17283		function _onPageLoad() {
17284			// To set the logo image on partner header	
17285			$rootScope.$broadcast("cbpInfoForLogo", $window.logoImagePath); 
17286			_getMemberDetails();
17287			vm.cbpInfo = getDataService.getCBPInfoData();
17288			if(angular.isDefined(authenticationService.getXsrfToken()) && angular.isDefined(vm.cbpInfo) && !angular.equals({}, vm.cbpInfo) && angular.isDefined(vm.cbpInfo.awdNumber) && vm.cbpInfo.awdNumber == vm.parentAwd){
17289				_initialize(vm.cbpInfo);
17290			}else{
17291				authenticationService.init(false, vm.parentAwd).then(function (data){
17292					if(angular.isDefined(data) && angular.isDefined(data.cbpInfo)){
17293						reservationModelService.load(data, true).then(function(resData){
17294							_initialize(data.cbpInfo);
17295						},function(error){
17296							
17297						});						
17298						getDataService.addCBPInfoData(data.cbpInfo);
17299					}
17300					$rootScope.$broadcast('Profile.initSuccess', data);
17301				},function (error){
17302					//handle error
17303				});
17304			}
17305			var waitUntilAngularReady = waitUntilAngularReady || {};
17306			(function(randomString) {
17307				waitUntilAngularReady[randomString] = setInterval(function() {
17308                        if (angular.isDefined(window.angular)) {
17309                            var element = angular.element('.teaser-container');
17310                            $compile(element)($scope);
17311                            $scope.$apply();
17312					}
17313				}, 300);
17314			})(Math.random().toString(36).substring(2, 15)+ Math.random().toString(36).substring(2, 15));
17315		}
17316		
17317		function _initialize(cbpInfo){
17318			if(angular.isDefined(cbpInfo)){ 
17319				vm.partnerDetails = cbpInfo;
17320				segmentDetails.awdNumber = cbpInfo.awdNumber;
17321				//TODO: Line 61-62 needs to be looked over for handling multiple countries
17322				var residency = (angular.isDefined(cbpInfo.country) && cbpInfo.country != '' && cbpInfo.country.length != 0) ? cbpInfo.country[0].toUpperCase() : 'US';
17323				segmentDetails.country = ((residency.indexOf("US") == -1) && (residency.indexOf("CA") != -1)) ? 'CA' : 'US';
17324				//Partner Changes to set partnername and requiresMembershipId Field.
17325				if(angular.isDefined(cbpInfo)){
17326					segmentDetails.requiresMemberID = cbpInfo.requiresMemberID;
17327					segmentDetails.partnerName = cbpInfo.partnerName;
17328				}
17329				//to set AWD in res-widget the moment init is called
17330                $timeout(function(){
17331                	$rootScope.$broadcast("setPartnerInfoInWidget", segmentDetails);
17332                },100)
17333				/*if(CQ_Analytics.ProfileDataMgr){
17334					 CQ_Analytics.ProfileDataMgr.fireEvent("update");
17335				}*/	 
17336                /*if(!($window.brand == carRentalConstant.brandName.PAYLESS))
17337                {*/
17338                	ABG.updateContextStores();
17339        				$rootScope.$broadcast('Update.Notificationdisplay');
17340               /* }*/
17341			}
17342		}
17343		//To set the member details fetching from dialog on welcome message
17344		function _getMemberDetails(){
17345			if(angular.isDefined(vm.member) && vm.member == 'custom'){
17346				if(angular.isDefined($window.customText)){
17347					vm.memberToDisplay = $window.customText;
17348				}
17349			}else if(angular.isDefined(vm.member) && vm.member !== 'none'){
17350				vm.memberToDisplay = vm.member;
17351			}
17352			segmentDetails.memberToDisplay = vm.memberToDisplay;
17353		}
17354		//To set the feature image URL if any
17355        function setUrl(url, id){
17356			linkUrl = url;
17357			trackingId = id;
17358        }
17359        //To redirect when Business or Leisure reservation deal calls
17360		function callPartnerReservation(reservation){			
17361			if(angular.isDefined(reservation) && (callPartnerReservationCount == 0)){
17362				callPartnerReservationCount++;
17363				var awdNumber = "";
17364				if(reservation.toUpperCase() == 'B'){
17365					if(angular.isDefined($window.businessDiscount) && $window.businessDiscount.length>0){
17366						awdNumber = $window.businessDiscount;
17367					}else{
17368						awdNumber = vm.parentAwd;
17369					}
17370				}else if(reservation.toUpperCase() == 'L'){
17371					if(angular.isDefined($window.leisureDiscount) && $window.leisureDiscount.length>0){
17372						awdNumber = $window.leisureDiscount;
17373					}else{
17374						awdNumber = vm.parentAwd.substring(0,vm.parentAwd.length-2) + "90";
17375					}
17376				}
17377				bridgeService.callToReservation(reservation,awdNumber).then(function(data){
17378                    count++;
17379					if(!angular.isDefined(trackingId) || trackingId === null || trackingId === ""){
17380						$window.location.href =linkUrl;
17381                        if(count<= 1 )
17382					    gtmHrefLinkTracking();
17383			        }
17384                    else{
17385					    linkUrl = linkUrl+"?"+trackingId;
17386						$window.location.href =linkUrl;
17387			            if(count<= 1 )
17388					    gtmHrefLinkTracking();
17389                    }
17390				},function(error){
17391					//handle error
17392				});
17393			} 
17394		}
17395		/*
17396		* As feature image component link property has 
17397		* anchor href void(null) therefore below block of code 
17398		* pushes the anchor hyperlink value to google analytics 
17399		* as 'Link Click' category and 'EvenLable' would be
17400		* navigation page url.
17401		*/
17402		function gtmHrefLinkTracking(){
17403			dataLayer.push({ 
17404                            'event': 'LinkClick',
17405                            'eventCategory': 'Link Click',
17406                            'eventCallLabel': $window.location.protocol +"//"+ $window.location.host + linkUrl,
17407                            'eventAction': 'Element_Clicks'
17408                        });
17409		}
17410		// Page Init...
17411		vm._onPageLoad();
17412	} 
17413})();
17414(function() {
17415	'use strict';
17416
17417	angular
17418	.module('reservation')
17419	.controller('MobileAppLandingController', MobileAppLandingController);
17420
17421	MobileAppLandingController.$inject = ['$scope','$rootScope','$controller','anchorSmoothScroll','$validation','utilityService'];
17422
17423	function MobileAppLandingController($scope, $rootScope, $controller, anchorSmoothScroll, $validationProvider, utilityService) {
17424
17425		$controller('ExceptionHandlerController', {
17426			$scope: $scope
17427		});
17428
17429		var vm = this;
17430		vm.emailSuccess = false;
17431		vm.errorDisplay = false;
17432		vm.prod="";
17433		vm.userEmail="";
17434		vm.os = ABG.getMobileOperatingSystem();
17435		
17436		vm.openEmailPopover = openEmailPopover;
17437		vm.gotoElement = gotoElement;
17438		vm.triggerEmail = triggerEmail;
17439		vm.cancelModal = cancelModal;
17440		
17441		vm._validationSuccess = _validationSuccess;
17442
17443		function cancelModal() {		
17444			vm.userEmail='';
17445			vm.emailSuccess = false;
17446			vm.errorDisplay = false;
17447			var elem = angular.element('form[name=emailForm] input[name=userEmail]');
17448			$validationProvider.removeError(elem, true);
17449		}
17450
17451		function gotoElement(eID){
17452			var triggeredEle = angular.element(eID.target);
17453			var trigParent = triggeredEle.closest("[id*='slide']");
17454			var targetEle = trigParent.next("[id*='slide']");
17455			var targetId = targetEle.attr('id');			
17456			anchorSmoothScroll.scrollTo(targetId);
17457		}
17458
17459		function triggerEmail(emailForm){
17460			$validationProvider.validate(emailForm).success(_validationSuccess);	
17461		}
17462
17463		function _validationSuccess(){
17464			$rootScope.requestInProgress = true;
17465			var email = vm.userEmail;
17466
17467			utilityService.getResponse(email).then(function(data) {
17468				data = $scope.processErrorMessage(data);
17469				vm.prod = data;
17470				vm.emailSuccess = vm.prod.success;	
17471				if(vm.prod.success == false){
17472					vm.errorDisplay = true;
17473				}
17474				if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0) {
17475					$validationProvider.displayServiceError("vm.userEmail", data.fieldErrors[0].classifier);
17476				} 
17477			});
17478			$rootScope.requestInProgress = false;		
17479		}
17480
17481		function openEmailPopover(){
17482			vm.cancelModal();
17483		}
17484
17485	}
17486})();
17487(function() {
17488  'use strict';
17489
17490  angular
17491    .module('reservation')
17492    .controller('TncController', TncController);
17493
17494  TncController.$inject = ['$scope', '$rootScope', '$state', '$location', 'carRentalConstant', 'locationTermsConditionsService'];
17495
17496  function TncController($scope, $rootScope, $state, $location, carRentalConstant, locationTermsConditionsService) {
17497	  var vm = this;
17498	  
17499	  function init(){
17500		  if(angular.isDefined($location.search().LocCode) && angular.isDefined($location.search().prepay)){
17501			  var contentType = ($location.search().prepay.toLowerCase() === "true") ? carRentalConstant.txnTypePrePay : carRentalConstant.txnTypePostPay;
17502			  var locCode = $location.search().LocCode			 
17503			  $rootScope.requestInProgress = true;
17504			  var promise = locationTermsConditionsService.load(contentType,locCode);
17505		      promise.then(function(data) {		    	  
17506		    	  $rootScope.requestInProgress = false;
17507		    	  vm.CompleteTexNew = data;
17508		      }, function(error) {
17509		    	  $rootScope.requestInProgress = false;		        
17510		      });
17511		  }
17512	  }
17513	  
17514	  init();
17515  }
17516})();
17517
17518(function() {
17519    'use strict';
17520    
17521    angular
17522		.module('receipt', ['receiptService']);
17523})();
17524(function() {
17525    'use strict';
17526    
17527    angular
17528		.module('receiptService', []);
17529})();
17530(function() {
17531    'use strict';
17532
17533    angular
17534        .module('receiptService')
17535        .service('ReceiptLookupService', ReceiptLookupService);
17536
17537    ReceiptLookupService.$inject = ['$http', '$q', '$window', '$filter', 'reservationModelService','storageService', 'carRentalConstant', 'exceptionHandler', '$rootScope','authenticationService'];
17538
17539
17540    function ReceiptLookupService($http, $q, $window, $filter, reservationModelService,storageService, carRentalConstant, exceptionHandler, $rootScope,authenticationService) {
17541        var result= {
17542        	getReceipt:getReceipt,
17543        	validateReceipt:validateReceipt,
17544        	load:load,
17545        	emailRequestHandler:emailRequestHandler
17546        }
17547        
17548        /**
17549         * Performs reservation look up
17550         * 
17551         * @return promise object with reservation data
17552         */
17553        function load(request, authorised) {
17554        	//check if the xsrf token in present, if not call the init and then call profile login
17555        	var token = authenticationService.getXsrfToken();
17556        	
17557        	if(!token) {
17558        		var deferred = $q.defer();
17559            	var initApiCall = authenticationService.init(true);
17560        		$q.all([initApiCall]).then(function(initApiData) {
17561        			validateReceipt(request).then(function(data){
17562                  	  deferred.resolve(data);
17563              	  });
17564            	});
17565        		return deferred.promise;
17566        	} else if(angular.isDefined(authorised) && authorised == true) {
17567        		return authValidateReceipt(request);
17568        	}else{
17569        		return validateReceipt(request);
17570        	}
17571        }
17572
17573        function getReceipt() {
17574
17575            var deferred = $q.defer();
17576            $http({
17577            	method: 'GET',
17578                url: apiurl + '/pdf/fetchpdf',
17579                responseType: 'arraybuffer'
17580	  		}).then(function onSuccess(response) {
17581	  			var data = response.data;		
17582	  			data = exceptionHandler.processError(data, reservationModelService.modelMap);
17583                deferred.resolve(data); 
17584	  		}).catch(function onError(response) {
17585	  			var data = response.data;
17586	  			console.log('Error');
17587	  		});
17588            return deferred.promise;
17589
17590        }
17591
17592        function validateReceipt(request) {
17593        	//console.log('Before validate '+ request.countryCode);
17594            var deferred = $q.defer();
17595            $http({
17596            	method: 'POST',
17597                url: apiurl + '/rental/validate-receipt',
17598                data: request
17599	  		}).then(function onSuccess(response) {
17600	  			var data = response.data;		
17601                data = exceptionHandler.processError(data, reservationModelService.modelMap);
17602                deferred.resolve(data);
17603	  		}).catch(function onError(response) {
17604	  			console.log('Error');
17605	  		});
17606            return deferred.promise;
17607        }
17608        
17609        function emailRequestHandler(request){
17610        	var token = authenticationService.getXsrfToken();
17611        	
17612        	if(!token) {
17613        		var deferred = $q.defer();
17614            	var initApiCall = authenticationService.init(true);
17615        		$q.all([initApiCall]).then(function(initApiData) {
17616        			validateEmailRequest(request).then(function(data){
17617                  	  deferred.resolve(data);
17618              	  });
17619            	});
17620        		return deferred.promise;        	
17621        	}else{
17622        		return validateEmailRequest(request);
17623        	}
17624        }
17625        
17626        function validateEmailRequest(request){
17627        	var deferred = $q.defer();
17628            $http({
17629            	method: 'POST',
17630                url: apiurl + '/ncore/rental/fetchEreceipt',
17631                data: request
17632	  		}).then(function onSuccess(response) {
17633	  			var data = response.data;			
17634	  			data = exceptionHandler.processError(data, reservationModelService.modelMap);
17635                deferred.resolve(data);
17636	  		}).catch(function onError(response) {
17637	  			console.log('Error');
17638	  		});
17639            return deferred.promise;
17640        }
17641        
17642        function authValidateReceipt(request) {
17643            var deferred = $q.defer();
17644            $http({
17645            	method: 'POST',
17646                url: apiurl + '/ncore/rental/view-receipt',
17647                data: request
17648	  		}).then(function onSuccess(response) {
17649	  			var data = response.data;		
17650	  			data = exceptionHandler.processError(data, reservationModelService.modelMap);
17651                deferred.resolve(data);
17652	  		}).catch(function onError(response) {
17653	  			console.log('Error');
17654	  		});
17655            return deferred.promise;
17656        }
17657        
17658        return result;
17659
17660    }
17661
17662})();
17663(function() {
17664    'use strict';
17665    angular
17666        .module('receipt')
17667        .controller('ReceiptController', ReceiptController);
17668    ReceiptController.$inject = ['$controller', '$scope', '$rootScope', '$state', '$window', '$sce', 'ftpService','storageService', 'authenticationService','$validation', 'carRentalConstant', 'reservationModelService', '$stateParams','ReceiptLookupService', '$filter', 'utilityService','lookupService'];
17669
17670    function ReceiptController($controller, $scope, $rootScope, $state, $window, $sce, ftpService, storageService, authenticationService,$validationProvider, carRentalConstant, reservationModelService, $stateParams,ReceiptLookupService, $filter, utilityService,lookupService) {
17671
17672    	$controller('ExceptionHandlerController', {
17673    	      $scope: $scope
17674    	    });
17675    	
17676        var vm = this;
17677        var urlQueryParamsJs = utilityService.getQueryParamsUsingJs();
17678        vm.showReceiptForm=false;
17679        vm.country={};
17680        vm.pageContent = {};
17681        vm.initSuccess = false;
17682        var countriesList = "";
17683        var countries={};
17684        var countriesJson = {};
17685        var closedRental = storageService.getStorageData('ClosedRental');
17686        vm.pageContent.countryList = {};
17687        vm.emailReceiptRequest = {};
17688        vm._setResidency=_setResidency;
17689        vm.session = authenticationService.getSessionModel();
17690        vm.customer = authenticationService.getCustomerModel();
17691        vm.receiptRequest = carRentalConstant.receiptRequest;
17692        vm.submit = submit;
17693        vm.validationSuccess = validationSuccess;
17694        vm.validationError = validationError;
17695        vm.loadPdf = loadPdf;
17696        vm.initialize = initialize;
17697        vm.viewPdf = viewPdf;
17698        vm.printPdf = printPdf;
17699        vm._validateReceipt = _validateReceipt;
17700        vm._initLookup= _initLookup;
17701        vm.addRntalFtp = addRntalFtp;
17702        vm.addRental = addRental;
17703        vm._validateFTPData=_validateFTPData;
17704        vm.lookupInitialize = lookupInitialize;
17705        vm.downloadPdf = downloadPdf;
17706        vm.lookupModel = carRentalConstant.lookupModel;
17707        vm.getLoginModalWindow = getLoginModalWindow;
17708		vm.submitGetPage =submitGetPage;
17709        var redirectUrl=$window.redirectUrl;
17710        vm.emailReqFlow = (window.location.pathname.toLowerCase().indexOf("get-e-receipt")>-1 && urlQueryParamsJs.KEY)?true:false;
17711        
17712        $rootScope.$on('initSuccess', function(event, data){
17713            if(storageService.sessionStorageSupport()===false){
17714                  vm.session = authenticationService.getSessionModel();
17715                  vm.customer = authenticationService.getCustomerModel();
17716                  vm.lookupModel = carRentalConstant.receiptRequest;
17717                  vm._initLookup();
17718            }
17719            if(vm.emailReqFlow && !vm.initSuccess){
17720            	vm.initSuccess = true;
17721            	vm.emailReceiptRequest = {
17722            		"key":urlQueryParamsJs.KEY,
17723            		"country":urlQueryParamsJs.COUNTRY?urlQueryParamsJs.COUNTRY:"",
17724            		"language":urlQueryParamsJs.LANGUAGE?urlQueryParamsJs.LANGUAGE:""
17725            	}            	
17726            	_validateEmailReceipt();
17727            }
17728          });
17729		  function submitGetPage(GetMorePage){
17730            $validationProvider.validate(GetMorePage).success(function(){
17731				$window.location.href =redirectUrl;
17732            }).error(function(data){
17733
17734            });
17735        }
17736        
17737        function lookupInitialize(){
17738        	$rootScope.requestInProgress = true;
17739        	/*if (angular.isDefined(vm.session) && ( vm.session.status == carRentalConstant.userStateAuthenticated || vm.session.status === carRentalConstant.userStateRememberMe)) {
17740            	 $window.location.href = $rootScope.contextPath + "/" + $rootScope.locale +  $window.contentRoot + "/dashboard/my-activity/past-rentals" + htmlExtension;
17741        		//This URL has to be replaced with SR Page URL once the SR Pages are available.
17742        		// $window.location.href = "/car-rental/profile/viewpastrentals.ac";
17743            }else */
17744        	if(vm.emailReqFlow){
17745            	vm.showReceiptForm = true;
17746            }else{
17747            	vm.showReceiptForm = true;
17748            	$rootScope.requestInProgress = false;
17749            }
17750        	 var countriesList = $window.countryList;
17751             var countries= angular.fromJson(countriesList)
17752             var countriesJson = countries.countryInfoList;
17753             vm.pageContent.countryList = countriesJson;
17754             if($window.brand == 'avis' && $window.domain.toLowerCase() == 'us') {
17755                 if($window.locale == 'es' || $window.locale == 'es_US') {
17756         			vm.pageContent.countryList.push({code: "U-U S A", name: "EE. UU."});
17757                 } 
17758                 else if($window.locale == 'pt' || $window.locale == 'pt_US') {
17759 					vm.pageContent.countryList.push({code: "U-U S A", name: "U S A"});
17760                 }
17761         	}
17762             vm._setResidency();
17763        	
17764        }
17765        
17766        function _initLookup(){
17767        	if(vm.emailReqFlow && angular.isDefined(authenticationService.getXsrfToken()) && !vm.initSuccess){
17768        		$rootScope.requestInProgress = true;
17769        		vm.initSuccess = true;
17770        		vm.emailReceiptRequest = {
17771                		"key":urlQueryParamsJs.KEY,
17772                		"country":urlQueryParamsJs.COUNTRY?urlQueryParamsJs.COUNTRY:"",
17773                		"language":urlQueryParamsJs.LANGUAGE?urlQueryParamsJs.LANGUAGE:""
17774                }            	
17775        		_validateEmailReceipt();
17776        	} else if(vm.emailReqFlow){
17777        		$rootScope.requestInProgress = true;
17778        	}
17779        	//invalid session error messages 
17780            vm.sessionErrorMessage = storageService.getStorageData('sessionErrMsg');
17781            reservationModelService.deleteDataBeforeLogoClick();
17782            vm.pdfError = storageService.getStorageData('pdfError');
17783            if(vm.pdfError){
17784          	  vm.errorDisplayList = vm.pdfError;
17785            }
17786            storageService.deleteStorageData('pdfError');
17787            if (vm.sessionErrorMessage) {        	
17788        	  var errorList = [];
17789        	  var error = {
17790        			"message": vm.sessionErrorMessage
17791        	  };            
17792              errorList.push(error);
17793              vm.errorDisplayList = errorList;
17794              $('.res-PageError .mainErrorText').text(vm.sessionErrorMessage);
17795              $('.res-PageError .mainErrorText').show();
17796              storageService.deleteStorageData('sessionErrMsg');
17797            }
17798            
17799            if (angular.isDefined(vm.session) && (vm.session.status == carRentalConstant.userStateRecognized 
17800            		|| vm.session.status == carRentalConstant.userStateAuthenticated || vm.session.status === carRentalConstant.userStateRememberMe)) {
17801                vm.receiptRequest.lastName = vm.customer.lastName;
17802            }
17803        }
17804
17805        function initialize() {
17806        	$rootScope.requestInProgress = true
17807            vm.validateResponse = storageService.getStorageData('receiptResponse');
17808            vm.receiptRequest = storageService.getStorageData('receiptRequest');
17809          }
17810        
17811        function getLoginModalWindow() {
17812            $rootScope.$broadcast("LoginActivity", {
17813              'requestType': 'Login',
17814              'variance': 'Small'
17815            });
17816          }
17817        
17818        /**
17819         * getPartnerName(_id)	 
17820         * Get the Partner Name from Partner Name list by passing partner code
17821         * Return partner Name
17822         */
17823        function getPartnerName(_id) {
17824        	//console.log("Hi");
17825          return $.grep(vm.ftp.partnersList, function(item) {
17826            return item.partnerId == _id
17827          });
17828        }
17829 		
17830  		 /**
17831  	     * _getFTPSectionMessage(messageList)
17832  	     * Generate message from code from web-api response
17833  	     * This message will be displayed at step3 FTP section
17834  	     */
17835  	    function _getFTPSectionMessage(messageList) {
17836//  	      var ftpMsgList = [];
17837  	      var ftpSectErrList = [];
17838  	      angular.forEach(messageList, function(message) {
17839//  	        message.message = Granite.I18n.get(message.code, message.values, '');
17840  	        if (angular.equals(message.type, 'ERROR')) {
17841  	          ftpSectErrList.push(message);
17842  	        } 
17843  	      });
17844  	      vm.ftpSectErrList = ftpSectErrList;
17845  	    }
17846  	    
17847  	  /**
17848  	     * _validateFTPData(flowcontrol)
17849  	     * Field level validation for FTP for both step3 and step4 globalsummary pop-up
17850  	     */
17851  	    function _validateFTPData() {
17852  	      var partnerDefined = true;
17853  	      var memberDefined = true;
17854  	      var errMsg = [];
17855  	      var error;
17856  	      var errorList = [];
17857  	      if (vm.reservationModel == undefined || vm.reservationModel.ftpDetail
17857s == undefined || vm.reservationModel.ftpDetails.partnerCode == undefined || vm.reservationModel.ftpDetails.partnerCode == "") {
17858  	        partnerDefined = false;
17859  	      }
17860  	      if (vm.reservationModel == undefined || vm.reservationModel.ftpDetails == undefined || vm.reservationModel.ftpDetails.ftpNumber == undefined || vm.reservationModel.ftpDetails.ftpNumber == "") {
17861  	        memberDefined = false;
17862  	      }
17863  	        if (memberDefined && !partnerDefined) {
17864  	          errMsg.push($validationProvider.displayServiceError('vm.reservationModel.ftpDetails.partnerCode', 'ftpInvalid'));
17865  	        } else if (partnerDefined && !memberDefined) {
17866  	          errMsg.push($validationProvider.displayServiceError('vm.reservationModel.ftpDetails.ftpNumber', 'ftpInvalid'));
17867  	        }else if(!partnerDefined && !memberDefined){
17868  	        	 errMsg.push("Please enter your rewards program name and membership number");
17869  	        }
17870  	      if (1 === errMsg.length) {
17871  	        error = {
17872  	          "message": errMsg[0]
17873  	        };
17874  	      }
17875  	      if (errMsg.length != 0) {
17876  	        errorList.push(error);
17877  	      }
17878  	      vm.errorList = errorList;
17879  	    }
17880  		
17881  		function addRntalFtp() {
17882  	    $rootScope.requestInProgress = true;
17883  	    var promise = ftpService.addRentalFTP(vm.reservationModel.ftpDetails.partnerCode,vm.reservationModel.ftpDetails.ftpNumber);
17884  	    promise.then(function(data) {
17885  	    	  if (angular.isDefined(data)) {
17886  	    			if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0 ||
17887  			          (angular.isDefined(data.errorList) && data.errorList.length > 0)) {
17888  			        	$rootScope.requestInProgress = false;
17889  			          data = $scope.processErrorMessage(data);
17890  			          vm.errorList = data.errorList;
17891  			        } else {
17892  		        		$rootScope.requestInProgress = false;
17893  		  	          //Close the popup
17894  		  	          //assign success to a variable
17895  		        		angular.element(".Rental-Receipt-FTP").modal("hide");
17896  		  	          vm.ftpSuccess = data.success;
17897  		  	          //console.log("Ftp Sucess Mesage" +data.success);
17898  			        }
17899  	    		}	        
17900  	      	
17901  	      }, function(error) {
17902  	    	  $rootScope.requestInProgress = false;
17903  	      });
17904  	    };
17905 
17906  	  function addRental(){
17907  		vm._validateFTPData();
17908			if (vm.errorList.length < 1) {
17909				addRntalFtp();
17910			}
17911		}
17912	
17913        
17914        function _setResidency() {
17915        		var residency = $window.defaultCountryName;
17916        		if(angular.isDefined(vm.pageContent.countryList)){
17917	     		    var index = vm.pageContent.countryList.indexOf($filter('filter')(
17918	    	        vm.pageContent.countryList,
17919	     	        function(d) {
17920	     		        return d.name === residency;
17921	     	        })[0]);
17922	   				vm.country = vm.pageContent.countryList[index].code;
17923        		}
17924   		}	
17925
17926        function submit(receipt_form){
17927        	$rootScope.requestInProgress = true;
17928            vm.errorDisplayList = [];
17929            vm.errorMessage = "";
17930            if(vm.prod && vm.prod.warningList){
17931      		  	vm.prod.warningList = [];
17932      	  	}
17933      	  	if(vm.prod && vm.prod.errorList){
17934      	  		vm.prod.errorList = [];
17935      	  	}
17936
17937            $validationProvider.validate(receipt_form).success(vm.validationSuccess).error(vm.validationError);
17938        }
17939
17940        function validationError(response) {
17941        	$rootScope.requestInProgress = false;
17942        	var errorList = ABG.getFormValidationError(response,false);
17943			/* TODO: condition check should not be rely with english language */
17944        	if(errorList[0].message.indexOf('Please enter a valid <strong>confirmation number') != -1){
17945        		var error = {
17946        				"message": Dictionary.I18n.get('13012')
17947        		};
17948        		errorList=[error];
17949        	}
17950//        	if (response.errorCount > 1) {
17951//        		var error = {
17952//        				"message": Granite.I18n.get('err.global.multi.errorMessage')
17953//        		};
17954//        	} else if(response.errorCount == 1 && response.MSG[0].indexOf('Please enter a valid <strong>confirmation number') != -1){
17955//        		var error = {
17956//        				"message": Granite.I18n.get('13012')
17957//        		};
17958//        	}else {
17959//        		var error = {
17960//        				"message": response.MSG[0]
17961//        		};
17962//        	}
17963//        	errorList.push(error);
17964        	vm.errorDisplayList = errorList;
17965        }
17966
17967        function validationSuccess(response) {
17968            //console.log(objbrowserName + " " + objfullVersion);
17969            vm.receiptRequest.countryCode = vm.country;
17970            //vm.receiptRequest.lastName = vm.receiptRequest.lastName.replace(/[^\w\s]/gi, '');
17971            vm.receiptRequest.lastName.trim();//remove space at end of line
17972            //remove all the chars until you find alphabhet
17973            vm.receiptRequest.lastName = vm.receiptRequest.lastName.replace(/^[^a-z|^A-Z]*/, "");
17974            //remove multiple spaces
17975            vm.receiptRequest.lastName = vm.receiptRequest.lastName.replace(/\s\s+/g, " ");        
17976            //remove all the special chars which are not allowed in last name
17977            vm.receiptRequest.lastName = vm.receiptRequest.lastName.replace(/[^a-zA-Z0-9\-\s]/g, "");
17978            //Call validate service
17979            
17980            _validateReceipt();
17981            
17982
17983        }
17984        
17985        function _validateEmailReceipt(){
17986        	$rootScope.requestInProgress = true;
17987        	var successFlag;
17988        	var errorList="";
17989        	var statusFlag;
17990        	if(angular.isDefined(vm.emailReceiptRequest)){
17991        		var promise = ReceiptLookupService.emailRequestHandler(vm.emailReceiptRequest);
17992        		promise.then(function(data){
17993        			//checking for success flag
17994        			if(angular.isDefined(data.success)){
17995        				successFlag = data.success;
17996        			}
17997        			//checking for errors
17998        			if(angular.isDefined(data.errorList)){
17999        				errorList = data.errorList;
18000        			}
18001        			//checking for status flag
18002        			if(angular.isDefined(data.status)){
18003        				statusFlag = data.status;
18004        			}
18005        			vm.validateResponse = data;
18006	            	if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0 ||
18007	            			(angular.isDefined(data.warningList) && data.warningList.length > 0) ||
18008	                        (angular.isDefined(data.errorList) && data.errorList.length > 0)) {
18009	            		vm.prod = $scope.processErrorMessage(data);
18010	            		$rootScope.requestInProgress = false;
18011	            	}else if(!angular.isDefined(data.document)){
18012	            			vm.prod = $scope.processErrorMessage(data);
18013	            			var genericErrorMessage = Dictionary.I18n.get('err.res.genericerrormsg,' + brand);
18014	        				var errorList = [];
18015	        				errorList.push({
18016	        					"message": genericErrorMessage
18017	        				})
18018	        				vm.prod.errorList = errorList;
18019	        				$rootScope.requestInProgress = false;
18020	            	}else{
18021	            		vm.receiptRequest.rentalAgreementNum = angular.isDefined(data.rentalAgreementNumber)?data.rentalAgreementNumber:"";
18022		            	storageService.setStorageData('receiptRequest', vm.receiptRequest);
18023	                    storageService.setStorageData('receiptResponse', vm.validateResponse);
18024	                    $window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + "/" +  "reservation/receipt-details" + htmlExtension;
18025	            	}
18026        		},function(error){
18027        			$rootScope.requestInProgress = false; 
18028        		})
18029        		/*//if errors are present / success flag is not true / status flag is not 200, call fetchEReceipt once again
18030        		if((angular.isDefined(successFlag) && !successFlag)){
18031        			promise = ReceiptLookupService.emailRequestHandler(vm.emailReceiptRequest);
18032        		}
18033        		else if((angular.isDefined(statusFlag) && statusFlag!=200)){
18034        			promise = ReceiptLookupService.emailRequestHandler(vm.emailReceiptRequest);
18035        		}
18036        		else if(angular.isDefined(errorList)){
18037        			promise = ReceiptLookupService.emailRequestHandler(vm.emailReceiptRequest);
18038        		}
18039        		promise.then(function(data){
18040        			vm.validateResponse = data;
18041	            	if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0 ||
18042	            			(angular.isDefined(data.warningList) && data.warningList.length > 0) ||
18043	                        (angular.isDefined(data.errorList) && data.errorList.length > 0)) {
18044	            		vm.prod = $scope.processErrorMessage(data);
18045	            		$rootScope.requestInProgress = false;
18046	            	}else if(!angular.isDefined(data.document)){
18047	            			vm.prod = $scope.processErrorMessage(data);
18048	            			var genericErrorMessage = Dictionary.I18n.get('err.res.genericerrormsg,' + brand);
18049	        				var errorList = [];
18050	        				errorList.push({
18051	        					"message": genericErrorMessage
18052	        				})
18053	        				vm.prod.errorList = errorList;
18054	        				$rootScope.requestInProgress = false;
18055	            	}else{
18056	            		vm.receiptRequest.rentalAgreementNum = angular.isDefined(data.rentalAgreementNumber)?data.rentalAgreementNumber:"";
18057		            	storageService.setStorageData('receiptRequest', vm.receiptRequest);
18058	                    storageService.setStorageData('receiptResponse', vm.validateResponse);
18059	                    $window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + "/" +  "reservation/receipt-details" + htmlExtension;
18060	            	}        			
18061        		},function(error){
18062        			$rootScope.requestInProgress = false; 
18063        		})*/
18064        	}
18065        }
18066        
18067        function _validateReceipt() {
18068        	if(angular.isDefined(vm.receiptRequest)){
18069	        	var promise = ReceiptLookupService.load(vm.receiptRequest);
18070	            
18071	            promise.then(function(data){
18072	            	vm.validateResponse = data;
18073	            	if (angular.isDefined(data.fieldErrors) && data.fieldErrors.length > 0 ||
18074	                        (angular.isDefined(data.warningList) && data.warningList.length > 0)) {
18075	            		vm.prod = $scope.processErrorMessage(data);
18076	                    $rootScope.requestInProgress = false;
18077	            	}else if(angular.isDefined(data.errorList) && data.errorList.length > 0){
18078	            		$rootScope.requestInProgress = false;
18079	            		var navigateToVMC = false;
18080	            		angular.forEach(data.errorList, function(error) {
18081	                        if (angular.equals(error.code, '05218') || ((angular.equals(error.code, '05222')) && (!vm.receiptRequest.rentalAgreementNum.match(carRentalConstant.noCouponCreditCardExp)))) {
18082	                        	vm.lookupModel.lastName = vm.receiptRequest.lastName;
18083	                            vm.lookupModel.confirmationNumber = vm.receiptRequest.rentalAgreementNum;
18084	                            reservationModelService.setLookUpModel(vm.lookupModel);
18085	                            $rootScope.requestInProgress = true;
18086	                          var promise = lookupService.load();
18087	                          promise.then(function(data) { 
18088	                        	  $window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + "/" + "reservation/reservation-details"+htmlExtension;
18089	                        	  $rootScope.requestInProgress = false;
18090	                          },function(error){
18091	                        	  $rootScope.requestInProgress = false;
18092	                        	  vm.errorDisplayList = error.errorList;
18093	                          });
18094	                        	//navigateToVMC = true;
18095	                        }
18096	                        //Open rental scenario error
18097	                        else if (angular.equals(error.code, '05222')){
18098	                        	var errorList = [];
18099	                      	  	var error = {
18100	                      			"message": Dictionary.I18n.get('err.receipt.openRental1')+vm.receiptRequest.rentalAgreementNum+Dictionary.I18n.get('err.receipt.openRental2')
18101	                      	  	};            
18102	                            errorList.push(error);
18103	                            vm.errorDisplayList = errorList;
18104	                        }else{
18105	                        	vm.prod = $scope.processErrorMessage(data);
18106	                        }
18107	                      });
18108	            		if(navigateToVMC){
18109	            			$window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + "/" + "reservation/view-modify-cancel"+htmlExtension;
18110	            		}
18111	            	}else if(data.errorList==null || data.errorList == undefined){
18112	            		storageService.setStorageData('receiptRequest', vm.receiptRequest);
18113	                    storageService.setStorageData('receiptResponse', vm.validateResponse);
18114	
18115	                    $rootScope.requestInProgress = false; 
18116	                    $window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + "/" +  "reservation/receipt-details" + htmlExtension;
18117	            	}
18118	            }, function(error){
18119	            	//console.log('error');
18120	            });
18121        	}
18122        }
18123
18124        function loadPdf() {
18125        	$rootScope.requestInProgress = true;
18126        	vm.clientInfo = ABG.getClientInfo();
18127          //  console.log("ClientInfo ",vm.clientInfo);
18128        	if(angular.isDefined(vm.receiptRequest) || (angular.isDefined(closedRental) && closedRental==true)){
18129        		
18130        		if(!angular.isDefined(vm.validateResponse) && angular.isDefined(closedRental) && closedRental==false){
18131        			_validateReceipt();
18132        		}
18133        		
18134	            if (vm.clientInfo.isIE && vm.clientInfo.isIE9 && navigator.userAgent.indexOf('Edge') == -1) {
18135	                //vm.ie9 = true;
18136	                //console.log("Form action : "+document.getElementsByName("receipt_form_hidden")[0].action)
18137	                document.getElementsByName("receipt_form_hidden")[0].action = apiurl+'/pdf/fetchpdf'
18138	                //document.getElementsByName("receipt_form_hidden")[0].action = '/bin/pdf';
18139	//                document.getElementsByName("countryCode")[0].value = vm.receiptRequest.countryCode;
18140	//                document.getElementsByName("lastName")[0].value = vm.receiptRequest.lastName;
18141	//                document.getElementsByName("rentalAgreementNum")[0].value = vm.receiptRequest.rentalAgreementNum;
18142	                document.forms['receipt_form_hidden'].submit();
18143	
18144	                //Else display PDF in canvas using PDF.js
18145	            } else {
18146	                vm.ie9 = false;
18147	                ReceiptLookupService.getReceipt().then(
18148	                    function(pdfData) {
18149	                    	$rootScope.requestInProgress = true;
18150	                    	if(angular.isDefined(pdfData) && angular.isDefined(pdfData.byteLength) && pdfData.byteLength < 500){
18151	                    		var genericErrorMessage = Dictionary.I18n.get('err.res.genericerrormsg,' + brand);
18152		        				var pdfErrorList = [];
18153		        				pdfErrorList.push({
18154		        					"message": genericErrorMessage
18155		        				})
18156	                            vm.errorDisplayList = pdfErrorList;
18157	                            storageService.setStorageData('pdfError',vm.errorDisplayList);
18158	                            $window.location.href = $rootScope.contextPath + "/" + $rootScope.locale + "/" + "reservation/get-e-receipt"+htmlExtension;
18159                        	}else if (pdfData.error == null || pdfData.error == undefined) {
18160	                            vm.displayPdf = true;
18161	                            vm.receiptResponse = pdfData;
18162	                            vm.file = new Blob([vm.receiptResponse], {
18163	                                type: 'application/pdf'
18164	                            });
18165	                            vm.fileURL = URL.createObjectURL(vm.file);
18166	                            var pdfDoc = null,
18167	                                pageNum = 1,
18168	                                pageRendering = false,
18169	                                pageNumPending = null,
18170	                                wrapper = document.getElementById('rental-receipt-pdf-wrapper'),
18171	                                canvas = document.getElementById('rental-receipt-pdf'),
18172	                                ctx = canvas.getContext('2d');
18173	                            //console.log("just before", vm.fileURL);
18174	                            PDFJS.workerSrc = '/etc/designs/platform/pdfjs-worker-clientlib.js';
18175	                            PDFJS.getDocument(vm.fileURL).then(function(pdf) {
18176	                                return pdf.getPage(pageNum);
18177	                            }).then(function(page) {
18178	                                var scale = 3;
18179	                                var viewport = page.getViewport(scale);
18180	                                canvas.width = viewport.width;
18181	                                canvas.height = viewport.height;
18182	                                if(vm.clientInfo.isIE && !vm.clientInfo.isIE9)
18183	                                {
18184	                                	$(" #rental-receipt-pdf-wrapper").css("height", 1723);
18185	                                	canvas.style.width=canvas.style.height ="100%";
18186	                                }
18187	                                else
18188	                                {
18189	                                	canvas.style.width = canvas.style.height = wrapper.style.width = wrapper.style.height = "100%";
18190	                                }
18191	
18192	                                var renderContext = {
18193	                                    canvasContext: ctx,
18194	                                    viewport: viewport
18195	                                };
18196									var promise = ftpService.load();
18197									promise.then(function(ftpdata) {
18198									  vm.ftp = ftpdata;
18199									  if (ftpdata && ftpdata.reservationSummary && ftpdata.reservationSummary.ftpDetail
18199s && ftpdata.reservationSummary.ftpDetails.messages) {
18200										  vm._getFTPSectionMessage(ftpdata.reservationSummary.ftpDetails.messages);
18201										}
18202									}, function(error) {
18203							  }); 
18204	                                $rootScope.requestInProgress = false;
18205	                                page.render(renderContext);
18206	                            });
18207	                        } else {
18208	                            //console.log('error processing pdf');
18209	                        }
18210	                    });
18211	            }
18212        	}
18213
18214            $rootScope.requestInProgress = false ;
18215        }
18216        
18217        function viewPdf(){
18218        	document.getElementsByName("receipt_form_view")[0].action = apiurl+'/pdf/fetchpdf'
18219            //document.getElementsByName("receipt_form_hidden")[0].action = '/bin/pdf';
18220//            document.getElementsByName("countryCode")[1].value = vm.receiptRequest.countryCode;
18221//            document.getElementsByName("lastName")[1].value = vm.receiptRequest.lastName;
18222//            document.getElementsByName("rentalAgreementNum")[1].value = vm.receiptRequest.rentalAgreementNum;
18223            document.forms['receipt_form_view'].submit();
18224        }
18225        function printPdf(){
18226        	if(vm.clientInfo.isIE || navigator.userAgent.indexOf('Trident') > -1){
18227        		viewPdf();
18228        	}else{
18229        		var canvas = document.getElementById('rental-receipt-pdf');
18230        		var img = new Image();
18231        		img.src = canvas.toDataURL();
18232        		img.setAttribute('width','100%');
18233        		var html = "<!doctype html><html><body id='body'></body></html>";
18234        		var win = window.open('', '', '');
18235        		win.document.write(html);
18236        		win.document.getElementById("body").appendChild(img);
18237        		//win.document.close();
18238        		
18239        		setTimeout(
18240        				function(){ 
18241        	        		win.focus();
18242        	        		win.print();
18243        	        		//win.close();
18244        					}, 1000);
18245
18246        	}
18247        }
18248
18249        function downloadPdf(){
18250        	if(vm.clientInfo.isIE || navigator.userAgent.indexOf('Trident') > -1){
18251        		viewPdf();
18252        	}else{
18253        	var a = document.createElement('a');
18254            vm.file = new Blob([vm.receiptResponse], {
18255                type: 'application/pdf'
18256            });
18257            vm.fileURL = window.URL.createObjectURL(vm.file);
18258           	a.href	=	vm.fileURL;
18259            a.download= 'e-receipt.pdf';
18260            document.body.appendChild(a);
18261            a.click();
18262        	}
18263        }
18264        
18265        vm._initLookup();
18266        jQuery(document).ready(function() {
18267           // vm._setResidency();
18268           reservationModelService.addGTMScript();
18269        });
18270    }
18271})();
18272(function () {
18273	'use strict';
18274
18275	angular
18276		.module('rental')
18277		.service('rentalVehicleService', rentalVehicleService);
18278	rentalVehicleService.$inject = ['$injector', '$http', '$q', '$window', 'authenticationService', 'reservationModelService', 'carRentalConstant', 'storageService', 'exceptionHandler', 'summaryEndPointService'];
18279
18280	function rentalVehicleService($injector, $http, $q, $window, authenticationService, reservationModelService, carRentalConstant, storageService, exceptionHandler, summaryEndPointService){
18281		var result = {
18282			getVehicleDetails: getVehicleDetails,
18283			vehicleConfirm: vehicleConfirm,
18284			getVehicleData: getVehicleData,
18285			getConfirmData: getConfirmData
18286		};
18287
18288		//Mapping the response to an object for Displaying the readyline vehicles
18289		function setReadyLineVehicleDetails(vehicle){
18290			var vehicleDetails = '';
18291			var value;
18292			if(angular.isDefined(vehicle) && angular.isDefined(vehicle.vehicleFeatures) && vehicle.vehicleFeatures.length > 0){
18293				vehicleDetails ={
18294						"carClass" : angular.isDefined(vehicle.carClass) ? vehicle.carClass : '',
18295						"makeNme" : angular.isDefined(vehicle.makeNme) ? vehicle.makeNme : '',
18296						"makeYr" : angular.isDefined(vehicle.makeYr) ? vehicle.makeYr : '',
18297						"color" : angular.isDefined(vehicle.color) ? vehicle.color : '',
18298						"makeModel" : angular.isDefined(vehicle.makeModel)? vehicle.makeModel : '',
18299						"connectedCar" : isFeatureAvailable(vehicle.vehicleFeatures,'connectedCar'),
18300						"carGroup" : angular.isDefined(vehicle.carGroup)? vehicle.carGroup : '',
18301						"startingFuel" : getFeatureValue(vehicle.vehicleFeatures,'startingFuel'),
18302						"mileage" : getFeatureValue(vehicle.vehicleFeatures,'mileage'),
18303						"lotSpaceNumber" : getFeatureValue(vehicle.vehicleFeatures,'lotSpaceNumber'),
18304						"Seats": getFeatureValue(vehicle.vehicleFeatures,'Seats'),
18305						"Suitcases": getFeatureValue(vehicle.vehicleFeatures,'Suitcases'),
18306						"Doors": getFeatureValue(vehicle.vehicleFeatures,'Doors'),
18307						"mpg": getFeatureValue(vehicle.vehicleFeatures,'mpg'),
18308						"airConditioned": isFeatureAvailable(vehicle.vehicleFeatures,'Air'),
18309						"automaticTransmission": isFeatureAvailable(vehicle.vehicleFeatures,'Auto'),
18310						"smokeFree" : isFeatureAvailable(vehicle.vehicleFeatures,'NS'),
18311						"bluetoothEnabled" : isFeatureAvailable(vehicle.vehicleFeatures,'bluetoothEnabled'),
18312						"upsellStatus" : angular.isDefined(vehicle.upsellStatus) ? vehicle.upsellStatus :'',
18313						"earlyPickUpCharge" : angular.isDefined(vehicle.earlyPickUpCharge) ? vehicle.earlyPickUpCharge : '',
18314						"earlyPickUpIndicator" : angular.isDefined(vehicle.earlyPickUpCharge) ? vehicle.earlyPickUpCharge : '',
18315						"image": angular.isDefined(vehicle.image) ? vehicle.image : '',
18316						"upgradeAmount": angular.isDefined(vehicle.upgradeAmount)? vehicle.upgradeAmount :'',
18317						"estimatedTotal": angular.isDefined(vehicle.estimatedTotal)? vehicle.estimatedTotal :'',
18318						"licensePlateNumber" : getFeatureValue(vehicle.vehicleFeatures, 'licensePlateNumber'),
18319						"isPerDayPrice" : angular.isDefined(vehicle.perDayPrice)? vehicle.perDayPrice : false,
18320						"isTaxFeesIncluded" : angular.isDefined(vehicle.taxFeesIncluded)? vehicle.taxFeesIncluded : true,
18321						"additionalCharges": angular.isDefined(vehicle.additionalCharges)? vehicle.additionalCharges : '',
18322						"fiveStarSafetyRate" : angular.isDefined(vehicle.fiveStarSafetyRate)? vehicle.fiveStarSafetyRate : false,
18323						"freeUpgrade" : angular.isDefined(vehicle.freeUpgrade)? vehicle.freeUpgrade : false,
18324						"mvaNumber" : angular.isDefined(vehicle.mvaNumber)? vehicle.mvaNumber : (angular.isDefined(getFeatureValue(vehicle.vehicleFeatures,'mvaNumber'))?getFeatureValue(vehicle.vehicleFeatures,'mvaNumber'):''),
18325
18326				}
18327				
18328			}
18329			return vehicleDetails;
18330		}
18331		
18332		//Processing the vehicles from the API response
18333		function processVehicle(data){
18334			var newArray = [];
18335			angular.forEach(data, function(value,key){
18336				value = setReadyLineVehicleDetails(value);
18337				newArray.push(value);
18338			});
18339			return newArray;
18340		}
18341		
18342		//Returns True/False value based on the feature availability in the API respons
18343		function isFeatureAvailable(featuresList, feature){
18344			var featureAvailable = false;
18345			angular.forEach(featuresList, function(value,key){
18346				if(value.name == feature && (value.value == 'Y' || value.value == 'TRUE')){
18347					featureAvailable = true; 
18348				}
18349			});
18350			return featureAvailable;
18351		}
18352		
18353		//Returns the count of the Features
18354		function getFeatureValue(featuresList , feature){
18355			var count = 0;
18356			angular.forEach(featuresList, function(value,key){
18357				if(value.name == feature){
18358					count = value.value; 
18359				}
18360			});
18361			return count;
18362		}
18363		
18364		//POST call for the RealyLine vehicles
18365		function getVehicleDetails(selfServiceRequestObj,flowType) {
18366			var url;
18367			var deferred = $q.defer();
18368			var refreshVehicleUrl = flowType ? "/self-checkout/vehicle-exchange":"/rental/vehicles";
18369			url = apiurl + refreshVehicleUrl;
18370			// url = apiurl + "/rental/vehicles";
18371			$http({
18372					method: 'POST',
18373					url: url,
18374					data: selfServiceRequestObj
18375		  		}).then(function onSuccess(response) {
18376		  			var data = response.data;		
18377		  			var response = {};
18378					if(angular.isDefined(data)){
18379						if (flowType) { // if vehicle exchange then vehicle list comes in the reservation summary
18380							if(angular.isDefined(data.reservationSummary) && angular.isDefined(data.reservationSummary.vehicleSummaryList) && data.reservationSummary.vehicleSummaryList.length > 0){
18381								if(angular.isDefined(data.reservationSummary.pickLoc)) {
18382									response.pickLoc = data.reservationSummary.pickLoc;
18383								}
18384								//five-star-safety changes for choose-vehicle flow.
18385								response.fiveStarCarAvailable = data.fiveStarCarAvailable;
18386								if(angular.isDefined(data.reservationSummary.confirmationNumber)) {
18387									response.confirmationNumber = data.reservationSummary.confirmationNumber;
18388								}
18389								response.vehicleSummaryList = processVehicle(data.reservationSummary.vehicleSummaryList);
18390							}
18391						} else if (!flowType) {
18392							if(angular.isDefined(data.vehicleSummaryList) && data.vehicleSummaryList.length > 0){
18393								if(angular.isDefined(data.reservationSummary) && angular.isDefined(data.reservationSummary.pickLoc)){
18394									response.pickLoc = data.reservationSummary.pickLoc;
18395								}
18396								//five-star-safety changes for choose-vehicle flow.
18397								response.fiveStarCarAvailable = data.fiveStarCarAvailable;
18398								if(angular.isDefined(data.reservationSummary) && angular.isDefined(data.reservationSummary.confirmationNumber)){
18399									response.confirmationNumber = data.reservationSummary.confirmationNumber;
18400								}
18401								response.vehicleSummaryList = processVehicle(data.vehicleSummaryList);
18402							}
18403						}
18404						if (angular.isDefined(data.instructionList) && data.instructionList.length > 0){
18405							response.instructionList = data.instructionList;
18406						} else if(angular.isDefined(data.errorList)){
18407							response = exceptionHandler.processError(data);
18408						}
18409						deferred.resolve(response);
18410					}else {
18411						deferred.reject(data);
18412					}
18413		  		}).catch(function onError(response) {
18414		  			var data = response.data;
18415		  			deferred.reject(data);
18416		  	});
18417			return deferred.promise;
18418		}
18419				
18420		//POST call for vehicle Confirm
18421		function vehicleConfirm(parkingNum,mvaNumber,flowType) {
18422			var url;
18423			var requestObj = {
18424				"parkingSpace": parkingNum,
18425				"mvaNumber":mvaNumber
18426			}
18427			var deferred = $q.defer();
18428			var confirmVehicleUrl = flowType ? '/self-checkout/vehicle-confirm':"/rental/checkout-confirm";
18429			url = apiurl + confirmVehicleUrl;
18430			$http({
18431				method: 'POST',
18432				url: url,
18433				data: requestObj
18434	  		}).then(function onSuccess(response) {
18435	  			var data = response.data;	
18436	  			var response = {};
18437	  			if (angular.isDefined(data)) {
18438					var pickLocationCode = "";
18439					if (angular.isDefined(data.reservationSummary) && angular.isDefined(data.reservationSummary.vehicle)) {
18440						if(angular.isDefined(data.reservationSummary.pickLoc) && angular.isDefined(data.reservationSummary.pickLoc.locationCode)){
18441							pickLocationCode = data.reservationSummary.pickLoc.locationCode;
18442						}
18443						var rentalAgreementNumber = data.reservationSummary.rentalAgreementNumber;
18444						data = setReadyLineVehicleDetails(data.reservationSummary.vehicle);
18445						data.rentalAgreementNumber = rentalAgreementNumber;
18446						data.pickLocationCode = pickLocationCode;
18447					}
18448					if (angular.isDefined(data.errorList)) {
18449						data = exceptionHandler.processError(data);
18450					}
18451				deferred.resolve(data);
18452	  			}
18453				else {
18454					deferred.reject(data);
18455				}
18456	  		}).catch(function onError(response) {
18457	  			var data = response.data;
18458	  			deferred.reject(data);
18459	  		});
18460			return deferred.promise;
18461		}
18462		
18463		
18464	//Summary Endpoint call for the Vehicles confirm call
18465		function getConfirmData(){
18466			var deferred = $q.defer();
18467			summaryEndPointService.loadRentalSummary('CHOICE_VEHICLES_CONFIRM').then(function (data){
18468				if(angular.isDefined(data.reservationSummary) &&  angular.isDefined(data.reservationSummary.vehicle)){
18469					if(angular.isDefined(data.reservationSummary) && angular.isDefined(data.reservationSummary.pickLoc)){
18470						var rentalAgreementNumber = data.reservationSummary.rentalAgreementNumber;
18471						data = setReadyLineVehicleDetails(data.reservationSummary.vehicle);
18472						data.rentalAgreementNumber = rentalAgreementNumber;
18473					}
18474					if (angular.isDefined(data.errorList)) {
18475						data = exceptionHandler.processError(data);
18476					}
18477					deferred.resolve(data);
18478				}
18479				else{
18480					deferred.reject(data);
18481				}
18482			
18483			});
18484			return deferred.promise;
18485		}
18486
18487		//Summary Endpoint call for the Readyline call
18488		function getVehicleData(flowType){
18489			var deferred = $q.defer();
18490			var summaryResponse = {};
18491			summaryEndPointService.loadRentalSummary('CHOICE_VEHICLES_URL',flowType).then(function (data) {
18492				if(angular.isDefined(data)){
18493					if(flowType){
18494						data.vehicleSummaryList = data.reservationSummary.vehicleSummaryList;
18495					}
18496					if(angular.isDefined(data.vehicleSummaryList) && data.vehicleSummaryList.length > 0){
18497						if(angular.isDefined(data.reservationSummary) && angular.isDefined(data.reservationSummary.pickLoc)){
18498							summaryResponse.pickLoc = data.reservationSummary.pickLoc;
18499						}
18500						//five-star-safety changes for choose-vehicle flow.
18501						summaryResponse.fiveStarCarAvailable = data.fiveStarCarAvailable;
18502						if(angular.isDefined(data.reservationSummary) && angular.isDefined(data.reservationSummary.confirmationNumber)){
18503							summaryResponse.confirmationNumber = data.reservationSummary.confirmationNumber;
18504						}
18505						summaryResponse.vehicleSummaryList = processVehicle(data.vehicleSummaryList);
18506					}
18507					else if(angular.isDefined(data.errorList)){
18508						summaryResponse = exceptionHandler.processError(data);
18509					}
18510					deferred.resolve(summaryResponse);
18511				}else{
18512					deferred.reject(data);
18513				}
18514				
18515			});
18516			return deferred.promise;
18517		}
18518	
18519		return result;
18520	}
18521})();
18522
18523
18524(function () {
18525    "use strict";
18526
18527    angular.module('account').config(verifyCardRouting);
18528    verifyCardRouting.$inject = ['$stateProvider'];
18529
18530    function verifyCardRouting($stateProvider) {
18531        $stateProvider.state('scan-card', {
18532            url: '/scan-card',
18533            templateUrl: rootpath + contentRoot + '/verify-card/scan.partial' + htmlExtension,
18534            controller: 'VerifyPaymentCardController',
18535            controllerAs: 'vm'
18536        });
18537    }
18538})();
18539(function () {
18540    "use strict";
18541
18542    angular.module("accountServices").service("verifyCardService", verifyCardService);
18543    verifyCardService.$inject = ['$q', '$http', 'exceptionHandler', 'reservationModelService', 'storageService', '$window'];
18544
18545    /**
18546     * @param {angular.IQService} $q
18547     * @param {angular.IHttpService} $http
18548     * @param {{processError: (arg0: any, arg1: any) => any;}} exceptionHandler
18549     * @param {{modelMap: any;}} reservationModelService
18550     * @param {{brand: string;location: typeof window.location;history: typeof window.history; contextPath: string; locale: string}} $window
18551     * @param {{getStorageData: (arg0: string) => {reservationSummary: any;customerInfo: any;};setStorageData: (arg0: string, arg1: string) => void;}} storageService
18552     */
18553    function verifyCardService($q, $http, exceptionHandler, reservationModelService, storageService, $window) {
18554        var CheckResult = ["NotPerformed", "Pass", "Fail"];
18555
18556        var MatchLevel = ['Disabled', 'Level1', 'Level2', 'Level3', 'Level4', 'Level5', 'Level6', 'Level7', 'Level8', 'Level9', 'Level10'];
18557
18558        var CardIssuer = ['Other', 'AmericanExpress', 'ChinaUnionPay', 'Diners', 'DiscoverCard', 'Elo', 'Jcb', 'Maestro', 'Mastercard', 'RuPay', 'Verve', 'Visa', 'VPay', 'Count'
18559        ];
18560
18561        var processingStatusOptions = ['Success', 'DetectionFailed', 'ImagePreprocessingFailed', 'StabilityTestFailed', 'ScanningWrongSide', 'FieldIdentificationFailed', 'ImageReturnFailed', 'UnsupportedCard', 'Count'];
18562
18563        // Process scan results
18564        /**
18565         * @param {{ recognizer: any; }} result
18566         */
18567        function processResults(result) {
18568//            console.log('process result: ', result);
18569            // Process scan results based on BlinkCard's data structure
18570            var recognizerResult = result.recognizer;
18571            var processResult = {
18572                cardNumber: recognizerResult.cardNumber || '',
18573                cardNumberValid: recognizerResult.cardNumberValid || false,
18574                expiryDate: recognizerResult.expiryDate || '',
18575                owner: recognizerResult.owner || '',
18576                expiryDate: recognizerResult.expiryDate || {},
18577                iban: recognizerResult.iban || '',
18578                issuer: recognizerResult.issuer,
18579                processingStatus: recognizerResult.processingStatus,
18580                documentLivenessCheck: recognizerResult.documentLivenessCheck || {},
18581            };
18582            // 
18583            var cardData = {};
18584            cardData.cardNumber = processResult && processResult.cardNumber;
18585            cardData.cardNumberValid = processResult && processResult.cardNumberValid;
18586            cardData.expiryDate = processResult && processResult.expiryDate && processResult.expiryDate.originalString;
18587            cardData.iban = processResult && processResult.iban;
18588            cardData.issuer = processResult && CardIssuer[processResult.issuer];
18589            cardData.processingStatus = processResult && processingStatusOptions[processResult.processingStatus];
18590            cardData.nameOnCard = processResult && processResult.owner;
18591            // liveliness of document
18592            var documentLivenessCheckFrontValue = documentLivenessCheck(processResult.documentLivenessCheck && processResult.documentLivenessCheck.front);
18593            var documentLivenessCheckBackValue = documentLivenessCheck(processResult.documentLivenessCheck && processResult.documentLivenessCheck.back);
18594            // front liveliness Value
18595            cardData.screenCheckFrontResult = documentLivenessCheckFrontValue && documentLivenessCheckFrontValue.screenCheckResult;
18596            cardData.screenCheckFrontMatch = documentLivenessCheckFrontValue && documentLivenessCheckFrontValue.screenCheckMatch;
18597            cardData.photocopyCheckFrontResult = documentLivenessCheckFrontValue && documentLivenessCheckFrontValue.photoCopyResult;
18598            cardData.photocopyCheckFrontMatch = documentLivenessCheckFrontValue && documentLivenessCheckFrontValue.photoCopyMatch;
18599            cardData.handPresenceCheckFront = documentLivenessCheckFrontValue && documentLivenessCheckFrontValue.handPresence;
18600            // back liveliness Value
18601            cardData.screenCheckBackResult = documentLivenessCheckBackValue && documentLivenessCheckBackValue.screenCheckResult;
18602            cardData.screenCheckBackMatch = documentLivenessCheckBackValue && documentLivenessCheckBackValue.screenCheckMatch;
18603            cardData.photocopyCheckBackResult = documentLivenessCheckBackValue && documentLivenessCheckBackValue.photoCopyResult;
18604            cardData.photocopyCheckBackMatch = documentLivenessCheckBackValue && documentLivenessCheckBackValue.photoCopyMatch;
18605            cardData.handPresenceCheckBack = documentLivenessCheckBackValue && documentLivenessCheckBackValue.handPresence;
18606
18607            return cardData;
18608        }
18609
18610        /**
18611         * @param {*}  { handPresence: Enum(CheckResult)
18612        //  *      photocopyCheck: {
18613        //  *          result: Enum(CheckResult),
18614        //  *          matchLevel: Enum(MatchLevel)    
18615        //  *      },
18616        screenCheck: {
18617        result: Enum(CheckResult),
18618        matchLevel: Enum(MatchLevel)    
18619        },
18620        }: documentResultObj}  
18621        This function would transform number mapping to relative status (string). For Ex: 0 -> Not Performed, 1 -> Pass, 2-> Fail Then if result is 0, Not Performed would be passed.
18622         * @param {{ screenCheck: { result: string | number; matchLevel: string | number; }; photocopyCheck: { result: string | number; matchLevel: string | number; }; handPresenceCheck: string | number; }} documentResultObj
18623         */
18624        function documentLivenessCheck(documentResultObj) {
18625            var documentResult = {
18626                handPresence: '',
18627                photoCopyMatch: '',
18628                photoCopyResult: '',
18629                screenCheckMatch: '',
18630                screenCheckResult: ''
18631            };
18632            // screenCheck Transformation
18633            if (documentResultObj && documentResultObj.screenCheck) {
18634                if (documentResultObj.screenCheck.result) {
18635                    var tScreenCheckResult = CheckResult[documentResultObj.screenCheck.result];
18636                    documentResult.screenCheckResult = tScreenCheckResult;
18637                }
18638                if (documentResultObj.screenCheck.matchLevel) {
18639                    var tScreenCheckMatch = MatchLevel[documentResultObj.screenCheck.matchLevel];
18640                    documentResult.screenCheckMatch = tScreenCheckMatch;
18641                }
18642            }
18643            // photocopy Transformation
18644            if (documentResultObj && documentResultObj.photocopyCheck) {
18645                if (documentResultObj.photocopyCheck.result) {
18646                    var tPhotocopyResult = CheckResult[documentResultObj.photocopyCheck.result];
18647                    documentResult.photoCopyResult = tPhotocopyResult;
18648                }
18649                if (documentResultObj.photocopyCheck.matchLevel) {
18650                    var tPhotocopyMatch = MatchLevel[documentResultObj.photocopyCheck.matchLevel];
18651                    documentResult.photoCopyMatch = tPhotocopyMatch;
18652                }
18653            }
18654            // handPresence Transformation
18655            if (documentResultObj && documentResultObj.handPresenceCheck) {
18656                var tHandPresence = CheckResult[documentResultObj.handPresenceCheck];
18657                documentResult.handPresence = tHandPresence;
18658            }
18659//            console.debug('liveliness: ', documentResult);
18660            return documentResult;
18661        }
18662
18663        /**
18664         * @param { BlinkCardEvent | Object | Error | ApiError } ex
18665         */
18666        function processException(ex) {
18667            try {
18668                if (angular.isDefined(ex)) {
18669                    // Handle errors from SDK
18670                    if (angular.isDefined(ex.detail) && angular.isDefined(ex.detail.message)) {
18671                        return ex.detail.message;
18672                    }
18673                    if (angular.isDefined(ex.message)) {
18674                        return ex.message;
18675                    }
18676                    /** @type {ApiException} */
18677                    var obj = exceptionHandler.processError(ex, reservationModelService.modelMap);
18678                    if (obj.errorList && obj.errorList.length > 0) {
18679                        /** @type {ApiError} */
18680                        var apiError = obj.errorList[0];
18681                        return apiError && apiError.message;
18682                    }
18683                }
18684            } catch (e) {
18685                console.error('Unable to handle exception: ', e);
18686            }
18687        }
18688
18689        /**
18690         * @param {CreditCardOcrRQ} reqObj
18691         * @requires {string} apiurl
18692         */
18693        function validateCardDetails(reqObj) {
18694            try {
18695//                console.log(reqObj);
18696                var apiProps = {
18697                    method: 'POST',
18698                    url: apiurl + '/self-checkout/verifycard',
18699                    data: reqObj,
18700                };
18701                var deferred = $q.defer();
18702                $http(apiProps)
18703                    .then(function (response) {
18704                        var data = response.data;
18705                        if ($window.brand !== 'payless') ABG.updateContextStores();
18706                        data = exceptionHandler.processError(
18707                            data,
18708                            reservationModelService.modelMap
18709                        );
18710                        if (angular.isDefined(data) && angular.isUndefined(data.errorList)) {
18711                            deferred.resolve(data);
18712                        }
18713                        else {
18714                            deferred.reject(data);
18715                        }
18716                    })
18717                    .catch(function (error) {
18718                        deferred.reject(error.data);
18719                    });
18720                return deferred.promise;
18721            } catch (e) {
18722                throw e;
18723            }
18724        }
18725
18726        /**
18727         * @typedef {Object} SessioModel
18728         * @property {Object} reservationSummary
18729         * @property {Object} customerInfo
18730         */
18731        function getSessionData() {
18732            try {
18733                /** @type {SessioModel} */
18734                var sessionData = {};
18735                /** @type {SessioModel} */
18736                var data = storageService.getStorageData('reservationModelSelfCheckOut');
18737
18738                if (data && data.reservationSummary) {
18739                    sessionData.reservationSummary = data.reservationSummary;
18740                }
18741
18742                if (data && data.customerInfo) {
18743                    sessionData.customerInfo = data.customerInfo;
18744                }
18745
18746                return Object.keys(sessionData).length > 0 ? sessionData : null;
18747            } catch (error) {
18748                console.error("Unable to get data from session: ", error);
18749                return null;
18750            }
18751        }
18752
18753        /**
18754         * @param {string} message
18755         * @returns {void}
18756         */
18757        function renderException(message) {
18758            if (message && message.length > 0) {
18759                // storageService.setStorageData('sessionErrMsg', message);
18760                // $window.history.back();
18761                $window.location.href = $window.contextPath + '/' + $window.locale + '/self-checkout' + htmlExtension + '#/ftp-driver-info?err=Y&redirsrc=verifycard&isError=N';
18762            }
18763        }
18764
18765        /**
18766         * @param {OCRAuditRQ} reqObj
18767         * @requires {string} apiurl
18768         */
18769        function audit(reqObj) {
18770            try {
18771                var apiProps = {
18772                    method: 'POST',
18773                    url: apiurl + '/self-checkout/auditocrevent',
18774                    data: reqObj,
18775                };
18776                var deferred = $q.defer();
18777                $http(apiProps)
18778                    .then(function (response) {
18779                        var data = response.data;
18780                        if ($window.brand !== 'payless') ABG.updateContextStores();
18781                        data = exceptionHandler.processError(data, reservationModelService.modelMap);
18782                        if (angular.isDefined(data) && angular.isUndefined(data.errorList)) {
18783                            deferred.resolve(data);
18784                        }
18785                        else {
18786                            deferred.reject(data);
18787                        }
18788                    })
18789                    .catch(function (error) {
18790                        deferred.reject(error.data);
18791                    });
18792                return deferred.promise;
18793            } catch (e) {
18794                throw e;
18795            }
18796        }
18797
18798        return {
18799            processResults: processResults,
18800            processException: processException,
18801            validateCardDetails: validateCardDetails,
18802            getSessionData: getSessionData,
18803            renderException: renderException,
18804            audit: audit
18805        };
18806    }
18807})();
18808(function () {
18809    'use strict';
18810
18811    angular.module('account').controller('VerifyPaymentCardController', VerifyPaymentCardController);
18812
18813    VerifyPaymentCardController.$inject = ['$scope', '$rootScope', '$element', 'verifyCardService', 'verifyCardFactory', '$window', '$timeout'];
18814
18815    /**
18816     * @param {angular.IScope & { countdown: number }} $scope
18817     * @param {ng.IRootScopeService & { requestInProgress: boolean; delayExceptionRedirect: boolean; contextPath: string; locale: string; err: string;  }} $rootScope
18818     * @param {JQLite | JQuery} $element
18819     * @param {{ processException: (arg0: BlinkCardEvent | Object | Error | ApiError ) => string; processResults: (arg0: any) => any; getSessionData: () => any; validateCardDetails: (arg0: any) => Promise<any>; renderException: (message: string) => void; audit: (r: OCRAuditRQ) => Promise<any> }} verifyCardService
18820     * @param {{ getCreditCardOcrRQ: (arg0: any, arg1: any) => any; createVerifyCardException: (arg0: any) => any; getOCRAuditRQ: (sessionData: SessioModel, event: AuditEvent) => OCRAuditRQ; }} verifyCardFactory
18821     * @param {{ history: typeof window.history; location: typeof window.location }} $window
18822     * @param {angular.ITimeoutService} $timeout
18823     */
18824    function VerifyPaymentCardController($scope, $rootScope, $element, verifyCardService, verifyCardFactory, $window, $timeout) {
18825
18826        var vm = this;
18827        vm.onInit = onInit;
18828
18829        // Scanner state
18830        /** 
18831         * @type {Object}
18832         * @deprecated 
18833        */
18834        vm.cardDataInfo = null;
18835
18836        /** @type {boolean} */
18837        vm.isScanning = false;
18838
18839        /** @type {string} */
18840        vm.err = null;
18841
18842        /** @type {boolean} */
18843        vm.isInitialized = false;
18844
18845        /** @type {SessioModel} */
18846        vm.sessionData = {
18847            reservationSummary: {},
18848            customerInfo: {},
18849        };
18850
18851        /**
18852         * @type {number}
18853         * @description to control the delay for redirection, refer DELAY and 
18854         * @see DELAY
18855         * @see delayRenderException
18856         * @constant TIME_TO_REDIRECT
18857         */
18858        var TIME_TO_REDIRECT = 20;
18859
18860        /** 
18861         * @type {number} 
18862         * @constant ONE_SECOND 
18863         * @description Described in mili-seconds
18864         */
18865        var ONE_SECOND = 1000;
18866
18867        /**
18868         * @type {string}
18869         * @constant SUCCESS_ROUTE
18870         * @see handleScanSuccess
18871         * @todo The success route may differ based on the consumer (flows which are doing payment card validation via OCR) of verify-card
18872         */
18873        var SUCCESS_ROUTE = $window.location.origin + $rootScope.contextPath + '/' + $rootScope.locale + '/' + 'self-checkout' + htmlExtension + '#/ftp-confirmation-page';
18874
18875        /**@type {number} */
18876        vm.countdown = TIME_TO_REDIRECT;
18877
18878        /**
18879         * @type {boolean}
18880         * @description make it false when we do not want to delay on verify-card/scan route. Typically used for DEV phase. Not for production use
18881         * @see TIME_TO_REDIRECT
18882         * @see delayRenderException
18883         * @constant DELAY
18884         */
18885        var DELAY = false;
18886
18887
18888        // Store scanner element reference
18889        var blinkcardElement = null;
18890
18891        // Initialize scanner on controller initialization
18892
18893        function onInit() {
18894            // Create container if it doesn't exist
18895            $rootScope.requestInProgress = true;
18896            $rootScope.delayExceptionRedirect = DELAY;
18897            try {
18898                var container = $element.find('#scanner-container');
18899                if (container.length === 0) {
18900                    console.log('container element not found, creating');
18901                    $element.append('<div id="scanner-container"></div>');
18902                    container = $element.find('#scanner-container');
18903                }
18904                // Create the BlinkCard element
18905                blinkcardElement = document.createElement('blinkcard-in-browser');
18906                container.append(blinkcardElement);
18907                console.log('adding element blinkcardElement')
18908                blinkcardElement.translations = {
18909                    "action-message": "Scan Payment Card",
18910                };
18911
18912
18913                // Configure the element
18914                blinkcardElement.licenseKey = microblinkLicenseKey;
18915                blinkcardElement.recognizers = ['BlinkCardRecognizer'];
18916                blinkcardElement.recognizerOptions = {
18917                    BlinkCardRecognizer: {
18918                        extractIban: false,
18919                        extractCvv: false,
18920                        extractExpiryDate: true,
18921                        extractOwner: true,
18922                        anonymizationSettings: {
18923                            cardNumberAnonymizationSettings: {
18924                                mode: 3,
18925                                prefixDigitsVisible: 0,
18926                                suffixDigitsVisible: 4
18927                            },
18928                            cardNumberPrefixAnonymizationMode: 0,
18929                            cvvAnonymizationMode: 0,
18930                            ibanAnonymizationMode: 0,
18931                            ownerAnonymizationMode: 0,
18932                            fallbackAnonymization: false
18933                        },
18934                    }
18935                };
18936
18937
18938                // Set paths to resources
18939                blinkcardElement.engineLocation = $window.location.origin + "/etc/designs/platform/clientlib/scripts/common/microblink/blinkit-browser-sdk/2.10.0/resources";
18940                blinkcardElement.workerLocation = $window.location.origin + "/etc/designs/platform/clientlib/scripts/common/microblink/blinkit-browser-sdk/2.10.0/resources/BlinkCardWasmSDK.worker.min.js";
18941
18942                vm.sessionData = verifyCardService.getSessionData();
18943
18944                // Setup event listeners
18945                blinkcardElement.addEventListener('ready', handleReady);
18946                blinkcardElement.addEventListener('scanSuccess', handleScanSuccess);
18947                blinkcardElement.addEventListener('scanError', handleScanError);
18948                blinkcardElement.addEventListener('fatalError', handleFatal
18948Error);
18949                blinkcardElement.addEventListener('closeEvent', handleCloseEvent);
18950                // blinkcardElement.addEventListener('feedback', handleFeedback);
18951                blinkcardElement.addEventListener('scanAborted', handleScanAborted);
18952                vm.isInitialized = true;
18953            } catch (error) {
18954                vm.err = verifyCardService.processException(error);
18955                console.error('Unable to scan your payment card: ', vm.err);
18956            }
18957        }
18958
18959        // Clean up listeners when scope is destroyed
18960        $scope.$on('$destroy', function () {
18961            console.log('destory');
18962            if (blinkcardElement) {
18963                blinkcardElement.removeEventListener('ready', handleReady);
18964                blinkcardElement.removeEventListener('scanSuccess', handleScanSuccess);
18965                blinkcardElement.removeEventListener('scanError', handleScanError);
18966                blinkcardElement.removeEventListener('fatalError', handleFatalError);
18967                blinkcardElement.removeEventListener('closeEvent', handleCloseEvent);
18968                // blinkcardElement.addEventListener('feedback', handleFeedback);
18969                blinkcardElement.addEventListener('scanAborted', handleScanAborted);
18970            }
18971        });
18972
18973        // Event handlers
18974        /**
18975         * @param {BlinkCardEvent} event
18976         */
18977        function handleReady(event) {
18978            console.log('ready function');
18979            $scope.$apply(function () {
18980                vm.isScanning = true;
18981                audit(event, 'PASS');
18982//                console.log('Scanner ready:', event.detail);
18983                $rootScope.requestInProgress = false;
18984                autoStartCameraScan();
18985//                console.log('change loader now');
18986            });
18987        }
18988
18989        // auto start the camera function
18990        function autoStartCameraScan() {
18991            if (blinkcardElement) {
18992
18993                // Clear previous results
18994                // vm.cardDataInfo = null;
18995                vm.err = null;
18996
18997                blinkcardElement.startCameraScan()
18998                    .then(function () {
18999                         console.log('Camera scan started successfully');
19000                    })
19001                    .catch(function (/** @type {any} */ error) {
19002                        $scope.$apply(function () {
19003                            vm.isScanning = false;
19004                            // since camera has not started and this promise so structuring it to handle in processException
19005                            var autoStartEventError = {
19006                                detail: {
19007                                    message: 'Failed to start camera scan: ' + error.message,
19008                                }
19009                            }
19010
19011                            vm.err = verifyCardService.processException(autoStartEventError);
19012                            console.error('Camera scan error:', vm.err);
19013                            if (DELAY) {
19014                                delayRenderException(ONE_SECOND, vm.err);
19015                            } else {
19016                                renderException(vm.err);
19017                            }
19018                        });
19019                    });
19020            }
19021        }
19022
19023        /**
19024         * @param {BlinkCardEvent} event
19025         */
19026        function handleScanSuccess(event) {
19027            $rootScope.requestInProgress = true;
19028            console.log('handled scan success');
19029            $scope.$apply(function () {
19030                vm.isScanning = false;
19031                try {
19032                    audit(event, 'PASS');
19033                    var cardData = verifyCardService.processResults(event.detail);
19034                    // vm.cardDataInfo = cardData;
19035                    validateCardDetails(cardData).then(function (_r) { $window.location.href = SUCCESS_ROUTE;  }).catch(function (e /** @type {any{}} */) {
19036                        $rootScope.requestInProgress = false;
19037                        vm.err = verifyCardService.processException(e);
19038                        console.error('Unable to validate card details: ', vm.err);
19039                        if (DELAY) {
19040                            delayRenderException(ONE_SECOND, vm.err);
19041                        } else {
19042                            renderException(vm.err);
19043                        }
19044                    });
19045                } catch (e) {
19046                    audit(event, 'FAIL');
19047                    $rootScope.requestInProgress = false;
19048                    vm.err = verifyCardService.processException(e);
19049                    console.error('Payment Card details not scanned successfully: ', vm.err);
19050                    if (DELAY) {
19051                        delayRenderException(ONE_SECOND, vm.err);
19052                    } else {
19053                        renderException(vm.err);
19054                    }
19055                }
19056            });
19057        }
19058
19059        /**
19060         * @param { BlinkCardEvent } event
19061         */
19062        function handleScanError(event) {
19063            console.log('handle scan error');
19064            $scope.$apply(function () {
19065                vm.isScanning = false;
19066                audit(event, 'FAIL');
19067                vm.err = verifyCardService.processException(event) || 'Scan failed';
19068                console.error('Scan error:', vm.err);
19069                if (DELAY) {
19070                    delayRenderException(ONE_SECOND, vm.err);
19071                } else {
19072                    renderException(vm.err);
19073                }
19074            });
19075        }
19076
19077        /**
19078         * @param {number} interval
19079         * @param {string} exceptionMessage
19080         * @returns {void}
19081         */
19082        function delayRenderException(interval, exceptionMessage) {
19083            for (var i /** @type {number} */ = 1; i <= TIME_TO_REDIRECT; i++) {
19084                $timeout(function () {
19085                    vm.countdown -= 1;
19086                    if (vm.countdown === 0) {
19087                        verifyCardService.renderException(exceptionMessage);
19088                    }
19089                }, i * interval);
19090            }
19091        }
19092
19093        /**
19094         * @param {string} exceptionMessage
19095         * @returns {void}
19096         */
19097        function renderException(exceptionMessage) {
19098            verifyCardService.renderException(exceptionMessage);
19099        }
19100
19101        /**
19102         * @param {BlinkCardEvent} event
19103         */
19104        function handleFatalError(event) {
19105            console.log('handle fatal error');
19106            $scope.$apply(function () {
19107                vm.isScanning = false;
19108                audit(event, 'FAIL');
19109                vm.err = verifyCardService.processException(event) || 'Unknown error';
19110                console.error('Fatal error:', vm.err);
19111                if (DELAY) {
19112                    delayRenderException(ONE_SECOND, vm.err);
19113                } else {
19114                    renderException(vm.err);
19115                }
19116            });
19117        }
19118
19119        /**
19120         * @param {BlinkCardEvent} event
19121         * @returns {void}
19122         * @description Function that handles event emitted during positive or negative user feedback. If attribute/property hideFeedback is set to false, UI component will display the feedback.
19123         * @deprecated
19124         */
19125        function handleFeedback(event) {
19126            console.log('handle feedback');
19127            // console.debug('handelFeedback :: event=', event);
19128            audit(event, 'PASS');
19129        }
19130
19131        /**
19132         * @param {BlinkCardEvent} event
19133         * @returns {void}
19134         * @description Function that handles event emitted when scan is aborted, i.e. when user clicks on close from the gallery toolbar, or presses escape key.
19135         */
19136        function handleScanAborted(event) {
19137            console.log('scan aborted');
19138            $scope.$apply(function () {
19139                vm.isScanning = false;
19140                audit(event, 'FAIL');
19141                vm.err = verifyCardService.processException(event) || 'Scan is aborted by the user';
19142                console.error('Scan aborted errorr:', vm.err);
19143                if (DELAY) {
19144                    delayRenderException(ONE_SECOND, vm.err);
19145                } else {
19146                    renderException(vm.err);
19147                }
19148            });
19149        }
19150
19151
19152        /**
19153         * @param {BlinkCardEvent} event
19154         * @returns void
19155         */
19156        function handleCloseEvent(event) {
19157            console.log('onClosing event navigate back to previous page');
19158            audit(event, 'PASS');
19159            $window.history.back();
19160        }
19161
19162        /**
19163         * @param {any} cardData
19164         * @returns Promise<any>
19165         * @throws {any} e
19166         */
19167        function validateCardDetails(cardData) {
19168            if (vm.sessionData === null) {
19169                throw new Error("Unable to get session data");
19170            }
19171
19172            /** @type {CreditCardOcrRQ} */
19173            var creditCardOcrRQ = verifyCardFactory.getCreditCardOcrRQ(cardData, vm.sessionData);
19174
19175            return verifyCardService.validateCardDetails(creditCardOcrRQ).then(function (r) {
19176                if (angular.isDefined(r) && angular.isDefined(r.errorList)) {
19177                    // HTTP 200 with error list from back end
19178                    throw verifyCardFactory.createVerifyCardException(r);
19179                } else if (angular.isDefined(r) && angular.isUndefined(r.errorList)) {
19180                    // success scenario
19181                    console.debug(r);
19182                    return r;
19183                } else throw new Error("Invalid response from verifycard API");
19184            }, function (e) {
19185                throw e;
19186            });
19187        }
19188
19189        /**
19190         * @param {BlinkCardEvent} event
19191         * @param {string} status
19192         * @returns {void}
19193         * @description Fires API transaction to /ocrauditevent to capture event details in back-end logs for monitoring
19194         */
19195        function audit(event, status) {
19196            /**@type {AuditEvent} */
19197            var auditEvent = {
19198                blinkCardEvent: event,
19199                status: status.toUpperCase().trim(),
19200                name: event.type
19201            };
19202
19203            /** @type {OCRAuditRQ} */
19204            var oCRAuditRQ = verifyCardFactory.getOCRAuditRQ(vm.sessionData, auditEvent);
19205
19206            verifyCardService.audit(oCRAuditRQ).catch(function (e /** @type {any} */) {
19207                vm.err = verifyCardService.processException(e);
19208                console.error('Camera scan error:', vm.err);
19209                if (DELAY) {
19210                    delayRenderException(ONE_SECOND, vm.err);
19211                } else {
19212                    renderException(vm.err);
19213                }
19214            });
19215        }
19216
19217        onInit();
19218    }
19219})();
19220(function () {
19221    'use strict';
19222    angular.module("accountServices").factory("verifyCardFactory", verifyCardFactory);
19223    /**
19224     * @type {any[]}
19225     */
19226    verifyCardFactory.$inject = [];
19227
19228
19229    function verifyCardFactory() {
19230
19231        /**
19232         * @param {string} message
19233         * @param {ApiError[]} errorList
19234         */
19235        function verifyCardException(message, errorList) {
19236            var ex = new Error(message);
19237            ex.errorList = errorList;
19238            return ex;
19239        }
19240
19241
19242        /**
19243         * @param {{ errorList: any; }} obj
19244         */
19245        function createVerifyCardException(obj) {
19246//            console.debug("createVerifyCardException :: obj=", obj);
19247            if (angular.isDefined(obj) && angular.isDefined(obj.errorList)) {
19248                return verifyCardException('Exception in verification of user\'s payment card', obj.errorList || [])
19249            }
19250        }
19251
19252        /**
19253         * @param {any} obj
19254         * @param {any[]} keys
19255         */
19256        function getProperty(obj, keys) {
19257            return keys.reduce(function (acc, key) {
19258                return acc && acc[key]
19259            }, obj);
19260        }
19261
19262        /**
19263         * @param {string} str
19264         * @description This function will return boolean result as true if the passed string is either 'True' or 'true'
19265         * @returns {boolean}
19266         * Please remove deprecared if this is getting used in the future
19267         * @deprecated
19268         */
19269        function checkPassValue(str) {
19270            var result = false;
19271            try {
19272                if (str && str.length > 0) {
19273                    result = str.toLowerCase().trim() === "pass"
19274                }
19275            } catch (e) {
19276                throw e;
19277            }
19278
19279            return result;
19280        }
19281
19282        /**
19283         * @param {any} cardData
19284         * @param {SessioModel} sessionData
19285         * @returns {CreditCardOcrRQ}
19286         * @description This function takes in user's payment card details returned by OCR vendor and the current session data of the user to create an object of type CreditCardOcrRQ. Which will be then consumed mostly by the back end API /verifycard as of March 2025
19287         */
19288        function getCreditCardOcrRQ(cardData, sessionData) {
19289            try {
19290                return {
19291                    confirmationNumber: getProperty(sessionData, ['reservationSummary', 'confirmationNumber']),
19292                    wizardNumber: getProperty(sessionData, ['customerInfo', 'wizardNumberMasked']),
19293                    state: getProperty(sessionData, ['reservationSummary', 'address', 'state']),
19294                    ccNum: getProperty(cardData, ['cardNumber']),
19295                    cardNumbervalid: getProperty(cardData, ['cardNumberValid']),
19296                    iban: getProperty(cardData, ['iban']),
19297                    issuer: getProperty(cardData, ['issuer']),
19298                    processingStatus: getProperty(cardData, ['processingStatus']),
19299                    nameOnCard: getProperty(cardData, ['nameOnCard']),
19300                    screenCheckFront: getProperty(cardData, ['screenCheckFrontResult']),
19301                    photocopyCheckFront: getProperty(cardData, ['photocopyCheckFrontResult']),
19302                    handPresenceCheckFront: getProperty(cardData, ['handPresenceCheckFront']),
19303                    screenCheckBack: getProperty(cardData, ['screenCheckBackResult']),
19304                    photocopyCheckBack: getProperty(cardData, ['photocopyCheckBackResult']),
19305                    handPresenceCheckBack: getProperty(cardData, ['handPresenceCheckBack']),
19306                };
19307            } catch (error) {
19308                console.error(error);
19309            }
19310        }
19311
19312        /**
19313         * @param {SessioModel} sessionData
19314         * @param {AuditEvent} event
19315         * @returns {OCRAuditRQ}
19316         */
19317        function getOCRAuditRQ(sessionData, event) {
19318            return {
19319                confirmationNumber: getProperty(sessionData, ['reservationSummary', 'confirmationNumber']),
19320                wizardNumber: getProperty(sessionData, ['customerInfo', 'wizardNumberMasked']),
19321                eventDetails: getProperty(event, ['blinkCardEvent', 'detail', 'code']),
19322                eventStatus: getProperty(event, ['status']),
19323                eventName: getProperty(event, ['name'])
19324            }
19325        }
19326
19327        return {
19328            createVerifyCardException: createVerifyCardException,
19329            getCreditCardOcrRQ: getCreditCardOcrRQ,
19330            getOCRAuditRQ: getOCRAuditRQ
19331        }
19332    }
19333})();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.