PageSourceSearch

https://www.brighthousefinancial.com/etc.clientlibs/bhf/clientlibs…ain.min.6dc33d51278c442e4c602ec16704d151.js

js brighthousefinancial.com collected 2026-09-25 19:13:06 UTC 1,271,588 bytes, 22,627 lines download raw bytes

1$(document).ready(function () {
2    const proDomain = 'brighthousefinancialpro.com';
3    const mainDomain = 'brighthousefinancial.com';
4    
5    const runmodeElement = document.querySelector('[data-runmode]');
6    const runmode = runmodeElement?.getAttribute('data-runmode') || '';
7    const runmodeParts = runmode.split(',').map(mode => mode.trim());
8    const isProd = runmodeParts.includes("prod");
9
10    const addScript = (domainScript) => {
11        const DEFAULT_DOMAIN_ID = isProd
12            ? '8675fb32-c71b-427a-8923-e1539357d8d4'
13            : '8675fb32-c71b-427a-8923-e1539357d8d4-test';
14
15        const finalDomainScript = domainScript || DEFAULT_DOMAIN_ID;
16
17        if (!document.querySelector(`script[data-domain-script='${finalDomainScript}']`)) {
18            const head = document.getElementsByTagName('head')[0];
19            const script = document.createElement('script');
20            script.type = 'text/javascript';
21            script.src = 'https://cdn.cookielaw.org/scripttemplates/otSDKStub.js';
22            script.setAttribute('data-domain-script', finalDomainScript);
23            script.async = true;
24            head.insertBefore(script, head.firstChild);
25            const wrapperScript = document.createElement('script');
26            wrapperScript.type = 'text/javascript';
27            wrapperScript.text = 'function OptanonWrapper() {}';
28            head.insertBefore(wrapperScript, head.firstChild);
29        }
30    };
31
32    const hostname = window.location.hostname;
33
34    if (hostname.includes(mainDomain)) {
35        addScript(isProd
36            ? '8675fb32-c71b-427a-8923-e1539357d8d4'
37            : '8675fb32-c71b-427a-8923-e1539357d8d4-test');
38    } else if (hostname.includes(proDomain)) {
39        addScript(isProd
40            ? '4a42e32b-587e-4f98-b493-5c93c69c0a88'
41            : '4a42e32b-587e-4f98-b493-5c93c69c0a88-test');
42    } else {
43        addScript(isProd
44            ? '8675fb32-c71b-427a-8923-e1539357d8d4'
45            : '8675fb32-c71b-427a-8923-e1539357d8d4-test');
46    }
47});
48
49
50// <!-- OneTrust Cookies Consent Notice start for brighthousefinancialpro.com -->
51// <script src="https://cdn.cookielaw.org/scripttemplates/otSDKStub.js"  type="text/javascript" charset="UTF-8" data-domain-script="4a42e32b-587e-4f98-b493-5c93c69c0a88" ></script>
52// <script type="text/javascript">
53// function OptanonWrapper() { }
54// </script>
55// <!-- OneTrust Cookies Consent Notice end for brighthousefinancialpro.com -->
56
57// <!-- OneTrust Cookies Consent Notice start for brighthousefinancial.com -->
58// <script src="https://cdn.cookielaw.org/scripttemplates/otSDKStub.js"  type="text/javascript" charset="UTF-8" data-domain-script="8675fb32-c71b-427a-8923-e1539357d8d4" ></script>
59// <script type="text/javascript">
60// function OptanonWrapper() { }
61// </script>
62// <!-- OneTrust Cookies Consent Notice end for brighthousefinancial.com -->
63
64//for lower environment
65// <!-- OneTrust Cookies Consent Notice start for brighthousefinancialpro.com -->
66// <script src="https://cdn.cookielaw.org/scripttemplates/otSDKStub.js"  type="text/javascript" charset="UTF-8" data-domain-script="4a42e32b-587e-4f98-b493-5c93c69c0a88-test" ></script>
67// <script type="text/javascript">
68// function OptanonWrapper() { }
69// </script>
70// <!-- OneTrust Cookies Consent Notice end for brighthousefinancialpro.com -->
71
72// <!-- OneTrust Cookies Consent Notice start for brighthousefinancial.com -->
73// <script src="https://cdn.cookielaw.org/scripttemplates/otSDKStub.js"  type="text/javascript" charset="UTF-8" data-domain-script="8675fb32-c71b-427a-8923-e1539357d8d4-test" ></script>
74// <script type="text/javascript">
75// function OptanonWrapper() { }
76// </script>
77/* Reveal Middle Align pop Up */
78var revealCenterAlign = {
79    resizeTimer : undefined ,
80    revealRePosition: function () {
81        var popOverHeight = $(window).height();
82        var assistReveal = $('.assist-reveal.top:visible');
83        var popHeight = assistReveal.outerHeight();
84        var x=0;
85        var averageHeight = ((popOverHeight - popHeight) < 0) ? 0 : (popOverHeight - popHeight);
86        x=averageHeight/2;
87        assistReveal.css({'transform': 'translateY('+0+')', 'margin-top': x});
88    },
89
90    // Functionality onload and resize Reveal Middle Align pop Up.
91    init: function () {
92        revealCenterAlign.revealRePosition();
93        $(window).on('resize', function () {
94            if($('.assist-reveal.top:visible').length > 0){
95                clearTimeout(revealCenterAlign.resizeTimer);
96                revealCenterAlign.resizeTimer = setTimeout(function () {
97                    revealCenterAlign.revealRePosition();
98                }, 200);
99            }
100        });
101    }
102};
103
104/**
105 * 'made for contentReport.js to enable case sensitive search'
106 */
107
108$.expr[':'].containsCase = function(a, i, m) {
109        return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
110};
111
112/**
113 * 'To serailize in tab index order'
114 * @return {[Array]}
115 */
116
117$.fn.customSerializeArray = function () {
118	const submittable = new RegExp(/^(?:input|select|textarea|keygen)/i),
119	submitterTypes = new RegExp(/^(?:submit|button|image|reset|file)$/i),
120	checkableType = new RegExp(/^(?:checkbox|radio)$/i),
121	CRLF = new RegExp(/\r?\n/g);
122	return this.map( function() {
123
124            // Can add propHook for "elements" to filter or add form elements
125            var elements = $.prop(this, "elements" );
126            var $data_to_sort = $(elements);
127            if(elements) {
128            	$data_to_sort.sort(function(a, b) {
129            		return +a.tabIndex - +b.tabIndex;
130            	});
131            }
132            return $data_to_sort ? $.makeArray( $data_to_sort ) : this;
133        })
134	.filter( function() {
135		var type = this.type;
136
137            // Use .is( ":disabled" ) so that fieldset[disabled] works
138            return this.name && !$( this ).is( ":disabled" ) &&
139            submittable.test( this.nodeName ) && !submitterTypes.test( type ) &&
140            ( this.checked || !checkableType.test( type ) );
141        } )
142	.map( function( i, elem ) {
143		var val = $( this ).val();
144
145		if ( val == null ) {
146			return null;
147		}
148
149		if ( Array.isArray( val ) ) {
150			return $.map( val, function( val ) {
151				return { name: elem.name, value: val.replace( CRLF, "\r\n" ) };
152			} );
153		}
154
155		return { name: elem.name, value: val.replace( CRLF, "\r\n" ) };
156	} ).get();
157};
158
159/**
160 * 'Generic Modal Popup Factory'
161 */
162
163var externalModalPopUp = (function () {
164
165    'use strict';
166
167    /**
168     * '_isValidMode to check run mode is not author [private]'
169     * @type {Boolean}
170     */
171
172    var _isValidMode = true;
173
174    /**
175     * '_popup to store reference of external modal [private]'
176     * @type {any}
177     */
178
179    var _popup = null;
180
181    /**
182     * 'userProfile to store the PLE APP details of the user'
183     * @type {any}
184     */
185
186    var userProfile = null;
187
188    /**
189     * '_isLoggedIn to check if the user is logged in'
190     * @type {Boolean}
191     */
192
193    var _isLoggedIn = false;
194
195
196    /**
197     * 'Initialize or config function [public]'
198     * @return {null}
199     */
200
201    function init() {
202        if (document.querySelector('[data-runMode]').dataset.runmode.indexOf('author') !== -1) {
203            _isValidMode = false;
204        }
205
206        if(_isValidMode){
207            if(ContextHub.get('profile').displayName != "anonymous") {
208                _isLoggedIn = true;
209            }
210    
211            userProfile = ContextHub.get('profile').PLE_APPS;
212
213            if (_isLoggedIn && userProfile) {
214                $(document).on('click', 'a.metlife-link', function (event) {
215                    event.stopPropagation();
216                    event.preventDefault();
217                    var target = $(this).attr('target');
218                    var url = $(this).attr('href');
219                    var id = $(this).attr('id');
220                    if (url) {
221                        if($(this).hasClass('pleopenModal')){
222                            pleFirmSelector($(this),'pleapp','pleModal');
223                        }
224                        else {
225                            _popup = new Foundation.Reveal($('#genericmodal-metlife'));
226                            _popup.open();
227                            revealCenterAlign.revealRePosition();
228                            var isIphoneIpad = (navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPad/i) != null);
229                            if (isIphoneIpad) {
230                                $('body').addClass('videoNoScroll');
231                            }
232                            var anchor = document.getElementById('genericRedirectBtn-metlife');
233                            if (target) {
234                                anchor.target = target;
235                            }
236                            anchor.href = url;
237                        }
238                    } else {
239                        $('body').removeClass('videoNoScroll');
240                    }
241                });
242                $('.metlife-link').each(function() {
243                    let _self = $(this);
244                    let appName = $(this).data('pleapp');
245                    if(appName) {
246                        $.each(userProfile, function(i, elem){
247                            let appDetail = JSON.parse(elem);
248                            if(appName.toLowerCase() === appDetail.appName.toLowerCase()) {
249                                _self.attr('href', appDetail.appUrl);
250                                _self.attr('target', '_blank');
251                            }
252                        });
253                    }
254                });
255            }
256            
257        }
258        if (homePageVideo.ElementExist($('#genericmodal')) || homePageVideo.ElementExist($('#genericmodal-metlife'))) {
259            $(document).on('click', '#secondmodalbtn, #genericRedirectBtn, #secondmodalbtn-metlife, #genericRedirectBtn-metlife', function (event) {
260                event.stopPropagation();
261                if(!$('a.hamburger').hasClass('pressed')) {
262                    $('body').removeClass('videoNoScroll stopScroll');
263                    $('body').css('position', '');
264                    $('.overlayWhite').css({ height: 0 });
265                }
266                _popup.close();
267            });
268        }
269    }
270
271    return {
272        init: init
273    };
274})();
275	function restrictAlphabets(event) {
276            const charCode = event.charCode;
277            if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || charCode === 32 || charCode === 45 || charCode === 39) {
278                return true;
279            }
280            return false;
281        }
282    function restrictCity(event) {
283            const charCode = event.charCode;
284            if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || charCode === 39) {
285                return true;
286            }
287            return false;
288        }  
289function restrictEmail(event) {
290    const charCode = event.charCode || event.keyCode;
291    const input = event.currentTarget;
292    const currentValue = input.value;
293    const cursorPosition = input.selectionStart;
294    const isAlphabetic = (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122);
295    const isNumber = charCode >= 48 && charCode <= 57;
296    const isDot = charCode === 46;
297    const isHyphen = charCode === 45;
298    const isUnderscore = charCode === 95;
299    const isAt = charCode === 64;
300    const isSpecial = isDot || isHyphen || isUnderscore || isAt;
301    const prevChar = cursorPosition > 0 ? currentValue[cursorPosition - 1] : '';
302    const atCount = (currentValue.match(/@/g) || []).length;
303    if (cursorPosition === 0 && isSpecial) {
304        event.preventDefault();
305        return false;
306    }
307
308    if (isSpecial && (prevChar === '.' || prevChar === '-' || prevChar === '_' || prevChar === '@')) {
309        event.preventDefault();
310        return false;
311    }
312
313    if (isAt && atCount > 0) {
314        event.preventDefault();
315        return false;
316    }
317
318    const atPosition = currentValue.indexOf('@');
319    if (atPosition !== -1) {
320        if (cursorPosition === atPosition + 1) {
321            if (isDot || isHyphen || isUnderscore || isNumber) {
322                event.preventDefault();
323                return false;
324            }
325        } else if (cursorPosition > atPosition) {
326            const afterAt = currentValue.substring(atPosition + 1);
327            const dotCount = afterAt.split('.').length - 1;
328            if (dotCount > 1 || isHyphen || isUnderscore || isNumber || (isDot && afterAt.startsWith('.'))) {
329                event.preventDefault();
330                return false;
331            }
332        }
333    }
334
335    if (isAlphabetic || isNumber || isSpecial && (cursorPosition > 0 && prevChar !== '')) {
336        return true;
337    }
338 
339    event.preventDefault();
340    return false;
341}  
342function recaptchaSupplierFormCallback() {
343    var response = grecaptcha.enterprise.getResponse();
344    let recaptchaThresholdValue = $('#recaptcha-threshold').val();
345    var url = "/content.enterpriseRecaptcha";
346    $.ajax({
347        type: "POST",
348        url: url,
349        data : {
350            token: response,
351            recaptchaThresholdValue: recaptchaThresholdValue
352        },
353        success: function (data) {
354            let userObj = JSON.parse(data);
355            if (userObj['isSuccess'] == true) {
356                $('.emailSection #recaptcha_html_element_form_container').attr('verified',true);
357                bhfFormValidator.submitValidator($('.emailSection .text-field-validation'));
358                $('#supplierForm').attr('disabled', false);
359                //return true;
360            } else {
361                $('.emailSection #recaptcha_html_element_form_container').attr('verified',false);
362                bhfFormValidator.submitValidator($('.emailSection .text-field-validation'));
363                return false
364            }
365        },
366        error: function () {
367            console.log('Error in getting verify response form');
368            return false
369        }
370    });
371}
372
373function recaptchaSupplierFormExpiredCallback() {
374    $('.emailSection #recaptcha_html_element_form_container').attr('verified',false);
375    bhfFormValidator.submitValidator($('.emailSection .text-field-validation'));
376}      
377$(document).ready(function() {
378	var isAndroidMobile = navigator.userAgent.indexOf('Android') > -1 && navigator.userAgent.indexOf('Mozilla/5.0') > -1 && navigator.userAgent.indexOf('AppleWebKit') > -1;
379	$( 'form' ).click( function ( ) { } );
380	$( 'html' ).css( "-webkit-tap-highlight-color", "rgba(0, 0, 0, 0)" );
381	if ($(window).width() < 640) {
382		  formFieldsSequence.smallView();
383	}
384	$(".emailSection").submit(function(e) {
385    	let isSubmitForm = true;
386		let isCookiesOpen = false;
387		let formEvent = $(this);
388    	//check if ccpa form present
389    	if(0 !== $("#webform-ccpa-california").length || 0 !== $("#webform-optout-ccpa-california").length) {
390    		$(".ccpa-error").remove();
391    		isSubmitForm = false;
392    		const errorSectionObj = {};
393    		
394    		//validate any one check-box is selected 
395    		const customerDiv = $(".customer_div input[type=\"checkbox\"]");
396    		const isCustomerDivValidate = (0 !== customerDiv.filter(":checked").length);
397    		if(!isCustomerDivValidate) {
398    			errorSectionObj["0"]=".customer_div";
399    		}
400
401    		const personalDiv = $(".personal_div input[type=\"checkbox\"]");
402    		const isPerDivValidate = (0 !== personalDiv.filter(":checked").length);
403    		if(!isPerDivValidate && $(personalDiv).length > 0) {
404    			errorSectionObj["1"]=".personal_div";
405    		}
406    		
407    		const preferredDiv = $(".preferred_div input[type=\"checkbox\"]");
408    		const isPreferredValidate = (0 !== preferredDiv.filter(":checked").length);
409    		if(!isPreferredValidate && $(preferredDiv).length > 0) {
410    			errorSectionObj["2"]=".preferred_div";
411    		}
412    		
413    		e.preventDefault();
414    		let selectedRadioSection = "secondyes1";
415    		if("no_not_behalf_of_someone" == $("input[name=yes]").filter(":checked").val()) {
416    			selectedRadioSection = "secondNo1";
417    		}
418    		
419    		//validate if any check-box is not selected(per section)
420    		if(0 === Object.keys(errorSectionObj).length) {
421    			isSubmitForm = true;
422    			//validate if 'other' check-box is selected, validate input-field
423    			$("#"+selectedRadioSection+" input[type=\"checkbox\"]").each(function() {
424        			const checkboxName = $(this).attr('name');
425        			if(("other1" === checkboxName || "other" === checkboxName || "other2" === checkboxName) && $(this).is(':checked')) {
426    					let textval = $("#"+checkboxName+"_text").val();
427    					if(0 === textval.length) {
428    						isSubmitForm = false;
429    						showError({"0":".customer_div"}, selectedRadioSection);
430    						return false;
431    					}
432        			}
433        		});
434    		} else {
435    			showError(errorSectionObj, selectedRadioSection);
436    		}
437			if($('#onetrust-pc-sdk').length && $("#webform-optout-ccpa-california").length){
438				if(isSubmitForm){
439					$('#ot-sdk-btn').trigger('click');
440					$('.ot-floating-button__open').trigger("click");
441					isCookiesOpen = true;
442					$(document).on('click',".ot-floating-button__close, .save-preference-btn-handler, #close-pc-btn-handler", function () {
443						isCookiesOpen = false;
444						submitCcpaForm(formEvent,isSubmitForm,e);
445					});
446		
447					$(document).keydown(function(event){
448						if(event.keyCode == 27){
449							if($('body').has("#webform-optout-ccpa-california").length){
450								isCookiesOpen = false;
451								submitCcpaForm(formEvent,isSubmitForm,e);
452							}
453						}
454					});
455				}
456				
457			}else{
458				submitCcpaForm($(this),isSubmitForm,e);
459			}	
460    	} 
461    });
462
463	$(".saleForceFormSubmit").submit(function(e){
464		e.preventDefault();
465		var form = $(this);
466		var url = '/content.salesforceAPI.connect';
467		var currentPagePath  = $("#currentPagePath").val();
468        var formData = form.serializeArray();
469        formData.push({name: "currentPagePath", value: currentPagePath});
470		$.ajax({
471			type: "POST",
472			url: url,
473			data: formData,
474			success: function()
475			{
476				console.log('Form Submitted');
477			},
478			error: function() {
479				console.log('Error in submitting form');
480			}
481		});
482		var redirectPage = $(this).find("input[name=retURL]").val();
483		setTimeout(function() {
484			window.location.href =  isEmpty(redirectPage)?window.location.pathname:redirectPage;
485		}, 2000);
486	});
487
488	function isEmpty(val){
489		return (val === undefined || val == null || val.length <= 0) ? true : false;
490	}
491
492	function submitCcpaForm(element,isSubmitForm,event){
493		if(isSubmitForm) {
494    		var postData = $(".emailSection").customSerializeArray();
495    		$.ajax({
496    			url: "/bin/formServlet",
497    			type: "POST",
498    			data: postData,
499    			success: function(data, textStatus, jqXHR) {
500    				console.log("Success");
501    			},
502    			error: function(jqXHR, textStatus, errorThrown) {
503    				console.log("Error");
504    			}
505    		});
506    		event.preventDefault();
507    		var redirectPage = $(element).find("input[name=emailSuccessPage]").val();
508    		setTimeout(function() {
509    			window.location.href =  isEmpty(redirectPage)?window.location.pathname:redirectPage;
510    		}, 2000);
511    	}
512	}
513	
514	// Function to direct the supplier form call to form servlet.
515		$(document).ready(function() {
516		$('#supplierprogram').submit(function(event) {
517			event.preventDefault();
518			var formData = $(this).serialize();
519			$.ajax({
520				url: "/bin/formServlet",
521				type: "POST",
522				data: formData,
523				success: function(response) {
524	                console.log('Form submitted successfully', response);
525	            },
526	            error: function(xhr, status, error) {
527	                console.log('An error occurred: ' + error);
528	            }
529	        });
530	        event.preventDefault();
531            var redirectPage = $("input[name='emailSuccessPage']").val();
532            setTimeout(function() {
533    			window.location.href =  isEmpty(redirectPage)?window.location.pathname:redirectPage;
534    		}, 2000);
535	    });
536	});
537
538    function isEmpty(val){
539            return (val === undefined || val == null || val.length <= 0) ? true : false;
540        }
541
542        $(document).on('focus','.text-field-validation', function (event) {
543        	if (isAndroidMobile) {
544        		bhfFormValidator.currentTextValue=$(this).val();
545        	}
546        });
547
548        $(document).on('input','.text-field-validation', function (event) {
549        	var current_element=$(this);
550        	if (isAndroidMobile) {
551        		var len = parseInt($(this).val().length);
552            	var max = parseInt($(this).attr("maxlength"));
553            	if (current_element.hasClass('phone')) {
554	            	max=10;
555	            }
556            	if (len > max ) {
557	            	$(this).val(bhfFormValidator.currentTextValue)
558	            }else{
559	            	bhfFormValidator.currentTextValue=$(this).val();
560	            }
561        	}
562		});
563		$(document).on('paste','.phone', function (event) {
564			if (window.clipboardData && window.clipboardData.getData) { // IE Support
565				if(window.clipboardData.getData('Text').match(/[^\d]/)){
566					event.preventDefault();
567				}
568			}
569			else if (event.originalEvent.clipboardData && event.originalEvent.clipboardData.getData) { // All other browsers
570				if(event.originalEvent.clipboardData.getData('Text').match(/[^\d]/)){
571					event.preventDefault();
572				}
573			}
574		});
575		$(document).ready(function(){
576			if(!$('.manage__boa__edit').length){
577				$("#mobile.phone").val('');
578				$("#boa-phone.phone").val('');
579			}
580			
581			var global_phone;
582			$(document).on("blur","#mobile.phone, #boa-phone.phone", function(){
583				if($(this).val().length===10){
584				 let phone_val=$(this).val();
585				global_phone=phone_val;
586				let formated_phone=bhfFormValidator.formatPhoneNumber(phone_val);
587				$(this).val(formated_phone);
588			}else {
589				global_phone=$(this).val();
590			}
591			$(this).attr('data-phone', global_phone);
592			});
593			$(document).on("focus click","#mobile.phone, #boa-phone.phone",function(){
594				if($(this).val().length>=10){
595				$(this).val(global_phone);
596				$(this).attr('data-phone', global_phone);
597			}else{
598				$(this).attr('data-phone', $(this).val());
599			}
600		});
601		if($('.manage__boa__edit').length && document.querySelector("[data-runMode]") && document.querySelector("[data-runMode]").dataset && document.querySelector("[data-runMode]").dataset.runmode.indexOf("author")==-1){
602			$('#boa-phone').trigger('blur');
603			$('#submit-boa').addClass('disable-boa-add');
604		}
605	});
606        $(document).on('keypress','.text-field-validation', function (event) {
607        	var current_element=$(this);
608            var my_val=current_element.val();
609            var len = parseInt($(this).val().length);
610            var max = parseInt($(this).attr("maxlength"));
611            if (current_element.hasClass('phone')) {
612            	max=10;
613            }
614            if (len >= max ) {
615                    event.preventDefault();
616                    return false;
617            }
618            if (current_element.hasClass('zipTextField') && zipKeyDownLimit(current_element,event,my_val) != true) {
619            		event.preventDefault();
620            		return false;
621            } else if (!isAndroidMobile && current_element.hasClass('phone') && bhfFormValidator.phoneNumberNumberFormat(current_element,event,my_val) != true) {
622            		event.preventDefault();
623            		return false;
624            }
625
626        });
627   
628        /* To prevent copy paste of unallowed characters in firstname, lastname and city field */
629
630    	   var nameValidation = document.getElementsByClassName('name-validation');
631           for(var i=0; i < nameValidation.length; i++){
632				nameValidation[i].addEventListener('paste', function(event) { 
633                const pastedData = (event.clipboardData || window.clipboardData).getData('text');
634                const allowedPatternName = /^[a-zA-Z\s'-]*$/;//alphabets, spaces and limited special characters (- and ')
635                if (!allowedPatternName.test(pastedData)) {
636                    event.preventDefault(); // Prevent paste if disallowed characters are found
637                }
638      		  });
639           }
640
641            var cityValidation = document.getElementsByClassName('city-validation');
642         	for(var i=0; i < cityValidation.length; i++){
643				cityValidation[i].addEventListener('paste', function(event) { 
644            	const pastedData = (event.clipboardData || window.clipboardData).getData('text');
645           		const allowedPatternCity = /^[a-zA-Z']*$/;//alphabets and limited special character: '
646            	if (!allowedPatternCity.test(pastedData)) {
647                	event.preventDefault(); // Prevent paste if disallowed characters are found
648          		}
649        	  });
650           }
651           
652             /* To prevent copy paste of unallowed characters in Email field */
653          var emailValidation = document.getElementsByClassName('email-validation');
654          for (var i = 0; i < emailValidation.length; i++) {
655              emailValidation[i].addEventListener('paste', function(event) {
656              const pastedData = (event.clipboardData || window.clipboardData).getData('text');
657              const allowedPatternEmail = /^[a-zA-Z0-9][a-zA-Z0-9._-]*@[a-zA-Z0-9][a-zA-Z0-9._-]*\.[a-zA-Z]{2,}$/;
658              if (!allowedPatternEmail.test(pastedData)) {
659              event.preventDefault(); // Prevent paste if disallowed characters or format are found
660              return;
661           }
662              if ((pastedData.match(/@/g) || []).length > 1) {
663              event.preventDefault(); // Prevent paste if more than one @ symbol is found
664              return;
665           }
666 
667             const adjacentSpecialChars = /[-_.@]{2}/;
668             if (adjacentSpecialChars.test(pastedData)) {
669             event.preventDefault(); // Prevent paste if adjacent special characters are found
670             return;
671          }
672 
673            const parts = pastedData.split('@');
674            if (parts.length !== 2) {
675            event.preventDefault();
675 // Check for correct '@' placement and only one '@'
676            return;
677         }
678 
679            const domainPart = parts[1];
680            if (/^\d/.test(domainPart) || /[^a-zA-Z0-9.-]/.test(domainPart) || (domainPart.match(/\./g) || []).length > 1) {
681            event.preventDefault(); // Check domain part for invalid start, characters, or dots
682            return;
683        }
684 
685            if (/\d/.test(domainPart)) {
686            event.preventDefault(); // Prevent paste if numbers are found in the domain part
687            return;
688        }
689    });
690}
691	    function zipKeyDownLimit(current_element,event,my_val){
692	    		var navU = navigator.userAgent;
693	    		var isAndroidMobile = navU.indexOf('Android') > -1 && navU.indexOf('Mozilla/5.0') > -1 && navU.indexOf('AppleWebKit') > -1;
694	    		var isNumber =  /^\d+$/.test(my_val);
695	    		if (isAndroidMobile) {
696	    			my_val = my_val.replace(/\D/g,'');
697	    			if (!isNumber) {
698	    				current_element.val($.trim(my_val));
699	    			}
700	    		}else{
701	    			var my_key = event.keyCode || event.which;
702	    			if ((my_key >57 || my_key<48)) {
703	    				event.preventDefault();
704	    				return false;
705	    			}
706	    		}
707	    		return true;
708	    }
709
710	    $(document).on('input','.zipTextField', function (event) {
711        	var current_element=$(this);
712            var my_val=current_element.val();
713            if (current_element.hasClass('zipTextField')) {
714            	zipKeyDownLimit(current_element,event,my_val);
715            }
716        });
717        
718        $(document).on('input', '.zip-code', function() {
719            var current_element=$(this);
720    		var zip_value = current_element.val().replace(/-/g, '');
721    		zip_value = zip_value.replace(/\D/g, '');
722   			 if (zip_value.length > 5) {
723        		zip_value = zip_value.slice(0, 5) + '-' + zip_value.slice(5, 9);
724    		 } else {
725       			 zip_value = zip_value.slice(0, 5);
726    		 }
727        	 current_element.val(zip_value);            
728		});
729
730	    if(isAndroidMobile) {
731	        $(document).on('input','.phone', function (event) {
732	        	var current_element=$(this);
733	            var my_val=current_element.val();
734	            bhfFormValidator.phoneNumberNumberFormat(current_element,event,my_val);
735	        });
736  	  }
737
738
739    $(".form-select-custom").select2({
740		tags: "true",
741        placeholder: "Select an option",
742	});
743
744	$(".form-select-search").select2({
745		multiple: true,
746		maximumSelectionLength: 1,
747		matcher: matchCustom,
748		placeholder: ($('.boaEditSection').length) ? 'State' : '',
749		combobox: true,
750	})
751	.on('select2:opening', function( event ) {
752		if ($(this).select2('val')) {
753			if ($(this).select2('val').length > 0) {
754				event.preventDefault();
755				let open = true;
756				searchWidthSet($(this), open);
757			}
758		}
759	})
760	.on('select2:closing', function( event ) {
761		if ($(this).select2('val')) {
762			if ($(this).select2('val').length > 0) {
763				let open = false;
764				searchWidthSet($(this), open);
765				$('.select2-selection--multiple').addClass('validated-field');
766				$(this).siblings('.custom-checkmark.formIconPosition').show();
767			}
768		}
769	});
770
771	$(".form-select-man").select2({
772		multiple: true,
773		maximumSelectionLength: 1,
774		matcher: matchCustom,
775		placeholder: '',
776		combobox: true
777	})
778	.on('select2:opening', function( event ) {
779		if ($(this).select2('val')) {
780			if ($(this).select2('val').length > 0) {
781				event.preventDefault();
782				let open = true;
783				searchWidthSet($(this), open);
784			}
785		}
786	})
787	.on('select2:closing', function( event ) {
788		if ($(this).select2('val')) {
789			if ($(this).select2('val').length > 0) {
790				let open = false;
791				searchWidthSet($(this), open);
792				$('.select2-selection--multiple').addClass('validated-field');
793				$(this).siblings('.custom-checkmark.formIconPosition').show();
794			}
795		}
796	});
797
798	$(document).on('keydown keyup', '.select2-search__field', function (e) {
799		if(!$(this).closest(".select__dropdown__boa").length ) {
800			let charCode = e.which || e.keyCode;
801			if (!isAndroidMobile) {
802				if ((charCode === 46 || charCode === 8) && $(this).parent('.select2-selection__rendered').find('.select2-selection__choice').length === 0) {
803					$(this).parent('.select2-search--inline').css('width', '100%');
804				} else if ($(this).parent('.select2-search--inline').parent('.select2-selection__rendered').find('.select2-selection__choice').length) {
805					e.preventDefault();
806					$(this).val('');
807				}
808			} else {
809				if ($(this).parent('.select2-search--inline').parent('.select2-selection__rendered').find('.select2-selection__choice').length) {
810					$(this).parent('.select2-search--inline').parent('.select2-selection__rendered').find('.select2-selection__choice__remove').trigger('click');
811				} else {
812					$(this).parent('.select2-search--inline').css('width', '100%');
813				}
814			}
815		}
816	});
817
818	$(document).on('focus', '.select2-search__field', function(e) {
819		e.stopPropagation();
820		var str = $(this).val();
821		if($(this).val() != "" && $(this).val().length != 1) {
822			$(this).val(str.substring(0, str.length -1));
823		}
824	});
825
826	$(document).on('blur', '.select2-search__field', function(e) {
827		$(this).parents('.select2-selection').blur();
828	});
829
830	$(document).on('click', '.select2-selection__rendered', function(e){
831		e.preventDefault();
832		e.stopPropagation();
833		$(this).find('.select2-search--inline').find('.select2-search__field').focus();
834	});
835
836    $(".form-select-custom").each(function(){
837    	$(this).attr('tabindex', $(this).parent().attr('dataindex'));
838    });
839
840   	$(".bhf-form-select").change(function(e){
841   		bhfFormValidator.submitValidator($(this));
842   	});
843
844   	$(".form-select-custom").on('select2:close',function(e){
845   		bhfFormValidator.selectValidator($(this));
846   	});
847
848   	$(document).on('blur', '.select2-selection',function(e){
849		if($(this).find('.select2-selection--multiple')) {
850			bhfFormValidator.selectSearchValidator($(this).parent('.selection').parent('.select2-container').siblings('.select-search-validator'));
851		} else {
852			bhfFormValidator.selectValidator($(this).parent('.selection').parent('.select2-container').siblings('.form-select-custom'));
853		}
854   	});
855
856	$(".text-field-validation").keydown(function(e){
857		if (e.which == 9) {
858			bhfFormValidator.textFieldValidator($(this));
859		}
860	});
861
862	$(".text-field-validation").blur(function(e){
863		bhfFormValidator.textFieldValidator($(this));
864	});
865
866	$(".bhf-form-textarea").blur(function(e){
867		bhfFormValidator.textFieldValidator($(this));
868	});
869
870    $(".phone").blur(function(element){
871    	var length = $(this).val().length;
872        if(length > 0){
873       		bhfFormValidator.maskPhoneElement($(this));
874       	}
875     });
876
877    $(document).on('click focus','.phone',function(element){
878    	bhfFormValidator.hidePhoneMask($(this));
879     });
880
881    $('.inputWrap').on('click focus','.masked-phone-div',function(element){
882    	var phone_div = $(this).siblings('.phone');
883    	phone_div.trigger('focus');
884	 });
885
886});
887
888function showError(errorSectionObj, selectedSection) {
889	let errorText = "Please select at least one option before submitting your request.";
890	const $errorField = $("#error_field_text");
891	if(0 !== $errorField.length) {
892		errorText = (undefined == $errorField.val() || 0 == $errorField.val().length) ? errorText: $errorField.val();
893	}
894	let _arr = [];
895	$.each( errorSectionObj, function( index, value ) {
896		_arr.push(parseInt(index));
897		$(value).prev().append("<span class=\"error-form ccpa-error\" style=\"display: block;\">"+ errorText + "</span>");
898	});
899	const target = errorSectionObj["" + Math.min.apply(Math, _arr) + ""];
900	$("html, body").animate({ scrollTop: $("#"+selectedSection+" "+target).offset().top - 150}, 2000);
901}
902
903function searchWidthSet(element, open) {
904	let rendered = element.next().find('.select2-selection__rendered');
905	let choice =  element.next().find('.select2-selection__choice');
906	let nextInput = element.next().find('.select2-search--inline');
907	if(!open) {
908		nextInput.width((rendered.width() - choice.width()) - 9);
909	} else {
910		if(choice.length > 0) {
911			nextInput.css({'width':'15%'});
912		}
913	}
914}
915
916function matchCustom(params, data) {
917	if ($.trim(params.term) === '') {
918	  return data;
919	}
920
921	if (typeof data.text === 'undefined') {
922	  return null;
923	}
924
925	if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
926	  var modifiedData = $.extend({}, data, true);
927	  return modifiedData;
928	}
929	return null;
930}
931
932function formatNumber(n) {
933	return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
934}
935
936$(window).on('debouncedresize.formValidation',function () {
937	if($(".bhfForm").length) {
938		if ($(window).width() < 640) {
939		  formFieldsSequence.smallView();
940		} else {
941			formFieldsSequence.largeView();
942		}
943	}
944});
945
946var isInSmallView = true;
947var isInLargeView = true;
948var formFieldsSequence = {
949		smallView: function () {
950			if(isInLargeView) {
951				isInSmallView = true;
952				isInLargeView = false;
953				$(".bhfForm").each(function() {
954					var populate_hash={};
955					var elements_parent=$(this).find(".inputWrap, .bhf-form-submit-container");
956					var elements=$(this).find(".inputField, .bhf-form-select, :button, .recaptcha");
957					var ti =[];
958					for (var j =0; j<elements.length; j++){
959						ti.push(elements[j].getAttribute("formindex"));
960					}
961					ti.sort(function(a, b) {
962						return a-b;
963					});
964					
965					for(var count=0; count < elements_parent.length; count++) {
966						populate_hash[elements_parent[count].getAttribute("dataindex")] = elements_parent[count];
967					}
968					var masterComp = $(this).find(".masterComponent");
969					masterComp.each(function() {
970						var elem = $(this).find(".inputField, .bhf-form-select, :button");
971						$(this).attr("dataindex",elem.attr("formindex"));
972					});
973					masterComp.hide();
974					var masterCompLast = masterComp.last()
975					for (var i=0; i<ti.length; i++) {
976						masterCompLast.append(populate_hash[ti[i]]);
977					}
978					masterCompLast.show();
979				});
980			}
981		},
982		largeView: function() {
983			if(isInSmallView) {
984				isInSmallView = false;
985				isInLargeView = true;
986				$(".bhfForm").each(function() {
987					var elements_parent = $(this).find(".inputWrap, .bhf-form-submit-container");
988					var populate_hash={};
989					for(var count=0; count < elements_parent.length; count++) {
990						populate_hash[elements_parent[count].getAttribute("dataindex")] = elements_parent[count];
991					}
992					$(this).find(".masterComponent").each(function() {
993						if($(this).css("display")=="none"){
994							$(this).append(populate_hash[$(this).attr("dataindex")]);
995							$(this).show();
996						}
997					});
998				});
999			}
1000		}
1001}
1002
1003bhfFormValidator = {
1004
1005	currentTextValue: "",
1006
1007	maskPhoneNumberInit: function(s){
1008		var phone_divs=$('.phone');
1009		for (var i = 0; i < phone_divs.length; i++) {
1010			bhfFormValidator.maskPhoneElement($(phone_divs[i]));
1011		}
1012	},
1013
1014	maskPhoneElement: function(current_phone){
1015		var current_parent=current_phone.parent('.inputWrap');
1016		var masked_div = $('<div>');
1017		masked_div.addClass('masked-phone-div');
1018		masked_div.height($('.phone').height());
1019		masked_div.width($('.phone').width());
1020		current_parent.append(masked_div);
1021		var formatted_number = bhfFormValidator.formatPhoneNumber(current_phone.val());
1022		if (formatted_number) {
1023			masked_div.html(formatted_number);
1024			bhfFormValidator.validationRemover(current_phone);
1025		}else{
1026			masked_div.html(current_phone.val());
1027			bhfFormValidator.validationErrorAdd(current_phone,"constraint");
1028		}
1029	},
1030
1031	hidePhoneMask: function(current_phone){
1032		var current_parent=current_phone.parent('.inputWrap');
1033		masked_div=current_phone.siblings('.masked-phone-div');
1034		setTimeout(function(){ current_phone.selectionStart = current_phone.selectionEnd = 10000; }, 0);
1035		masked_div.remove();
1036	},
1037
1038	formatPhoneNumber: function(s){
1039	  		var s2 = (""+s).replace(/\D/g, '');
1040	  		var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
1041	  		return (!m) ? null : "(" + m[1] + ") " + m[2] + "-" + m[3];
1042	},
1043
1044	phoneNumberNumberFormat: function(current_element,event,my_val){
1045		var navU = navigator.userAgent;
1046	    var isAndroidMobile = navU.indexOf('Android') > -1 && navU.indexOf('Mozilla/5.0') > -1 && navU.indexOf('AppleWebKit') > -1;
1047	    var isNumber =  /^\d+$/.test(my_val);
1048	    if (isAndroidMobile) {
1049	    	my_val = my_val.replace(/\D/g,'');
1050	    	if (!isNumber) {
1051	    		current_element.val($.trim(my_val));
1052	    	}
1053	    }else{
1054	    	var my_key = event.keyCode || event.which;
1055	    	if ((my_key >57 || my_key<48)) {
1056	    		event.preventDefault();
1057	    		return false;
1058	    	}
1059	    }
1060	    return true;
1061	},
1062
1063	enableButton:function(){
1064		$(".bhfForm").each(function() {
1065		var length = $(this).find(".required").length;
1066		if(length==0)
1067			$(this).find(".button").removeAttr("disabled");
1068		});
1069	},
1070
1071	textAreaValidator: function(element){
1072		console.log("text area validator not available");
1073	},
1074	selectValidator: function(element){
1075		var has_error = false;
1076		if (element.hasClass("required")) {
1077			if (element.val() === null || element.val().trim() == "Select" || element.val().trim() == "") {
1078				has_error = true;
1079				bhfFormValidator.selectValidationErrorAdd(element,"required");
1080				return false;
1081			}
1082		}
1083
1084		bhfFormValidator.selectValidationRemover(element);
1085	},
1086	selectSearchValidator: function(element) {
1087		if (element.hasClass("required")) {
1088			if(element.val() == null || element.val().length === 0) {
1089				element.siblings('.select2-container').find('.select2-selection').removeClass('validated-field');
1090				element.siblings('.custom-checkmark.formIconPosition').hide();
1091				bhfFormValidator.selectValidationErrorAdd(element,"required");
1092				return false;
1093			} else {
1094				error_element = element.siblings('.select2-container').find('.select2-selection');
1095				error_element.removeClass("bhf-form-error");
1096				element.siblings('.bhf-form-error-container').children(".error-form").hide();
1097				element.siblings('.bhf-form-error-container').children(".required-msg").hide();
1098			}
1099		}
1100	},
1101	textFieldValidator: function(element){
1102		var has_error = false;
1103		if (element.hasClass("required")) {
1104			if (element.val().trim().length == 0) {
1105				has_error = true;
1106				bhfFormValidator.validationErrorAdd(element,"required");
1107				return false;
1108			}
1109		}
1110
1111		if (element.hasClass("zip-field")) {
1112			if (element.val().trim().length != 5 && element.val().trim().length < 10) {
1113				has_error = true;
1114				bhfFormValidator.validationErrorAdd(element,"constraint");
1115				return false;
1116			}
1117		}
1118
1119		if (element.hasClass("email")) {
1120			var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
1121			var emailaddress = element.val();
1122			if(!emailReg.test(emailaddress)){
1123				bhfFormValidator.validationErrorAdd(element,"constraint");
1124				return false;
1125			}
1126		}
1127		if (element.hasClass("ccInputEmail")) {
1128			let ccEmailReg = /^([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@([\w-]+\.)+[\w-]{2,4})?$/;
1129			let ccEmailAdd = element.val();
1130			if(!ccEmailReg.test(ccEmailAdd)){
1131				bhfFormValidator.validationErrorAdd(element,"constraint");
1132				return false;
1133			}
1134		}
1135		if(element.hasClass("zip-code")) {
1136     		if(element.val().trim().length != 5 && element.val().trim().length < 10)  {
1137        		has_error = true;
1138        		bhfFormValidator.validationErrorAdd(element, "constraint");
1139        		return false;
1140            }
1141		}
1142		
1143		bhfFormValidator.validationRemover(element);
1144	},
1145/* Assign BOA form validation starts */
1146	boaFormValidator: function(element){
1147		if(element.hasClass('required')){
1148			if (element.val().trim().length == 0){
1149				element.siblings('.bhf-form-error-container').children(".constraint-msg").hide();
1150				element.siblings('.bhf-form-error-container').children(".required-msg").show();
1151				element.addClass("bhf-form-error");
1152			}else{
1153				element.siblings('.bhf-form-error-container').children(".required-msg").hide();
1154				element.removeClass("bhf-form-error");
1155			}
1156		}
1157		if(element.hasClass('boaEmail')){
1158			let domains = [];
1159			if(document.querySelector("[data-runMode]") && document.querySelector("[data-runMode]").dataset && document.querySelector("[data-runMode]").dataset.runmode.indexOf('prod') > -1){
1160				domains = ["gmail", "yahoo", "outlook", "hotmail", "msn", "icloud", "aol", "hushmail","yahoomail"];
1161			}else {
1162				domains = ["yahoo", "outlook", "hotmail", "msn", "icloud", "aol", "hushmail","yahoomail"];
1163			}
1164			let emailReg = /^([a-zA-Z0-9.!#$%&'*+\/=?^_`|~-]+@([\w-]+\.)+[\w-]{2,6})?$/;
1165			let emailaddress = element.val();
1166			if(element.val().trim().length==0){
1167				element.siblings('.bhf-form-error-container').children(".required-msg").show();
1168				element.addClass("bhf-form-error");
1169			}
1170			else{
1171				element.siblings('.bhf-form-error-container').children(".required-msg").hide();
1172				element.removeClass("bhf-form-error");
1173			}
1174			if(emailReg.test(emailaddress)){
1175				if(emailaddress.length){
1176					var at = emailaddress.substring(emailaddress.indexOf('@')+1,emailaddress.length);
1177					var dotAfterAt = at.substring(0,at.indexOf('.'));
1178				}
1179				if (domains.indexOf(dotAfterAt) > -1) {
1180					element.siblings('.bhf-form-error-container').children(".constraint-msg").show();
1181					element.addClass("bhf-form-error");
1182				 }
1183				else{
1184					element.siblings('.bhf-form-error-container').children(".constraint-msg").hide();
1185					element.removeClass("bhf-form-error");
1186				}
1187			}else{
1188				if(element.val().trim().length!==0){
1189					element.siblings('.bhf-form-error-container').children(".constraint-msg").show();
1190					element.addClass("bhf-form-error");
1191				}
1192			}
1193			
1194		}
1195		// if(element.hasClass('socialSecurity')){
1196		// 	var ssnPattern = /^[0-9]{3}\-?[0-9]{2}\-?[0-9]{4}$/;
1197		// 	var ssnValue = element.val();
1198		// 	if(!ssnPattern.test(ssnValue)){
1199		// 		requiredVars.socialSecurity = true;
1200		// 		element.siblings('.bhf-form-error-container').children(".constraint-msg").show();
1201		// 		element.addClass("bhf-form-error");
1202		// 	}else {
1203		// 		requiredVars.socialSecurity = false;
1204		// 		element.siblings('.bhf-form-error-container').children(".constraint-msg").hide();
1205		// 		element.removeClass("bhf-form-error");
1206		// 	}
1207		// }
1208	},
1209/* Assign BOA form validation Ends */
1210
1211	validationRemover: function(element){
1212		if (element.val().trim().length > 0) {
1213			element.removeClass("bhf-form-error");
1214			element.siblings('.bhf-form-error-container').children(".error-form").hide();
1215			element.addClass("validated-field");
1216			element.siblings(".formIconPosition").show();
1217		}else{
1218			element.removeClass("bhf-form-error");
1219			element.siblings('.bhf-form-error-container').children(".error-form").hide();
1220			element.removeClass("validated-field");
1221			element.siblings(".formIconPosition").hide();
1222		}
1223
1224			bhfFormValidator.submitValidator(element);
1225			$(".form-select-custom").trigger('change.select2');
1226	},
1227
1228	selectValidationRemover: function(element){
1229		if (element.val() != null && (element.val().trim() != "Select" || element.val().trim() != "")) {
1230			error_element = element.siblings('.select2-container').find('.select2-selection');
1231			error_element.removeClass("bhf-form-error");
1232			element.siblings('.bhf-form-error-container').children(".error-form").hide();
1233			element.siblings('.bhf-form-error-container').children(".required-msg").hide();
1234		}
1235
1236			bhfFormValidator.submitValidator(element);
1237			$(".form-select-custom").trigger('change.select2');
1238	},
1239
1240	selectValidationErrorAdd: function(element,error_type){
1241		error_element = element.siblings('.select2-container').find('.select2-selection');
1242		error_element.addClass("bhf-form-error");
1243		element.siblings('.bhf-form-error-container').children(".error-form").hide();
1244		element.siblings('.bhf-form-error-container').children(".required-msg").show();
1245	},
1246
1247	validationErrorAdd: function(element,error_type){
1248		element.removeClass("validated-field");
1249		element.siblings(".formIconPosition").hide();
1250		element.addClass("bhf-form-error");
1251		if (error_type == "required") {
1252			element.siblings('.bhf-form-error-container').children(".error-form").hide();
1253			element.siblings('.bhf-form-error-container').children(".required-msg").show();
1254		}else if(error_type == "constraint"){
1255			element.siblings('.bhf-form-error-container').children(".error-form").hide();
1256			element.siblings('.bhf-form-error-container').children(".constraint-msg").show();
1257		}
1258		bhfFormValidator.submitValidator(element);
1259		$(".form-select-custom").trigger('change.select2');
1260	},
1261
1262	addValidationError: function() {
1263		$('#unsubscribeForm').find(':input:visible').each(function(){
1264			if(this.id != 'mobileNo' && this.id != 'email' && this.id != 'unsubscribeButton') {
1265				var tempVal = $(this).val();
1266				if(tempVal !== null && (tempVal === undefined || tempVal.trim().length === 0)) {
1267					$(this).addClass('bhf-form-error');
1268				} else if(tempVal === null) {
1269					$('.select2-selection').addClass('bhf-form-error');
1270				}
1271			}
1272		});
1273
1274	},
1275
1276	removeValidationError: function() {
1277		$('#unsubscribeForm').find(':input:visible').each(function(){
1278			if(this.id != 'mobileNo' && this.id != 'email' && this.id != 'unsubscribeButton') {
1279					$(this).removeClass('bhf-form-error');
1280					$('.select2-selection').removeClass('bhf-form-error');
1281			}
1282		});
1283	},
1284
1285	isEmptyField: function(formField) {
1286		return formField.val() === undefined || formField.val().trim().length === 0 || formField.val() === 'Select'? true:false;
1287	},
1288
1289	submitValidator: function(element,force_false){
1290
1291		var form = element.parents('form');
1292		var required_elements = form.find('input');
1293		var recaptcha_elements = form.find('.recaptcha').length ? form.find('.recaptcha') : null;
1294		var req_el = form.find('.inputField');
1295		var select = form.find('select');
1296		var is_form_complete = true;
1297		var is_valid = false;
1298		var is_form_valid = true;
1299
1300		
1301
1302		if($(select).hasClass('form-select-custom')) {
1303			if($(select).val() === "Select") is_form_complete = false;
1304		} else if($(select).hasClass('form-select-search')) {
1305			if($(select).val() === null || $(select).val().length === 0) {
1306				is_form_complete = false;
1307			}
1308		}else if($(select).hasClass('form-select-man')) {
1309			if($(select).val() === null || $(select).val().length === 0) {
1310				is_form_complete = false;
1311			}
1312		}
1313
1314		for (var i = 0; i < required_elements.length; i++) {
1315			if ($(required_elements[i]).hasClass('validation') && $(required_elements[i]).val().trim().length === 0) {
1316				$(required_elements[i]).val('');
1317				is_form_complete=false;	
1318			}
1319			if ($(required_elements[i]).hasClass('bhf-form-error')) {
1320				is_form_complete=false;
1321			}
1322
1323			if ((($(required_elements[i]).hasClass('phone') || $(required_elements[i]).hasClass('email'))) && ($(required_elements[i]).val().trim().length !== 0) && !($(required_elements[i]).hasClass('bhf-form-error'))) {
1324				is_valid = true;
1325			}
1326		}
1327		var sub_btn = $('#unsubscribeButton');
1328		if (is_form_complete || is_valid) sub_btn.prop("disabled",false);
1329		else sub_btn.prop("disabled",true);
1330		
1331		$(req_el).each(function(){
1332			if(($(this).hasClass("required") && $(this).val().trim().length == 0) || $(this).hasClass("bhf-form-error")) {
1333				is_form_valid = false;
1334			} else if ($(".validated-field").length === 0) {
1335				is_form_valid = false;
1336			}
1337		});
1338
1339		$(select).each(function(){
1340			if($(this).hasClass('required')) {
1341				if($(this).hasClass('form-select-custom')){
1342					if($(select).val() === "Select" || $(select).val() === null || $(select).val().trim() === "") is_form_valid = false;
1343				} else if($(select).hasClass('form-select-search')) {
1344					if($(select).val() === null || $(select).val().length === 0) {
1345						is_form_valid = false;
1346					}
1347				}else if($(select).hasClass('form-select-man')) {
1348					if($(select).val() === null || $(select).val().length === 0) {
1349						is_form_valid = false;
1350					}
1351				}
1352			}
1353		});	
1354		
1355		if(recaptcha_elements){
1356			if($(recaptcha_elements).attr('verified') == 'false') is_form_valid = false;
1357		}
1358		
1359		var ano_btn = form.find("#submit");
1360		if(is_form_valid) ano_btn.prop("disabled", false);
1361		else ano_btn.prop("disabled", true);
1362
1363		return is_form_valid;
1364	}		
1365};
1366
1367// For all browsers except Safari Mobile
1368
1369$(window).load(function() {
1370    $(".formResetTarget").each(function(){
1371	    this.reset();
1372	});
1373
1374	if ($(".form-select-custom .bhf-form-select").length) {
1375		$(".form-select-custom").val("Select").trigger('change');
1376	}
1377});
1378
1379// For Safari Mobile as page is not loaded. It is ajax load by default.
1380window.addEventListener("pageshow", function(evt){
1381        if(evt.persisted){
1382	        setTimeout(function(){
1383	            $(".formResetTarget").each(function(){
1384			    	this.reset();
1385				});
1386			    // Safari Doesn't respect form reset
1387			    var reset_elements= $(".text-field-validation");
1388				reset_elements.removeClass("bhf-form-error");
1389				reset_elements.siblings('.bhf-form-error-container').children(".error-form").hide();
1390				reset_elements.removeClass("validated-field");
1391				reset_elements.siblings(".formIconPosition").hide();
1392				if ($(".form-select-custom").length) {
1393					// Keep values restored by the browser's back/forward cache.
1394					// Not every dropdown has an option with value "Select"; assigning
1395					// it clears those native selects and leaves Select2 empty.
1396					$(".form-select-custom").trigger('change.select2');
1397				}
1398		    },1);
1399		}
1400}, false);
1401
1402function getCookie(cname) {
1403	var name = cname + "=";
1404	var ca = document.cookie.split(';');
1405	for (var i = 0; i < ca.length; i++) {
1406		var c = ca[i];
1407		while (c.charAt(0) == ' ') {
1408			c = c.substring(1);
1409		}
1410		if (c.indexOf(name) == 0) {
1411			return c.substring(name.length, c.length);
1412		}
1413	}
1414	return "";
1415};
1416
1417$(window).load(function(){
1418   var name = "success-message";
1419   var delayName = "delay-success-message";
1420 document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
1421 document.cookie = delayName +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
1422 });
1423(function($, scope) {
1424	scope.breakWidth = $('.header-container.professional').length ? 1024 : 768;
1425	scope.scrollBreak = $('.header-container.professional').length ? 85 : 75;
1426	scope.lastScrollPos = 0;
1427
1428    scope.getScrollingBehaviour = function() {
1429        scope.lastScrollPos = window.pageYOffset || document.documentElement.scrollTop;
1430    };
1431
1432    scope.setScrollingBehaviour = function() {
1433        window.scrollTo(0, scope.lastScrollPos);
1434    },
1435
1436	scope.ribbonInit = function (pos, reset) {
1437		if(reset) {
1438			$('.ribbon-bar').css('left', '-100%');
1439		} else if ($(window).width() >= scope.breakWidth) {
1440			const scrollPos = pos ? pos : window.pageYOffset;
1441			const d_height = $(document).height();
1442        	const c_height = window.innerHeight;
1443
1444			let scrollPercent = ((scrollPos / (d_height-c_height)) * 100) - 100;
1445        	let position = parseFloat(scrollPercent) + '%';
1446   			$('.ribbon-bar').css('left', position);
1447		}
1448	};
1449
1450	scope.navOnScroll = function () {
1451		$(window).on('scroll', function() {
1452			var scrollPos = window.pageYOffset;
1453			var width = $(window).width();
1454			if(scrollPos < scope.scrollBreak) {
1455				if(width >= scope.breakWidth) {
1456					$('.header-container, .header-rollover').removeClass('__fixed');
1457					$('.home-logo-slider').removeClass('__shiftLogo');
1458					$('.global-nav-content-pro').addClass('hide');
1459					$('.header-container.header-container .support-links.professional .proLogo').removeClass('hide');
1460					$('.header-container.header-container .support-links.professional .pro-collpase-logo').addClass('hide');
1461				}
1462			} else {
1463				if(width >= scope.breakWidth) {
1464					!$('.header-rollover').hasClass('__fixed') && $('.header-rollover').addClass('__fixed');
1465					!$('.header-container').hasClass('__fixed') && $('.header-container').addClass('__fixed');
1466					!$('.home-logo-slider').hasClass('__shiftLogo') && $('.home-logo-slider').addClass('__shiftLogo');
1467					!$('.global-nav-content-pro').hasClass('__fixed') && $('.global-nav-content-pro').removeClass('hide');
1468					!$('.global-nav-content-pro').hasClass('__fixed') && $('.proLogo').addClass('hide') && $('.pro-collpase-logo').removeClass('hide');
1469					const collpaseHeaderHeight = $('.header-container').addClass('__fixed').outerHeight(); 
1470					if(collpaseHeaderHeight > 140){
1471						!$('.global-nav-content-pro').hasClass('__fixed') && $('.global-nav-content-pro').addClass('hide');
1472					}
1473				}
1474			}
1475			scope.ribbonInit(scrollPos, false);
1476		});
1477	};
1478
1479	scope.globalNavMenu = function () {
1480		// For Tablet and Large Screen
1481		if($(window).width() >= scope.breakWidth) {
1482			if(topNavigation.isTouchDevice()) {
1483				$('.global-nav-item').on('click',function(){
1484					const width = $(this).outerWidth();
1485					const left = $(this).position().left;
1486					rolledIndicator({show: true, width: width, left: left});
1487
1488					if($(this).hasClass('__selected')) {
1489						$('.menu-container.__display').removeClass('__display');
1490						$('.global-nav-item').removeClass('__selected');
1491						scope.rolloverCatcher(false);
1492						rolledIndicator({show: false});
1493						bodyScrollLock.clearAllBodyScrollLocks();
1494					} else {
1495						const target = $(this).data('id');
1496						var el = $('.menu-container[data-id="'+target+'"]')[0];
1497						const others = $('.global-nav-item').filter(function(){
1498							return $(this).data('id') != target;
1499						});
1500						others.on('click', function(){
1501							$('.menu-container[data-id="'+target+'"]').scrollTop(0);
1502						});
1503						$('.global-nav-item').removeClass('__selected');
1504						$(this).addClass('__selected');
1505						$('.menu-container.__display').removeClass('__display');
1506						$('.menu-container[data-id="'+target+'"]').addClass('__display');
1507						scope.rolloverCatcher(true);
1508						if($('.contactLabel').length){
1509							bodyScrollLock.clearAllBodyScrollLocks();
1510						}
1511						$('.menu-container[data-id="'+target+'"]').on('touchmove', function(e){
1512							e.stopPropagation();
1513							bodyScrollLock.disableBodyScroll(el);
1514							$('body').addClass('stopScroll');
1515						});
1516					}
1517				});
1518
1519				$('.rollover-catcher, .header-rollover, .contactWholesaler').on('touchstart',function() {
1520					$('.menu-container').removeClass('__display');
1521					$('.global-nav-item').removeClass('__selected');
1522					rolledIndicator({show: false});
1523					scope.rolloverCatcher(false);
1524					$('.menu-container').scrollTop(0);
1525					bodyScrollLock.clearAllBodyScrollLocks();
1526					$('body').removeClass('stopScroll');
1527				});
1528
1529			} else {
1530				if(navigator.platform !== 'MacIntel'){
1531					$('.menu-container').each(function(){
1532						let actHeight = $(this).height();
1533						let newheight = actHeight - 1;
1534						$(this).css('max-height', newheight + 'px');
1535					});
1536				}
1537				$('.global-nav-item').hover(function(){
1538					if (!$('body').data('wcmode')){
1539						const width = $(this).outerWidth();
1540						const left = $(this).position().left;
1541						rolledIndicator({show: true, width: width, left: left});
1542						$('.menu-container').removeClass('__display');
1543						$('.global-nav-item').removeClass('__selected');
1544						$('body').removeClass('stopScroll');
1545						$(this).addClass('__selected');
1546						if($(this).hasClass('has-child')) {
1547							const target = $(this).data('id');
1548							const others = $('.global-nav-item').filter(function(){
1549								return $(this).data('id') != target;
1550							});
1551							$('.menu-container[data-id="'+target+'"]').addClass('__display');
1552							scope.rolloverCatcher(true);
1553							if(navigator.platform === 'MacIntel'){
1554								setTimeout(function(){$('body').addClass('stopScroll');});
1555							}else{
1556								$(".global-nav-item.has-child, .menu-container").hover(function() {
1557								var oldScrollPos = $(window).scrollTop();						  
1558								$(document).on('scroll.scrolldisabler', function(event) {
1559									$(window).scrollTop(oldScrollPos);
1560									event.preventDefault();
1561									
1562								});
1563							}, function() {
1564								$(document).off('scroll.scrolldisabler');
1565							});
1566							}
1567							others.hover(function(){
1568								$('.menu-container[data-id="'+target+'"]').scrollTop(0);
1569							});
1570						} else {
1571							scope.rolloverCatcher(false);
1572							$('.menu-container').scrollTop(0);
1573						}
1574					}
1575				});
1576					
1577
1578				$(".global-nav-item:not(.has-child)").mouseout(function(){
1579					$(this).removeClass("__selected");
1580					$(".rolled-indicator").removeClass("__over");
1581					$(".rolled-indicator").css({"transform":"translateX(0px)","width":"0px"});
1582				});
1583
1584				$('.rollover-catcher, .header-rollover, .custom-video-box,.custom-video-box-new,.contactWholesaler').hover(function() {
1585					if ($('.global-nav-item.has-child').is(':focus')) {
1586						return;
1587					}
1588					$('.menu-container').removeClass('__display');
1589					$('.global-nav-item').removeClass('__selected');
1590					$('body').removeClass('stopScroll');
1591					$('.menu-container').scrollTop(0);
1592					rolledIndicator({show: false});
1593					scope.rolloverCatcher(false);
1594				});
1595			}
1596		} else { // For Mobile Only
1597			$('.global-nav-item.has-child').on('click', function () {
1598				const target = $(this).data('id');
1599				$('.menu-container[data-id="'+target+'"]').addClass('__display');
1600				$('.hamburger-container > a').css('opacity', 0);
1601			});
1602		}
1603	};
1604
1605	scope.rolledIndicator = function (args) {
1606		if(args.show) {
1607			$('.rolled-indicator').removeClass('__over').addClass('__over').css({'width': args.width + 'px', 'transform': 'translateX('+args.left+'px)'});
1608		} else {
1609			$('.rolled-indicator').removeClass('__over').css({'width':'0', 'transform': 'translateX(0)'});
1610		}
1611	};
1612
1613	scope.rolloverCatcher = function (flag) {
1614		if(flag) {
1615			$('.header-rollover').addClass('__display');
1616			$('.rollover-catcher').addClass('__display');
1617		} else {
1618			$('.header-rollover').removeClass('__display');
1619			$('.rollover-catcher').removeClass('__display');
1620		}
1621	};
1622
1623	scope.hamburgerMenu = function () {
1624		$('.hamburger-container .hamburger-wrapper').on('click', function() {
1625			if($('.global-nav').hasClass('__open')) { //Close Nav;
1626				$(this).parent().removeClass('pressed');
1627				$('.global-nav').removeClass('__open');
1628				$('.menu-container').removeClass('__display');
1629				$('.hamburger-container > a').css('opacity',1);
1630				$('.menu-content').scrollTop(0);
1631				$('body').removeClass('stopScroll');
1632				$('body').removeClass('videoNoScroll');
1633				$('body').css('position', '');
1634				scope.setScrollingBehaviour();
1635				scope.ribbonInit(null, false);
1636			} else { // Open Nav
1637				scope.getScrollingBehaviour();
1638				$(this).parent().addClass('pressed');
1639				$('.global-nav').addClass('__open');
1640				const timeOut = $(window).width() < scope.breakWidth ? 250 : 0;
1641				setTimeout(function() { // To Hide Body Jump Behaviour
1642					$('body').removeClass('stopScroll').addClass('stopScroll');
1643					$('body').css('position', 'fixed');
1644				}, timeOut);
1645			}
1646		});
1647		$('.return-link').on('click', function() {
1648			if($('.menu-container.__display').length) {
1649				$('.menu-container').removeClass('__display');
1650				$('.hamburger-container > a').css('opacity', 1);
1651				$('.menu-content').scrollTop(0);
1652			}
1653		});
1654	};
1655
1656	renderSupportLogin = function(templates, elem, data) {
1657		const target = $(elem).text().trim();
1658  		templates.header.append(Mustache.render(templates.level2, {name: target}));
1659  		const $menu = $('.menu-container[data-id="'+target+'"]').find('.link-column');
1660  		$(elem).siblings('ul.menu').find('li a').each(function() {
1661			$(this).clone().addClass('column-link-item nav-a').appendTo($menu);
1662			
1663		});
1664  		templates.list.append(Mustache.render(templates.generic, data));
1665	};
1666
1667	renderNotification = function (templates) {
1668		templates.list.append(Mustache.render(templates.message, {
1669      			name: $('.message-gn').text().trim(),
1670      			path: $('.message-gn').attr('href'),
1671      			target: $('.message-gn').attr('target')
1672      	}));
1673	};
1674
1675	scope.arrangeForMobileNav = function () {
1676		const templates = {
1677			level2: $('#generic-nav-template').html(),
1678			generic: $('#mobile-list-template').html(),
1679			message: $('#mobile-message-list').html(),
1680			loginModal: $('#mobile-modal-list').html(),
1681			list: $('.global-nav .global-nav-content'),
1682			tabletLogin: $('#tablet-login-template').html(),
1683			header: $('.header-container'),
1684		};
1685
1686		// If Support List Exist
1687		if(homePageVideo.ElementExist($('.support-gn'))) {
1688			scope.renderSupportLogin(templates, '.support-nav .support-gn', {
1689	  			name: $('.support-nav .support-gn').text().trim(),
1690	  			hasIcon: 'support-link',
1691	  			hasChild: true
1692  			});
1693		}
1694
1695		// If Message notification Exist
1696		if(homePageVideo.ElementExist($('.message-gn'))) {
1697      		scope.renderNotification(templates)
1698		}
1699
1700		// If Saml Login configured
1701		if(homePageVideo.ElementExist($('.login-gn')) && $('#loginType').val() === 'loginSAMLGn') {
1702			if($('#checkFlag').val() === 'true') { // LoggedIn
1703				scope.renderSupportLogin(templates, '.support-nav .login-gn', {
1704					name: $('.support-nav .login-gn').text().trim(),
1705					hasIcon: 'user-profile',
1706					hasChild: true,
1707					isLoginPage:true
1708				});
1709			} else { // Not Logged
1710				templates.list.append(Mustache.render(templates.generic, {
1711      				name: $('.support-nav .login-gn').text().trim(),
1712					path: $('.login-gn').attr('href'),
1713					target: $('.login-gn').attr('target'),
1714      				hasIcon: 'user-profile',
1715					isLoginPage:true,
1716      				hasChild: false
1717      			}))
1718			}
1719		}
1720
1721		// If Modal Login conifgured
1722		if(homePageVideo.ElementExist($('.login-modal-gn')) && $('#loginType').val() === 'loginGn') {
1723			templates.list.append(Mustache.render(templates.loginModal, {
1724      			name: $('.login-modal-gn').text().trim(),
1725      		}));
1726		}
1727
1728		// If Saml Login configured on Tablet
1729		if(homePageVideo.ElementExist($('.login-gn')) && $('#loginType').val() === 'loginSAMLGn') {
1730			if($('#checkFlag').val() === 'true') { // LoggedIn
1731				// Logged In user
1732				templates.header.find(".login-content").append(Mustache.render(templates.tabletLogin, {
1733					isLogin:true,
1734					name: $('.support-nav .login-gn').first().text().trim(),
1735					path: $('.login-gn').first().attr('href'),
1736					target: $('.login-gn').first().attr('target'),
1737					subMenus: scope.getSubMenuItems($('.support-nav .login-gn').first().next())
1738				}));
1739				$('.header-container.professional').find('.pro-logo').addClass('right-230');
1740			} else { // Not Logged
1741				templates.header.find(".login-content").append(Mustache.render(templates.tabletLogin, {
1742					isLogin:false,
1743					name: $('.support-nav .login-gn').first().text().trim(),
1744				  	path: $('.login-gn').attr('href'),
1745				  	target: $('.login-gn').attr('target')
1746				}));
1747				$('.header-container.professional').find('.pro-logo').addClass('right-210');
1748			}
1749		}
1750
1751		// If Site Link configured
1752		if(homePageVideo.ElementExist($('.site-link-gn'))) {
1753			if($('.site-link-gn').hasClass('to-pro')) {
1754				templates.list.append(Mustache.render(templates.generic, {
1755					name: $('.site-link-gn').text().trim(),
1756					path: $('.site-link-gn').attr('href'),
1757					target: $('.site-link-gn').attr('target')
1758				}));
1759			} else {
1760				$('.hamburger-container a').attr('href',$('.site-link-gn').attr('href'));
1761				$('.hamburger-container a').attr('target',$('.site-link-gn').attr('target'));
1762				$('.hamburger-container a').text($('.site-link-gn').text().trim()).removeClass('hide');
1763			}
1764		}
1765	};
1766
1767	scope.getSubMenuItems = function($elem){
1768		const subMenuItems=[];
1769		if($elem.length){
1770			$($elem).find('li').each(function(){
1771				subMenuItems.push({
1772					name: $(this).find('a span').text().trim(),
1773					path: $(this).find('a').attr('href'),
1774					target: $(this).find('a').attr('target'),
1775					logoutUrl: $(this).find('a').data('logouturl'),
1776					userId: $(this).find('a').data('userid'),
1777					id: $(this).find('a').attr('id'),
1778				})
1779			})
1780		};
1781		return subMenuItems;
1782	};
1783
1784	scope.setActiveClass = function ($elem, regex, loop) {
1785		var checkString = $elem.text().trim().toLowerCase().replace(/ /g,'-');
1786		if(checkString.match(regex)) {
1787			$elem.addClass('__active');
1788			found = true;
1789			if(loop) return false;
1790		}
1791	};
1792
1793	scope.setActiveLink = function () {
1794		if(window.location.pathname === '/' ) {
1795			$('.home-nav').addClass('__active');
1796		} else {
1797			const value = window.location.pathname.match(/\pro\b/g) ? 2 : 1;
1798		 	var url = window.location.pathname;
1799		 	var found = false;
1800        	var matchstring = url.split('/')[value];
1801        	if (matchstring.match(/\bhtml\b/g)) {
1802            	matchstring = matchstring.split('.')[0];
1803        	}
1804        	var matchRegex = new RegExp(matchstring, 'i');
1805        	$('.global-nav-content .global-nav-item').each(function(){
1806				scope.setActiveClass($(this),matchRegex, true);
1807			});
1808
1809        	if($('.support-links .support-gn').length && !found) {
1810        		scope.setActiveClass($('.support-links .support-gn'),matchRegex, false);
1811        	}
1812
1813        	if($('.support-links .message-gn').length && !found) {
1814        		scope.setActiveClass($('.support-links .message-gn'),matchRegex, false);
1815        	}
1816		}
1817	};
1818
1819	$(function() {
1820		if($('.header-container').length !== 0) {
1821			scope.setActiveLink();
1822			if($(window).width() < scope.breakWidth) {
1823				scope.arrangeForMobileNav();
1824			}
1825			if($('#modalLogin').length) {
1826				$('.login-modal-gn').on('click', function() {
1827					setTimeout(function () {
1828	                	new Foundation.Reveal($('#modalLogin')).open();
1829						revealCenterAlign.revealRePosition();
1830						var isIphoneIpad = (navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPad/i) != null);
1831                        if (isIphoneIpad) {
1832                            $('body').addClass('videoNoScroll');
1833                        }
1834	            	}, 10);
1835				});
1836				$('#modalLogin .revealCloseWrapper, #modalLogin .secondaryBtn').on('click', function(){
1837					$('body').removeClass('videoNoScroll');
1838				});
1839			}
1840			scope.navOnScroll();
1841			scope.globalNavMenu();
1842			scope.hamburgerMenu();
1843		}
1844	});
1845	$(function() {
1846		if (homePageVideo.ElementExist($('.support-nav'))) {
1847			$('.support-nav .support-nav-content a').on('focusin', function () {
1848				$(document).scrollTop(0);
1849			});
1850		}
1851
1852		$(document).on('focusin', '.global-nav-item', function (e) {
1853			const width = $(this).outerWidth();
1854			const left = $(this).position().left;
1855			rolledIndicator({ show: true, width: width, left: left });
1856			$('.menu-container').removeClass('__display');
1857			$('.global-nav-item').removeClass('__selected');
1858			$('body').removeClass('stopScroll');
1859			$(this).addClass('__selected');
1860			if ($(this).hasClass('has-child')) {
1861				const target = $(this).data('id');
1862				const others = $('.global-nav-item').filter(function () {
1863					return $(this).data('id') != target;
1864				});
1865				$('.menu-container[data-id="' + target + '"]').addClass('__display');
1866				scope.rolloverCatcher(true);
1867			} else {
1868				scope.rolloverCatcher(false);
1869				$('.menu-container').scrollTop(0);
1870				$('.menuitem').removeClass('is-active');
1871			}
1872		});
1873
1874		$(document).on('focus', 'a', function (e) {
1875			if ($('.global-nav-item.has-child').is(':focus') || $('.nav-a').is(':focus')) {
1876				return;
1877			}
1878			$('.menu-container').removeClass('__display');
1879			$('.global-nav-item').removeClass('__selected');
1880			$('body').removeClass('stopScroll');
1881			$('.menu-container').scrollTop(0);
1882			rolledIndicator({ show: false });
1883			scope.rolloverCatcher(false);
1884		});
1885	});
1886
1887	$(document).ready(function(){
1888		var isIphone = /iphone/i.test(navigator.userAgent.toLocaleLowerCase());
1889		var isIpad = /ipad/i.test(navigator.userAgent.toLocaleLowerCase());
1890		var isAndroidTablet = /(android(?!.*mobile))/i.test(navigator.userAgent.toLocaleLowerCase());
1891		windowWidth=$(window).width();
1892		if(isIphone &&  windowWidth > 375){
1893			$(".menu-content").css({"height":"calc(100vh - 80px)"});
1894		}
1895		else if(isIpad && windowWidth == 820){
1896			$(".menu-content").css({"height":"calc(100vh - 450px)"});
1897		}
1898		else if(isIpad && windowWidth > 640 && windowWidth <= 768){
1899			$(".menu-content").css({"height":"calc(100vh - 400px)"});
1900		}
1901    	else if(isAndroidTablet && windowWidth > 640){
1902				$(".menu-content").css({"height":"calc(100vh - 400px)"});
1903		}
1904		else{
1905			$(".menu-content").css({"height":"calc(100% - 150px)"});
1906		}
1907		$(window).resize(function(){
1908			windowWidth=$(window).width();
1909			var isIphone = /iphone/i.test(navigator.userAgent.toLocaleLowerCase());
1910			var isIpad = /ipad/i.test(navigator.userAgent.toLocaleLowerCase());
1911			var isAndroidTablet = /(android(?!.*mobile))/i.test(navigator.userAgent.toLocaleLowerCase());
1912			if(isIphone &&  windowWidth > 375){
1913				$(".menu-content").css({"height":"calc(100vh - 80px)"});
1914			}
1915			else if(isIpad && windowWidth == 820){
1916				$(".menu-content").css({"height":"calc(100vh - 450px)"});
1917			}
1918			else if(isIpad && windowWidth > 640 && windowWidth <= 768){
1919				$(".menu-content").css({"height":"calc(100vh - 400px)"});
1920			}
1921			else if(isAndroidTablet && windowWidth > 640){
1922				$(".menu-content").css({"height":"calc(100vh - 400px)"});
1923			}
1924			else{
1925				$(".menu-content").css({"height":"calc(100% - 150px)"});
1926			}
1927		});
1928		if ($(window).width() < scope.breakWidth) {
1929			if ($('.global-nav-item').length === 0) {
1930				$('.hamburger-container').hide();
1931			}
1932		}
1933	});
1934}($, this));
1935
1936;
1937/* HPHV Stands for Home Page Hero Video
1938   Code Deleted on 2 May 2k18. [2170]
1939*/
1940var homePageVideo = {
1941    target: null,
1942    playPauseFlag: false,
1943    inlineYoutubeQueue: [],
1944    youtubeEvent: null,
1945    aemEvent: {
1946        mediaPlayerName: null,
1947        mediaOffset: null,
1948    },
1949
1950    HPHVPublishModeConfiguration: function () {
1951
1952        $(window).on('debouncedresize.homePageVideo',function () {
1953            homePageVideo.HPHVResize();
1954        });
1955    },
1956
1957    ElementExist: function (element) {
1958        return element.length;
1959    },
1960
1961    loadPlayer: function (target, flag, mode) {
1962        if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
1963
1964            var tag = document.createElement('script');
1965            tag.src = "https://www.youtube.com/iframe_api";
1966            var firstScriptTag = document.getElementsByTagName('script')[0];
1967            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
1968
1969            window.onYouTubePlayerAPIReady = function () {
1970                if(mode === "Inline") {
1971                    homePageVideo.initInlineYouTubePlayer();
1972                } else {
1973                    homePageVideo.initModalYouTubePlayer(target, flag);
1974                }
1975            };
1976
1977        } else {
1978            if(mode === "Inline") {
1979                homePageVideo.initInlineYouTubePlayer();
1980            } else {
1981                homePageVideo.initModalYouTubePlayer(target, flag);
1982            }
1983        }
1984    },
1985
1986    initInlineYouTubePlayer: function () {
1987        $('.youtube-inline-video').map(function() {
1988            var index = $('.genericYoutubeVideo .youtube-inline-video').index(this);
1989            var playerId = $(this).attr('id');
1990            var videoId = $(this).next().val();
1991            var listId = $(this).next().next().val();
1992            homePageVideo.inlineYoutubeQueue[index] = homePageVideo.createInlinePlayer({playerId: playerId, videoId: videoId, listId: listId});
1993        });
1994    },
1995
1996    createInlinePlayer: function(playerInfo) {
1997        function onPlayerStateChange(event) {
1998            if(event.data === YT.PlayerState.PLAYING) {
1999                genericVideo.pauseYoutubeInlineVideos(event, false);
2000                genericVideo.pauseInlineVideos();
2001            }
2002            if(typeof s !== 'undefined' && typeof videoAnalytics === 'object') {
2003                videoAnalytics.forYoutube(event, YT);
2004            }
2005        }
2006        var paramObj = new Object({ 'rel': 0,'modestbranding': 1});
2007
2008        playerInfo.listId ? Object.assign(paramObj, {'list': genericVideo.getIdOnly(playerInfo.listId), 'listType': 'playlist'}) : null;
2009
2010        return new YT.Player(playerInfo.playerId, {
2011            videoId: genericVideo.getIdOnly(playerInfo.videoId),
2012            playerVars: paramObj,
2013            events: {
2014                'onStateChange': onPlayerStateChange
2015            }
2016        });
2017    },
2018
2019    initModalYouTubePlayer: function (target, flag) {
2020        var player;
2021        player = new YT.Player(target, {
2022            events: {
2023                'onReady': ready,
2024                'onStateChange': onPlayerStateChange
2025            }
2026        });
2027
2028        function ready(event) {
2029            homePageVideo.target = player;
2030            homePageVideo.youtubeEvent = event;
2031
2032            if (flag == 2) {
2033
2034            }
2035
2036            if (flag == 1) {
2037                $(document).on('click', '.genericCloseBtn', function (e) {
2038                    genericVideo.GVCloseButtonClick(e);
2039                });
2040            }
2041            homePageVideo.youtubeFullscreenfix(flag);
2042        }
2043
2044        function onPlayerStateChange(event) {
2045            homePageVideo.windowFocusCallback(flag);
2046            if(typeof s !== 'undefined' && typeof videoAnalytics === 'object') {
2047                videoAnalytics.forYoutube(event, YT);
2048            }
2049        }
2050    },
2051
2052    HPHVPreviewModeConfiguration: function () {
2053        homePageVideo.HPHVPreviewModeResize();
2054    },
2055
2056    youtubeFullscreenfix: function(flag) {
2057        $(document).on('webkitfullscreenchange.yt mozfullscreenchange.yt fullscreenchange.yt MSFullscreenChange.yt',function(e){
2058            if(!(document.fullscreenElement ||
2059                document.msFullscreenElement ||
2060                document.mozFullScreen ||
2061                document.webkitIsFullScreen)) {
2062                setTimeout(function() {
2063                    homePageVideo.windowFocusCallback(flag);
2064                }, 100);
2065            } else {
2066                $(window).off('keyup.windowFocusCallback');
2067            }
2068        });
2069    },
2070
2071    HPHVResize: function () {
2072
2073        var fullwindowW = $(window).outerWidth();
2074        var fullwindowH = $(window).outerHeight();
2075        if ($(window).width() > 929) {
2076            var sectionVideoH = fullwindowH - 125;
2077            var videoH = fullwindowH - 125 - 40;
2078        } else {
2079            var sectionVideoH = fullwindowH - $('.topNav').outerHeight();
2080            var videoH = fullwindowH - $('.topNav').outerHeight() - 40;
2081        }
2082        $('.topNav').css('padding-top', '');
2083        $('.scrollTop').css('display', '');
2084    },
2085
2086    HPHVPreviewModeResize: function () {
2087
2088        var heroSectionHeight = $('.hero-section').css('height');
2089        var heroSectionWidth = $('.hero-section').css('width');
2090    },
2091
2092    windowFocusCallback: function (flag) {
2093        $(window).focus();
2094        if($(document.activeElement).prop('tagName') === 'IFRAME') {
2095            document.activeElement.blur();
2096            document.activeElement = document.body;
2097        }
2098        $(window).off('keyup.windowFocusCallback').on('keyup.windowFocusCallback', function (e) {
2099            if (e.keyCode == 27 && homePageVideo.playPauseFlag) {
2100
2101                if (flag === 2) {
2102                    $('.closeBtn').trigger('click');
2103                }
2104
2105                if (flag === 1) {
2106                    genericVideo.GVCloseButtonClick(e);
2107                }
2108            }
2109            if (e.keyCode == 32 && event.data == 1 && homePageVideo.playPauseFlag && flag === 2) {
2110                event.target.pauseVideo();
2111            }
2112
2113            if (e.keyCode == 32 && event.data == 2 && homePageVideo.playPauseFlag && flag === 2) {
2114                event.target.playVideo();
2115            }
2116        });
2117    },
2118
2119    // Functionality to fix the video playing on the back button.
2120    HPHVFixYoutubeAutoplay: function () {
2121        var videoPlayer = $(".videoPlayer")[0];
2122        if (typeof videoPlayer !== "undefined") {
2123            videoPlayer.src = videoPlayer.src;
2124        }
2125    },
2126};
2127;
2128/* Top Navigation Plugin */
2129var readMoreWrapper = {
2130
2131
2132    configureShowMoreLess: function (anchorObject) {
2133        anchorObject.on('click', function () {
2134            var showMore = anchorObject.next().val();
2135            var showLess = anchorObject.next().next().val();
2136            if (anchorObject.hasClass('active')) {
2137                anchorObject.text(showMore);
2138                anchorObject.removeClass('active');
2139
2140            } else {
2141                anchorObject.text(showLess);
2142                anchorObject.addClass('active');
2143            }
2144            if (typeof text !== "undefined") {
2145                text.toggleClass("show-more-height");
2146            }
2147        });
2148
2149    }
2150};
2151;
2152/* GV Stands for Generic Video */
2153var genericVideo = {
2154
2155    currentPagePosition: 0,
2156    playerType: null,
2157    isFullscreen: false,
2158    playerIndex: 0,
2159    isEventBound: false,
2160    playerName: '',
2161    playerLength: 0,
2162    allPlayers: $('a.playButton[data-cta="aemVideo"], .genericAEMVideo #aemPlayer_inline_html5_api'),
2163    isAdvisor2:false,
2164
2165    GVPublishModeConfiguration: function () {
2166
2167        $(window).on('debouncedresize.genericVideo',function () {
2168            genericVideo.GVResize();
2169        });
2170
2171        $('.genericVideo').on('click', function (e) {
2172            const $allPlayers = $('a.playButton[data-cta="aemVideo"], #aemPlayer_inline_html5_api');
2173            genericVideo.playerName = $(this).data('name');
2174            genericVideo.playerLength = $allPlayers.length;
2175            genericVideo.playerIndex = $allPlayers.index(this);
2176            var videoId = $(this).next().val();
2177            var listId = $(this).next().next().val();
2178            genericVideo.isAdvisor2 = false;
2179            genericVideo.GVPlayButtonPublishModeClick(e, videoId, listId, this);
2180        });
2181
2182        $('.genericVideo_advisor').on('click', function (e) {
2183            e.stopPropagation();
2184            const $allPlayers = $('a.playButton[data-cta="aemVideo"], #aemPlayer_inline_html5_api');
2185            genericVideo.playerName = $(this).data('name');
2186            genericVideo.playerLength = $allPlayers.length;
2187            genericVideo.playerIndex = $allPlayers.index(this);
2188            var videoId = $(this).next().val();
2189            var listId = $(this).next().next().val();
2190            genericVideo.isAdvisor2 = true;
2191            genericVideo.GVPlayButtonPublishModeClick(e, videoId, listId, this);
2192        });
2193    },
2194
2195    GVResize: function () {
2196
2197        var topNav = $('.topNav');
2198        topNav.css('padding-top', '');
2199        $('.scrollTop').css('display', '');
2200    },
2201
2202    GVPlayButtonPublishModeClick: function (ev, currentVideoId, currentListId, elem) {
2203        if (undefined != currentVideoId || undefined != currentListId) {
2204            var fullwindowH = $(window).outerHeight();
2205            var topNavObject = $('.topNav');
2206            genericVideo.GVPlayButtonClick(ev, currentVideoId, currentListId, elem);
2207            genericVideo.GVResize();
2208            if ($(".progressContainerBox").length) {
2209                $('.progressContainerBox').hide();
2210                $('.progressContainerBox').addClass('force-hide-ribbon');
2211            }
2212            ev.preventDefault();
2213        }
2214    },
2215
2216    pauseInlineVideos: function () {
2217        $(".video-js").each(function (videoIndex) {
2218            this.player.pause();
2219            this.player.load();
2220        });
2221    },
2222
2223    pauseYoutubeInlineVideos: function(event, forAll) {
2224        if(forAll) {
2225            homePageVideo.inlineYoutubeQueue.forEach(function(e){
2226                e.stopVideo();
2227            });
2228        } else {
2229            homePageVideo.inlineYoutubeQueue.forEach(function(e){
2230                if(event.target.g !== e.g) {
2231                    e.stopVideo();
2232                }
2233            });
2234        }
2235    },
2236
2237    GVPlayButtonClick: function (ev, currentVideoId, currentListId, elem) {
2238        genericVideo.currentPagePosition = window.pageYOffset;
2239        $(window).off('keyup');
2240        genericVideo.pauseInlineVideos();
2241        genericVideo.pauseYoutubeInlineVideos(null, true);
2242        var videoPath = "https://www.youtube.com/embed/";
2243        var dataCta = ev.currentTarget.attributes.getNamedItem("data-cta");
2244        $(document).on('click', '.screenClose', function (e) {
2245            genericVideo.GVCloseButtonClick(e);
2246        });
2247        if (dataCta != null && dataCta.value === "aemVideo") {
2248            var videoName = ev.currentTarget.attributes.getNamedItem("data-name").value;
2249            videoPath = currentVideoId;
2250            $('iframe.genericVideoPlayer').parent().hide();
2251            var videocontainer = genericVideo.isAdvisor2 ? $('#aemVideoPlayerAdvisor') : $('#aemVideoPlayer'); // set the ID of the container that you want to insert the video in
2252            if (videocontainer.has('video').length === 0) {
2253                genericVideo.isAdvisor2 ? $('#overlay-video-new').hide() : $('#overlay-video').hide();
2254                var videoTags = '<video width="640" name="'+ videoName +'" height="264" id="aemPlayer"  class="zindex1000 aemGenericVideoPlayer genericVideoPlayer video-js vjs-default-skin videoPlayer aemHtml5VideoPlayer"  controls playsinline oncontextmenu="return false" autoplay></video>'; // setup the video element
2255                videocontainer.append(videoTags); // insert the video element into its container
2256                videocontainer.show();
2257                $(document).on('click', '.genericCloseBtn', function (e) {
2258                    genericVideo.GVCloseButtonClick(e);
2259                });
2260            }
2261            homePageVideo.playPauseFlag = true;
2262            const mediumId = $(elem).next().next().val();
2263            const smallId = $(elem).next().next().next().val();
2264            genericVideo.loadAemVideoPlayer(videoPath,{medium: mediumId, small: smallId});
2265            genericVideo.playerType = 'aem';
2266            if( homePageVideo.ElementExist($('#aemPlayer_html5_api')) &&
2267                typeof s !== 'undefined' &&
2268                typeof videoAnalytics === 'object' ) {
2269                var myvideo = $('#aemPlayer_html5_api');
2270                myvideo.on('play seeked seeking pause ended', videoAnalytics.invokeAemModalHandlers);
2271            }
2272
2273            $(function () {
2274                $(window).focus();
2275                $(window).off('keyup');
2276                $(window).on('keyup', function (e) {
2277                    if (e.keyCode == 27) {
2278                        var ua = window.navigator.userAgent;
2279                        var old_ie = ua.indexOf('MSIE '); //Check For Old IE Browsers
2280                        var new_ie = ua.indexOf('Trident/'); //Check For New IE Browsers
2281                        if (((old_ie < 0) || (new_ie < 0)) && !genericVideo.isFullscreen) {
2282                            genericVideo.GVCloseButtonClick(e);
2283                        }
2284                    }
2285                })
2286            });
2287
2288        } else {
2289            if(genericVideo.isAdvisor2){
2290                $('#youtubeVideoPlayerAdvisor').html('<div class="custom-video-close-button-new"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" class="close-btn-svg-style-new genericCloseBtn"><path fill="none" d="M0 0H16V16H0z"/><path fill="#fff" stroke="rgba(0,0,0,0)" stroke-miterlimit="10" d="M9157.961 20952.816l-5.126 5.125-1.062-1.062 5.126-5.125-5.126-5.127 1.063-1.062 5.126 5.127 5.125-5.127 1.063 1.063-5.125 5.127 5.125 5.125-1.062 1.063z" transform="translate(-9149.961 -20943.754)"/></svg></div> <iframe src="" width="640" height="360" frameborder="0" class="genericVideoPlayer" id="player" allowfullscreen="1"></iframe>');
2291            }else{
2292                $('#youtubeVideoPlayer').html('<iframe src="" width="640" height="360" frameborder="0" class="genericVideoPlayer" id="player" allowfullscreen="1"></iframe>');
2293            }
2294            
2295            if (currentListId != "") {
2296                videoPath += genericVideo.getIdOnly(currentVideoId) + "?listType=playlist&list=" + genericVideo.getIdOnly(currentListId) + "&enablejsapi=1&theme=light&rel=0&modestbranding=1&fs=1&autoplay=1";
2297            } else {
2298                videoPath += genericVideo.getIdOnly(currentVideoId) + "?enablejsapi=1&theme=light&rel=0&modestbranding=1&fs=1&autoplay=1";
2299            }
2300            $(".genericVideoPlayer")[0].src = videoPath;
2301            homePageVideo.playPauseFlag = true;
2302            homePageVideo.loadPlayer($('.genericVideoPlayer')[0], 1);
2303            $('.aemHtml5VideoPlayer').parent().hide();
2304            genericVideo.playerType = 'youtube';
2305        }
2306        genericVideo.isAdvisor2 ?  $("#genericVideoBoxAdvisor").foundation('open') : $("#genericVideoBox").foundation('open');
2307        $(".tableType").hide();
2308        $("#sticky-wrapper").hide();
2309        $(".genericCloseBtn").show();
2310        var bodyObj = $('body');
2311        bodyObj.addClass('stopScroll');
2312        $('.topNav').css('padding-top', '');
2313        $('.scrollTop').css('display', '');
2314        var isIphoneIpad = (navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPad/i) != null);
2315        if (isIphoneIpad) {
2316            bodyObj.addClass('IphonevideoNoScroll');
2317        }
2318        if ($(".progressContainerBox").length) {
2319            $('.progressContainerBox').hide();
2320            $('.progressContainerBox').addClass('force-hide-ribbon');
2321        }
2322    },
2323
2324    GVCloseButtonClick: function () {
2325        var bodyObj = $('body');
2326        if (genericVideo.playerType === 'aem') {
2327            videojs('aemPlayer').pause();
2328            videojs('aemPlayer').dispose();
2329            if( typeof s !== 'undefined' &&
2330                typeof videoAnalytics === 'object' && typeof safeToRun !== 'undefined') {
2331                videoAnalytics.invokeAemModalHandlers('close_video');
2332            }
2333        }
2334        if (genericVideo.playerType === 'youtube') {
2335            $(window).focus();
2336            homePageVideo.target.pauseVideo();
2337            genericVideo.isAdvisor2 ? $('#youtubeVideoPlayerAdvisor').html('') : $('#youtubeVideoPlayer').html('');
2338            if(typeof s !== 'undefined' && typeof videoAnalytics === 'object' && typeof safeToRun !== 'undefined') {
2339                homePageVideo.youtubeEvent.data = 'close_video';
2340                videoAnalytics.forYoutube(homePageVideo.youtubeEvent, YT);
2341            }
2342        }
2343        homePageVideo.youtubeEvent = null;
2344        homePageVideo.aemEvent.mediaPlayerName = null;
2345        homePageVideo.aemEvent.mediaOffset = null;
2346        $(window).off('webkitfullscreenchange.yt mozfullscreenchange.yt fullscreenchange.yt MSFullscreenChange.yt');
2347        homePageVideo.playPauseFlag = false;
2348        homePageVideo.target = null;
2349        bodyObj.removeClass('stopScroll');
2350        bodyObj.removeClass('videoNoScroll');
2351        genericVideo.isAdvisor2 ?  $("#genericVideoBoxAdvisor").foundation('close') : $("#genericVideoBox").foundation('close');
2352        $(".tableType").show();
2353        $('.genericCloseBtn').hide();
2354        $('.overlayWhite').removeClass('fixed');
2355        $('.overlayWhite').css({height: 0});
2356        $('.topNav').removeClass('topLinksPosition');
2357        $('.topNav').addClass('show-nicely');
2358        if (topNavigation.iScrollPos > 75) {
2359            $('.topNav').removeClass('show-nicely-60');
2360        }
2361        $("#sticky-wrapper").css({'display': ''});
2362        $('body').css('position', '');
2363        $("body, html").scrollTop(genericVideo.currentPagePosition);
2364        var isIphoneIpad = (navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPad/i) != null);
2365        if (isIphoneIpad) {
2366            bodyObj.removeClass('IphonevideoNoScroll');
2367        }
2368        if ($(".progressContainerBox").length) {
2369            $('.progressContainerBox').removeClass('force-hide-ribbon');
2370            $('.progressContainerBox').show();
2371            ribbon.ribonVisibleCondition(false, false);
2372        }
2373
2374        $('.aemHtml5VideoPlayer').parent().show();
2375        $('iframe.genericVideoPlayer').parent().show();
2376        genericVideo.isAdvisor2 ? $('#aemVideoPlayerAdvisor').hide() : $('#aemVideoPlayer').hide();
2377        $(document).off('click', '.genericCloseBtn');
2378        $(window).off('keyup');
2379        genericVideo.playerType = null;
2380    },
2381
2382    // Functionality to fix the video playing on the back button.
2383    GVFixYoutubeVideoAutoPlay: function () {
2384        var videoPlayer = $(".genericVideoPlayer")[0];
2385        if (typeof videoPlayer !== "undefined") {
2386            videoPlayer.src = "";
2387        }
2388    },
2389
2390    loadAemVideoPlayer: function (videoPath, args) {
2391
2392        videojs('aemPlayer', {"fluid": true, "aspectRatio": "1280:600", "techOrder": ["html5"],
2393            "preload": "auto",
2394            "autoplay": true,
2395            "controlBar": {
2396                "pictureInPictureToggle": false,
2397                "children": [
2398                    "playToggle",
2399                    "volumePanel",
2400                    "progressControl",
2401                    'remainingTimeDisplay',
2402                    "qualitySelector",
2403                    "fullscreenToggle"
2404                ]
2405            }
2406        }, function () {
2407            var lastTime = 0,
2408                lastBuffer = 0,
2409                buffered = false,
2410                bufferPause = false;
2411            var myPlayer = this;
2412
2413            myPlayer.src(genericVideo.aemVideoResolutionObject(videoPath, args));
2414            myPlayer.on('fullscreenchange', function() {
2415                if(myPlayer.isFullscreen()) {
2416                    genericVideo.isFullscreen = true;
2417                } else {
2418                    setTimeout(function(){
2419                        genericVideo.isFullscreen = false;
2420                    }, 300);
2421                }
2422            });
2423            $('a.replay-button').on('click', function () {
2424                genericVideo.isAdvisor2 ? $('#overlay-video-new').hide() : $('#overlay-video').hide();
2425                videojs('aemPlayer').load();
2426            });
2427            if (!genericVideo.isEventBound) {
2428                genericVideo.isEventBound = true;
2429                if(genericVideo.isAdvisor2){
2430                    $('#overlay-video-new .playNextVideo').on('click', function () {
2431                        const next = genericVideo.playerIndex + 1;
2432                        if (genericVideo.playerLength > next) {
2433                            genericVideo.playerIndex += 1;
2434                        } else {
2435                            genericVideo.playerIndex = 0;
2436                        }
2437                        genericVideo.playerName = $('#overlay-video-new').find('.detailVideoTitle').text();
2438                        const highSrc = $('#overlay-video-new .set-high').val();
2439                        const medSrc = $('#overlay-video-new .set-medium').val();
2440                        const lowSrc = $('#overlay-video-new .set-low').val();
2441                        videojs('aemPlayer').src(genericVideo.aemVideoResolutionObject(highSrc, {medium: medSrc, small: lowSrc}));
2442                        $('#overlay-video-new').hide();
2443                    });
2444                }else{
2445                    $('#overlay-video .playNextVideo').on('click', function () {
2446                        const next = genericVideo.playerIndex + 1;
2447                        if (genericVideo.playerLength > next) {
2448                            genericVideo.playerIndex += 1;
2449                        } else {
2450                            genericVideo.playerIndex = 0;
2451                        }
2452                        genericVideo.playerName = $('#overlay-video').find('.detailVideoTitle').text();
2453                        const highSrc = $('#overlay-video .set-high').val();
2454                        const medSrc = $('#overlay-video .set-medium').val();
2455                        const lowSrc = $('#overlay-video .set-low').val();
2456                        videojs('aemPlayer').src(genericVideo.aemVideoResolutionObject(highSrc, {medium: medSrc, small: lowSrc}));
2457                        $('#overlay-video').hide();
2458                    });
2459                }
2460            };
2461            myPlayer.on('loadedmetadata', function() {
2462                if(myPlayer.paused()) {
2463                    myPlayer.play();
2464                }
2465                genericVideo.videoEventHandlers();
2466            });
2467            myPlayer.on("progress", function () {
2468                // (this.paused() will return true even if it's buffering, so we have to check the time advancement)
2469                var currentTime = myPlayer.currentTime();
2470
2471                if (lastTime !== currentTime) {
2472                    lastTime = currentTime;
2473
2474                } else if (myPlayer.paused() === false) {
2475
2476                    // Video is buffering/waiting.
2477                    buffered = false;
2478
2479                    //myPlayer.pause();
2480                    bufferPause = true; // To indicate pause was initiated by this buffer check
2481
2482                    lastBuffer = myPlayer.bufferedPercent();
2483                    myPlayer.addClass('vjs-waiting');
2484                } else if (!buffered && (myPlayer.bufferedPercent() - lastBuffer > 0 || myPlayer.bufferedPercent() > 0.1)) {
2485
2486                    buffered = true;
2487
2488                    // Resume playing if an additional 10% has been buffered.
2489                    if (bufferPause) {
2490                        myPlayer.play();
2491                    }
2492                    myPlayer.removeClass('vjs-waiting');
2493                }
2494            });
2495            myPlayer.on("play", function () {
2496                // Ensure that bufferPause is reset
2497                bufferPause = false;
2498                myPlayer.removeClass('vjs-waiting');
2499                genericVideo.isAdvisor2 ? $('#overlay-video-new').hide() : $('#overlay-video').hide();
2500            });
2501            myPlayer.on("ended", function () {
2502                genericVideo.setupOverlay(genericVideo.initVideoOverlay());
2503            });
2504        });
2505    },
2506
2507    videoEventHandlers: function () {
2508        $('.vjs-control-bar .vjs-quality-selector').off('click.openMenu').on('click.openMenu', function(e) {
2509            e.stopPropagation();
2510            var $elem = $(this);
2511            if($(e.target).hasClass('vjs-quality-selector')) {
2512                $elem.hasClass('active') ?  $elem.removeClass('active') : $elem.addClass('active');
2513            }
2514        });
2515    },
2516
2517    /**
2518     * 'Return Resolution object based on the videos added'
2519     */
2520
2521    aemVideoResolutionObject: function(videoPath, args) {
2522        var data = [
2523                {
2524                    src: args.medium,
2525                    type: 'video/mp4',
2526                    res: 480,
2527                    label: 'Med',
2528                    selected: true,
2529                },
2530        ];
2531
2532        if(videoPath) {
2533            var highObj = {
2534                src: videoPath,
2535                type: 'video/mp4',
2536                res: 720,
2537                label: 'High <span class="hd">HD</span>'
2538            };
2539            data.unshift(highObj);
2540        }
2541        if(args.small) {
2542            var lowObj = {
2543                src: args.small,
2544                type: 'video/mp4',
2545                res: 320,
2546                label: 'Low'
2547            };
2548            data.push(lowObj);
2549        }
2550        return data;
2551    },
2552
2553    applyGenericAemVideoHeight: function() {
2554        const $this = $('.genericAEMVideo .responsive-embed,.genericYoutubeVideo .responsive-embed');
2555        function setHeight(applyHeight) {
2556            $.map($this, function (elem){
2557                $(elem).height($(elem).data(applyHeight));
2558            });
2559        }
2560
2561        if($(window).width() < 640) {
2562            setHeight('small');
2563        } else if($(window).width() < 1024 ) {
2564            setHeight('medium');
2565        } else {
2566            setHeight('large');
2567        }
2568    },
2569
2570    initVideoOverlay: function() {
2571        const $allPlayers = $('a.playButton[data-cta="aemVideo"], .genericAEMVideo #aemPlayer_inline_html5_api');
2572        let nextVideo = genericVideo.playerIndex + 1;
2573        if(genericVideo.playerLength > nextVideo) {
2574            const flagVar = genericVideo.checkIsModalVideo($allPlayers.eq(nextVideo));
2575            return genericVideo.setNextVideo({flag: flagVar, next: nextVideo});
2576        } else if(genericVideo.playerLength === 1) {
2577            if(genericVideo.isAdvisor2){
2578                $('#overlay-video-new .single-video-wrapper').show();
2579                $('#overlay-video-new .multile-video-wrapper').hide();
2580                $('#overlay-video-new').show();
2581                $('#overlay-video-new').find('h4').text(genericVideo.playerName);
2582            }else{
2583                $('#overlay-video .single-video-wrapper').show();
2584                $('#overlay-video .multile-video-wrapper').hide();
2585                $('#overlay-video').show();
2586                $('#overlay-video').find('h4').text(genericVideo.playerName);
2587            }
2588            
2589        } else {
2590            const flag = genericVideo.checkIsModalVideo($allPlayers.eq(0));
2591            return genericVideo.setNextVideo({flag: flag, next: 0});
2592        }
2593
2594    },
2595
2596    checkIsModalVideo: function(elem) {
2597        return elem.hasClass('playButton');
2598    },
2599
2600    setNextVideo: function(args) {
2601        const $allPlayers = $('a.playButton[data-cta="aemVideo"], .genericAEMVideo #aemPlayer_inline_html5_api');
2602        function performModalOp(nextIndex) {
2603            const $elem = $allPlayers.eq(nextIndex);
2604            let bg;
2605            if($elem.prev().prop('tagName') === 'IMG') {
2606                bg = $elem.prev().attr('src');
2607            } else {
2608                bg = bg = $elem.prev().val();
2609            }
2610            const name = $elem.data('name');
2611            const highSrc = $elem.next().val();
2612            const mediumSrc = $elem.next().next().val();
2613            const lowSrc = $elem.next().next().next().val();
2614            return {high: highSrc, medium: mediumSrc, low: lowSrc, name: name, bg: bg};
2615        }
2616
2617        function performInlineOp(nextIndex) {
2618            const name = $allPlayers.eq(nextIndex).attr('name');
2619            var bg = $allPlayers.eq(nextIndex).next().css('background-image');
2620            const thumbnail = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
2621            var arr = $allPlayers.eq(nextIndex).find('source').map(function(e){
2622                var src = $(this).attr('src');
2623                return src ? src : '';
2624            });
2625            return {high: arr[0], medium: arr[1], low: arr[2], name: name, bg: thumbnail};
2626        }
2627        if(args.flag) {
2628            return performModalOp(args.next);
2629        } else {
2630           return performInlineOp(args.next);
2631        }
2632    },
2633
2634    setupOverlay: function(args) {
2635        if(args) {
2636            if(genericVideo.isAdvisor2){
2637                //Current Section
2638                $('#overlay-video-new').find('h4').text(genericVideo.playerName);
2639                //Next Section
2640                $('#overlay-video-new').find('.grayBackground').css('background-image', 'url(' + args.bg + ')');
2641                $('#overlay-video-new').find('.set-high').val(args.high);
2642                $('#overlay-video-new').find('.set-medium').val(args.medium);
2643                $('#overlay-video-new').find('.set-low').val(args.low);
2644                $('#overlay-video-new').find('.detailVideoTitle').text(args.name);
2645                $('#overlay-video-new .single-video-wrapper').hide();
2646                $('#overlay-video-new .multile-video-wrapper').show();
2647                $('#overlay-video-new').show();
2648            }else{
2649                //Current Section
2650                $('#overlay-video').find('h4').text(genericVideo.playerName);
2651                //Next Section
2652                $('#overlay-video').find('.grayBackground').css('background-image', 'url(' + args.bg + ')');
2653                $('#overlay-video').find('.set-high').val(args.high);
2654                $('#overlay-video').find('.set-medium').val(args.medium);
2655                $('#overlay-video').find('.set-low').val(args.low);
2656                $('#overlay-video').find('.detailVideoTitle').text(args.name);
2657                $('#overlay-video .single-video-wrapper').hide();
2658                $('#overlay-video .multile-video-wrapper').show();
2659                $('#overlay-video').show();
2660            }
2661        }
2662    },
2663
2664    getIdOnly: function(value) {
2665        return value.split('?')[0];
2666    },
2667};
2668
vendor: 19,413 bytes, lines 2669-3453
2669/*
2670 *  Remodal - v1.1.1
2671 *  Responsive, lightweight, fast, synchronized with CSS animations, fully customizable modal window plugin with declarative configuration and hash tracking.
2672 *  http://vodkabears.github.io/remodal/
2673 *
2674 *  Made by Ilya Makarov
2675 *  Under MIT License
2676 */
2677
2678!(function(root, factory) {
2679  if (typeof define === 'function' && define.amd) {
2680    define(['jquery'], function($) {
2681      return factory(root, $);
2682    });
2683  } else if (typeof exports === 'object') {
2684    factory(root, require('jquery'));
2685  } else {
2686    factory(root, root.jQuery || root.Zepto);
2687  }
2688})(this, function(global, $) {
2689
2690  'use strict';
2691
2692  /**
2693   * Name of the plugin
2694   * @private
2695   * @const
2696   * @type {String}
2697   */
2698  var PLUGIN_NAME = 'remodal';
2699
2700  /**
2701   * Namespace for CSS and events
2702   * @private
2703   * @const
2704   * @type {String}
2705   */
2706  var NAMESPACE = global.REMODAL_GLOBALS && global.REMODAL_GLOBALS.NAMESPACE || PLUGIN_NAME;
2707
2708  /**
2709   * Animationstart event with vendor prefixes
2710   * @private
2711   * @const
2712   * @type {String}
2713   */
2714  var ANIMATIONSTART_EVENTS = $.map(
2715    ['animationstart', 'webkitAnimationStart', 'MSAnimationStart', 'oAnimationStart'],
2716
2717    function(eventName) {
2718      return eventName + '.' + NAMESPACE;
2719    }
2720
2721  ).join(' ');
2722
2723  /**
2724   * Animationend event with vendor prefixes
2725   * @private
2726   * @const
2727   * @type {String}
2728   */
2729  var ANIMATIONEND_EVENTS = $.map(
2730    ['animationend', 'webkitAnimationEnd', 'MSAnimationEnd', 'oAnimationEnd'],
2731
2732    function(eventName) {
2733      return eventName + '.' + NAMESPACE;
2734    }
2735
2736  ).join(' ');
2737
2738  /**
2739   * Default settings
2740   * @private
2741   * @const
2742   * @type {Object}
2743   */
2744  var DEFAULTS = $.extend({
2745    hashTracking: true,
2746    closeOnConfirm: true,
2747    closeOnCancel: true,
2748    closeOnEscape: true,
2749    closeOnOutsideClick: true,
2750    modifier: '',
2751    appendTo: null
2752  }, global.REMODAL_GLOBALS && global.REMODAL_GLOBALS.DEFAULTS);
2753
2754  /**
2755   * States of the Remodal
2756   * @private
2757   * @const
2758   * @enum {String}
2759   */
2760  var STATES = {
2761    CLOSING: 'closing',
2762    CLOSED: 'closed',
2763    OPENING: 'opening',
2764    OPENED: 'opened'
2765  };
2766
2767  /**
2768   * Reasons of the state change.
2769   * @private
2770   * @const
2771   * @enum {String}
2772   */
2773  var STATE_CHANGE_REASONS = {
2774    CONFIRMATION: 'confirmation',
2775    CANCELLATION: 'cancellation'
2776  };
2777
2778  /**
2779   * Is animation supported?
2780   * @private
2781   * @const
2782   * @type {Boolean}
2783   */
2784  var IS_ANIMATION = (function() {
2785    var style = document.createElement('div').style;
2786
2787    return style.animationName !== undefined ||
2788      style.WebkitAnimationName !== undefined ||
2789      style.MozAnimationName !== undefined ||
2790      style.msAnimationName !== undefined ||
2791      style.OAnimationName !== undefined;
2792  })();
2793
2794  /**
2795   * Is iOS?
2796   * @private
2797   * @const
2798   * @type {Boolean}
2799   */
2800  var IS_IOS = /iPad|iPhone|iPod/.test(navigator.platform);
2801
2802  /**
2803   * Current modal
2804   * @private
2805   * @type {Remodal}
2806   */
2807  var current;
2808
2809  /**
2810   * Scrollbar position
2811   * @private
2812   * @type {Number}
2813   */
2814  var scrollTop;
2815
2816  /**
2817   * Returns an animation duration
2818   * @private
2819   * @param {jQuery} $elem
2820   * @returns {Number}
2821   */
2822  function getAnimationDuration($elem) {
2823    if (
2824      IS_ANIMATION &&
2825      $elem.css('animation-name') === 'none' &&
2826      $elem.css('-webkit-animation-name') === 'none' &&
2827      $elem.css('-moz-animation-name') === 'none' &&
2828      $elem.css('-o-animation-name') === 'none' &&
2829      $elem.css('-ms-animation-name') === 'none'
2830    ) {
2831      return 0;
2832    }
2833
2834    var duration = $elem.css('animation-duration') ||
2835      $elem.css('-webkit-animation-duration') ||
2836      $elem.css('-moz-animation-duration') ||
2837      $elem.css('-o-animation-duration') ||
2838      $elem.css('-ms-animation-duration') ||
2839      '0s';
2840
2841    var delay = $elem.css('animation-delay') ||
2842      $elem.css('-webkit-animation-delay') ||
2843      $elem.css('-moz-animation-delay') ||
2844      $elem.css('-o-animation-delay') ||
2845      $elem.css('-ms-animation-delay') ||
2846      '0s';
2847
2848    var iterationCount = $elem.css('animation-iteration-count') ||
2849      $elem.css('-webkit-animation-iteration-count') ||
2850      $elem.css('-moz-animation-iteration-count') ||
2851      $elem.css('-o-animation-iteration-count') ||
2852      $elem.css('-ms-animation-iteration-count') ||
2853      '1';
2854
2855    var max;
2856    var len;
2857    var num;
2858    var i;
2859
2860    duration = duration.split(', ');
2861    delay = delay.split(', ');
2862    iterationCount = iterationCount.split(', ');
2863
2864    // The 'duration' size is the same as the 'delay' size
2865    for (i = 0, len = duration.length, max = Number.NEGATIVE_INFINITY; i < len; i++) {
2866      num = parseFloat(duration[i]) * parseInt(iterationCount[i], 10) + parseFloat(delay[i]);
2867
2868      if (num > max) {
2869        max = num;
2870      }
2871    }
2872
2873    return max;
2874  }
2875
2876  /**
2877   * Returns a scrollbar width
2878   * @private
2879   * @returns {Number}
2880   */
2881  function getScrollbarWidth() {
2882    if ($(document).height() <= $(window).height()) {
2883      return 0;
2884    }
2885
2886    var outer = document.createElement('div');
2887    var inner = document.createElement('div');
2888    var widthNoScroll;
2889    var widthWithScroll;
2890
2891    outer.style.visibility = 'hidden';
2892    outer.style.width = '100px';
2893    document.body.appendChild(outer);
2894
2895    widthNoScroll = outer.offsetWidth;
2896
2897    // Force scrollbars
2898    outer.style.overflow = 'scroll';
2899
2900    // Add inner div
2901    inner.style.width = '100%';
2902    outer.appendChild(inner);
2903
2904    widthWithScroll = inner.offsetWidth;
2905
2906    // Remove divs
2907    outer.parentNode.removeChild(outer);
2908
2909    return widthNoScroll - widthWithScroll;
2910  }
2911
2912  /**
2913   * Locks the screen
2914   * @private
2915   */
2916  function lockScreen() {
2917    if (IS_IOS) {
2918      return;
2919    }
2920
2921    var $html = $('html');
2922    var lockedClass = namespacify('is-locked');
2923    var paddingRight;
2924    var $body;
2925
2926    if (!$html.hasClass(lockedClass)) {
2927      $body = $(document.body);
2928
2929      // Zepto does not support '-=', '+=' in the `css` method
2930      paddingRight = parseInt($body.css('padding-right'), 10) + getScrollbarWidth();
2931
2932      $body.css('padding-right', paddingRight + 'px');
2933      $html.addClass(lockedClass);
2934    }
2935  }
2936
2937  /**
2938   * Unlocks the screen
2939   * @private
2940   */
2941  function unlockScreen() {
2942    if (IS_IOS) {
2943      return;
2944    }
2945
2946    var $html = $('html');
2947    var lockedClass = namespacify('is-locked');
2948    var paddingRight;
2949    var $body;
2950
2951    if ($html.hasClass(lockedClass)) {
2952      $body = $(document.body);
2953
2954      // Zepto does not support '-=', '+=' in the `css` method
2955      paddingRight = parseInt($body.css('padding-right'), 10) - getScrollbarWidth();
2956
2957      $body.css('padding-right', paddingRight + 'px');
2958      $html.removeClass(lockedClass);
2959    }
2960  }
2961
2962  /**
2963   * Sets a state for an instance
2964   * @private
2965   * @param {Remodal} instance
2966   * @param {STATES} state
2967   * @param {Boolean} isSilent If true, Remodal does not trigger events
2968   * @param {String} Reason of a state change.
2969   */
2970  function setState(instance, state, isSilent, reason) {
2971
2972    var newState = namespacify('is', state);
2973    var allStates = [namespacify('is', STATES.CLOSING),
2974                     namespacify('is', STATES.OPENING),
2975                     namespacify('is', STATES.CLOSED),
2976                     namespacify('is', STATES.OPENED)].join(' ');
2977
2978    instance.$bg
2979      .removeClass(allStates)
2980      .addClass(newState);
2981
2982    instance.$overlay
2983      .removeClass(allStates)
2984      .addClass(newState);
2985
2986    instance.$wrapper
2987      .removeClass(allStates)
2988      .addClass(newState);
2989
2990    instance.$modal
2991      .removeClass(allStates)
2992      .addClass(newState);
2993
2994    instance.state = state;
2995    !isSilent && instance.$modal.trigger({
2996      type: state,
2997      reason: reason
2998    }, [{ reason: reason }]);
2999  }
3000
3001  /**
3002   * Synchronizes with the animation
3003   * @param {Function} doBeforeAnimation
3004   * @param {Function} doAfterAnimation
3005   * @param {Remodal} instance
3006   */
3007  function syncWithAnimation(doBeforeAnimation, doAfterAnimation, instance) {
3008    var runningAnimationsCount = 0;
3009
3010    var handleAnimationStart = function(e) {
3011      if (e.target !== this) {
3012        return;
3013      }
3014
3015      runningAnimationsCount++;
3016    };
3017
3018    var handleAnimationEnd = function(e) {
3019      if (e.target !== this) {
3020        return;
3021      }
3022
3023      if (--runningAnimationsCount === 0) {
3024
3025        // Remove event listeners
3026        $.each(['$bg', '$overlay', '$wrapper', '$modal'], function(index, elemName) {
3027          instance[elemName].off(ANIMATIONSTART_EVENTS + ' ' + ANIMATIONEND_EVENTS);
3028        });
3029
3030        doAfterAnimation();
3031      }
3032    };
3033
3034    $.each(['$bg', '$overlay', '$wrapper', '$modal'], function(index, elemName) {
3035      instance[elemName]
3036        .on(ANIMATIONSTART_EVENTS, handleAnimationStart)
3037        .on(ANIMATIONEND_EVENTS, handleAnimationEnd);
3038    });
3039
3040    doBeforeAnimation();
3041
3042    // If the animation is not supported by a browser or its duration is 0
3043    if (
3044      getAnimationDuration(instance.$bg) === 0 &&
3045      getAnimationDuration(instance.$overlay) === 0 &&
3046      getAnimationDuration(instance.$wrapper) === 0 &&
3047      getAnimationDuration(instance.$modal) === 0
3048    ) {
3049
3050      // Remove event listeners
3051      $.each(['$bg', '$overlay', '$wrapper', '$modal'], function(index, elemName) {
3052        instance[elemName].off(ANIMATIONSTART_EVENTS + ' ' + ANIMATIONEND_EVENTS);
3053      });
3054
3055      doAfterAnimation();
3056    }
3057  }
3058
3059  /**
3060   * Closes immediately
3061   * @private
3062   * @param {Remodal} instance
3063   */
3064  function halt(instance) {
3065    if (instance.state === STATES.CLOSED) {
3066      return;
3067    }
3068
3069    $.each(['$bg', '$overlay', '$wrapper', '$modal'], function(index, elemName) {
3070      instance[elemName].off(ANIMATIONSTART_EVENTS + ' ' + ANIMATIONEND_EVENTS);
3071    });
3072
3073    instance.$bg.removeClass(instance.settings.modifier);
3074    instance.$overlay.removeClass(instance.settings.modifier).hide();
3075    instance.$wrapper.hide();
3076    unlockScreen();
3077    setState(instance, STATES.CLOSED, true);
3078  }
3079
3080  /**
3081   * Parses a string with options
3082   * @private
3083   * @param str
3084   * @returns {Object}
3085   */
3086  function parseOptions(str) {
3087    var obj = {};
3088    var arr;
3089    var len;
3090    var val;
3091    var i;
3092
3093    // Remove spaces before and after delimiters
3094    str = str.replace(/\s*:\s*/g, ':').replace(/\s*,\s*/g, ',');
3095
3096    // Parse a string
3097    arr = str.split(',');
3098    for (i = 0, len = arr.length; i < len; i++) {
3099      arr[i] = arr[i].split(':');
3100      val = arr[i][1];
3101
3102      // Convert a string value if it is like a boolean
3103      if (typeof val === 'string' || val instanceof String) {
3104        val = val === 'true' || (val === 'false' ? false : val);
3105      }
3106
3107      // Convert a string value if it is like a number
3108      if (typeof val === 'string' || val instanceof String) {
3109        val = !isNaN(val) ? +val : val;
3110      }
3111
3112      obj[arr[i][0]] = val;
3113    }
3114
3115    return obj;
3116  }
3117
3118  /**
3119   * Generates a string separated by dashes and prefixed with NAMESPACE
3120   * @private
3121   * @param {...String}
3122   * @returns {String}
3123   */
3124  function namespacify() {
3125    var result = NAMESPACE;
3126
3127    for (var i = 0; i < arguments.length; ++i) {
3128      result += '-' + arguments[i];
3129    }
3130
3131    return result;
3132  }
3133
3134  /**
3135   * Handles the hashchange event
3136   * @private
3137   * @listens hashchange
3138   */
3139  function handleHashChangeEvent() {
3140    var id = location.hash.replace('#', '');
3141    var instance;
3142    var $elem;
3143
3144    if (!id) {
3145
3146      // Check if we have currently opened modal and animation was completed
3147      if (current && current.state === STATES.OPENED && current.settings.hashTracking) {
3148        current.close();
3149      }
3150    } else {
3151
3152      // Catch syntax error if your hash is bad
3153      try {
3154        $elem = $(
3155          '[data-' + PLUGIN_NAME + '-id="' + id + '"]'
3156        );
3157      } catch (err) {}
3158
3159      if ($elem && $elem.length) {
3160        instance = $[PLUGIN_NAME].lookup[$elem.data(PLUGIN_NAME)];
3161
3162        if (instance && instance.settings.hashTracking) {
3163          instance.open();
3164        }
3165      }
3166
3167    }
3168  }
3169
3170  /**
3171   * Remodal constructor
3172   * @constructor
3173   * @param {jQuery} $modal
3174   * @param {Object} options
3175   */
3176  function Remodal($modal, options) {
3177    var $body = $(document.body);
3178    var $appendTo = $body;
3179    var remodal = this;
3180
3181    remodal.settings = $.extend({}, DEFAULTS, options);
3182    remodal.index = $[PLUGIN_NAME].lookup.push(remodal) - 1;
3183    remodal.state = STATES.CLOSED;
3184
3185    remodal.$overlay = $('.' + namespacify('overlay'));
3186
3187    if (remodal.settings.appendTo !== null && remodal.settings.appendTo.length) {
3188      $appendTo = $(remodal.settings.appendTo);
3189    }
3190
3191    if (!remodal.$overlay.length) {
3192      remodal.$overlay = $('<div>').addClass(namespacify('overlay') + ' ' + namespacify('is', STATES.CLOSED)).hide();
3193      $appendTo.append(remodal.$overlay);
3194    }
3195
3196    remodal.$bg = $('.' + namespacify('bg')).addClass(namespacify('is', STATES.CLOSED));
3197
3198    remodal.$modal = $modal
3199      .addClass(
3200        NAMESPACE + ' ' +
3201        namespacify('is-initialized') + ' ' +
3202        remodal.settings.modifier + ' ' +
3203        namespacify('is', STATES.CLOSED))
3204      .attr('tabindex', '-1');
3205
3206    remodal.$wrapper = $('<div>')
3207      .addClass(
3208        namespacify('wrapper') + ' ' +
3209        remodal.settings.modifier + ' ' +
3210        namespacify('is', STATES.CLOSED))
3211      .hide()
3212      .append(remodal.$modal);
3213    $appendTo.append(remodal.$wrapper);
3214
3215    // Add the event listener for the close button
3216    remodal.$wrapper.on('click.' + NAMESPACE, '[data-' + PLUGIN_NAME + '-action="close"]', function(e) {
3217      e.preventDefault();
3218
3219      remodal.close();
3220    });
3221
3222    // Add the event listener for the cancel button
3223    remodal.$wrapper.on('click.' + NAMESPACE, '[data-' + PLUGIN_NAME + '-action="cancel"]', function(e) {
3224      e.preventDefault();
3225
3226      remodal.$modal.trigger(STATE_CHANGE_REASONS.CANCELLATION);
3227
3228      if (remodal.settings.closeOnCancel) {
3229        remodal.close(STATE_CHANGE_REASONS.CANCELLATION);
3230      }
3231    });
3232
3233    // Add the event listener for the confirm button
3234    remodal.$wrapper.on('click.' + NAMESPACE, '[data-' + PLUGIN_NAME + '-action="confirm"]', function(e) {
3235      e.preventDefault();
3236
3237      remodal.$modal.trigger(STATE_CHANGE_REASONS.CONFIRMATION);
3238
3239      if (remodal.settings.closeOnConfirm) {
3240        remodal.close(STATE_CHANGE_REASONS.CONFIRMATION);
3241      }
3242    });
3243
3244    // Add the event listener for the overlay
3245    remodal.$wrapper.on('click.' + NAMESPACE, function(e) {
3246      var $target = $(e.target);
3247
3248      if (!$target.hasClass(namespacify('wrapper'))) {
3249        return;
3250      }
3251
3252      if (remodal.settings.closeOnOutsideClick) {
3253        remodal.close();
3254      }
3255    });
3256  }
3257
3258  /**
3259   * Opens a modal window
3260   * @public
3261   */
3262  Remodal.prototype.open = function() {
3263    var remodal = this;
3264    var id;
3265
3266    // Check if the animation was completed
3267    if (remodal.state === STATES.OPENING || remodal.state === STATES.CLOSING) {
3268      return;
3269    }
3270
3271    id = remodal.$modal.attr('data-' + PLUGIN_NAME + '-id');
3272
3273    if (id && remodal.settings.hashTracking) {
3274      scrollTop = $(window).scrollTop();
3275      location.hash = id;
3276    }
3277
3278    if (current && current !== remodal) {
3279      halt(current);
3280    }
3281
3282    current = remodal;
3283    lockScreen();
3284    remodal.$bg.addClass(remodal.settings.modifier);
3285    remodal.$overlay.addClass(remodal.settings.modifier).show();
3286    remodal.$wrapper.show().scrollTop(0);
3287    remodal.$modal.focus();
3288
3289    syncWithAnimation(
3290      function() {
3291        setState(remodal, STATES.OPENING);
3292      },
3293
3294      function() {
3295        setState(remodal, STATES.OPENED);
3296      },
3297
3298      remodal);
3299  };
3300
3301  /**
3302   * Closes a modal window
3303   * @public
3304   * @param {String} reason
3305   */
3306  Remodal.prototype.close = function(reason) {
3307    var remodal = this;
3308
3309    // Check if the animation was completed
3310    if (remodal.state === STATES.OPENING || remodal.state === STATES.CLOSING || remodal.state === STATES.CLOSED) {
3311      return;
3312    }
3313
3314    if (
3315      remodal.settings.hashTracking &&
3316      remodal.$modal.attr('data-' + PLUGIN_NAME + '-id') === location.hash.substr(1)
3317    ) {
3318      location.hash = '';
3319      $(window).scrollTop(scrollTop);
3320    }
3321
3322    syncWithAnimation(
3323      function() {
3324        setState(remodal, STATES.CLOSING, false, reason);
3325      },
3326
3327      function() {
3328        remodal.$bg.removeClass(remodal.settings.modifier);
3329        remodal.$overlay.removeClass(remodal.settings.modifier).hide();
3330        remodal.$wrapper.hide();
3331        unlockScreen();
3332
3333        setState(remodal, STATES.CLOSED, false, reason);
3334      },
3335
3336      remodal);
3337  };
3338
3339  /**
3340   * Returns a current state of a modal
3341   * @public
3342   * @returns {STATES}
3343   */
3344  Remodal.prototype.getState = function() {
3345    return this.state;
3346  };
3347
3348  /**
3349   * Destroys a modal
3350   * @public
3351   */
3352  Remodal.prototype.destroy = function() {
3353    var lookup = $[PLUGIN_NAME].lookup;
3354    var instanceCount;
3355
3356    halt(this);
3357    this.$wrapper.remove();
3358
3359    delete lookup[this.index];
3360    instanceCount = $.grep(lookup, function(instance) {
3361      return !!instance;
3362    }).length;
3363
3364    if (instanceCount === 0) {
3365      this.$overlay.remove();
3366      this.$bg.removeClass(
3367        namespacify('is', STATES.CLOSING) + ' ' +
3368        namespacify('is', STATES.OPENING) + ' ' +
3369        namespacify('is', STATES.CLOSED) + ' ' +
3370        namespacify('is', STATES.OPENED));
3371    }
3372  };
3373
3374  /**
3375   * Special plugin object for instances
3376   * @public
3377   * @type {Object}
3378   */
3379  $[PLUGIN_NAME] = {
3380    lookup: []
3381  };
3382
3383  /**
3384   * Plugin constructor
3385   * @constructor
3386   * @param {Object} options
3387   * @returns {JQuery}
3388   */
3389  $.fn[PLUGIN_NAME] = function(opts) {
3390    var instance;
3391    var $elem;
3392
3393    this.each(function(index, elem) {
3394      $elem = $(elem);
3395
3396      if ($elem.data(PLUGIN_NAME) == null) {
3397        instance = new Remodal($elem, opts);
3398        $elem.data(PLUGIN_NAME, instance.index);
3399
3400        if (
3401          instance.settings.hashTracking &&
3402          $elem.attr('data-' + PLUGIN_NAME + '-id') === location.hash.substr(1)
3403        ) {
3404          instance.open();
3405        }
3406      } else {
3407        instance = $[PLUGIN_NAME].lookup[$elem.data(PLUGIN_NAME)];
3408      }
3409    });
3410
3411    return instance;
3412  };
3413
3414  $(document).ready(function() {
3415
3416    // data-remodal-target opens a modal window with the special Id
3417    $(document).on('click', '[data-' + PLUGIN_NAME + '-target]', function(e) {
3418      e.preventDefault();
3419
3420      var elem = e.currentTarget;
3421      var id = elem.getAttribute('data-' + PLUGIN_NAME + '-target');
3422      var $target = $('[data-' + PLUGIN_NAME + '-id="' + id + '"]');
3423
3424      $[PLUGIN_NAME].lookup[$target.data(PLUGIN_NAME)].open();
3425    });
3426
3427    // Auto initialization of modal windows
3428    // They should have the 'remodal' class attribute
3429    // Also you can write the `data-remodal-options` attribute to pass params into the modal
3430    $(document).find('.' + NAMESPACE).each(function(i, container) {
3431      var $container = $(container);
3432      var options = $container.data(PLUGIN_NAME + '-options');
3433
3434      if (!options) {
3435        options = {};
3436      } else if (typeof options === 'string' || options instanceof String) {
3437        options = parseOptions(options);
3438      }
3439
3440      $container[PLUGIN_NAME](options);
3441    });
3442
3443    // Handles the keydown event
3444    $(document).on('keydown.' + NAMESPACE, function(e) {
3445      if (current && current.settings.closeOnEscape && current.state === STATES.OPENED && e.keyCode === 27) {
3446        current.close();
3447      }
3448    });
3449
3450    // Handles the hashchange event
3451    $(window).on('hashchange.' + NAMESPACE, handleHashChangeEvent);
3452  });
3453});
3454
3455;
3456/* Top Navigation Plugin */
3457var topNavigation = {
3458
3459    iScrollPos: 0,
3460
3461    iScrollGifPosition: 0,
3462    currentScroll: 0,
3463    productBenefitGif1: '',
3464    productBenefitLength1: '',
3465    productBenefitGif2: '',
3466    productBenefitLength2: '',
3467    productBenefitGif3: '',
3468    productBenefitLength3: '',
3469    hasAnimated: false,
3470    isMobile: false,
3471    dragging: false,
3472    surpriseTextPos: 0,
3473    resizeTimer: 0,
3474
3475    windowWidth: $(window).width(),
3476
3477    configureTopSticky: function() {
3478        if ($('.surprise-text-show').is(':visible')) {
3479            topNavigation.surpriseTextPos = $('.surprise-text-start').position().top;
3480        }
3481
3482    },
3483    isIphone: function() {
3484        return (navigator.userAgent.match(/iPhone/i));
3485    },
3486    isTouchDevice: function() {
3487        return typeof window.ontouchstart !== 'undefined';
3488    },
3489    isIpad: function() {
3490        return (navigator.userAgent.match(/iPad/i));
3491    },
3492    isSafari: function() {
3493        return (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1 && navigator.userAgent.indexOf('Android') == -1);
3494    },
3495    stickyUpdateOrientation: function() {
3496        setTimeout(function() {
3497            topNavigation.surpriseTextPos = $('.surprise-text-start').position().top;
3498            var iCurScrollPos = window.pageYOffset;
3499            ribbon.stickyVisibleCondition(iCurScrollPos);
3500        }, 100);
3501    },
3502    enableDragging: function() {
3503
3504        $("body").on("touchmove", function() {
3505            topNavigation.dragging = true;
3506            $('.dropdown a.selectedLink').removeClass('selectedLink');
3507        });
3508
3509        $("body").on("touchend", function() {
3510            if (topNavigation.dragging) {
3511                topNavigation.dragging = false;
3512                return;
3513            }
3514        });
3515
3516        $('body').on("touchstart", function() {
3517            topNavigation.dragging = false;
3518        });
3519    },
3520    disableDragging: function() {
3521        $('body').off('touchend touchmove touchstart');
3522    },
3523    configureGif: function() {
3524        topNavigation.gifInitParams();
3525    },
3526
3527    configureGenericGif: function() {
3528        topNavigation.initGenricGifParams();
3529    },
3530
3531    gifInitParams: function() {
3532        if ($('.gif-position img').length) {
3533            var large_em_width = getEmPixels() * 64;
3534            if ($(window).width() < large_em_width || (($('.gif-position img')[0] !== undefined) && ($('.gif-position:nth-of-type(1)').attr('data-gif') == undefined))) {
3535                topNavigation.isMobile = true;
3536                $('.gif-position img').css('visibility', 'visible');
3537            } else {
3538                $('.gif-position img').css('visibility', 'visible');
3539                topNavigation.isMobile = false;
3540                topNavigation.iScrollGifPosition = $('.productBenefit').position().top;
3541                if ($('.gif-position')[0] !== undefined) {
3542                    topNavigation.productBenefitGif1 = $('.gif-position:nth-of-type(1)').attr('data-gif') + "?" + Math.random();
3543                    topNavigation.productBenefitLength1 = parseInt($('.gif-position:nth-of-type(1)').attr('data-length'), 10);
3544                }
3545                if ($('.gif-position')[1] !== undefined) {
3546                    topNavigation.productBenefitGif2 = $('.gif-position:nth-of-type(2)').attr('data-gif') + "?" + Math.random();
3547                    topNavigation.productBenefitLength2 = parseInt($('.gif-position:nth-of-type(2)').attr('data-length'), 10);
3548                }
3549                if ($('.gif-position')[2] !== undefined) {
3550                    topNavigation.productBenefitGif3 = $('.gif-position:nth-of-type(3)').attr('data-gif') + "?" + Math.random();
3551                    topNavigation.productBenefitLength3 = parseInt($('.gif-position:nth-of-type(3)').attr('data-length'), 10);
3552                }
3553            }
3554        }
3555    },
3556
3557    initGenricGifParams: function() {
3558
3559        var medium_em_width = getEmPixels() * 39.9375;
3560        $('.parent-gif-track').each(function(index) {
3561            var parent_gif_track = $(this);
3562            parent_gif_track.children('.gen-gif-position').each(function(index1) {
3563                var gen_gif = $(this);
3564                if ($(window).width() < medium_em_width || (($('.gen-gif-position img')[0] !== undefined) && ($('.gen-gif-position:nth-of-type(1)').attr('data-gif') == undefined))) {
3565                    topNavigation.isMobile = true;
3566                    gen_gif.children('.imagebox-medium-up').css('display', 'none');
3567                    gen_gif.children('.imagebox-small-only').css('display', 'block');
3568                } else {
3569                    gen_gif.children('.imagebox-medium-up').css('display', 'block');
3570                    gen_gif.children('.imagebox-small-only').css('display', 'none');
3571
3572                    gen_gif.children('.imagebox-medium-up').css('visibility', 'visible');
3573                    topNavigation.isMobile = false;
3574                }
3575
3576            });
3577        });
3578
3579    },
3580
3581    configureTopNavigation: function() {
3582        $('a.hamburger').on('click', function() {
3583            topNavigation.hamburgerClick(this);
3584        });
3585        $('.mainClose').on('click', function() {
3586            topNavigation.mainCloseClick();
3587        });
3588        $('.largeIcon').on('click', function() {
3589            topNavigation.largeIconClick();
3590        });
3591        $('.back-menu-span').on('click', function () {
3592            topNavigation.backToMenuClick(this);
3593        });
3594        $('.backToClose').off('click');
3595        /*$('.desktopMenu li > a').on('click', function () {
3596         topNavigation.desktopMenuLiClick(this);
3597     });*/
3598        if ($(window).width() > 929) {
3599            topNavigation.desktopMenuLiBind();
3600            topNavigation.windowOnLoadStart();
3601        } else {
3602            $('.desktopMenu li > a').on('click', function() {
3603                topNavigation.desktopMenuLiClick(this);
3604            });
3605        }
3606
3607        $(window).resize(function() {
3608            if ($(window).width() !== topNavigation.windowWidth) {
3609                topNavigation.windowWidth = $(window).width();
3610                topNavigation.topNavigationOnResize();
3611                topNavigation.windowOnLoadStart();
3612                if ($('.surprise-text-hidden').length) {
3613                    topNavigation.stickyUpdateOrientation();
3614                }
3615                if ((($('.gif-position')[0] !== undefined) && ($('.gif-position:nth-of-type(1)').attr('data-gif') != undefined && $('.gif-position:nth-of-type(1)').attr('data-gif').indexOf(".gif") != -1))) {
3616                    topNavigation.configureGif();
3617                    if (topNavigation.isElementInViewport($('.productBenefit'))) {
3618                        topNavigation.animateGifStart();
3619                    }
3620                    if ((($('.gen-gif-position')[0] !== undefined) && ($('.gif-position:nth-of-type(1)').attr('data-gif') != undefined && $('.gif-position:nth-of-type(1)').attr('data-gif').indexOf(".gif") != -1))) {
3621                        topNavigation.configureGenericGif();
3622                    }
3623                }
3624                topNavigation.invokeEffects();
3625            }
3626        });
3627
3628        $(document).on('scroll',window,function(){
3629            topNavigation.topNavigationOnScroll(this);
3630            clearTimeout( $.data( this, "scrollCheck" ) );
3631            $.data(this, "scrollCheck", setTimeout(function() {
3632                if ($('.surprise-text-hidden').length) {
3633                    ribbon.stickyVisibleCondition(window.pageYOffset);
3634                }
3635            }, 100));
3636        });
3637
3638        topNavigation.forEachULDesktopMenuChildren();
3639        topNavigation.invokeEffects();
3640
3641        if(homePageVideo.ElementExist($('#loginBox')) && homePageVideo.ElementExist($('#loginBox .secondaryBtn'))) {
3642            $(document).on('click','#loginBox .secondaryBtn', function(e) {
3643                e.stopPropagation();
3644                if(!$('a.hamburger').hasClass('pressed')) {
3645                    $('body').removeClass('videoNoScroll stopScroll');
3646                    $('.topNav').removeClass('topLinksPosition');
3647                    $('body').css('position', '');
3648                    $('.overlayWhite').css({ height: 0 });
3649                    $('.progressContainerBox').removeClass('force-hide-ribbon');
3650                    $('.progressContainerBox').removeClass('ribbon-hide-scroll');
3651                }
3652            });
3653        }
3654    },
3655    invokeEffects : function () {
3656        // PL - 625
3657        /**
3658         * 'Block contains the event handler callbacks for events'
3659         */
3660
3661        function dropdownTouchLiA(e) {
3662            e.stopPropagation();
3663            var that = $(e.target);
3664            if (!topNavigation.dragging) {
3665                if ($(that).is('li')) {
3666                    $('.dropdown a.selectedLink').removeClass('selectedLink');
3667                    topNavigation.add($(that).children(), 'selectedLink');
3668                }
3669                if ($(that).is('span')) {
3670                    $('.dropdown a.selectedLink').removeClass('selectedLink');
3671                    topNavigation.add($(that).parent(), 'selectedLink');
3672                } else {
3673                    $('.dropdown a.selectedLink').removeClass('selectedLink');
3674                    topNavigation.add($(that), 'selectedLink');
3675                }
3676            }
3677        }
3678
3679        function dropdownNoSubMenu(e) {
3680            e.stopPropagation();
3681            var that = $(e.target);
3682            if(!$(this).hasClass('subMenu')) {
3683                if ($(that).is('li')) {
3684                    $('.dropdown a.selectedLink').removeClass('selectedLink');
3685                    topNavigation.add($(that).children(), 'selectedLink');
3686                }
3687                if ($(that).is('span')) {
3688                    $('.dropdown a.selectedLink').removeClass('selectedLink');
3689                    topNavigation.add($(that).parent(), 'selectedLink');
3690                } else {
3691                    $('.dropdown a.selectedLink').removeClass('selectedLink');
3692                    topNavigation.add($(that), 'selectedLink');
3693                }
3694            }
3695        }
3696
3697        function dropdownNoSubMenuLarge(e) {
3698            e.stopPropagation();
3699            if(!$(this).hasClass('subMenu')) {
3700                $('.dropdown a.selectedLink').removeClass('selectedLink');
3701                topNavigation.add($(this), 'selectedLink');
3702            }
3703        }
3704
3705        function stopPropagations(e) {
3706            e.stopPropagation();
3707        }
3708
3709        // Callback Block end
3710
3711        /**
3712         * 'Removing previous events before invoking (to prevent stacking)'
3713         */
3714
3715        (function() {
3716            $('.dropdown li a').off('touchstart.dropdownTouchLiA');
3717            $('.dropdown > li a').off('touchstart.dropdownNoSubMenu click.dropdownNoSubMenuLarge');
3718            $('.desktopMenu li a').off('mouseenter mouseleave');
3719            $('.dropdown li').off('click.stopPropagation');
3720        })();
3721
3722        // Stacking Prevention ends
3723
3724        /**
3725         * 'Events for Navigation links'
3726         */
3727
3728        $('.dropdown li').on('click.stopPropagation', stopPropagations);
3729
3730        if (topNavigation.isIphone() || topNavigation.isIpad() || topNavigation.isTouchDevice()) {
3731
3732            if ($(window).width() < 930) {
3733                $('.dropdown li a').on('touchstart.dropdownTouchLiA', dropdownTouchLiA);
3734            } else {
3735                $('.dropdown > li a').on('touchstart.dropdownNoSubMenu', dropdownNoSubMenu);//Call on only nodropdown a tag for non i-devices
3736            }
3737        } else {
3738            $('.dropdown > li a').on('click.dropdownNoSubMenuLarge', dropdownNoSubMenuLarge); //Call on only nodropdown a tag for non i-devices
3739            $('.desktopMenu li a').hover(
3740                function() { //callback when hover binds
3741                    topNavigation.add($(this), 'selectedhover');
3742                },
3743                function() { //Callback when hover unbinds
3744                    topNavigation.remove($(this), 'selectedhover');
3745                }
3746            );
3747        }
3748        // Events Block Ends
3749        // PL - 625 Ends
3750    },
3751
3752    desktopMenuLiBind: function() {
3753        var menuAnchor = $('.desktopMenu li > a');
3754
3755        function bindLiHandler() {
3756            menuAnchor.off('click', bindLiHandler);
3757            topNavigation.desktopMenuLiClick(this);
3758            reinit();
3759        }
3760
3761        function reinit() {
3762            setTimeout(function(){
3763                menuAnchor.on('click', bindLiHandler);
3764            }, 600);
3765        }
3766
3767        menuAnchor.on('click', bindLiHandler);
3768    },
3769
3770    add: function(element, clickClass) {
3771        element.addClass(clickClass);
3772    },
3773
3774    remove: function(element, clickClass) {
3775        element.removeClass(clickClass);
3776    },
3777
3778    invokeLoginCTATouchFunction: function() {
3779        /**
3780         * PL - 634
3781         */
3782        $('.dropdown li.professionalsCTALinks a').off('touchstart');
3783        $('.dropdown li.professionalsCTALinks a').on('touchstart', function() {
3784            if (!topNavigation.dragging) { topNavigation.add($(this), 'selectedLink'); }
3785        });
3786        // PL - 634 Ends
3787    },
3788
3789    revokeLoginCTATouchFunction: function() {
3790        /**
3791         * PL - 634
3792         */
3793        $('.dropdown li.professionalsCTALinks a').off('touchstart');
3794        // PL - 634 Ends
3795    },
3796
3797    hamburgerClick: function(hamburgerObj) {
3798        /**
3799         * PL - 461
3800         */
3801
3802        //$(window).unbind("scroll");
3803
3804        // 461 - Ends
3805        topNavigation.getScrollingBehaviour();
3806        $('body').removeClass('stopScroll');
3807        $('body').addClass('stopScroll');
3808        if ($(window).width() < 930) {
3809            $('.search_icon').hide();
3810            if($('.simplifiedNav').length && topNavigation.isIphone() && $('ul.desktopMenu > li').length <=2) {
3811                setTimeout(function() {
3812                    $('.backToClose').on('click', function() {
3813                        topNavigation.backToCloseClick();
3814                    });
3815                }, 500);
3816            } else {
3817                $('.overlayWhite').animate({ height: 100 + '%' }, {
3818                complete: function() {
3819                    topNavigation.isIphone() && $('.overlayWhite').css('height', 0);
3820                    $('.backToClose').on('click', function() {
3821                        topNavigation.backToCloseClick();
3822                    });
3823                }
3824            }, 500);
3825            }
3826        }
3827        $('.profCTA').toggleClass('showText');
3828        $('.desktopMenu').addClass('menuToggle');
3829        $(hamburgerObj).addClass('pressed');
3830        $('a.hamburger').next().show();
3831        $('.topNav').addClass('animated');
3832
3833        var windowHeight = window.innerHeight - 55;
3834        $('ul.desktopMenu').css('height', windowHeight);
3835        $('body').css('position', 'fixed');
3836        topNavigation.insertLoginCTA();
3837        topNavigation.enableDragging();
3838
3839        if(/iPhone/i.test(navigator.userAgent)) {
3840            topNavigation.iphoneAddressBarFix();
3841            $(window).on('orientationchange.iphoneAddressOrientation', function() {
3842                //do whatever, or reload site
3843                topNavigation.iphoneAddressBarFix();
3844            });
3845        }
3846
3847        $('.progressContainerBox').hide();
3848        $('.progressContainerBox').addClass('force-hide-ribbon');
3849        // Let the interaction happen before deciding sticky nav
3850        if ($(window).width() < 929) {
3851            if ($('.surprise-text-hidden').length) {
3852                var iCurScrollPos = window.pageYOffset;
3853                ribbon.stickyVisibleCondition(iCurScrollPos);
3854                $('.updated-background-sticky').hide();
3855            }
3856        }
3857
3858    },
3859    iphoneAddressBarFix: function (checkFlag) {
3860        if (window.orientation === 90 || window.orientation === -90) {
3861            $(window).off('scroll.iphoneAddressScroll');
3862            setTimeout(function(){
3863                var windowHeight = window.innerHeight - 55;
3864                $('ul.desktopMenu').animate('height', windowHeight);
3865                var scrollTest = $(window).scrollTop();
3866                $(window).on('scroll.iphoneAddressScroll', function (e) {
3867                    var st = $(this).scrollTop();
3868                    if (st > scrollTest) {
3869                        var windowHeight = window.innerHeight;
3870                        $('ul.desktopMenu').animate('height', windowHeight);
3871                    } else {
3872                        var windowHeight = window.innerHeight - 55;
3873                        $('ul.desktopMenu').animate('height', windowHeight);
3874                    }
3875                });
3876            },700);
3877        } else {
3878            $(window).off('scroll.iphoneAddressScroll');
3879        }
3880    },
3881    getScrollingBehaviour: function() {
3882        // PL - 461
3883        topNavigation.currentScroll = window.pageYOffset || document.documentElement.scrollTop;
3884        // PL - 461 : Ends
3885    },
3886    setScrollingBehaviour: function() {
3887        // PL - 461
3888        window.scrollTo(0, topNavigation.currentScroll);
3889        // PL - 461 : Ends
3890    },
3891    mainCloseClick: function() {
3892        $('.mainClose').hide();
3893        $('.loginField').hide();
3894        $('.desktopMenu').removeClass('menuToggle');
3895        $('body').removeClass('stopScroll');
3896        $('.desktopMenu').removeClass('showMenuUL');
3897        $('body').css('position', '');
3898        $('a.hamburger').removeClass('pressed');
3899        topNavigation.disableDragging();
3900
3901        setTimeout(function() {
3902            if ($('.surprise-text-hidden').length) {
3903                var iCurScrollPos = window.pageYOffset;
3904                ribbon.stickyVisibleCondition(iCurScrollPos);
3905                $('.surprise-text-hidden').show();
3906                $('.progressContainerBox').show();
3907                $('.progressContainerBox').removeClass('force-hide-ribbon');
3908            }
3909        }, 50);
3910
3911    },
3912
3913    backToCloseClick: function() {
3914        $('.mainClose').hide();
3915        $('.loginField').hide();
3916        if ($(window).width() < 929) {
3917            $('.search_icon').show();
3918        }
3919        $(window).off('scroll.iphoneAddressScroll');
3920        $(window).off('orientationchange.iphoneAddressOrientation');
3921        $('.profCTA').toggleClass('showText');
3922        $('.desktopMenu').removeClass('menuToggle');
3923        $('li.active a').removeClass("selectedLink");
3924        $(' li.active').removeClass('active');
3925        $('body').removeClass('stopScroll');
3926        $('body').removeClass('videoNoScroll');
3927        $('a.hamburger').removeClass('pressed');
3928        $('.desktopMenu').removeClass('showMenuUL');
3929        $('.profCTA').removeClass('showText');
3930        $('.overlayWhite').css({ height: 0 });
3931        $('ul.desktopMenu').find('li').each(function() {
3932            $(this).removeClass('hideForMobile');
3933            $(this).find('a').removeClass('hideForMobile');
3934        });
3935        topNavigation.removeLoginCTA();
3936        //topNavigation.revokeLoginCTATouchFunction();
3937
3938        ribbon.ribonVisibleCondition(false, true);
3939
3940
3941        $('body').css('position', '');
3942        topNavigation.removeAnimation();
3943        topNavigation.setScrollingBehaviour();
3944        setTimeout(function() {
3945            if ($(window).width() > 639) {
3946                $('.progressContainerBox').show();
3947                $('.progressContainerBox').removeClass('force-hide-ribbon');
3948            }
3949            if ($('.surprise-text-hidden').length) {
3950                var iCurScrollPos = window.pageYOffset;
3951                ribbon.stickyVisibleCondition(iCurScrollPos);
3952                $('.surprise-text-hidden').show();
3953
3954            }
3955        }, 50);
3956        $('.backToClose').off('click');
3957    },
3958
3959    largeIconClick: function() {
3960        $('.desktopMenu > li').removeClass('active');
3961        topNavigation.backToMenuClick($('.back-menu-span'));
3962        topNavigation.removeLoginCTA();
3963        $('.mainClose').hide();
3964        $('.search_icon').show();
3965        $('.desktopMenu').removeClass('menuToggle');
3966        $('.desktopMenu').removeClass('showMenuUL');
3967        $('body').removeClass('videoNoScroll');
3968        $('ul.desktopMenu').find('li').each(function() {
3969            $(this).removeClass('hideForMobile');
3970            $(this).find('a').removeClass('hideForMobile');
3971        });
3972        $('body').css('position', '');
3973        $('a.hamburger').removeClass('pressed');
3974        topNavigation.removeAnimation();
3975        // For Touch device only forcing set Scroll.
3976        if(topNavigation.isTouchDevice()) {
3977           $('body').off('touchmove.stopScroll');
3978           topNavigation.setScrollingBehaviour();
3979        }
3980        $('.progressContainerBox').show();
3981        $('.progressContainerBox').removeClass('force-hide-ribbon');
3982        ribbon.ribonVisibleCondition(false, true);
3983        if ($('.surprise-text-hidden').length) {
3984            $('.surprise-text-hidden').show();
3985            $('.surprise-text-hidden').css('top', '');
3986            $('.surprise-text-hidden').removeClass('top-147-animate-surprise');
3987            $('.surprise-text-hidden').removeClass('top-107-animate-surprise');
3988            $('.surprise-text-hidden').removeClass('updated-background-sticky');
3989        }
3990
3991    },
3992
3993    backToMenuClick: function(backToMenuObject) {
3994        var currentVisibleUl = $('.desktopMenu').find('.tracking');
3995        currentVisibleUl.removeClass('tracking');
3996        var parentLi = currentVisibleUl.parent().parent();
3997        parentLi.removeClass('active');
3998        parentLi.siblings().removeClass('hideForMobile');
3999        var parentUl = parentLi.parent();
4000        parentUl.children('li').children('a').removeClass('hideForMobile');
4001        parentUl.children('li').children('a').removeClass('selectedLink');
4002        parentUl.addClass('tracking');
4003    },
4004    bindEvent: function(selector, event) {
4005        selector.on(event, function() {
4006            topNavigation.add($(this), 'selectedLink');
4007        });
4008    },
4009    unbindEvent: function(selector, event) {
4010        selector.off(event);
4011    },
4012    desktopMenuLiClick: function (desktopMenuLiObj) {
4013        var that = $(desktopMenuLiObj);
4014        if($(that).parent().hasClass('not-desktop-li')) {
4015            setTimeout(function () {
4016                new Foundation.Reveal($('#loginBox')).open();
4017                revealCenterAlign.revealRePosition();
4018            }, 10);
4019
4020            if (topNavigation.isIpad() || topNavigation.isIphone() || topNavigation.isTouchDevice()) {
4021                $('body').addClass('videoNoScroll');
4022            }
4023
4024            setTimeout(function () {
4025                topNavigation.remove($(that), 'selectedLink');
4026                if ($(window).width() > 929) {
4027                    $('.topNav').removeClass('topLinksPosition');
4028                }
4029            }, 500);
4030
4031        } else {
4032            setTimeout(function() {
4033                var isActive = $(that).parent().hasClass('active');
4034                var subMenu = $(that).parent().children('a.subMenu');
4035                var subMenuMobile = $(that).parent().children('a.subMenuMobile');
4036                if (!isActive) {
4037                    // For Touch device only forcing set Scroll.
4038                    if(topNavigation.isTouchDevice()) {
4039                        topNavigation.getScrollingBehaviour();
4040                    }
4041                    $('a.hamburger').addClass('pressed');
4042                    $('.progressContainerBox').hide();
4043                    $('.progressContainerBox').addClass('force-hide-ribbon');
4044                    $('.dropdown li a.selectedLink').removeClass('selectedLink');
4045                    if ($('.surprise-text-hidden').length) {
4046                        $('.updated-background-sticky').hide();
4047                        $('.surprise-text-hidden').css('top', '');
4048                        $('.surprise-text-hidden').removeClass('top-147-animate-surprise');
4049                        $('.surprise-text-hidden').removeClass('top-107-animate-surprise');
4050                        $('.surprise-text-hidden').removeClass('updated-background-sticky');
4051                    }
4052
4053                    if ($(window).width() > 929) {
4054                        $('.desktopMenu li.active').removeClass('active');
4055
4056                    }
4057                    if ($(window).width() < 930) {
4058                        $(that).parent().addClass('active');
4059                    }
4060
4061                    $('.desktopMenu').addClass('showMenuUL');
4062
4063                    $('.desktopMenu').show();
4064
4065                    if ((subMenu.length >= 1) || (subMenuMobile.length >= 1)) {
4066                        $(that).parent().removeClass('hideForMobile').addClass('active');
4067                        if ($(window).width() < 929) {
4068                            $('body').css('position', 'fixed');
4069                            var windowHeight = $(window).height() - 55;
4070                            var menuUl = $('.desktopMenu').children().children('div');
4071                            menuUl.css('height', windowHeight);
4072                            menuUl.find('.menuSection').css('height', windowHeight);
4073                        }
4074                        var childList = $(that).parent().children('div').children('ul');
4075                        $(that).parent().parent().removeClass('tracking');
4076                        childList.removeClass('hideForMobile').addClass('tracking');
4077
4078                        $('.desktopMenu > li').each(function() {
4079                            $(this).removeClass('hideForMobile');
4080                            if (!$(this).hasClass('active')) {
4081                                $(this).addClass('hideForMobile');
4082                            }
4083                        });
4084
4085                        $(that).parent().children('a').addClass('hideForMobile');
4086
4087                        topNavigation.addAnimation();
4088                    } else {
4089                        topNavigation.removeAnimation();
4090                    }
4091                } else {
4092                    $('a.hamburger').removeClass('pressed');
4093                    $('.dropdown li a.selectedLink').removeClass('selectedLink');
4094                    $('.desktopMenu li.active').removeClass('active');
4095                    topNavigation.largeIconClick();
4096                    topNavigation.removeAnimation();
4097                    $('.progressContainerBox').show();
4098                    $('.progressContainerBox').removeClass('force-hide-ribbon');
4099                    ribbon.ribonVisibleCondition(false, true);
4100
4101                    $('body').removeClass('stopScroll videoNoScroll');
4102                    $('body').css('position', '');
4103                    $('a.hamburger').removeClass('pressed');
4104                    // For Touch device only forcing set Scroll.
4105                    if(topNavigation.isTouchDevice()) {
4106                        topNavigation.setScrollingBehaviour();
4107                    }
4108                    if ($('.surprise-text-hidden').length) {
4109                        $('.surprise-text-hidden').show();
4110                        $('.surprise-text-hidden').css('top', '');
4111                        $('.surprise-text-hidden').removeClass('top-147-animate-surprise');
4112                        $('.surprise-text-hidden').removeClass('top-107-animate-surprise');
4113                        $('.surprise-text-hidden').removeClass('updated-background-sticky');
4114                        var iCurScrollPos = window.pageYOffset;
4115                        ribbon.stickyVisibleCondition(iCurScrollPos);
4116                    }
4117                }
4118            });
4119        }
4120
4121    },
4122
4123    addAnimation: function() {
4124        $('body').addClass('stopScroll');
4125        if(window.navigator.platform === 'win32') {
4126            $('body').addClass('nav-scroll-stop-fixed');
4127        }
4128
4129        if ($(window).width() > 929) {
4130            if(topNavigation.isTouchDevice()) {
4131                $('body').on('touchmove.stopScroll', function(e){e.preventDefault()});
4132            }
4133            $('.overlayWhite').animate({ height: 100 + '%' }, 500, function() {
4134                if(topNavigation.isTouchDevice()) {
4135                    $('body').css('position','fixed');
4136                    $('body').off('touchmove.stopScroll');
4137                }
4138            });
4139            $('.topNav').addClass('animated');
4140            if (homePageVideo.ElementExist($('.topCTA-links > p')) && $('.topNav').hasClass('show-nicely-60')) {
4141                $('.topNav').addClass('topLinksPosition');
4142            }
4143        }
4144    },
4145
4146    removeAnimation: function() {
4147
4148        $('body').off('touchmove.stopScroll');
4149        if(window.navigator.platform === 'win32') {
4150            $('body').removeClass('nav-scroll-stop-fixed');
4151        }
4152        if ($(window).width() > 929) {
4153            if ($('.topNav').hasClass('animated')) {
4154                $('.overlayWhite').animate({ height: 0 }, 500);
4155                $('.topNav').removeClass('animated');
4156                $('body').removeClass('stopScroll');
4157                $('body').removeClass('nav-scroll-stop-fixed');
4158                if (homePageVideo.ElementExist($('.topCTA-links > p'))) {
4159                    $('.topNav').removeClass('topLinksPosition');
4160                }
4161
4162            }
4163        }
4164    },
4165
4166    insertLoginCTA: function() {
4167        /**
4168         * PL - 634
4169         */
4170        $('#top-nav-append-template').find('.professionalsCTALinks').remove(); // Calling this maintain the order of li
4171        if ($('.topCTA-links').find('p').length > 0) {
4172            var anchorHTML = '<span>' + $('.topCTA-links').find('p').find('a').text() + '</span>';
4173            $('.topCTA-links').find('p').find('a').html(anchorHTML);
4174            var profesionalCTABox = $('.topCTA-links').find('p').html();
4175            var insertLiProfessionalWrapper = $('<li class="professionalsCTALinks">' + profesionalCTABox + '</li>');
4176            $('#top-nav-append-template').last().append(insertLiProfessionalWrapper);
4177            topNavigation.invokeLoginCTATouchFunction();
4178        }
4179        // PL - 634 Ends
4180    },
4181
4182    removeLoginCTA: function() {
4183        /**
4184         * PL - 634
4185         */
4186        $('#top-nav-append-template').find('.professionalsCTALinks').remove();
4187        topNavigation.revokeLoginCTATouchFunction();
4188        $('.scrollBarMobile').css('height', '');
4189        // PL - 634 Ends
4190    },
4191
4192    topNavigationOnResize: function() {
4193
4194        isMobileSafari=false;
4195        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
4196            isMobileSafari = true;
4197        }
4198
4199        if (($('#player').is(':visible') || $('#genericVideoBox').is(':visible')) && (isMobileSafari == true)) {
4200            return false;
4201        }
4202
4203        if (($('#player').is(':visible') || $('#genericVideoBoxAdvisor').is(':visible')) && (isMobileSafari == true)) {
4204            return false;
4205        }
4206
4207        if ($(window).width() > 929) {
4208            if ($('a.hamburger').hasClass('pressed')) {
4209                var iCurScrollPos = window.pageYOffset;
4210                ribbon.stickyVisibleCondition(iCurScrollPos);
4211                $('.progressContainerBox').removeClass('force-hide-ribbon');
4212            }
4213
4214            if ($('.desktopMenu li').is('.active')) {
4215                $('.overlayWhite').addClass('fixed');
4216                $('.overlayWhite').css({height: 100 + '%'});
4217                $('body').addClass('stopScroll');
4218                $('.topNav').addClass('animated');
4219                if (homePageVideo.ElementExist($('.topCTA-links > p'))) {
4220                    $('.topNav').addClass('topLinksPosition');
4221                }
4222                //$('.topNav').addClass('topLinksPosition');
4223                if (/Android|iPhone|iPad/i.test(navigator.userAgent)) {
4224                    $('body').css('position', 'fixed');
4225                }
4226            } else {
4227                $('body').css('position', '');
4228                $('body').removeClass('stopScroll videoNoScroll');
4229                $('.overlayWhite').css({height: 0});
4230                $('.desktopMenu').removeClass('showMenuUL');
4231
4232            }
4233            topNavigation.removeLoginCTA();
4234        } else {
4235
4236            if($('body').hasClass('is-reveal-open') || $('.desktopMenu li').is('.active')) {
4237                $('body').addClass('videoNoScroll');
4238            }
4239
4240            if ($('a.hamburger').hasClass('pressed')) {
4241                $('body').css('position', 'fixed');
4242                var windowHeight = $(window).height() - 55;
4243                $('ul.desktopMenu').css('height', windowHeight);
4244                var windowHeight = $(window).height() - 55;
4245                var menuUl = $('.desktopMenu').children().children('div');
4246                menuUl.css('height', windowHeight);
4247                menuUl.find('.menuSection').css('height', windowHeight);
4248                topNavigation.insertLoginCTA();
4249                $('.mainClose').show();
4250                $('.backToClose').off('click').on('click', function() {
4251                    topNavigation.backToCloseClick();
4252                });
4253
4254
4255            } else {
4256                if(!$('.header-container').length) {
4257                    $('body').css('position', '');
4258                    $('.backToClose').off('click');
4259                }
4260            }
4261
4262        }
4263    },
4264
4265    topNavigationOnScroll: function(scrollObject) {
4266
4267        if ($('.videoPlayer').is(':visible') || $('#genericVideoBox').is(':visible')) {
4268            return false;
4269        }
4270
4271        if ($('.videoPlayer').is(':visible') || $('#genericVideoBoxAdvisor').is(':visible')) {
4272            return false;
4273        }
4274
4275        var iCurScrollPos = window.pageYOffset;
4276
4277        if ($('.gif-position').length && !topNavigation.isMobile && !topNavigation.hasAnimated) {
4278            if (topNavigation.isElementInViewport($('.productBenefit .btn-bottom'))) {
4279                topNavigation.hasAnimated = true;
4280                topNavigation.animateGifStart();
4281            }
4282        }
4283
4284        $('.parent-gif-track').each(function(index) {
4285            if (!topNavigation.isMobile && $(this).attr("data-has-animated") == "false") {
4286                var trigger = '';
4287                var trigger_element = '';
4288                if ($(this).attr('data-cta-trigger') == "true") {
4289                    trigger = '.animated-cta-gif';
4290                    trigger_element = $(this).parent('.animated-gif-parent-cont').find(trigger).eq(0);
4291                } else {
4292                    trigger = '.animated-desc-gif';
4293                    trigger_element = $(this).find(trigger).eq(0);
4294                }
4295                if (topNavigation.isElementInViewport(trigger_element)) {
4296                    $(this).attr("data-has-animated", "true")
4297                    topNavigation.animateGenGifStart($(this));
4298                    topNavigation.animateGifStart();
4299                }
4300            }
4301        });
4302
4303        topNavigation.topNavReadjust(iCurScrollPos);
4304
4305
4306
4307        // After a youtube video exits fullscreen, it forces a scroll on document.
4308        // This code is to ensure that video code doesn't interfere with any other code.
4309        if ($('.videoPlayer').is(':visible') || $('#genericVideoBox').is(':visible')) {
4310            homePageVideo.HPHVResize();
4311        }
4312
4313        if ($('.videoPlayer').is(':visible') || $('#genericVideoBoxAdvisor').is(':visible')) {
4314            homePageVideo.HPHVResize();
4315        }
4316
4317        if ($('.surprise-text-hidden').length) {
4318            ribbon.stickyVisibleCondition(iCurScrollPos);
4319        }
4320
4321
4322        topNavigation.iScrollPos = iCurScrollPos;
4323
4324    },
4325
4326    topNavReadjust: function(iCurScrollPos) {
4327
4328        if (iCurScrollPos > topNavigation.iScrollPos) {
4329            if (iCurScrollPos > 75) {
4330                $('.scrollTop').removeClass('hide-nicely-no');
4331                $('.scrollTop').addClass('hide-nicely');
4332
4333                $('.logoLarge').removeClass('show');
4334                $('.logoLarge').addClass('hide');
4335
4336                $('.logoSmall').removeClass('hide');
4337                $('.logoSmall').addClass('show');
4338
4339                $('.topNav').removeClass('show-nicely-60');
4340                $('.topNav').addClass('show-nicely');
4341            }
4342        } else {
4343
4344            $('.topNav').removeClass('show-nicely');
4345        }
4346
4347        if (iCurScrollPos < 75) {
4348
4349            if ($(window).width() > 929) {
4350                if(!$('.desktopMenu').hasClass('showMenuUL')) {
4351                    $('.topNav').addClass('show-nicely-60');
4352                    $('.scrollTop').removeClass('hide-nicely').addClass('hide-nicely-no');
4353                    $('.logoSmall').removeClass('show').addClass('hide');
4354
4355                    $('.logoLarge').removeClass('hide').addClass('show');
4356                }
4357            } else {
4358                $('.scrollTop').addClass('hide-nicely');
4359                $('.scrollTop').removeClass('hide-nicely-no');
4360            }
4361        } else {
4362
4363            $('.scrollTop').addClass('hide-nicely');
4364            $('.scrollTop').removeClass('hide-nicely-no');
4365            $('.logoSmall').removeClass('hide');
4366            $('.logoSmall').addClass('show');
4367            $('.logoLarge').addClass('hide');
4368            $('.logoLarge').removeClass('show');
4369
4370        }
4371    },
4372
4373    isElementInViewport: function(el) {
4374
4375        //special bonus for those using jQuery
4376        if (typeof jQuery === "function" && el instanceof jQuery) {
4377            el = el[0];
4378        }
4379
4380        var rect = el.getBoundingClientRect();
4381
4382        //The comment below needs to be kept so we update if the trigger point is changed again.
4383        return (
4384            // rect.top <= $('.topNav').outerHeight(true) &&
4385            rect.top >= 0 &&
4386            rect.left >= 0 &&
4387            rect.bottom <= window.innerHeight &&
4388            rect.right <= $(window).width()
4389        );
4390    },
4391
4392    animateGenGifStart: function(element) {
4393        var length1 = 0;
4394        var length2 = 0;
4395        var length3 = 0;
4396        if (element.children('.gen-gif-position').eq(0).length) {
4397            length1 = parseInt(element.children('.gen-gif-position').eq(0).attr('data-length'), 10);
4398        }
4399        if (element.children('.gen-gif-position').eq(1).length) {
4400            length2 = parseInt(element.children('.gen-gif-position').eq(1).attr('data-length'), 10);
4401        }
4402        if (element.children('.gen-gif-position').eq(2).length) {
4403            length3 = parseInt(element.children('.gen-gif-position').eq(2).attr('data-length'), 10);
4404        }
4405        setTimeout(function() {
4406            if (length1 != 0) {
4407                var gif_source = element.children('.gen-gif-position').eq(0).attr('data-gif') + "?" + Math.random();
4408                element.children('.gen-gif-position').eq(0).children('.imagebox-medium-up').css("visibility", "visible");
4409                element.children('.gen-gif-position').eq(0).children('.imagebox-medium-up').attr("src", gif_source);
4410            }
4411        }, 1);
4412
4413        if (length1 != 0) {
4414            setTimeout(function() {
4415                if (length2 != 0) {
4416                    var gif_source = element.children('.gen-gif-position').eq(1).attr('data-gif') + "?" + Math.random();
4417                    element.children('.gen-gif-position').eq(1).children('.imagebox-medium-up').css("visibility", "visible");
4418                    element.children('.gen-gif-position').eq(1).children('.imagebox-medium-up').attr("src", gif_source);
4419                }
4420            }, length1);
4421        }
4422
4423
4424        if (length2 != 0) {
4425            setTimeout(function() {
4426                if (length3 != 0) {
4427                    var gif_source = element.children('.gen-gif-position').eq(2).attr('data-gif') + "?" + Math.random();
4428                    element.children('.gen-gif-position').eq(2).children('.imagebox-medium-up').css("visibility", "visible");
4429                    element.children('.gen-gif-position').eq(2).children('.imagebox-medium-up').attr("src", gif_source);
4430                }
4431            }, length1 + length2);
4432        }
4433
4434    },
4435
4436    animateGifStart: function() {
4437        setTimeout(function() {
4438            if ($('.gif-position img')[0] !== undefined) {
4439                $('.gif-position img')[0].style.height = "90px";
4440                $('.gif-position img')[0].style.visibility = "visible";
4441                $('.gif-position img')[0].src = topNavigation.productBenefitGif1;
4442            }
4443        }, 1);
4444
4445        setTimeout(function() {
4446            if ($('.gif-position img')[1] !== undefined) {
4447                $('.gif-position img')[1].style.height = "90px";
4448                $('.gif-position img')[1].style.visibility = "visible";
4449                $('.gif-position img')[1].src = topNavigation.productBenefitGif2;
4450            }
4451        }, topNavigation.productBenefitLength1);
4452        setTimeout(function() {
4453            if ($('.gif-position img')[2] !== undefined) {
4454                $('.gif-position img')[2].style.height = "90px";
4455                $('.gif-position img')[2].style.visibility = "visible";
4456                $('.gif-position img')[2].src = topNavigation.productBenefitGif3;
4457            }
4458        }, (topNavigation.productBenefitLength1 + topNavigation.productBenefitLength2));
4459    },
4460
4461    windowOnLoadStart: function() {
4462
4463        var iScrollPostion = window.pageYOffset;
4464        if (iScrollPostion < 75) {
4465            if ($(window).width() > 929) {
4466                if(!$('.desktopMenu').hasClass('showMenuUL')) {
4467                    $('.topNav').addClass('show-nicely-60');
4468                    $('.topNav').show();
4469                    $('.scrollTop').removeClass('hide-nicely').addClass('hide-nicely-no');
4470                    $('.logoSmall').removeClass('show').addClass('hide');
4471                    $('.logoLarge').removeClass('hide').addClass('show');
4472                }
4473
4474            } else {
4475                $('.topNav').show().removeClass('show-nicely-60');
4476                $('.scrollTop').removeClass('hide-nicely').addClass('hide-nicely-no');
4477
4478            }
4479        } else {
4480            $('.topNav').show();
4481        }
4482        topNavigation.topNavReadjust(iScrollPostion);
4483
4484    },
4485    forEachULDesktopMenuChildren: function() {
4486
4487        $('ul.desktopMenu').children().each(function() {
4488            var firstColumnChildren = $(this).find('li.firstColumn');
4489            var secondColumnChildren = $(this).find('li.secondColumn');
4490            var firstColumnSectionDiv = $("<section></section>").addClass('firstColumnSection');
4491            var firstColumnSectionUl = $("<ul></ul>").addClass('vertical').addClass('topLevel');
4492            var secondColumnSectionDiv = $("<section></section>").addClass('secondColumnSection');
4493            var secondColumnSectionUl = $("<ul></ul>").addClass('vertical').addClass('topLevel');
4494
4495            firstColumnChildren.each(function() {
4496                $(this).clone().appendTo(firstColumnSectionUl);
4497            });
4498            firstColumnSectionUl.appendTo(firstColumnSectionDiv);
4499
4500            secondColumnChildren.each(function() {
4501                $(this).clone().appendTo(secondColumnSectionUl);
4502            });
4503            secondColumnSectionUl.appendTo(secondColumnSectionDiv);
4504
4505            var scrollColumnSectionDiv = $("<section></section>").addClass('scrollBarSection');
4506            scrollColumnSectionDiv.append(firstColumnSectionDiv);
4507            scrollColumnSectionDiv.append(secondColumnSectionDiv);
4508            $(this).children('div').append(scrollColumnSectionDiv);
4509
4510            $(scrollColumnSectionDiv).wrap("<section class='scrollBarSectionWrapper'></section>");
4511        });
4512    }
4513};
4514;
4515var imageRendition = (function($, w) {
4516
4517    // Enable strict mode
4518    "use strict";
4519
4520    w.showRendition = function(context) {
4521        var undefined;
4522        if (context === undefined) {
4523            context = $("body");
4524        }
4525
4526        $("data-picture-rendition", context).each(function() {
4527            var currentPicture = this;
4528            var matches = [];
4529            $("div[data-media]", currentPicture).each(function() {
4530                var media = $(this).attr("data-media");
4531                if (!media || (w.matchMedia && w.matchMedia(media).matches)) {
4532                    matches.push(this);
4533                }
4534            });
4535
4536            var $picImg = $("img", currentPicture).first();
4537
4538            if (matches.length) {
4539                var match = matches.pop();
4540                if ($picImg.size() === 0) {
4541                    var $currentPicture = $(currentPicture);
4542                    if (match.hasAttribute("data-alt")) {
4543                        $picImg = $("<img />").attr("alt", match.getAttribute("data-alt")).appendTo($currentPicture);
4544                    } else {
4545                        $picImg = $("<img />").attr("alt","").appendTo($currentPicture);
4546                    }
4547                    if (match.hasAttribute("data-title")) {
4548                        $picImg.attr('title',match.getAttribute("data-title"));
4549                    }
4550                }
4551                $picImg.attr("src", match.getAttribute("data-src"));
4552            } else {
4553                $picImg.remove();
4554            }
4555        });
4556
4557        $("div[data-picture-rendition]", context).each(function() {
4558            var currentPicture = this;
4559            var matches = [];
4560            $("div[data-media]", currentPicture).each(function() {
4561                var media = $(this).attr("data-media");
4562                if (!media || (w.matchMedia && w.matchMedia(media).matches)) {
4563                    matches.push(this);
4564                }
4565            });
4566
4567            var $picImg = $("img", currentPicture).first();
4568
4569            if (matches.length) {
4570                var parentElement = $(currentPicture).parent();
4571                if (parentElement.hasClass("data-picture-rendition")) {
4572                    var match = matches.pop();
4573                    parentElement.css('background-image', 'url("' + match.getAttribute("data-src") + '")');
4574                    if (match.hasAttribute("data-alt")) {
4575                        parentElement.attr('alt',match.getAttribute("data-alt"));
4576                    }
4577                    if (match.hasAttribute("data-title")) {
4578                        parentElement.attr('title',match.getAttribute("data-title"));
4579                    }
4580                } else if (!parentElement.hasClass("data-picture-without-background")) {
4581                    var match = matches.pop();
4582                    if ($picImg.size() === 0) {
4583                        var $currentPicture = $(currentPicture);
4584                        if (match.hasAttribute("data-alt")) {
4585                            $picImg = $("<img />").attr("alt", match.getAttribute("data-alt")).appendTo($currentPicture);
4586                        } else {
4587                            $picImg = $("<img />").attr("alt", "").appendTo($currentPicture);
4588                        }
4589                        if (match.hasAttribute("data-title")) {
4590                            $picImg.attr('title',match.getAttribute("data-title"));
4591                        }
4592                    }
4593                    $picImg.attr("src", match.getAttribute("data-src"));
4594                }
4595            } else {
4596                $picImg.remove();
4597            }
4598        });
4599    };
4600
4601    // Run on debounced resize and domready
4602    $(function() {
4603        w.showRendition();
4604    });
4605
4606    $(w).on("debouncedresize.imageRendition", function() {
4607        w.showRendition();
4608    });
4609
4610    return { showRendition : w.showRendition };
4611
4612}($CQ, this));
4613;
4614/* Ribbon Scroll */
4615var ribbon = {
4616    configureRibbon: function () {
4617        $(document).on('scroll',window,function(){
4618            ribbon.scrollingBehaviour();
4619            ribbon.ribbonOnResize();
4620        });
4621    },
4622
4623    scrollingBehaviour: function () {
4624        var wintop = window.pageYOffset;
4625        var docheight = $('html > body').height();
4626        var winheight = $(window).height();
4627        var totalScroll = (wintop / (docheight - winheight)) * 100;
4628        var totalScroll1 = (wintop / (docheight - winheight)) * 100 - 100;
4629        if (totalScroll1 > 0) {
4630            totalScroll1 = 0;
4631        }
4632        $(".progressBarBoxBg").css("left", totalScroll1 + "%");
4633        $(".progressBarBox").css("left", totalScroll + "%");
4634        ribbon.ribonVisibleCondition(true, true);
4635    },
4636
4637    ribbonOnResize: function () {
4638        var headerHeight = $('.topNav').outerHeight();
4639    },
4640
4641    /*
4642     ** This function ensures tht the ribbon is visible only when intended to
4643     ** The first arguement decides whether the ribbon hide is instant or with animation
4644     ** The second arguement decides whether the ribbon show is istant (Eg: Loading of page) or with animation (After scroll)
4645     */
4646
4647    stickyVisibleCondition: function (iCurScrollPos) {
4648        var lastSurpriseState = $('.surprise-text-hidden').is(':visible');
4649        if($('.header-container').length) {
4650            ribbon.globalNavSticky(iCurScrollPos);
4651        } else {
4652            if (topNavigation.iScrollPos > (topNavigation.surpriseTextPos)) {
4653                if ($(window).width() > 929) {
4654                    if (iCurScrollPos > topNavigation.iScrollPos) {
4655                        $('.surprise-text-hidden').removeClass('top-147-animate-surprise');
4656                        $('.surprise-text-hidden').removeClass('top-107-animate-surprise');
4657                        $('.updated-background-sticky').css('top', '10px');
4658                    } else {
4659                        $('.surprise-text-hidden').removeClass('top-107-animate-surprise');
4660                        $('.surprise-text-hidden').removeClass('top-147-animate-surprise');
4661                    }
4662                } else {
4663                    if ($(window).width() > 639) {
4664                        $('.surprise-text-hidden').removeClass('top-147-animate-surprise');
4665                        $('.surprise-text-hidden').removeClass('top-107-animate-surprise');
4666                        $('.surprise-text-hidden').css('top', '10px');
4667                    }else{
4668                        $('.surprise-text-hidden').removeClass('top-147-animate-surprise');
4669                        $('.surprise-text-hidden').removeClass('top-107-animate-surprise');
4670                        $('.surprise-text-hidden').css('top', '10px');
4671                    }
4672                }
4673                $('.surprise-text-hidden').addClass('updated-background-sticky');
4674            } else {
4675                $('.surprise-text-hidden').css('top', '');
4676                $('.surprise-text-hidden').removeClass('top-147-animate-surprise');
4677                $('.surprise-text-hidden').removeClass('top-107-animate-surprise');
4678                $('.surprise-text-hidden').removeClass('updated-background-sticky');
4679            }
4680        }
4681    },
4682
4683    globalNavSticky: function(scrollPos) {
4684        if(scrollPos > topNavigation.surpriseTextPos) {
4685            if($(window).width() >= 768) {
4686                $('.surprise-text-hidden').css('top', '70px');
4687            } else {
4688                $('.surprise-text-hidden').css('top', '90px');
4689            }
4690            $('.surprise-text-hidden').addClass('updated-background-sticky');
4691        } else {
4692            $('.surprise-text-hidden').css('top', '');
4693            $('.surprise-text-hidden').removeClass('updated-background-sticky');
4694        }
4695    }, 
4696
4697    ribonTransitionLoad: function () {
4698
4699        if ($('.progressContainerBox').length) {
4700            var iCurScrollPos = window.pageYOffset;
4701            if (iCurScrollPos > topNavigation.iScrollPos) {
4702                if (iCurScrollPos > 75) {
4703                    $('.topNav').removeClass('show-nicely-60');
4704                    $('.topNav').addClass('show-nicely');
4705                    if ($(window).width() > 929) {
4706                    }
4707                }
4708            } else {
4709                $('.topNav').removeClass('show-nicely');
4710                if ($(window).width() > 929) {
4711                    $('.topNav').addClass('show-nicely-60');
4712                }
4713            }
4714            topNavigation.iScrollPos = iCurScrollPos;
4715        }
4716    },
4717
4718    ribonVisibleCondition: function (shouldHideSlide, shouldShowSlide) {
4719        var userAgent = window.navigator.userAgent;
4720        var isMobileSafari = false;
4721        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
4722            isMobileSafari = true
4723        }
4724
4725        if ($(".progressContainerBox").length) {
4726            var $heroSection;
4727            var heroHeight;
4728            var outerHeightNav = $('.topNav').outerHeight();
4729            var progressHeight = window.pageYOffset;
4730            if (progressHeight > 75) {
4731                if (shouldShowSlide === true && !isMobileSafari) {
4732                    $('.progressContainerBox').removeClass('ribbon-initital-opacity');
4733                    $('.progressContainerBox').removeClass('ribbon-hide-scroll');
4734                    $('.progressContainerBox').addClass('ribbon-show-scroll');
4735                } else {
4736                    if ($(window).width() > 639) {
4737                        $('.progressContainerBox').removeClass('ribbon-initital-opacity');
4738                        $('.progressContainerBox').show();
4739
4740                        setTimeout(function () {
4741                            $('.progressContainerBox').removeClass('ribbon-hide-scroll');
4742                            $('.progressContainerBox').addClass('ribbon-show-scroll-mobile');
4743                        }, 100);
4744                    }
4745                    else{
4746                        $('.progressContainerBox').removeClass('ribbon-show-scroll-mobile');
4747                        $('.progressContainerBox').addClass('ribbon-hide-scroll');
4748                        $('.progressContainerBox').hide();
4749                   }
4750
4751                }
4752
4753            } else {
4754                if (shouldHideSlide === true && !isMobileSafari) {
4755                    $('.progressContainerBox').removeClass('ribbon-show-scroll');
4756                    $('.progressContainerBox').removeClass('ribbon-show-scroll-mobile');
4757                    $('.progressContainerBox').addClass('ribbon-hide-scroll');
4758                    $('.progressContainerBox').addClass('ribbon-initital-opacity');
4759                }else if(isMobileSafari && progressHeight < 75){
4760                    if ($(window).width() > 639) {
4761                        $('.progressContainerBox').hide();
4762                        $('.progressContainerBox').removeClass('ribbon-initital-opacity');
4763                        $('.progressContainerBox').removeClass('ribbon-show-scroll-mobile');
4764                        $('.progressContainerBox').addClass('ribbon-hide-scroll');
4765}
4766                } else {
4767                    if (progressHeight > 75) {
4768                        $('.progressContainerBox').hide();
4769                    } 
4770                }
4771            }
4772        }
4773
4774    }
4775};
4776$(document).ready(function(){
4777    let isSurprise=$(".surprise-text-hidden").length;
4778    let windowWidth=$(window).width();
4779    if(isSurprise){
4780        let surpriseText=$(".surprise-text-hidden").position().top;
4781        $(window).scroll(function(){
4782            let windowTop=$(window).scrollTop();
4783            if(windowTop > surpriseText){
4784                $(".surprise-text-hidden").addClass("updated-background-sticky");
4785                if(windowWidth >= 768){
4786                $(".surprise-text-hidden").css({"top":"70px"});
4787                }
4788                else{
4789                    $(".surprise-text-hidden").css({"top":"90px"});
4790                }
4791            }
4792            else{
4793                $(".surprise-text-hidden").removeClass("updated-background-sticky");
4794                $(".surprise-text-hidden").css({"top":""});
4795            }
4796        })
4797    }
4798});
4799$(document).ready(function () {
4800
4801    $('.js-copytextarea').on('click touchstart', function (e) {
4802        var textArea = document.createElement("INPUT");
4803        textArea.style.position = 'fixed';
4804        textArea.style.right = "-99999em";
4805        textArea.style.bottom = '-30px';
4806        textArea.style.top = '-20px';
4807        textArea.style.zIndex = '-1';
4808        textArea.style.opacity = 0;
4809        textArea.style.cursor = 'pointer';
4810        // Clean up any borders.
4811        textArea.style.border = 'none';
4812        textArea.style.outline = 'none';
4813        textArea.style.boxShadow = 'none';
4814        textArea.value = window.location.href;
4815        $(this).append(textArea);
4816        var currentFocus = document.activeElement;
4817        var att = document.createAttribute("readonly");       // Create a "readonly" attribute
4818        att.value = "true";                           // Set the value of the true attribute
4819        textArea.setAttributeNode(att);
4820        textArea.focus();
4821        textArea.setSelectionRange(0, textArea.value.length);
4822        try {
4823            var successful = document.execCommand('copy');
4824        } catch (err) {
4825            console.log('Oops, unable to copy');
4826        }
4827        // restore original focus
4828        $(textArea).remove();
4829        if (currentFocus && typeof currentFocus.focus === "function") {
4830            currentFocus.focus();
4831        }
4832
4833        // To fade Copied message after click
4834         $(".message", this).show().delay(2000).fadeOut();
4835    });
4836});
4837
4838(function () {
4839    //replace multiple slashes with single slash
4840    if (window.location.pathname.match(/\/{2,}/g, '/') != null) {
4841        window.location.pathname = window.location.pathname.replace(/\/{2,}/g, '/');
4842    }
4843})();
4844
4845$(document).ready(function () {
4846    if(window.outerWidth < 640){
4847        $('.quick-links-container').last().css('margin-bottom','32px');
4848
4849    }else{
4850        $('.quick-links-container').last().css('margin-bottom','72px');
4851    }
4852    setTimeout(() => {
4853        function getQueryParam(param) {
4854            const urlParams = new URLSearchParams(window.location.search);
4855            return urlParams.get(param);
4856        }
4857        if(getQueryParam('wcmmode') === 'disabled' && window.outerWidth >= 1024){
4858            $('.xf-content-height').addClass("bhfHeader__top")
4859        }else if(getQueryParam('wcmmode') === 'disabled' && window.outerWidth < 1024){
4860            $('.xf-content-height').addClass("bhfHeader__top")
4861        };
4862        if($('.ols-component-wrapper').length){
4863            $('.ols-component-wrapper').hide();
4864            const olsValidentitlement = $('#olsValidEntitlement').val()
4865            const editMode = $('#editMode').val()
4866            const previewMode = $('#previewMode').val()
4867            if(editMode == 'true' || previewMode == 'true' || getQueryParam('wcmmode') === 'disabled'){
4868                $('.ols-component-wrapper').show();
4869            }else if(olsValidentitlement == 'true'){
4870                $('.ols-component-wrapper').show();
4871            }
4872        }
4873    }, 0)
4874	// Function to retrieve cookies by their names
4875	function getCookie(name) {
4876		var re = new RegExp(name + "=([^;]+)");
4877		var value = re.exec(document.cookie);
4878		return (value != null) ? unescape(value[1]) : null;
4879	}
4880
4881	// Retrieve the value of the "isAdvisor" cookie
4882	var isAdvisorValue = getCookie('isAdvisor');
4883
4884	// Set digitalData.isAdvisor based on the value of the "isAdvisor" cookie
4885	if(typeof digitalData != "undefined"){
4886	if (isAdvisorValue === "true") {
4887		digitalData.isAdvisor = true;
4888	} else {
4889		digitalData.isAdvisor = false;
4890	}
4891	}
4892
4893    const windowInnerHeight = window.innerHeight;
4894
4895    $(document).foundation();
4896
4897    /**
4898     *  'Anonymous Closure'
4899     *  @type {null}
4900     */
4901
4902    (function () {
4903        if (homePageVideo.ElementExist($('.genericAEMVideo .responsive-embed, .genericYoutubeVideo .responsive-embed'))) {
4904            genericVideo.applyGenericAemVideoHeight();
4905        }
4906        if (homePageVideo.ElementExist($('.metlife-link'))) {
4907            externalModalPopUp.init();
4908        }
4909        formAnalytics.init();
4910        navigationMenu.init();
4911        loginLogout.init();
4912        onboardUser.init();
4913        formGroup.init();
4914        ribbon.configureRibbon();
4915        homePageVideo.HPHVFixYoutubeAutoplay();
4916        ribbon.ribonTransitionLoad();
4917        ribbon.ribonVisibleCondition(false, false);
4918        genericShortcuts.init();
4919        /**
4920         *  PL - 224 | 225: Message Notification Component (messageNotification.html)
4921         */
4922        message.init();
4923        // PL -224 | 225 Ends
4924        formGroupLink.init();
4925
4926        /* Reval Pop up Align middle */
4927        revealCenterAlign.init();
4928    })();
4929
4930    if (!(navigator.appVersion.indexOf('Mac') !== -1)) {
4931        if ($.browser.mozilla) {
4932            $('body').addClass('fix-nav-scroll');
4933        }
4934    }
4935
4936    if (!topNavigation.isTouchDevice()) {
4937        $('body').addClass('not-touch');
4938    }
4939
4940    if (homePageVideo.ElementExist($('.genericAEMVideo .responsive-embed, .genericYoutubeVideo .responsive-embed'))) {
4941        $(window).on('debouncedresize.applyGenericAemVideoHeight', function () {
4942            genericVideo.applyGenericAemVideoHeight();
4943        });
4944    }
4945
4946    genericVideo.GVPublishModeConfiguration();
4947    genericVideo.GVFixYoutubeVideoAutoPlay();
4948
4949    $('.video-js').each(function (videoIndex) {
4950        var videoId = $(this).attr('id');
4951        $(this)[0].addEventListener('play', function (e) {
4952            homePageVideo.inlineYoutubeQueue.forEach(function (e) {
4953                e.stopVideo();
4954            });
4955            $('.video-js').each(function (index) {
4956                if (videoIndex !== index) {
4957                    this.player.pause();
4958                    this.player.load();
4959                }
4960            });
4961        });
4962    });
4963
4964    $(window).on('load', function () {
4965        genericVideo.videoEventHandlers();
4966    });
4967
4968    // capturing the click event on generic AEM video
4969    $('video.genericVideoCta').each(function () {
4970        $(this)[0].addEventListener('playing', function () {
4971            digitalData.cta = { name: $(this).attr('data-cta') };
4972        }, true);
4973    });
4974
4975
4976    /* Code for Smooth Scroll on Key Benefits */
4977    $(document).on('click', 'a.smooth-scroll', function (event) {
4978        event.preventDefault();
4979        if (topNavigation.isIphone()) {
4980            var offsetPoint = (windowInnerHeight !== window.innerHeight) ? 10 : 40;
4981        } else if (topNavigation.isIpad()) {
4982            var offsetPoint = (windowInnerHeight !== window.innerHeight) ? 40 : 60;
4983        } else {
4984            var offsetPoint = 10;
4985        }
4986        var offsettop = $($.attr(this, 'href')).offset().top - offsetPoint;
4987        $('html, body').animate({ scrollTop: offsettop }, 500);
4988    });
4989
4990    $(document).on('click', 'a.smooth-scroll-qLinks', function (event) {
4991        event.preventDefault();
4992        var offsettop = $($.attr(this, 'href')).offset().top - 10;
4993        $('html, body').animate({ scrollTop: offsettop }, 500);
4994    });
4995
4996    var ids = [];
4997    $('a.smooth-scroll-generic').each(function () {
4998        ids.push($(this).attr('href'));
4999    });
5000
5001    $(document).on('click', 'a.smooth-scroll-generic', function (event) {
5002        event.preventDefault();
5003        var offsettop;
5004        if (topNavigation.isIphone()) {
5005            offsettop = (windowInnerHeight !== window.innerHeight) ? $($.attr(this, 'href')).offset().top - 45 : $($.attr(this, 'href')).offset().top - 85;
5006        } else {
5007            offsettop = $($.attr(this, 'href')).offset().top - 75;
5008        }
5009        if ($(this).attr('href') === ids[0]) {
5010            $('html, body').animate({ scrollTop: offsettop }, 500);
5011        } else if ($(this).attr('href') === ids[1]) {
5012            $('html, body').animate({ scrollTop: offsettop }, 1000);
5013        } else {
5014            $('html, body').animate({ scrollTop: offsettop }, 1500);
5015        }
5016
5017    });
5018
5019
5020    $(document).on('replace', 'img', function () {
5021        $(document).foundation('equalizer', 'reflow');
5022    });
5023
5024    //FOR THE MODAL NOT INTERFERING WITH STICKY
5025    (function () {
5026        $(window).bind('orientationchange', function (event) {
5027            $('.topNav').css('opacity', '0');
5028            $('.progressContainerBox').css('opacity', '0');
5029
5030            // $('.topNav').css({ 'position': 'relative', 'transform': 'translateZ(0)' });
5031            setTimeout(function () {
5032                $('.topNav').css('width', '100%');
5033                // $('.topNav').css({ 'position': '', 'transform': 'none' });
5034                if (pageYOffset > 75) {
5035                    $(window).scrollTop($(window).scrollTop() - 0);
5036                }
5037                $('.progressContainerBox').css('opacity', '1');
5038            }, 350);
5039
5040            // FORCE HARDWARE ACCELERATION
5041
5042            setTimeout(function () {
5043                $('.topNav').css('opacity', '1');
5044            }, 10);
5045
5046
5047        });
5048    })();
5049
5050
5051    // for print preview
5052    if (window.matchMedia) {
5053        var mediaQueryList = window.matchMedia('print');
5054        mediaQueryList.addListener(function (mql) {
5055            if (mql.matches) {
5056                $(Window).trigger('resize');
5057            }
5058        });
5059    }
5060
5061    $('.revealCloseWrapper').on('click', function () {
5062        if (!$('a.hamburger').hasClass('pressed')) {
5063            $('body').removeClass('videoNoScroll stopScroll');
5064            $('body').css('position', '');
5065            $('.overlayWhite').css({ height: 0 });
5066            $('.topNav').removeClass('topLinksPosition');
5067            $('.progressContainerBox').removeClass('force-hide-ribbon');
5068            $('.progressContainerBox').removeClass('ribbon-hide-scroll');
5069        }
5070    });
5071
5072    (function () {
5073        if (homePageVideo.ElementExist($('.benifit-submenu'))) {
5074            $('.benifit-submenu li a').on('click', function () {
5075                $('.benifit-submenu li a').removeClass('active');
5076                $(this).addClass('active');
5077            });
5078        }
5079
5080        if (homePageVideo.ElementExist($('.faq-sublink'))) {
5081            $('.faq-sublink li:eq(1)').addClass('active');
5082            $('.faq-sublink li a').on('click', function () {
5083                $('.faq-sublink li').removeClass('active');
5084                $(this).parent().addClass('active');
5085            });
5086        }
5087    })();
5088
5089    // BDEV-2755 : Clickable card bubbling fix
5090
5091    $(function () {
5092        function openWindow(url, target) {
5093            if (target) {
5094                window.open(url, target);
5095            } else {
5096                window.location = url;
5097            }
5098        }
5099
5100        $(document).on('click', '.redirectable-card:not(a)', function (event) {
5101            event.stopPropagation();
5102            setCta($(this).data('analytics-text'),this);
5103            let element = $(this).find("a:first");
5104            let target = element.attr("target");
5105            let url = element.attr("href");
5106            openWindow(url, target);
5107        });
5108
5109        $(document).on('click', '.redirectable-card a', function (event) {
5110            event.stopPropagation();
5111        });
5112    });
5113
5114    // BDEV-2755 [Ends]
5115
5116    $(function () {
5117        if (homePageVideo.ElementExist($('.animated-gif-parent-cont'))) {
5118            topNavigation.configureGenericGif();
5119        }
5120    });
5121
5122    $(function () {
5123        if (homePageVideo.ElementExist($('.searchResultTags'))) {
5124            window.scrollTo(0, 0);
5125        }
5126    });
5127
5128    $(function () {
5129        if (homePageVideo.ElementExist($('.product-benefit'))) {
5130            topNavigation.configureGif();
5131            if ((($('.gif-position')[0] !== undefined) && ($('.gif-position:nth-of-type(1)').attr('data-gif') != undefined && $('.gif-position:nth-of-type(1)').attr('data-gif').indexOf(".gif") != -1)) && topNavigation.isElementInViewport($('.productBenefit'))) {
5132                topNavigation.animateGifStart();
5133            }
5134        }
5135    });
5136
5137    $(function () {
5138        if (homePageVideo.ElementExist($('.product-category-hero'))) {
5139            topNavigation.configureTopSticky();
5140            onTouchMove = function (e) {
5141                e.stopPropagation();
5142                e.stopImmediatePropagation();
5143            };
5144            ribbon.ribonVisibleCondition(false, false);
5145            var iCurScrollPos = window.pageYOffset;
5146            if ($('.surprise-text-hidden').length) {
5147                ribbon.stickyVisibleCondition(iCurScrollPos);
5148            }
5149        }
5150    });
5151
5152    $(function () {
5153        $('.showPopupModal').on('click', function () {
5154            setTimeout(function () {
5155                revealCenterAlign.revealRePosition();
5156            }, 10);
5157        });
5158    });
5159
5160    $(function () {
5161        onTouchMove = function (e) {
5162            e.stopPropagation();
5163            e.stopImmediatePropagation();
5164        };
5165        ribbon.ribonVisibleCondition(false, false);
5166
5167        var wcmodepublish = $('#bhf-page-data').attr('data-publish');
5168        var wcmode = $('#bhf-page-data').attr('data-wcmode');
5169        if (wcmode) {
5170            $('.hightlight-box').parent().addClass('dotted-border');
5171        } else {
5172            if (homePageVideo.ElementExist($('.show-more'))) {
5173                $('.show-more').each(function () {
5174                    var anchorObject = $(this);
5175                    readMoreWrapper.configureShowMoreLess(anchorObject);
5176                })
5177            }
5178            if (wcmodepublish) {
5179                if (homePageVideo.ElementExist($('#videoBoxReveal'))) {
5180                    homePageVideo.HPHVPublishModeConfiguration();
5181                }
5182
5183            } else {
5184                if (homePageVideo.ElementExist($('#videoBoxReveal'))) {
5185                    homePageVideo.HPHVPreviewModeConfiguration();
5186                }
5187
5188            }
5189
5190        }
5191    });
5192    // BDEV-2755 [Ends]
5193
5194    // BDEV-2798 [Start]
5195    if (homePageVideo.ElementExist($('#video-bg-hero'))) {
5196        let loopCount = 0;
5197        let durationVid = 30.0;
5198        var bgVidElem = $('#video-bg-hero');
5199        var bgVid = bgVidElem[0];
5200        bgVid.play();
5201        bgVidElem.on("timeupdate", function () {
5202            if (bgVid.duration < durationVid) {
5203                durationVid = bgVid.duration - 0.5;
5204            }
5205            if (bgVid.currentTime >= durationVid && bgVid.duration >= durationVid) {
5206                loopCount += 1;
5207                bgVid.currentTime = 0;
5208            }
5209
5210            if (loopCount >= 4) {
5211                bgVid.pause();
5212                bgVidElem.off('timeupdate');
5213            }
5214        });
5215    }
5216    // BDEV-2798 [End] or BDEV-2780
5217    if (/iPhone|iPad/i.test(navigator.userAgent) && 'ontouchstart' in document.documentElement) {
5218        $('body').css('cursor', 'pointer');
5219    }
5220    // BDEV-2780 [End]
5221
5222
5223    //Show Skip-to-content Button on Edit mode
5224    if (homePageVideo.ElementExist($('#skip-to-content'))) {
5225        var modePublish = $('#bhf-page-data').attr('data-publish');
5226        if (topNavigation.isTouchDevice()) {
5227            $('#skip-to-content').css('display', 'none');
5228        }
5229        else {
5230            if (modePublish) {
5231                $('#skip-to-content').addClass('sr-hidden');
5232                $('body').prepend($('#skip-to-content'));
5233            }
5234        }
5235    }
5236
5237    /* Code for on click of skip-to-content button */
5238    $(document).on('click', '.sr-hidden', function (event) {
5239        event.preventDefault();
5240        var offsettop = $($.attr(this, 'href')).offset().top - 80;
5241        $('html, body').animate({ scrollTop: offsettop }, 500);
5242    });
5243
5244    // PL - Redirection page JS
5245
5246    if (homePageVideo.ElementExist($('.redirection-wrapper'))) {
5247
5248        var profileStore = ContextHub.getStore('profile');
5249        var authPath = $('#authPath').val();
5250        var redirectPath = $('#redirectPath').val();
5251
5252        if (!authPath) {
5253            authPath = profileStore.config.initialValues.path;
5254        }
5255        var contextHubUserPath = profileStore.getTree().path;
5256        if (!contextHubUserPath || contextHubUserPath !== authPath) {
5257            profileStore.loadProfile(authPath);
5258        }
5259        if (document.querySelector('[data-runMode]').dataset.runmode.indexOf('author') === -1) {
5260            setTimeout(function () {
5261                window.location.href = redirectPath;
5262            }, 2000);
5263        }
5264
5265    }
5266
5267    var mode = document.querySelector("[data-wcmode]");
5268    if (mode && mode.dataset.wcmode) {
5269        $('body').addClass('no-top-padding');
5270    }
5271
5272    // Redirection [Ends]
5273
5274    if (homePageVideo.ElementExist($('.mode-selection'))) {
5275        $('.mode-selector').removeClass('topNav');
5276        $('.professionals.scrollTop').hide();
5277
5278    } else {
5279        $('.professionals.scrollTop').show();
5280        $('.editable-professionals').remove();
5281    }
5282
5283    // BDEV - 2738 [Start]
5284    const tooltipEvent = topNavigation.isTouchDevice() ? 'mousedown.zf.tooltip' : 'mouseenter.zf.tooltip';
5285    $('[data-tooltip]').on(tooltipEvent, function () {
5286        var element = this;
5287        if ($(element).data('disable-hover') || $(element).data('disable-click')) {
5288            if (!$(element).hasClass('already-init')) {
5289                $.ajax({
5290                    url: '/content.jargonDetailsServlet.fetch?jargonId=' + $(element).text().replace(/ /g, "_"),
5291                    type: 'get',
5292                    success: function (d) {
5293                        $(element).addClass('already-init');
5294                        var id = $(element).data('toggle');
5295                        if (d) {
5296                            $('#' + id).text(d);
5297                        }
5298                        $(element).foundation('show');
5299                    },
5300                    error: function () {
5301                        console.log('Error in fetching tooltip jargon');
5302                    }
5303                });
5304            } else {
5305                $(element).foundation('show');
5306            }
5307        } else {
5308            $(element).foundation('show');
5309        }
5310    });
5311
5312    $('[data-tooltip]').on('mouseleave.zf.tooltip', function () {
5313        $(this).foundation('hide');
5314    });
5315
5316    // BDEV-2738 [Ends]
5317
5318    /**
5319     * 'Load Players for Inline Youtube Video'
5320     */
5321
5322    homePageVideo.loadPlayer(null, null, 'Inline');
5323    if (homePageVideo.ElementExist($('#aemPlayer_inline')) && typeof videojs === 'function') {
5324        genericVideo.videoEventHandlers();
5325    }
5326
5327    // BDEV-3636
5328
5329    /**
5330     * 'set page property, firmName as browser cookie'
5331     */
5332    if (homePageVideo.ElementExist($('#firm-name'))) {
5333        var firmName = document.getElementById("firm-name").value;
5334        document.cookie = "firmName=" + firmName + ";path=/";
5335    }
5336
5337    if (homePageVideo.ElementExist($('.product-information .loadMoreButton')) &&
5338        homePageVideo.ElementExist($('.product-information .inputField'))) {
5339
5340        const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
5341        $('.product-information .inputField').on('focus', function () {
5342            if (!$(this).hasClass('tracked')) {
5343                formAnalytics.track({
5344                    event: 'formstart',
5345                    data: { formName: $(this).data('name'), formType: $(this).data('type') }
5346                });
5347                $(this).addClass('tracked');
5348            }
5349        });
5350
5351        $('.product-information .inputField').on('keyup paste', function (e) {
5352            let value = $(this).val().trim();
5353            if (pattern.test(value)) {
5354                $('.product-information .loadMoreButton').prop('disabled', false);
5355            } else {
5356                $('.product-information .loadMoreButton').prop('disabled', true);
5357            }
5358        });
5359
5360        $('.product-information .loadMoreButton').on('click', function (e) {
5361            e.preventDefault();
5362            e.stopPropagation();
5363            formAnalytics.track({ event: 'formcomplete' });
5364            $(this).prop('disabled', true);
5365            $.ajax({
5366                url: '/form.salesforceClient.triggerEmail',
5367                type: 'post',
5368                data: {
5369                    'emailId': $('.product-information .inputField').val(),
5370                    'downloadLink': $('.product-information .download-wrapper a').attr('href'),
5371                    'customerKey': $('.product-information .customerKey').val(),
5372                },
5373                success: function (data) {
5374                    if (data === 'true') {
5375                        $('.product-information .content-wrapper').addClass('hide');
5376                        $('.product-information .success-wrapper').removeClass('hide');
5377                    } else {
5378                        $('.product-information .error-msg').removeClass('hide');
5379                    }
5380                    $('.product-information .loadMoreButton').prop('disabled', false);
5381                },
5382                error: function () {
5383                    $('.product-information .loadMoreButton').prop('disabled', false);
5384                    $('.product-information .error-msg').removeClass('hide');
5385                }
5386            });
5387        });
5388    }
5389
5390    // to find the location of anchor and to smooth scroll
5391    $(window).on('load', function () {
5392        if (window.location.hash) {
5393            if (location.href.indexOf("#/") != -1) {
5394                // solve for console error running for angular
5395            } else if (window.location.hash) {
5396                var hash = window.location.hash;
5397
5398                if ($(window).width() > 767) {
5399                    $('html, body').animate({
5400                        scrollTop: $(hash).offset().top - 100
5401                    }, 1500);
5402                } else {
5403                    $('html, body').animate({
5404                        scrollTop: $(hash).offset().top - 35
5405                    }, 1500);
5406                }
5407            }
5408        }
5409    });
5410
5411
5412
5413    // Super Grid Section
5414    const isAuthor = (document.querySelector('[data-runMode]').dataset.runmode.indexOf('author') !== -1);
5415    isAuthor && $('.masterRowContainer .grid-x').addClass('author');
5416
5417    //PageSharing
5418    $('.social-icons-list #email').each(function () {
5419        let body_line = escape('\n\n');
5420        $(this).attr('href', $(this).attr('href') + encodeURIComponent($(this).prev().val()) + body_line + window.location.href)
5421    });
5422
5423    $('#content').parent().css({ 'overflow': 'hidden', 'clear': 'both' });
5424
5425    //Account Profile mobile number format
5426    var ph_num = $("#mobilePhoneNumber");
5427    if (ph_num.text().length === 10) {
5428        var formatted_num = bhfFormValidator.formatPhoneNumber(ph_num.text());
5429        $('#mobilePhoneNumber').text(formatted_num);
5430    }
5431
5432    //Calling function Email Break
5433
5434    $(document).ready(breakEmail);
5435    $(window).resize(breakEmail);
5436
5437    //breaking email text
5438    function breakEmail() {
5439        $('.accountEditEmail').each(function () {
5440            var text = $(this).text();
5441            var index = text.indexOf('@');
5442            var firstPart = text.substr(0, index);
5443            var secondPart = text.substr(index);
5444            if ($(this).width() > $(this).parent().width()) {
5445
5446                $(this).html(firstPart + '<br>' + secondPart);
5447            } else {
5448                $(this).html(text);
5449                if ($(this).width() > $(this).parent().width()) {
5450                    $(this).html(firstPart + '<br>' + secondPart);
5451                }
5452            }
5453
5454        });
5455    };
5456
5457    function masterRowEqualizer() {
5458        $('.masterRowContainer, .preLoginHomepageHero .cards-container, .columnctrl, .equalizeCard').each(function () {
5459            for (var i = 0; i < $('[class^="equalize-"]').length + 5; i++) {
5460                if ($(window).width() >= 640) {
5461                    var maxHeight = 0;
5462                    var presentEqualize = $(this).find('.equalize-' + i);
5463                    if (presentEqualize.length) {
5464                        presentEqualize.each(function () {
5465                            if ($(this).height() > maxHeight) {
5466                                maxHeight = $(this).height();
5467                            }
5468                        });
5469                        presentEqualize.height(maxHeight);
5470                    }
5471                } else {
5472                    var smallEqualize = $(this).find('.equalize-' + i);
5473                    if (smallEqualize.length) {
5474                        smallEqualize.each(function () {
5475                            $(this).css('height', '');
5476                        });
5477                    }
5478                }
5479            }
5480        });
5481    }
5482
5483    $(function () {
5484        var last_width = $(window).width();
5485        $(window).on('load', function () {
5486            setTimeout(function () { masterRowEqualizer(); }, 250);
5487        });
5488        $(window).on('resize', function () {
5489            var new_width = $(window).width();
5490            if (new_width !== last_width) {
5491                $('[class^="equalize-"]').css('height', '');
5492                setTimeout(function () { masterRowEqualizer(); }, 250);
5493                last_width = new_width;
5494            }
5495        });
5496    });
5497
5498    $(window).load(function () {
5499        let quickLinksData = $('#quick-links-data').children().last();
5500        quickLinksData.css('margin-bottom', '200px');
5501    });
5502
5503
5504    // Focus visible task
5505
5506    $(document).focus('a:not(:has(*))', function () {
5507        $(this).css('background', '#e9e9e9');
5508    }, function () {
5509        $(this).css('background', '');
5510    });
5511
5512    $(document).on('mousedown', function () {
5513        $('body').removeClass('using-keys');
5514    });
5515
5516    $(document).on('keydown', function (e) {
5517        if (e.which || e.keyCode == 9) {
5518            $('body').addClass('using-keys');
5519        }
5520    });
5521
5522});
5523$('*').on('touchstart', function () { });
5524var formAnalytics = {
5525    init: function () {
5526        $('form.enable-analytics').each(function() {
5527
5528            var lastFocusedElement = null;
5529            var isClick = false;
5530            var firstTimeClick = true;
5531            var inputField = $(this).find('input[type="text"],input[type="number"],input[type="tel"],input[type="phone"],input[type="email"], textarea, .select2-selection');
5532
5533            inputField.mousedown(function(e) {
5534                if (firstTimeClick) {
5535                    isClick = true;
5536                }
5537            }).focus(function(e) {
5538                // To prevent focus firing when element already had focus
5539                if (lastFocusedElement != e.target) {
5540                    if (isClick) {
5541                        var formName = "n/a";
5542                        var formType = "n/a";
5543                        $(this).closest('form').find('input[type="hidden"]').each(function() {
5544                            if ($(this).attr("name") == "formName") {
5545                                formName = $(this).val();
5546                            }
5547                            if ($(this).attr("name") == "formType") {
5548                                formType = $(this).val();
5549                            }
5550                        });
5551                        formAnalytics.track({event: 'formstart', data: { formName: formName, formType: formType }});
5552                        isClick = false;
5553                        firstTimeClick = false;
5554                    }
5555                    lastFocusedElement = e.target;
5556                    isClick = false;
5557                }
5558            });
5559            $(this).submit(function(e) {
5560                $(this).closest('form').find('input[type="hidden"]').each(function() {
5561                    if ($(this).attr("name") == "formName") {
5562                        setFormName($(this).val());
5563                    }
5564                    if ($(this).attr("name") == "formType") {
5565                        setFormType($(this).val());
5566                    }
5567                });
5568                formAnalytics.track({event: 'formcomplete'});
5569                if($(this).data("cwanalytics"))
5570                {
5571                setToolComplete();
5572                }
5573            });
5574        });
5575    },
5576
5577    track: function (args) {
5578        if (typeof _satellite !== 'undefined' && args.event) {   
5579            if(args.data)  {
5580                digitalData.form = args.data
5581            }
5582            _satellite.track(args.event);
5583        }
5584    }
5585};
5586$(function(){
5587    if($('.custom-dropdown-option').length){
5588        $(document).on('click','.custom-dropdown-option',function(e){
5589            $('.custom-dropdown-btn').html($(this).html()+' <i class="fix-dropdown-icon-location icon caret-medium-dark"></i>');
5590            d_pane=$('#example-dropdown').children().length
5591            if (d_pane > 0) {
5592                $('#example-dropdown').foundation('toggle');
5593            }
5594        });
5595    }
5596});
5597
5598/*! getEmPixels  | Author: Tyson Matanich (http://matanich.com), 2013 | License: MIT */
5599(function(n,t){"use strict";var i="!important;",r="position:absolute"+i+"visibility:hidden"+i+"width:1em"+i+"font-size:1em"+i+"padding:0"+i;window.getEmPixels=function(u){var f,e,o;return u||(u=f=n.createElement("body"),f.style.cssText="font-size:1em"+i,t.insertBefore(f,n.body)),e=n.createElement("i"),e.style.cssText=r,u.appendChild(e),o=e.clientWidth,f?t.removeChild(f):u.removeChild(e),o}})(document,document.documentElement);
5600var isResponseRecievedForTaggedPages = 0;
5601var resultSet = "";
5602var parsed_process = [];
5603var requested_page = 0;
5604function getLazyLoadPagesFromTag(tagId, pageUrl, isAuthorSearch) {
5605
5606	if (tagId.indexOf(' ') !== -1) {
5607		tagId = tagId.replace(/ /g, '_');
5608	}
5609
5610	if (isResponseRecievedForTaggedPages === 0) {
5611		isResponseRecievedForTaggedPages = isResponseRecievedForTaggedPages + 1;
5612		var isPro = false;
5613		if (window.location.href.indexOf('/pro') !== -1) {
5614			isPro = true;
5615		}
5616		var ajaxUrl = '';
5617
5618		if (isPro) {
5619			ajaxUrl = '/pro' + '/tagResultsServlet.allTagPost/?searchKey=' + tagId + '&pageUrl=' + pageUrl.trim();
5620		} else {
5621			ajaxUrl = '/tagResultsServlet.allTagPost/?searchKey=' + tagId + '&pageUrl=' + pageUrl.trim();
5622		}
5623
5624		if (isAuthorSearch) {
5625			ajaxUrl = ajaxUrl + '&authorSearch=true';
5626		}
5627
5628		$.ajax({
5629			url : ajaxUrl,
5630			type : 'GET',
5631			success : function(result) {
5632				resultSet = result;
5633				for (var i = 0; i < resultSet.data.length; i++) {
5634					parsed_array = resultSet.data[i];
5635					if (parsed_array.articleType == "article") {
5636						parsed_array.article = true;
5637					} else if (parsed_array.articleType == "video") {
5638						parsed_array.video = true;
5639					} else if (parsed_array.articleType == "graph") {
5640						parsed_array.graph = true;
5641					}else if (parsed_array.articleType == "quiz") {
5642                        parsed_array.quiz = true;
5643                    }else if (parsed_array.articleType == "panel") {
5644                        parsed_array.panel = true;
5645                    }else if (parsed_array.articleType == "podcast") {
5646                        parsed_array.podcast = true;
5647                    }else if (parsed_array.articleType == "house") {
5648                        parsed_array.house = true;
5649                    }else if (parsed_array.articleType == "guide") {
5650                        parsed_array.guide = true;
5651                    }
5652
5653					tag_list = parsed_array.tagDetailsList;
5654					// if tag found
5655					if (tag_list.length != 0) {
5656						var first_tag = tag_list[0];
5657						var last_tag = tag_list[tag_list.length - 1];
5658						last_tag.last = true;
5659						first_tag.first = true;
5660						tag_list[0] = first_tag;
5661						tag_list[tag_list.length - 1] = last_tag;
5662						parsed_array.tagDetailsList = tag_list;
5663					} else {
5664						var last_tag = {};
5665						last_tag.last = true;
5666						tag_list[0] = last_tag;
5667						parsed_array.tagDetailsList = tag_list;
5668					}
5669
5670					contributor_list = parsed_array.contributors;
5671					// if contributor found
5672					if (contributor_list && contributor_list.length) {
5673						var first_tag = contributor_list[0];
5674						var last_tag = contributor_list[contributor_list.length - 1];
5675						last_tag.last = true;
5676						first_tag.first = true;
5677						contributor_list[0] = first_tag;
5678						contributor_list[contributor_list.length - 1] = last_tag;
5679						parsed_array.contributors = contributor_list;
5680					} else {
5681						var last_tag = {};
5682						last_tag.last = true;
5683						contributor_list[0] = last_tag;
5684						parsed_array.contributors = contributor_list;
5685					}
5686
5687
5688					parsed_process.push(parsed_array);
5689				}
5690				var current_process = parsed_process.slice(
5691						(requested_page * 10), (requested_page * 10) + 10);
5692				var template = $('#mustache-templ').html();
5693				var html = Mustache.to_html(template, current_process);
5694				$('#parent-tag').html(html);
5695				Foundation.reInit('equalizer');
5696				if (requested_page == 0) {
5697					$('#previousBtn').hide();
5698				} else {
5699					$('#previousBtn').show();
5700				}
5701
5702				if ((requested_page + 1) * 10 >= parsed_process.length) {
5703					$('#nextBtn').hide();
5704				} else {
5705					$('#nextBtn').show();
5706				}
5707				$('html,body').scrollTop(0);
5708			}
5709		});
5710	} else {
5711		var current_process = parsed_process.slice((requested_page * 10),
5712				(requested_page * 10) + 10);
5713		var template = $('#mustache-templ').html();
5714		var html = Mustache.to_html(template, current_process);
5715
5716		$('#parent-tag').html(html);
5717		Foundation.reInit('equalizer');
5718		if (requested_page == 0) {
5719			$('#previousBtn').hide();
5720		} else {
5721			$('#previousBtn').show();
5722		}
5723
5724		if ((requested_page + 1) * 10 >= parsed_process.length) {
5725			$('#nextBtn').hide();
5726		} else {
5727			$('#nextBtn').show();
5728		}
5729		$('html,body').scrollTop(0);
5730	}
5731
5732}
5733
5734function getPaginatedLazyLoad(page, tagId, pageUrl, isAuthorSearch) {
5735    if(!$('.tag-page-link-' + page).hasClass('tag-page-active')) {
5736        $('.tag-page-link').removeClass('tag-page-active');
5737        $('.tag-page-link-' + page).addClass('tag-page-active');
5738        requested_page = parseInt(page, 10) - 1;
5739        getLazyLoadPagesFromTag(tagId, pageUrl, isAuthorSearch);
5740        $('.tag-page-link').blur();
5741        $('.tagNextButton').blur();
5742        $('.tagPrevButton').blur();
5743	}
5744}
5745
5746function getPaginatedLazyLoadPrev(tagId, pageUrl, isAuthorSearch) {
5747	requested_page = requested_page - 1;
5748	getLazyLoadPagesFromTag(tagId, pageUrl, isAuthorSearch);
5749	$('.tag-page-link').removeClass('tag-page-active');
5750	$('.tag-page-link-' + (requested_page + 1)).addClass('tag-page-active');
5751	$('.tag-page-link').blur();
5752	$('.tagNextButton').blur();
5753	$('.tagPrevButton').blur();
5754}
5755
5756function getPaginatedLazyLoadNext(tagId, pageUrl, isAuthorSearch) {
5757	requested_page = requested_page + 1;
5758	getLazyLoadPagesFromTag(tagId, pageUrl, isAuthorSearch);
5759	$('.tag-page-link').removeClass('tag-page-active');
5760	$('.tag-page-link-' + (requested_page + 1)).addClass('tag-page-active');
5761	$('.tag-page-link').blur();
5762	$('.tagNextButton').blur();
5763	$('.tagPrevButton').blur();
5764}
5765
5766$(function(){
5767
5768	/**
5769	 * 'Jump to Previous'
5770	 */
5771
5772	$('#previousBtn').on('click',function() {
5773		var data = $(this).data('options');
5774		getPaginatedLazyLoadPrev(data.tagId, data.pageUrl, data.isAuthorSearch);
5775	});
5776
5777	/**
5778	 * 'Jump to Next'
5779	 */
5780
5781	$('#nextBtn').on('click',function() {
5782		var data = $(this).data('options');
5783		getPaginatedLazyLoadNext(data.tagId, data.pageUrl, data.isAuthorSearch);
5784	});
5785
5786	/**
5787	 * 'Jump to Specific Page'
5788	 */
5789
5790	$('.tag-page-link').on('click', function() {
5791		var data = $(this).data('options');
5792		getPaginatedLazyLoad(data.page, data.tagId, data.pageUrl, data.isAuthorSearch);
5793	});
5794});
5795(function defineMustache(global,factory){if(typeof exports==="object"&&exports&&typeof exports.nodeName!=="string"){factory(exports)}else if(typeof define==="function"&&define.amd){define(["exports"],factory)}else{global.Mustache={};factory(global.Mustache)}})(this,function mustacheFactory(mustache){var objectToString=Object.prototype.toString;var isArray=Array.isArray||function isArrayPolyfill(object){return objectToString.call(object)==="[object Array]"};function isFunction(object){return typeof object==="function"}function typeStr(obj){return isArray(obj)?"array":typeof obj}function escapeRegExp(string){return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(obj,propName){return obj!=null&&typeof obj==="object"&&propName in obj}var regExpTest=RegExp.prototype.test;function testRegExp(re,string){return regExpTest.call(re,string)}var nonSpaceRe=/\S/;function isWhitespace(string){return!testRegExp(nonSpaceRe,string)}var entityMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function escapeHtml(string){return String(string).replace(/[&<>
5795"'`=\/]/g,function fromEntityMap(s){return entityMap[s]})}var whiteRe=/\s*/;var spaceRe=/\s+/;var equalsRe=/\s*=/;var curlyRe=/\s*\}/;var tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate(template,tags){if(!template)return[];var sections=[];var tokens=[];var spaces=[];var hasTag=false;var nonSpace=false;function stripSpace(){if(hasTag&&!nonSpace){while(spaces.length)delete tokens[spaces.pop()]}else{spaces=[]}hasTag=false;nonSpace=false}var openingTagRe,closingTagRe,closingCurlyRe;function compileTags(tagsToCompile){if(typeof tagsToCompile==="string")tagsToCompile=tagsToCompile.split(spaceRe,2);if(!isArray(tagsToCompile)||tagsToCompile.length!==2)throw new Error("Invalid tags: "+tagsToCompile);openingTagRe=new RegExp(escapeRegExp(tagsToCompile[0])+"\\s*");closingTagRe=new RegExp("\\s*"+escapeRegExp(tagsToCompile[1]));closingCurlyRe=new RegExp("\\s*"+escapeRegExp("}"+tagsToCompile[1]))}compileTags(tags||mustache.tags);var scanner=new Scanner(template);var start,type,value,chr,token,openSection;while(!scanner.eos()){start=scanner.pos;value=scanner.scanUntil(openingTagRe);if(value){for(var i=0,valueLength=value.length;i<valueLength;++i){chr=value.charAt(i);if(isWhitespace(chr)){spaces.push(tokens.length)}else{nonSpace=true}tokens.push(["text",chr,start,start+1]);start+=1;if(chr==="\n")stripSpace()}}if(!scanner.scan(openingTagRe))break;hasTag=true;type=scanner.scan(tagRe)||"name";scanner.scan(whiteRe);if(type==="="){value=scanner.scanUntil(equalsRe);scanner.scan(equalsRe);scanner.scanUntil(closingTagRe)}else if(type==="{"){value=scanner.scanUntil(closingCurlyRe);scanner.scan(curlyRe);scanner.scanUntil(closingTagRe);type="&"}else{value=scanner.scanUntil(closingTagRe)}if(!scanner.scan(closingTagRe))throw new Error("Unclosed tag at "+scanner.pos);token=[type,value,start,scanner.pos];tokens.push(token);if(type==="#"||type==="^"){sections.push(token)}else if(type==="/"){openSection=sections.pop();if(!openSection)throw new Error('Unopened section "'+value+'" at '+start);if(openSection[1]!==value)throw new Error('Unclosed section "'+openSection[1]+'" at '+start)}else if(type==="name"||type==="{"||type==="&"){nonSpace=true}else if(type==="="){compileTags(value)}}openSection=sections.pop();if(openSection)throw new Error('Unclosed section "'+openSection[1]+'" at '+scanner.pos);return nestTokens(squashTokens(tokens))}function squashTokens(tokens){var squashedTokens=[];var token,lastToken;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];if(token){if(token[0]==="text"&&lastToken&&lastToken[0]==="text"){lastToken[1]+=token[1];lastToken[3]=token[3]}else{squashedTokens.push(token);lastToken=token}}}return squashedTokens}function nestTokens(tokens){var nestedTokens=[];var collector=nestedTokens;var sections=[];var token,section;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];switch(token[0]){case"#":case"^":collector.push(token);sections.push(token);collector=token[4]=[];break;case"/":section=sections.pop();section[5]=token[2];collector=sections.length>0?sections[sections.length-1][4]:nestedTokens;break;default:collector.push(token)}}return nestedTokens}function Scanner(string){this.string=string;this.tail=string;this.pos=0}Scanner.prototype.eos=function eos(){return this.tail===""};Scanner.prototype.scan=function scan(re){var match=this.tail.match(re);if(!match||match.index!==0)return"";var string=match[0];this.tail=this.tail.substring(string.length);this.pos+=string.length;return string};Scanner.prototype.scanUntil=function scanUntil(re){var index=this.tail.search(re),match;switch(index){case-1:match=this.tail;this.tail="";break;case 0:match="";break;default:match=this.tail.substring(0,index);this.tail=this.tail.substring(index)}this.pos+=match.length;return match};function Context(view,parentContext){this.view=view;this.cache={".":this.view};this.parent=parentContext}Context.prototype.push=function push(view){return new Context(view,this)};Context.prototype.lookup=function lookup(name){var cache=this.cache;var value;if(cache.hasOwnProperty(name)){value=cache[name]}else{var context=this,names,index,lookupHit=false;while(context){if(name.indexOf(".")>0){value=context.view;names=name.split(".");index=0;while(value!=null&&index<names.length){if(index===names.length-1)lookupHit=hasProperty(value,names[index]);value=value[names[index++]]}}else{value=context.view[name];lookupHit=hasProperty(context.view,name)}if(lookupHit)break;context=context.parent}cache[name]=value}if(isFunction(value))value=value.call(this.view);return value};function Writer(){this.cache={}}
5795Writer.prototype.clearCache=function clearCache(){this.cache={}};Writer.prototype.parse=function parse(template,tags){var cache=this.cache;var tokens=cache[template];if(tokens==null)tokens=cache[template]=parseTemplate(template,tags);return tokens};Writer.prototype.render=function render(template,view,partials){var tokens=this.parse(template);var context=view instanceof Context?view:new Context(view);return this.renderTokens(tokens,context,partials,template)};Writer.prototype.renderTokens=function renderTokens(tokens,context,partials,originalTemplate){var buffer="";var token,symbol,value;for(var i=0,numTokens=tokens.length;i<numTokens;++i){value=undefined;token=tokens[i];symbol=token[0];if(symbol==="#")value=this.renderSection(token,context,partials,originalTemplate);else if(symbol==="^")value=this.renderInverted(token,context,partials,originalTemplate);else if(symbol===">")value=this.renderPartial(token,context,partials,originalTemplate);else if(symbol==="&")value=this.unescapedValue(token,context);else if(symbol==="name")value=this.escapedValue(token,context);else if(symbol==="text")value=this.rawValue(token);if(value!==undefined)buffer+=value}return buffer};
5795Writer.prototype.renderSection=function renderSection(token,context,partials,originalTemplate){var self=this;var buffer="";var value=context.lookup(token[1]);function subRender(template){return self.render(template,context,partials)}if(!value)return;if(isArray(value)){for(var j=0,valueLength=value.length;j<valueLength;++j){buffer+=this.renderTokens(token[4],context.push(value[j]),partials,originalTemplate)}}else if(typeof value==="object"||typeof value==="string"||typeof value==="number"){buffer+=this.renderTokens(token[4],context.push(value),partials,originalTemplate)}else if(isFunction(value)){if(typeof originalTemplate!=="string")throw new Error("Cannot use higher-order sections without the original template");value=value.call(context.view,originalTemplate.slice(token[3],token[5]),subRender);if(value!=null)buffer+=value}else{buffer+=this.renderTokens(token[4],context,partials,originalTemplate)}return buffer};Writer.prototype.renderInverted=function renderInverted(token,context,partials,originalTemplate){var value=context.lookup(token[1]);if(!value||isArray(value)&&value.length===0)return this.renderTokens(token[4],context,partials,originalTemplate)};Writer.prototype.renderPartial=function renderPartial(token,context,partials){if(!partials)return;var value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null)return this.renderTokens(this.parse(value),context,partials,value)};Writer.prototype.unescapedValue=function unescapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function escapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return mustache.escape(value)};Writer.prototype.rawValue=function rawValue(token){return token[1]};mustache.name="mustache.js";mustache.version="2.3.0";mustache.tags=["{{","}}"];var defaultWriter=new Writer;mustache.clearCache=function clearCache(){return defaultWriter.clearCache()};mustache.parse=function parse(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function render(template,view,partials){if(typeof template!=="string"){throw new TypeError('Invalid template! Template should be a "string" '+'but "'+typeStr(template)+'" was given as the first '+"argument for mustache#render(template, view, partials)")}return defaultWriter.render(template,view,partials)};mustache.to_html=function to_html(template,view,partials,send){var result=mustache.render(template,view,partials);if(isFunction(send)){send(result)}else{return result}};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;return mustache});
5796/**
5797 * Initialize Block
5798 */
5799
5800var ajaxCall = false;
5801var pendingRequest = false;
5802var resultSetFeed = '';
5803var parsed_process_feed = [];
5804var requested_page_feed = 0;
5805var align = 'right';
5806var last_width = $(window).width();
5807
5808var LatestFeedAction = {
5809    customEqualiser: function() {
5810        if ($(window).width() >= 640) {
5811            $('.equalisible-pennel:visible').css('height', '');
5812            $('.equalisible-green-imag:visible').css('height', ''); // To compensate paddings
5813            $('.equalisible-green-text:visible').css('height', '');
5814
5815            var maxHeight = Math.max.apply(null, $('.equalise-all-penels:visible').map(function() {
5816                var heightToAdd = $(this).find('.results-tag-links').height() ? $(this).find('.results-tag-links').height() : 0;
5817                return $(this).height() + heightToAdd;
5818            }).get());
5819
5820            if(homePageVideo.ElementExist($('.single-panel-equalizer'))) {
5821                var featurePostHeight = LatestFeedAction.singleCardEqualizer()
5822                $('.single-panel-equalizer:visible').css('height','').height(featurePostHeight);
5823            }
5824
5825            $('.equalisible-pennel:visible').height(maxHeight - 20);
5826            $('.equalisible-green-imag:visible').height(maxHeight); // To compensate paddings
5827            $('.equalisible-green-text:visible').height(maxHeight);
5828        } else {
5829            // Code added to equalize for devices
5830            $('.equalisible-pennel:visible').css('height', '');
5831            $('.equalisible-green-imag:visible').css('height', ''); // To compensate paddings
5832            $('.equalisible-green-text:visible').css('height', '');
5833            if(homePageVideo.ElementExist($('.single-panel-equalizer'))) {
5834                var maxHeight = LatestFeedAction.singleCardEqualizer();
5835                $('.single-panel-equalizer:visible').css('height','').height(maxHeight); //Compensate Padding
5836            }
5837
5838            $('.equalise-all-penels:visible').map(function() {
5839                var heightToAdd = $(this).find('.results-tag-links').height() ? $(this).find('.results-tag-links').height() : 0;
5840                if (heightToAdd > 0 && $(this).hasClass('equalisible-green-text')) {
5841                    let _finalHeight = $(this).height() + heightToAdd;
5842                    let _heightCheck =  $(this).find('.opaque-article').height() + $(this).find('.results-tag-links').height();
5843                    if($(this).find('.opaque-article') && (_heightCheck > parseInt($(this).css('min-height'), 10))) {
5844                        $(this).height(_finalHeight);
5845                    }
5846                }
5847            });
5848        }
5849    },
5850
5851    singleCardEqualizer: function() {
5852        return Math.max.apply(null, $('.single-panel-equalizer:visible .equalize-me').map(function() {
5853                    var heightToAdd = $(this).parent().find('.results-tag-links').height() ? $(this).parent().find('.results-tag-links').height() : 0;
5854                    return $(this).height() + heightToAdd;
5855                }).get());
5856    }
5857};
5858
5859/**
5860 * Function to be invoked on DOM ready
5861 */
5862
5863$(function() {
5864    if ($('.equalise-all-penels').length) {
5865        setTimeout(function() {
5866            LatestFeedAction.customEqualiser();
5867        }, 250);
5868
5869        $(window).on('resize', function() {
5870            var new_width = $(window).width();
5871            if (new_width !== last_width) {
5872                LatestFeedAction.customEqualiser();
5873                last_width = new_width;
5874            }
5875        });
5876    }
5877});
5878
5879/**
5880 * Function to execute on click of load more button.
5881 */
5882
5883function getLatestPosts(path, authorName) {
5884    var position = $(window).scrollTop();
5885    var isPro = false;
5886    if (window.location.href.indexOf('/pro') !== -1) {
5887        isPro = true;
5888    }
5889    var ajaxUrl = '';
5890    if (isPro) {
5891        ajaxUrl = '/pro' + '/latestfeed/latestFeedServlet.createLatestFeed/';
5892    } else {
5893        ajaxUrl = '/latestfeed/latestFeedServlet.createLatestFeed/';
5894    }
5895    if(!pendingRequest) {
5896        if (!ajaxCall) {
5897            pendingRequest = true;
5898            $.ajax({
5899                url: ajaxUrl,
5900                type: 'get',
5901                data: {"path":path,
5902                  "authorName" : authorName},
5903                success: function(data) {
5904                    resultSetFeed = data;
5905                    if ($('.last-graph-image').length > 1) {
5906                        if ($('.last-graph-image:nth-last-child(2)').hasClass('right')) {
5907                            align = '';
5908                        }
5909                    }
5910                    for (var i = 0; i < resultSetFeed.list.length; i+=1) {
5911                        var parsed_array = resultSetFeed.list[i];
5912                        if (parsed_array.articleType === 'article') {
5913                            parsed_array.article = true;
5914                        } else if (parsed_array.articleType === 'video') {
5915                            parsed_array.video = true;
5916                        } else if (parsed_array.articleType === 'graph') {
5917                            parsed_array.graph = true;
5918                        } else if (parsed_array.articleType === 'quiz') {
5919                            parsed_array.quiz = true;
5920                        } else if (parsed_array.articleType === 'house') {
5921                            parsed_array.house = true;
5922                        } else if (parsed_array.articleType === 'panel') {
5923                            parsed_array.panel = true;
5924                        } else if (parsed_array.articleType === 'podcast') {
5925                            parsed_array.podcast = true;
5926                        }
5927
5928                        if (parsed_array.postType === 'hightlighted-post') {
5929                            parsed_array.hightlighted = true;
5930                            parsed_array.align = align;
5931                            if (align === 'right') {
5932                                align = '';
5933                            } else {
5934                                align = 'right';
5935                            }
5936
5937                        }
5938                        var tag_list = parsed_array.tagDetailsList;
5939                        if (tag_list.length > 0) {
5940                            var first_tag = tag_list[0];
5941                            var last_tag = tag_list[tag_list.length - 1];
5942                            last_tag.last = true;
5943                            first_tag.first = true;
5944                            tag_list[0] = first_tag;
5945                            tag_list[tag_list.length - 1] = last_tag;
5946                        }
5947
5948                        parsed_array.tagDetailsList = tag_list;
5949                        parsed_process_feed.push(parsed_array);
5950                    }
5951
5952                    var current_process = parsed_process_feed.slice((requested_page_feed * 10), (requested_page_feed * 10) + 10);
5953                    var template = $('#mustache-templ-latest-feed').html();
5954
5955                    var html = Mustache.to_html(template, current_process);
5956                    $('#parent-latest-feed').append(html);
5957                    imageRendition.showRendition();
5958                    LatestFeedAction.customEqualiser();
5959                    $(window).scrollTop(position);
5960                    if ((requested_page_feed + 1) * 10 >= parsed_process_feed.length) {
5961                        $('.loadButtonWrapper').hide();
5962                    }
5963                    if ((requested_page_feed + 2) * 10 >= parsed_process_feed.length) {
5964                        $('#load-more-num').html(parsed_process_feed.length - ((requested_page_feed + 1) * 10));
5965                    } else {
5966                        $('#load-more-num').html('10 +');
5967                    }
5968
5969                    requested_page_feed = requested_page_feed + 1;
5970                    ajaxCall = true;
5971                    pendingRequest = false;
5972                }
5973            });
5974        } else {
5975            var current_process = parsed_process_feed.slice((requested_page_feed * 10), (requested_page_feed * 10) + 10);
5976            var template = $('#mustache-templ-latest-feed').html();
5977            var html = Mustache.to_html(template, current_process);
5978            $('#parent-latest-feed').append(html);
5979            imageRendition.showRendition();
5980            LatestFeedAction.customEqualiser();
5981            $(window).scrollTop(position);
5982            if ((requested_page_feed + 1) * 10 >= parsed_process_feed.length) {
5983                $('.loadButtonWrapper').hide();
5984            }
5985            if ((requested_page_feed + 2) * 10 >= parsed_process_feed.length) {
5986                $('#load-more-num').html(parsed_process_feed.length - ((requested_page_feed + 1) * 10));
5987            } else {
5988                $('#load-more-num').html('10 +');
5989            }
5990
5991            requested_page_feed = requested_page_feed + 1;
5992        }
5993    }
5994}
5995
5996;
5997/* GV Stands for Generic Video */
5998var genericEqualizer = {
5999
6000    EqualizerConfiguration: function () {
6001        genericEqualizer.EqualizerResize();
6002        $(window).on('debouncedresize.genericEqualizer',function () {
6003            genericEqualizer.Equalizerblank();
6004            genericEqualizer.EqualizerResize();
6005        });
6006
6007    },
6008
6009    Equalizerblank: function () {
6010        $('.headSection').each(function () {
6011            $(this).css('height', '');
6012        });
6013
6014    },
6015
6016    EqualizerResize: function () {
6017        var maxHeight = -1;
6018        $('.headSection').each(function () {
6019            maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
6020        });
6021        $('.headSection').each(function () {
6022            $(this).height(maxHeight);
6023        });
6024
6025    }
6026
6027};
6028$(document).ready(function() {
6029	$('#unsubscribeForm').on('submit', function(e) {
6030		e.preventDefault();
6031		e.stopPropagation();
6032		$("#unsubscribeButton").attr('disabled'  , true);
6033		$.ajax({
6034			url : '/bin/content.unsubscribeServlet.unsubscribe',
6035			type : 'post',
6036			data : {
6037				"firstName" : $("#firstName").val(),
6038				"lastName" : $("#lastName").val(),
6039				"address1" : $("#address1").val(),
6040				"city"	   : $("#city").val(),
6041				"state" : $("#state").val(),
6042				"zip" : $("#zip").val(),
6043				"email"	   : $("#email").val(),
6044				"mobileNo" : $("#mobileNo").val()
6045			},
6046			success : function(data) {
6047				if(data.length) {
6048					$('#msg').html($('#errMsg').val());
6049					$('#msg').css("display", "block");
6050					$('#msg').css("color", "red");
6051					$('#msg').hide().fadeIn();
6052					bhfFormValidator.addValidationError();
6053					setTimeout(function() {
6054						$('#msg').fadeOut();
6055						$('#msg').html("");
6056						$('#msg').css("display", "none");
6057					}, 4000);
6058			
6059				} else {
6060					document.getElementById('unsubscribeForm').reset();
6061					if ($(".unsubscribe-search").length) {
6062						$(".unsubscribe-search").val([]).trigger('change');
6063					}
6064					bhfFormValidator.hidePhoneMask($('.phone'));
6065					$(".formIconPosition").each(function(){
6066						$(this).hide();
6067					});
6068					$('#msg').html("Request Submitted Successfully!");
6069					$('#msg').css("display", "block");
6070					$('#msg').css("color", "green");
6071					$('#msg').hide().fadeIn();
6072					setTimeout(function() {
6073						$('#msg').fadeOut();
6074						$('#msg').html("");
6075						$('#msg').css("display", "none");
6076					}, 2000);
6077				}
6078			},
6079			error : function() {
6080				$('#msg').html("Failed to submit the request, please try again after sometime!");
6081				$('#msg').css("display", "block");
6082				$('#msg').css("color", "red");
6083				$('#msg').hide().fadeIn();
6084				setTimeout(function() {
6085					$('#msg').fadeOut();
6086					$('#msg').html("");
6087					$('#msg').css("display", "none");
6088				}, 2000);
6089			}
6090		});
6091	});
6092});
6093
6094var genericShortcuts = {
6095
6096/************ Track total checkbox selected */
6097  limit_track: 0,
6098
6099/************ Limit to select the checkbox */
6100  limit_selection: 5,
6101
6102/************ Data which will save to session */
6103  sessionData: {
6104    "form_items":[]
6105  },
6106
6107/************ 'USERID' will store here for now */
6108  userID: 'eyzOEg1FonFOHtEIDM3mi1bnus4xoYtz',
6109
6110/************* Initialization starts from here */
6111  init: function(){
6112    if($('.shortcuts').length!==0 && $('.shortcutJson').length!==0)
6113    {
6114      genericShortcuts.shortcutsSideNavConfig();
6115      genericShortcuts.createShortcuts();
6116      genericShortcuts.apiGetGist({url:'userPreferenceServlet.userPreference/?userId=',user:genericShortcuts.userID,type:'GET'});
6117    }
6118  },
6119
6120/************ CALLBACK TO SET VALUE OF CHECKBOX ACCORDING TO THE G
6120ET REQUEST : FUNCTION CALL FROM apiGetGist() */
6121  onLoadCheckbox: function(data) {
6122      for(var i in data)
6123      {
6124        $('input[type="checkbox"]').each(function(){
6125          if(($(this).data('link')+'.html') === data[i].link)
6126          {
6127            $(this).attr('checked','checked');
6128            genericShortcuts.limit_track+=1;
6129          }
6130        });
6131      }
6132  },
6133
6134/************ SIDENAV USER FLOW : FUNCTION CALL FROM init() */
6135  shortcutsSideNavConfig: function(){
6136      if($(window).width() > 929) {
6137          $(document).on('click','.open-shortcuts',function(){
6138              $('.shortcuts').css('left','-25%');
6139          });
6140          $('.my-shortcuts').on('click','.close-shortcuts',function(){
6141              $('.shortcuts').css('left','-51%');
6142          });
6143          $('.my-shortcuts').on('click','.show-all-shortcuts',function(){
6144              $('.shortcuts').css('left','0%');
6145          });
6146      }
6147      else {
6148          $(document).on('click','.open-shortcuts',function(){
6149              $('.shortcuts').css('left','-50%');
6150          });
6151          $('.my-shortcuts').on('click','.close-shortcuts',function(){
6152              $('.shortcuts').css('left','-101%');
6153          });
6154          $('.my-shortcuts').on('click','.show-all-shortcuts',function(){
6155              $('.shortcuts').css('left','0%');
6156          });
6157      }
6158  },
6159
6160/************ CALLBACK TO THE LIST OF ALL SHORTCUTS : FUNCTION CALL FROM createShortcuts() */
6161  jsonResponse:function(){
6162      return $(document).find('.shortcutJson').data('shortcut-json');
6163  },
6164
6165/************ CALLBACK FUNCTION TO GENERATE ALL SHORTCUTS : FUNCTION CALL FROM createShortcuts() */
6166  shortcutTemplate:function(item){
6167      var $ul = $('.all-shortcuts .all-shortcuts-ul');
6168      var $template= $('#shortcuts-template').html();
6169      $ul.append(Mustache.render($template, item));
6170  },
6171
6172/************ FFUNCTION TO CREATE THE ALL SHORTCUTS LIST : FUNCTION CALL FROM init() */
6173  createShortcuts: function(){
6174      var cmsShortcuts=genericShortcuts.jsonResponse();
6175      for (var i in cmsShortcuts) {
6176        genericShortcuts.shortcutTemplate(cmsShortcuts[i]);
6177      }
6178      var $template= $('#save-template').html();
6179      $('.all-shortcuts ul').append(Mustache.render($template,{value:'SAVE'}));
6180      genericShortcuts.handlerInvoke();
6181  },
6182
6183/************* CALLBACK TO SHOW THE LIMIT WARNING MESSAGE : FUNCTION CALL FROM handlerInvoke() */
6184  showLimitMessage: function(){
6185      $('.selection-limit').css('opacity','1');
6186      setTimeout(function(){
6187          $('.selection-limit').css('opacity','0');
6188      },1200);
6189  },
6190
6191/************ FUNCTION TO SET EVENTS ON THE CHECKBOX AND SAVE BUTTON : FUNCTION CALL FROM createShortcuts() */
6192  handlerInvoke: function(){
6193      $('.all-shortcuts input[type="checkbox"]').on('change', function(e) {
6194         if($(e.target).is(':checked')) {
6195          if(genericShortcuts.limit_track < genericShortcuts.limit_selection) {
6196              genericShortcuts.limit_track+=1;
6197          }
6198          else {
6199              $(e.target).prop('checked',false);
6200              genericShortcuts.showLimitMessage();
6201          }
6202         }
6203         else {
6204          genericShortcuts.limit_track-=1;
6205         }
6206      });
6207
6208      $('.all-shortcuts-ul').on('click','.save-shortcuts',function(){
6209          $('li .md-chip-remove').off('click');
6210          var selectedShortcuts=[];
6211          if (typeof(Storage) !== 'undefined') {
6212              $('input[type="checkbox"]:checked').each(function(){
6213                  var item = {};
6214                  item.title = $(this).data('title');
6215                  item.link = $(this).data('link')+'.html';
6216                  item.label = $(this).data('label');
6217                  selectedShortcuts.push(item);
6218              });
6219              genericShortcuts.sessionData.form_items.length = 0;
6220              for(var i in selectedShortcuts){
6221                genericShortcuts.sessionData.form_items.push(selectedShortcuts[i]);
6222              }
6223              genericShortcuts.storeInSession({key:'shortcut_links',data:genericShortcuts.sessionData});
6224              genericShortcuts.createChipList();
6225              genericShortcuts.apiPostGist({url:'/userPreferenceServlet.userPreference',type:'POST',user:genericShortcuts.userID});
6226
6227          } else {
6228              alert('No Storage available');
6229          }
6230      });
6231  },
6232
6233/************ FUNCTION TO STORE IN SESSION : * */
6234  storeInSession: function(args){
6235      window.localStorage.setItem(args.key, JSON.stringify(args.data));
6236  },
6237
6238/************ FUNCTION TO GET DATA FROM SESSION : * */
6239  getFromSession: function(key){
6240      if(localStorage.getItem(key)) {
6241        try{
6242            return JSON.parse(localStorage.getItem(key));
6243        }catch(e){
6244            console.log('Error getting the session data',e);
6245        }
6246      }
6247      else {
6248        return false;
6249      }
6250  },
6251
6252/************ THE CHIP TEMPLATE FUNCTION : FUNCTION CALL FROM createChipList() */
6253  chipTemplate:function(value,flagValue){
6254      var $ul = $('.my-shortcuts .my-shortcuts-ul');
6255      var $template= $('#chip-template').html();
6256      $ul.append(Mustache.render($template, {value: value,flag : flagValue}));
6257  },
6258
6259/************ FUNCTION TO CREATE THE CHIP LIST AND ALSO SET IN SESSION : FUNCTION CALL FROM getApiGist() && handlerInvoke() */
6260  createChipList: function(){
6261      var storedArray = genericShortcuts.getFromSession('shortcut_links');
6262      $('.my-shortcuts ul').empty();
6263      for (var i in storedArray.form_items){
6264          genericShortcuts.chipTemplate(storedArray.form_items[i],1);
6265      }
6266      genericShortcuts.removeChipInvoke();
6267  },
6268
6269/************ FUNCTION TO SET EVENT HANDLER TO REMOVE CHIP : FUNCTION CALL FROM createChipList() */
6270  removeChipInvoke:function(){
6271      $('li .md-chip-remove').on('click',function(){
6272          var this_element = $(this).parent('li:first').data('link').split('.')[0];
6273          $('.all-shortcuts ul li').find('[data-link="'+this_element+'"]').prop('checked',false);
6274          $(this).parent('li:first').remove();
6275          genericShortcuts.popItem($(this).parent('li:first').data('flag'),$(this).parent('li:first').data('link'));
6276      });
6277  },
6278
6279/************ FUNCTION TO REMOVE CHIP FROM UI AND ALSO SESSION : FUNCTION CALL FROM removeChipInvoke() */
6280  popItem: function(flag,value){
6281      genericShortcuts.popItemCallback({value:value,elements:genericShortcuts.sessionData.form_items});
6282      genericShortcuts.limit_track-=1;
6283      genericShortcuts.storeInSession({key:'shortcut_links',data:genericShortcuts.sessionData});
6284  },
6285
6286/************ CALLBACK of popItem() : FUNCTION CALL FROM popItem() */
6287  popItemCallback:function(args){
6288      try {
6289          args.elements = $.grep(args.elements,function(e){
6290            return e.link!==args.value;
6291          });
6292          genericShortcuts.sessionData.form_items.length = 0;
6293          genericShortcuts.sessionData.form_items=
6294          genericShortcuts.sessionData.form_items.concat(args.elements);
6295          genericShortcuts.storeInSession({key:'shortcut_links',data:genericShortcuts.sessionData});
6296          genericShortcuts.apiPostGist({url:'/userPreferenceServlet.userPreference',type:'POST',user:genericShortcuts.userID});
6297      }catch(e){
6298          console.log('Something Went wrong with removing an item',e);
6299      }
6300  },
6301
6302/************ Function to remove even-handlers */
6303  handlerRevoke: function(){
6304      $('.save-shortcuts').off('click');
6305      $('.all-shortcuts input[type="checkbox"]').off('change');
6306  },
6307
6308/*****************************************************************************************
6309*                                                                                        *
6310*                                   API CALL BLOCK                                       *
6311*                                                                                        *
6312******************************************************************************************/
6313
6314/************ GET REQUEST TO GET DATA FROM API : FUNCTION CALL FROM init() */
6315  apiGetGist:function(args){
6316      $.ajax({
6317        type: args.type,
6318        url: args.url+args.user,
6319        success: function(data) {
6320          data=JSON.parse(data);
6321          if(!$.isEmptyObject(data))
6322          {
6323            window.data=data;
6324             if(window.localStorage.getItem('shortcut_links')) {
6325                try{
6326                    window.localStorage.removeItem('shortcut_links');
6327                }catch(e){
6328                    console.log('Error clearing session',e);
6329                }
6330             }
6331            var testData=[];
6332            testData=testData.concat(data.form_items);
6333            genericShortcuts.sessionData.form_items.length = 0;
6334            genericShortcuts.sessionData.form_items=genericShortcuts.sessionData.form_items.concat(testData);
6335            window.localStorage.setItem('shortcut_links',JSON.stringify(genericShortcuts.sessionData));
6336            genericShortcuts.createChipList();
6337            genericShortcuts.onLoadCheckbox(genericShortcuts.getFromSession('shortcut_links').form_items);
6338          }
6339        },
6340        error: function(err){
6341          console.log('OOPS',err);
6342        }
6343      });
6344  },
6345
6346/************ POST REQUEST TO POST DATA TO API : FUNCTION CALL FROM save-shortcuts event and popItemCallback() */
6347  apiPostGist:function(args){
6348      var test={
6349        "userId" : args.user,
6350        "preferences" : ''
6351      };
6352      test.preferences=JSON.stringify(genericShortcuts.sessionData);
6353      $.ajax({
6354          type: args.type,
6355          url: args.url,
6356          data: test,
6357          success:function(data){
6358            console.log('Success',data);
6359          },
6360          error:function(err){
6361            console.log('Error',err);
6362          }
6363      });
6364  }
6365};
6366/**
6367 * html2pdf v0.8.0
6368 * Copyright (c) 2017 Erik Koopmans
6369 * Released under the MIT License.
6370 */
6371(function (global, factory) {
6372    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
6373        typeof define === 'function' && define.amd ? define(factory) :
6374            (global.html2pdf = factory());
6375}(this, (function () {
6376    'use strict';
6377
6378    var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
6379
6380    function commonjsRequire() {
6381        throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
6382    }
6383
6384
6385
6386    function createCommonjsModule(fn, module) {
6387        return module = { exports: {} }, fn(module, module.exports), module.exports;
6388    }
6389
6390    var es6Promise = createCommonjsModule(function (module, exports
vendor: 24,482 bytes, lines 6390-7064
6390) {
6391        /*!
6392         * @overview es6-promise - a tiny implementation of Promises/A+.
6393         * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
6394         * @license   Licensed under MIT license
6395         *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
6396         * @version   4.1.1
6397         */
6398
6399        (function (global, factory) {
6400            module.exports = factory();
6401        }(commonjsGlobal, (function () {
6402            function objectOrFunction(x) {
6403                var type = typeof x;
6404                return x !== null && (type === 'object' || type === 'function');
6405            }
6406
6407            function isFunction(x) {
6408                return typeof x === 'function';
6409            }
6410
6411            var _isArray = undefined;
6412            if (Array.isArray) {
6413                _isArray = Array.isArray;
6414            } else {
6415                _isArray = function (x) {
6416                    return Object.prototype.toString.call(x) === '[object Array]';
6417                };
6418            }
6419
6420            var isArray = _isArray;
6421
6422            var len = 0;
6423            var vertxNext = undefined;
6424            var customSchedulerFn = undefined;
6425
6426            var asap = function asap(callback, arg) {
6427                queue[len] = callback;
6428                queue[len + 1] = arg;
6429                len += 2;
6430                if (len === 2) {
6431                    // If len is 2, that means that we need to schedule an async flush.
6432                    // If additional callbacks are queued before the queue is flushed, they
6433                    // will be processed by this flush that we are scheduling.
6434                    if (customSchedulerFn) {
6435                        customSchedulerFn(flush);
6436                    } else {
6437                        scheduleFlush();
6438                    }
6439                }
6440            };
6441
6442            function setScheduler(scheduleFn) {
6443                customSchedulerFn = scheduleFn;
6444            }
6445
6446            function setAsap(asapFn) {
6447                asap = asapFn;
6448            }
6449
6450            var browserWindow = typeof window !== 'undefined' ? window : undefined;
6451            var browserGlobal = browserWindow || {};
6452            var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
6453            var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
6454
6455            // test for web worker but not in IE10
6456            var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
6457
6458            // node
6459            function useNextTick() {
6460                // node version 0.10.x displays a deprecation warning when nextTick is used recursively
6461                // see https://github.com/cujojs/when/issues/410 for details
6462                return function () {
6463                    return process.nextTick(flush);
6464                };
6465            }
6466
6467            // vertx
6468            function useVertxTimer() {
6469                if (typeof vertxNext !== 'undefined') {
6470                    return function () {
6471                        vertxNext(flush);
6472                    };
6473                }
6474
6475                return useSetTimeout();
6476            }
6477
6478            function useMutationObserver() {
6479                var iterations = 0;
6480                var observer = new BrowserMutationObserver(flush);
6481                var node = document.createTextNode('');
6482                observer.observe(node, { characterData: true });
6483
6484                return function () {
6485                    node.data = iterations = ++iterations % 2;
6486                };
6487            }
6488
6489            // web worker
6490            function useMessageChannel() {
6491                var channel = new MessageChannel();
6492                channel.port1.onmessage = flush;
6493                return function () {
6494                    return channel.port2.postMessage(0);
6495                };
6496            }
6497
6498            function useSetTimeout() {
6499                // Store setTimeout reference so es6-promise will be unaffected by
6500                // other code modifying setTimeout (like sinon.useFakeTimers())
6501                var globalSetTimeout = setTimeout;
6502                return function () {
6503                    return globalSetTimeout(flush, 1);
6504                };
6505            }
6506
6507            var queue = new Array(1000);
6508            function flush() {
6509                for (var i = 0; i < len; i += 2) {
6510                    var callback = queue[i];
6511                    var arg = queue[i + 1];
6512
6513                    callback(arg);
6514
6515                    queue[i] = undefined;
6516                    queue[i + 1] = undefined;
6517                }
6518
6519                len = 0;
6520            }
6521
6522            function attemptVertx() {
6523                try {
6524                    var r = commonjsRequire;
6525                    var vertx = r('vertx');
6526                    vertxNext = vertx.runOnLoop || vertx.runOnContext;
6527                    return useVertxTimer();
6528                } catch (e) {
6529                    return useSetTimeout();
6530                }
6531            }
6532
6533            var scheduleFlush = undefined;
6534            // Decide what async method to use to triggering processing of queued callbacks:
6535            if (isNode) {
6536                scheduleFlush = useNextTick();
6537            } else if (BrowserMutationObserver) {
6538                scheduleFlush = useMutationObserver();
6539            } else if (isWorker) {
6540                scheduleFlush = useMessageChannel();
6541            } else if (browserWindow === undefined && typeof commonjsRequire === 'function') {
6542                scheduleFlush = attemptVertx();
6543            } else {
6544                scheduleFlush = useSetTimeout();
6545            }
6546
6547            function then(onFulfillment, onRejection) {
6548                var _arguments = arguments;
6549
6550                var parent = this;
6551
6552                var child = new this.constructor(noop);
6553
6554                if (child[PROMISE_ID] === undefined) {
6555                    makePromise(child);
6556                }
6557
6558                var _state = parent._state;
6559
6560                if (_state) {
6561                    (function () {
6562                        var callback = _arguments[_state - 1];
6563                        asap(function () {
6564                            return invokeCallback(_state, child, callback, parent._result);
6565                        });
6566                    })();
6567                } else {
6568                    subscribe(parent, child, onFulfillment, onRejection);
6569                }
6570
6571                return child;
6572            }
6573
6574            /**
6575              `Promise.resolve` returns a promise that will become resolved with the
6576              passed `value`. It is shorthand for the following:
6577            
6578              ```javascript
6579              let promise = new Promise(function(resolve, reject){
6580                resolve(1);
6581              });
6582            
6583              promise.then(function(value){
6584                // value === 1
6585              });
6586              ```
6587            
6588              Instead of writing the above, your code now simply becomes the following:
6589            
6590              ```javascript
6591              let promise = Promise.resolve(1);
6592            
6593              promise.then(function(value){
6594                // value === 1
6595              });
6596              ```
6597            
6598              @method resolve
6599              @static
6600              @param {Any} value value that the returned promise will be resolved with
6601              Useful for tooling.
6602              @return {Promise} a promise that will become fulfilled with the given
6603              `value`
6604            */
6605            function resolve$1(object) {
6606                /*jshint validthis:true */
6607                var Constructor = this;
6608
6609                if (object && typeof object === 'object' && object.constructor === Constructor) {
6610                    return object;
6611                }
6612
6613                var promise = new Constructor(noop);
6614                resolve(promise, object);
6615                return promise;
6616            }
6617
6618            var PROMISE_ID = Math.random().toString(36).substring(16);
6619
6620            function noop() { }
6621
6622            var PENDING = void 0;
6623            var FULFILLED = 1;
6624            var REJECTED = 2;
6625
6626            var GET_THEN_ERROR = new ErrorObject();
6627
6628            function selfFulfillment() {
6629                return new TypeError("You cannot resolve a promise with itself");
6630            }
6631
6632            function cannotReturnOwn() {
6633                return new TypeError('A promises callback cannot return that same promise.');
6634            }
6635
6636            function getThen(promise) {
6637                try {
6638                    return promise.then;
6639                } catch (error) {
6640                    GET_THEN_ERROR.error = error;
6641                    return GET_THEN_ERROR;
6642                }
6643            }
6644
6645            function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
6646                try {
6647                    then$$1.call(value, fulfillmentHandler, rejectionHandler);
6648                } catch (e) {
6649                    return e;
6650                }
6651            }
6652
6653            function handleForeignThenable(promise, thenable, then$$1) {
6654                asap(function (promise) {
6655                    var sealed = false;
6656                    var error = tryThen(then$$1, thenable, function (value) {
6657                        if (sealed) {
6658                            return;
6659                        }
6660                        sealed = true;
6661                        if (thenable !== value) {
6662                            resolve(promise, value);
6663                        } else {
6664                            fulfill(promise, value);
6665                        }
6666                    }, function (reason) {
6667                        if (sealed) {
6668                            return;
6669                        }
6670                        sealed = true;
6671
6672                        reject(promise, reason);
6673                    }, 'Settle: ' + (promise._label || ' unknown promise'));
6674
6675                    if (!sealed && error) {
6676                        sealed = true;
6677                        reject(promise, error);
6678                    }
6679                }, promise);
6680            }
6681
6682            function handleOwnThenable(promise, thenable) {
6683                if (thenable._state === FULFILLED) {
6684                    fulfill(promise, thenable._result);
6685                } else if (thenable._state === REJECTED) {
6686                    reject(promise, thenable._result);
6687                } else {
6688                    subscribe(thenable, undefined, function (value) {
6689                        return resolve(promise, value);
6690                    }, function (reason) {
6691                        return reject(promise, reason);
6692                    });
6693                }
6694            }
6695
6696            function handleMaybeThenable(promise, maybeThenable, then$$1) {
6697                if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
6698                    handleOwnThenable(promise, maybeThenable);
6699                } else {
6700                    if (then$$1 === GET_THEN_ERROR) {
6701                        reject(promise, GET_THEN_ERROR.error);
6702                        GET_THEN_ERROR.error = null;
6703                    } else if (then$$1 === undefined) {
6704                        fulfill(promise, maybeThenable);
6705                    } else if (isFunction(then$$1)) {
6706                        handleForeignThenable(promise, maybeThenable, then$$1);
6707                    } else {
6708                        fulfill(promise, maybeThenable);
6709                    }
6710                }
6711            }
6712
6713            function resolve(promise, value) {
6714                if (promise === value) {
6715                    reject(promise, selfFulfillment());
6716                } else if (objectOrFunction(value)) {
6717                    handleMaybeThenable(promise, value, getThen(value));
6718                } else {
6719                    fulfill(promise, value);
6720                }
6721            }
6722
6723            function publishRejection(promise) {
6724                if (promise._onerror) {
6725                    promise._onerror(promise._result);
6726                }
6727
6728                publish(promise);
6729            }
6730
6731            function fulfill(promise, value) {
6732                if (promise._state !== PENDING) {
6733                    return;
6734                }
6735
6736                promise._result = value;
6737                promise._state = FULFILLED;
6738
6739                if (promise._subscribers.length !== 0) {
6740                    asap(publish, promise);
6741                }
6742            }
6743
6744            function reject(promise, reason) {
6745                if (promise._state !== PENDING) {
6746                    return;
6747                }
6748                promise._state = REJECTED;
6749                promise._result = reason;
6750
6751                asap(publishRejection, promise);
6752            }
6753
6754            function subscribe(parent, child, onFulfillment, onRejection) {
6755                var _subscribers = parent._subscribers;
6756                var length = _subscribers.length;
6757
6758                parent._onerror = null;
6759
6760                _subscribers[length] = child;
6761                _subscribers[length + FULFILLED] = onFulfillment;
6762                _subscribers[length + REJECTED] = onRejection;
6763
6764                if (length === 0 && parent._state) {
6765                    asap(publish, parent);
6766                }
6767            }
6768
6769            function publish(promise) {
6770                var subscribers = promise._subscribers;
6771                var settled = promise._state;
6772
6773                if (subscribers.length === 0) {
6774                    return;
6775                }
6776
6777                var child = undefined,
6778                    callback = undefined,
6779                    detail = promise._result;
6780
6781                for (var i = 0; i < subscribers.length; i += 3) {
6782                    child = subscribers[i];
6783                    callback = subscribers[i + settled];
6784
6785                    if (child) {
6786                        invokeCallback(settled, child, callback, detail);
6787                    } else {
6788                        callback(detail);
6789                    }
6790                }
6791
6792                promise._subscribers.length = 0;
6793            }
6794
6795            function ErrorObject() {
6796                this.error = null;
6797            }
6798
6799            var TRY_CATCH_ERROR = new ErrorObject();
6800
6801            function tryCatch(callback, detail) {
6802                try {
6803                    return callback(detail);
6804                } catch (e) {
6805                    TRY_CATCH_ERROR.error = e;
6806                    return TRY_CATCH_ERROR;
6807                }
6808            }
6809
6810            function invokeCallback(settled, promise, callback, detail) {
6811                var hasCallback = isFunction(callback),
6812                    value = undefined,
6813                    error = undefined,
6814                    succeeded = undefined,
6815                    failed = undefined;
6816
6817                if (hasCallback) {
6818                    value = tryCatch(callback, detail);
6819
6820                    if (value === TRY_CATCH_ERROR) {
6821                        failed = true;
6822                        error = value.error;
6823                        value.error = null;
6824                    } else {
6825                        succeeded = true;
6826                    }
6827
6828                    if (promise === value) {
6829                        reject(promise, cannotReturnOwn());
6830                        return;
6831                    }
6832                } else {
6833                    value = detail;
6834                    succeeded = true;
6835                }
6836
6837                if (promise._state !== PENDING) {
6838                    // noop
6839                } else if (hasCallback && succeeded) {
6840                    resolve(promise, value);
6841                } else if (failed) {
6842                    reject(promise, error);
6843                } else if (settled === FULFILLED) {
6844                    fulfill(promise, value);
6845                } else if (settled === REJECTED) {
6846                    reject(promise, value);
6847                }
6848            }
6849
6850            function initializePromise(promise, resolver) {
6851                try {
6852                    resolver(function resolvePromise(value) {
6853                        resolve(promise, value);
6854                    }, function rejectPromise(reason) {
6855                        reject(promise, reason);
6856                    });
6857                } catch (e) {
6858                    reject(promise, e);
6859                }
6860            }
6861
6862            var id = 0;
6863            function nextId() {
6864                return id++;
6865            }
6866
6867            function makePromise(promise) {
6868                promise[PROMISE_ID] = id++;
6869                promise._state = undefined;
6870                promise._result = undefined;
6871                promise._subscribers = [];
6872            }
6873
6874            function Enumerator$1(Constructor, input) {
6875                this._instanceConstructor = Constructor;
6876                this.promise = new Constructor(noop);
6877
6878                if (!this.promise[PROMISE_ID]) {
6879                    makePromise(this.promise);
6880                }
6881
6882                if (isArray(input)) {
6883                    this.length = input.length;
6884                    this._remaining = input.length;
6885
6886                    this._result = new Array(this.length);
6887
6888                    if (this.length === 0) {
6889                        fulfill(this.promise, this._result);
6890                    } else {
6891                        this.length = this.length || 0;
6892                        this._enumerate(input);
6893                        if (this._remaining === 0) {
6894                            fulfill(this.promise, this._result);
6895                        }
6896                    }
6897                } else {
6898                    reject(this.promise, validationError());
6899                }
6900            }
6901
6902            function validationError() {
6903                return new Error('Array Methods must be provided an Array');
6904            }
6905
6906            Enumerator$1.prototype._enumerate = function (input) {
6907                for (var i = 0; this._state === PENDING && i < input.length; i++) {
6908                    this._eachEntry(input[i], i);
6909                }
6910            };
6911
6912            Enumerator$1.prototype._eachEntry = function (entry, i) {
6913                var c = this._instanceConstructor;
6914                var resolve$$1 = c.resolve;
6915
6916                if (resolve$$1 === resolve$1) {
6917                    var _then = getThen(entry);
6918
6919                    if (_then === then && entry._state !== PENDING) {
6920                        this._settledAt(entry._state, i, entry._result);
6921                    } else if (typeof _then !== 'function') {
6922                        this._remaining--;
6923                        this._result[i] = entry;
6924                    } else if (c === Promise$2) {
6925                        var promise = new c(noop);
6926                        handleMaybeThenable(promise, entry, _then);
6927                        this._willSettleAt(promise, i);
6928                    } else {
6929                        this._willSettleAt(new c(function (resolve$$1) {
6930                            return resolve$$1(entry);
6931                        }), i);
6932                    }
6933                } else {
6934                    this._willSettleAt(resolve$$1(entry), i);
6935                }
6936            };
6937
6938            Enumerator$1.prototype._settledAt = function (state, i, value) {
6939                var promise = this.promise;
6940
6941                if (promise._state === PENDING) {
6942                    this._remaining--;
6943
6944                    if (state === REJECTED) {
6945                        reject(promise, value);
6946                    } else {
6947                        this._result[i] = value;
6948                    }
6949                }
6950
6951                if (this._remaining === 0) {
6952                    fulfill(promise, this._result);
6953                }
6954            };
6955
6956            Enumerator$1.prototype._willSettleAt = function (promise, i) {
6957                var enumerator = this;
6958
6959                subscribe(promise, undefined, function (value) {
6960                    return enumerator._settledAt(FULFILLED, i, value);
6961                }, function (reason) {
6962                    return enumerator._settledAt(REJECTED, i, reason);
6963                });
6964            };
6965
6966            /**
6967              `Promise.all` accepts an array of promises, and returns a new promise which
6968              is fulfilled with an array of fulfillment values for the passed promises, or
6969              rejected with the reason of the first passed promise to be rejected. It casts all
6970              elements of the passed iterable to promises as it runs this algorithm.
6971            
6972              Example:
6973            
6974              ```javascript
6975              let promise1 = resolve(1);
6976              let promise2 = resolve(2);
6977              let promise3 = resolve(3);
6978              let promises = [ promise1, promise2, promise3 ];
6979            
6980              Promise.all(promises).then(function(array){
6981                // The array here would be [ 1, 2, 3 ];
6982              });
6983              ```
6984            
6985              If any of the `promises` given to `all` are rejected, the first promise
6986              that is rejected will be given as an argument to the returned promises's
6987              rejection handler. For example:
6988            
6989              Example:
6990            
6991              ```javascript
6992              let promise1 = resolve(1);
6993              let promise2 = reject(new Error("2"));
6994              let promise3 = reject(new Error("3"));
6995              let promises = [ promise1, promise2, promise3 ];
6996            
6997              Promise.all(promises).then(function(array){
6998                // Code here never runs because there are rejected promises!
6999              }, function(error) {
7000                // error.message === "2"
7001              });
7002              ```
7003            
7004              @method all
7005              @static
7006              @param {Array} entries array of promises
7007              @param {String} label optional string for labeling the promise.
7008              Useful for tooling.
7009              @return {Promise} promise that is fulfilled when all `promises` have been
7010              fulfilled, or rejected if any of them become rejected.
7011              @static
7012            */
7013            function all$1(entries) {
7014                return new Enumerator$1(this, entries).promise;
7015            }
7016
7017            /**
7018              `Promise.race` returns a new promise which is settled in the same way as the
7019              first passed promise to settle.
7020            
7021              Example:
7022            
7023              ```javascript
7024              let promise1 = new Promise(function(resolve, reject){
7025                setTimeout(function(){
7026                  resolve('promise 1');
7027                }, 200);
7028              });
7029            
7030              let promise2 = new Promise(function(resolve, reject){
7031                setTimeout(function(){
7032                  resolve('promise 2');
7033                }, 100);
7034              });
7035            
7036              Promise.race([promise1, promise2]).then(function(result){
7037                // result === 'promise 2' because it was resolved before promise1
7038                // was resolved.
7039              });
7040              ```
7041            
7042              `Promise.race` is deterministic in that only the state of the first
7043              settled promise matters. For example, even if other promises given to the
7044              `promises` array argument are resolved, but the first settled promise has
7045              become rejected before the other promises became fulfilled, the returned
7046              promise will become rejected:
7047            
7048              ```javascript
7049              let promise1 = new Promise(function(resolve, reject){
7050                setTimeout(function(){
7051                  resolve('promise 1');
7052                }, 200);
7053              });
7054            
7055              let promise2 = new Promise(function(resolve, reject){
7056                setTimeout(function(){
7057                  reject(new Error('promise 2'));
7058                }, 100);
7059              });
7060            
7061              Promise.race([promise1, promise2]).then(function(result){
7062                // Code here never runs
7063              }, function(reason){
7064                // reason.message === 'promise 2' because promise 2 be
7064came rejected before
7065                // promise 1 became fulfilled
7066              });
7067              ```
7068            
7069              An example real-world use case is implementing timeouts:
7070            
7071              ```javascript
7072              Promise.race([ajax('foo.json'), timeout(5000)])
7073              ```
7074            
7075              @method race
7076              @static
7077              @param {Array} promises array of promises to observe
7078              Useful for tooling.
7079              @return {Promise} a promise which settles in the same way as the first passed
7080              promise to settle.
7081            */
7082            function race$1(entries) {
7083                /*jshint validthis:true */
7084                var Constructor = this;
7085
7086                if (!isArray(entries)) {
7087                    return new Constructor(function (_, reject) {
7088                        return reject(new TypeError('You must pass an array to race.'));
7089                    });
7090                } else {
7091                    return new Constructor(function (resolve, reject) {
7092                        var length = entries.length;
7093                        for (var i = 0; i < length; i++) {
7094                            Constructor.resolve(entries[i]).then(resolve, reject);
7095                        }
7096                    });
7097                }
7098            }
7099
7100            /**
7101              `Promise.reject` returns a promise rejected with the passed `reason`.
7102              It is shorthand for the following:
7103            
7104              ```javascript
7105              let promise = new Promise(function(resolve, reject){
7106                reject(new Error('WHOOPS'));
7107              });
7108            
7109              promise.then(function(value){
7110                // Code here doesn't run because the promise is rejected!
7111              }, function(reason){
7112                // reason.message === 'WHOOPS'
7113              });
7114              ```
7115            
7116              Instead of writing the above, your code now simply becomes the following:
7117            
7118              ```javascript
7119              let promise = Promise.reject(new Error('WHOOPS'));
7120            
7121              promise.then(function(value){
7122                // Code here doesn't run because the promise is rejected!
7123              }, function(reason){
7124                // reason.message === 'WHOOPS'
7125              });
7126              ```
7127            
7128              @method reject
7129              @static
7130              @param {Any} reason value that the returned promise will be rejected with.
7131              Useful for tooling.
7132              @return {Promise} a promise rejected with the given `reason`.
7133            */
7134            function reject$1(reason) {
7135                /*jshint validthis:true */
7136                var Constructor = this;
7137                var promise = new Constructor(noop);
7138                reject(promise, reason);
7139                return promise;
7140            }
7141
7142            function needsResolver() {
7143                throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
7144            }
7145
7146            function needsNew() {
7147                throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object c
7147onstructor cannot be called as a function.");
7148            }
7149
7150            /**
7151              Promise objects represent the eventual result of an asynchronous operation. The
7152              primary way of interacting with a promise is through its `then` method, which
7153              registers callbacks to receive either a promise's eventual value or the reason
7154              why the promise cannot be fulfilled.
7155            
7156              Terminology
7157              -----------
7158            
7159              - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
7160              - `thenable` is an object or function that defines a `then` method.
7161              - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
7162              - `exception` is a value that is thrown using the throw statement.
7163              - `reason` is a value that indicates why a promise was rejected.
7164              - `settled` the final resting state of a promise, fulfilled or rejected.
7165            
7166              A promise can be in one of three states: pending, fulfilled, or rejected.
7167            
7168              Promises that are fulfilled have a fulfillment value and are in the fulfilled
7169              state.  Promises that are rejected have a rejection reason and are in the
7170              rejected state.  A fulfillment value is never a thenable.
7171            
7172              Promises can also be said to *resolve* a value.  If this value is also a
7173              promise, then the original promise's settled state will match the value's
7174              settled state.  So a promise that *resolves* a promise that rejects will
7175              itself reject, and a promise that *resolves* a promise that fulfills will
7176              itself fulfill.
7177            
7178            
7179              Basic Usage:
7180              ------------
7181            
7182              ```js
7183              let promise = new Promise(function(resolve, reject) {
7184                // on success
7185                resolve(value);
7186            
7187                // on failure
7188                reject(reason);
7189              });
7190            
7191              promise.then(function(value) {
7192                // on fulfillment
7193              }, function(reason) {
7194                // on rejection
7195              });
7196              ```
7197            
7198              Advanced Usage:
7199              ---------------
7200            
7201              Promises shine when abstracting away asynchronous interactions such as
7202              `XMLHttpRequest`s.
7203            
7204              ```js
7205              function getJSON(url) {
7206                return new Promise(function(resolve, reject){
7207                  let xhr = new XMLHttpRequest();
7208            
7209                  xhr.open('GET', url);
7210                  xhr.onreadystatechange = handler;
7211                  xhr.responseType = 'json';
7212                  xhr.setRequestHeader('Accept', 'application/json');
7213                  xhr.send();
7214            
7215                  function handler() {
7216                    if (this.readyState === this.DONE) {
7217                      if (this.status === 200) {
7218                        resolve(this.response);
7219                      } else {
7220                        reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
7221                      }
7222                    }
7223                  };
7224                });
7225              }
7226            
7227              getJSON('/posts.json').then(function(json) {
7228                // on fulfillment
7229              }, function(reason) {
7230                // on rejection
7231              });
7232              ```
7233            
7234              Unlike callbacks, promises are great composable primitives.
7235            
7236              ```js
7237              Promise.all([
7238                getJSON('/posts'),
7239                getJSON('/comments')
7240              ]).then(function(values){
7241                values[0] // => postsJSON
7242                values[1] // => commentsJSON
7243            
7244                return values;
7245              });
7246              ```
7247            
7248              @class Promise
7249              @param {function} resolver
7250              Useful for tooling.
7251              @constructor
7252            */
7253            function Promise$2(resolver) {
7254                this[PROMISE_ID] = nextId();
7255                this._result = this._state = undefined;
7256                this._subscribers = [];
7257
7258                if (noop !== resolver) {
7259                    typeof resolver !== 'function' && needsResolver();
7260                    this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();
7261                }
7262            }
7263
7264            Promise$2.all = all$1;
7265            Promise$2.race = race$1;
7266            Promise$2.resolve = resolve$1;
7267            Promise$2.reject = reject$1;
7268            Promise$2._setScheduler = setScheduler;
7269            Promise$2._setAsap = setAsap;
7270            Promise$2._asap = asap;
7271
7272            Promise$2.prototype = {
7273                constructor: Promise$2,
7274
7275                /**
7276                  The primary way of interacting with a promise is through its `then` method,
7277                  which registers callbacks to receive either a promise's eventual value or the
7278                  reason why the promise cannot be fulfilled.
7279                
7280                  ```js
7281                  findUser().then(function(user){
7282                    // user is available
7283                  }, function(reason){
7284                    // user is unavailable, and you are given the reason why
7285                  });
7286                  ```
7287                
7288                  Chaining
7289                  --------
7290                
7291                  The return value of `then` is itself a promise.  This second, 'downstream'
7292                  promise is resolved with the return value of the first promise's fulfillment
7293                  or rejection handler, or rejected if the handler throws an exception.
7294                
7295                  ```js
7296                  findUser().then(function (user) {
7297                    return user.name;
7298                  }, function (reason) {
7299                    return 'default name';
7300                  }).then(function (userName) {
7301                    // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
7302                    // will be `'default name'`
7303                  });
7304                
7305                  findUser().then(function (user) {
7306                    throw new Error('Found user, but still unhappy');
7307                  }, function (reason) {
7308                    throw new Error('`findUser` rejected and we're unhappy');
7309                  }).then(function (value) {
7310                    // never reached
7311                  }, function (reason) {
7312                    // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
7313                    // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
7314                  });
7315                  ```
7316                  If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
7317                
7318                  ```js
7319                  findUser().then(function (user) {
7320                    throw new PedagogicalException('Upstream error');
7321                  }).then(function (value) {
7322                    // never reached
7323                  }).then(function (value) {
7324                    // never reached
7325                  }, function (reason) {
7326                    // The `PedgagocialException` is propagated all the way down to here
7327                  });
7328                  ```
7329                
7330                  Assimilation
7331                  ------------
7332                
7333                  Sometimes the value you want to propagate to a downstream promise can only be
7334                  retrieved asynchronously. This can be achieved by returning a promise in the
7335                  fulfillment or rejection handler. The downstream promise will then be pending
7336                  until the returned promise is settled. This is called *assimilation*.
7337                
7338                  ```js
7339                  findUser().then(function (user) {
7340                    return findCommentsByAuthor(user);
7341                  }).then(function (comments) {
7342                    // The user's comments are now available
7343                  });
7344                  ```
7345                
7346                  If the assimliated promise rejects, then the downstream promise will also reject.
7347                
7348                  ```js
7349                  findUser().then(function (user) {
7350                    return findCommentsByAuthor(user);
7351                  }).then(function (comments) {
7352                    // If `findCommentsByAuthor` fulfills, we'll have the value here
7353                  }, function (reason) {
7354                    // If `findCommentsByAuthor` rejects, we'll have the reason here
7355                  });
7356                  ```
7357                
7358                  Simple Example
7359                  --------------
7360                
7361                  Synchronous Example
7362                
7363                  ```javascript
7364                  let result;
7365                
7366                  try {
7367                    result = findResult();
7368                    // success
7369                  } catch(reason) {
7370                    // failure
7371                  }
7372                  ```
7373                
7374                  Errback Example
7375                
7376                  ```js
7377                  findResult(function(result, err){
7378                    if (err) {
7379                      // failure
7380                    } else {
7381                      // success
7382                    }
7383                  });
7384                  ```
7385                
7386                  Promise Example;
7387                
7388                  ```javascript
7389                  findResult().then(function(result){
7390                    // success
7391                  }, function(reason){
7392                    // failure
7393                  });
7394                  ```
7395                
7396                  Advanced Example
7397                  --------------
7398                
7399                  Synchronous Example
7400                
7401                  ```javascript
7402                  let author, books;
7403                
7404                  try {
7405                    author = findAuthor();
7406                    books  = findBooksByAuthor(author);
7407                    // success
7408                  } catch(reason) {
7409                    // failure
7410                  }
7411                  ```
7412                
7413                  Errback Example
7414                
7415                  ```js
7416                
7417                  function foundBooks(books) {
7418                
7419                  }
7420                
7421                  function failure(reason) {
7422                
7423                  }
7424                
7425                  findAuthor(function(author, err){
7426                    if (err) {
7427                      failure(err);
7428                      // failure
7429                    } else {
7430                      try {
7431                        findBoooksByAuthor(author, function(books, err) {
7432                          if (err) {
7433                            failure(err);
7434                          } else {
7435                            try {
7436                              foundBooks(books);
7437                            } catch(reason) {
7438                              failure(reason);
7439                            }
7440                          }
7441                        });
7442                      } catch(error) {
7443                        failure(err);
7444                      }
7445                      // success
7446                    }
7447                  });
7448                  ```
7449                
7450                  Promise Example;
7451                
7452                  ```javascript
7453                  findAuthor().
7454                    then(findBooksByAuthor).
7455                    then(function(books){
7456                      // found books
7457                  }).catch(function(reason){
7458                    // something went wrong
7459                  });
7460                  ```
7461                
7462                  @method then
7463                  @param {Function} onFulfilled
7464                  @param {Function} onRejected
7465                  Useful for tooling.
7466                  @return {Promise}
7467                */
7468                then: then,
7469
7470                /**
7471                  `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
7472                  as the catch block of a try/catch statement.
7473                
7474                  ```js
7475                  function findAuthor(){
7476                    throw new Error('couldn't find that author');
7477                  }
7478                
7479                  // synchronous
7480                  try {
7481                    findAuthor();
7482                  } catch(reason) {
7483                    // something went wrong
7484                  }
7485                
7486                  // async with promises
7487                  findAuthor().catch(function(reason){
7488                    // something went wrong
7489                  });
7490                  ```
7491                
7492                  @method catch
7493                  @param {Function} onRejection
7494                  Useful for tooling.
7495                  @return {Promise}
7496                */
vendor: 1,462 bytes, lines 7497-7546
7497                'catch': function _catch(onRejection) {
7498                    return this.then(null, onRejection);
7499                }
7500            };
7501
7502            /*global self*/
7503            function polyfill$1() {
7504                var local = undefined;
7505
7506                if (typeof commonjsGlobal !== 'undefined') {
7507                    local = commonjsGlobal;
7508                } else if (typeof self !== 'undefined') {
7509                    local = self;
7510                } else {
7511                    try {
7512                        local = Function('return this')();
7513                    } catch (e) {
7514                        throw new Error('polyfill failed because global object is unavailable in this environment');
7515                    }
7516                }
7517
7518                var P = local.Promise;
7519
7520                if (P) {
7521                    var promiseToString = null;
7522                    try {
7523                        promiseToString = Object.prototype.toString.call(P.resolve());
7524                    } catch (e) {
7525                        // silently ignored
7526                    }
7527
7528                    if (promiseToString === '[object Promise]' && !P.cast) {
7529                        return;
7530                    }
7531                }
7532
7533                local.Promise = Promise$2;
7534            }
7535
7536            // Strange compat..
7537            Promise$2.polyfill = polyfill$1;
7538            Promise$2.Promise = Promise$2;
7539
7540            return Promise$2;
7541
7542        })));
7543
7544
7545    });
7546
7547    var auto = es6Promise.polyfill();
7548
7549    var jspdf_min = createCommonjsModule(function (module, exports) {
7550        !function (t, e) { module.exports = e(); }(commonjsGlobal, function () {
7551            var t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (t) { return typeof t } : function (t) { return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t }, e = (function (e) { function n(t) { var n = {}; this.subscribe = function (t, e, r) { if ("function" != typeof e) return !1; n.hasOwnProperty(t) || (n[t] = {}); var i = Math.random().toString(35); return n[t][i] = [e, !!r], i }, this.unsubscribe = function (t) { for (var e in n) if (n[e][t]) return delete n[e][t], !0; return !1 }, this.publish = function (r) { if (n.hasOwnProperty(r)) { var i = Array.prototype.slice.call(arguments, 1), o = []; for (var a in n[r]) { var s = n[r][a]; try { s[0].apply(t, i); } catch (t) { e.console && console.error("jsPDF PubSub Error", t.message, t); } s[1] && o.push(a); } o.length && o.forEach(this.unsubscribe); } }; } function i(c, l, u, h) { var f = {}; "object" === (void 0 === c ? "undefined" : t(c)) && (c = (f = c).orientation, l = f.unit || l, u = f.format || u, h = f.compress || f.compressPdf || h), l = l || "mm", u = u || "a4", c = ("" + (c || "P")).toLowerCase(); ("" + u).toLowerCase(); var d, p, m, g, w, y, v, b, x, k = !!h && "function" == typeof Uint8Array, _ = f.textColor || "0 g", C = f.drawColor || "0 G", A = f.fontSize || 16, S = f.lineHeight || 1.15, q = f.lineWidth || .200025, T = 2, P = !1, I = [], E = {}, O = {}, F = 0, B = [], R = [], D = [], j = [], z = [], N = 0, L = 0, M = 0, U = { title: "", subject: "", author: "", keywords: "", creator: "" }, H = {}, W = new n(H), X = f.hotfixes || [], V = function (t) { return t.toFixed(2) }, G = function (t) { return t.toFixed(3) }, Y = function (t) { return ("0" + parseInt(t)).slice(-2) }, J = function (t) { P ? B[g].push(t) : (M += t.length + 1, j.push(t)); }, Q = function () { return T++, I[T] = M, J(T + " 0 obj"), T }, K = function (t) { J("stream"), J(t), J("endstream"); }, $ = function () { var t, n, r, a, s, c, l, u, h, f = []; for (l = e.adler32cs || i.adler32cs, k && void 0 === l && (k = !1), t = 1; t <= F; t++) { if (f.push(Q()), u = (w = D[t].width) * p, h = (y = D[t].height) * p, J("<</Type /Page"), J("/Parent 1 0 R"), J("/Resources 2 0 R"), J("/MediaBox [0 0 " + V(u) + " " + V(h) + "]"), W.publish("putPage", { pageNumber: t, page: B[t] }), J("/Contents " + (T + 1) + " 0 R"), J(">>"), J("endobj"), n = B[t].join("\n"), Q(), k) { for (r = [], a = n.length; a--;)r[a] = n.charCodeAt(a); c = l.from(n), (s = new o(6)).append(new Uint8Array(r)), n = s.flush(), (r = new Uint8Array(n.length + 6)).set(new Uint8Array([120, 156])), r.set(n, 2), r.set(new Uint8Array([255 & c, c >> 8 & 255, c >> 16 & 255, c >> 24 & 255]), n.length + 2), n = String.fromCharCode.apply(null, r), J("<</Length " + n.length + " /Filter [/FlateDecode]>>"); } else J("<</Length " + n.length + ">>"); K(n), J("endobj"); } I[1] = M, J("1 0 obj"), J("<</Type /Pages"); var d = "/Kids ["; for (a = 0; a < F; a++)d += f[a] + " 0 R "; J(d + "]"), J("/Count " + F), J(">>"), J("endobj"), W.publish("postPutPages"); }, Z = function (t) { t.objectNumber = Q(), J("<</BaseFont/" + t.PostScriptName + "/Type/Font"), "string" == typeof t.encoding && J("/Encoding/" + t.encoding), J("/Subtype/Type1>>"), J("endobj"); }, tt = function () { for (var t in E) E.hasOwnProperty(t) && Z(E[t]); }, et = function () { W.publish("putXobjectDict"); }, nt = function () { J("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"), J("/Font <<"); for (var t in E) E.hasOwnProperty(t) && J("/" + t + " " + E[t].objectNumber + " 0 R"); J(">>"), J("/XObject <<"), et(), J(">>"); }, rt = function () { tt(), W.publish("putResources"), I[2] = M, J("2 0 obj"), J("<<"), nt(), J(">>"), J("endobj"), W.publish("postPutResources"); }, it = function () { W.publish("putAdditionalObjects"); for (var t = 0; t < z.length; t++) { var e = z[t]; I[e.objId] = M, J(e.objId + " 0 obj"), J(e.content), J("endobj"); } T += z.length, W.publish("postPutAdditionalObjects"); }, ot = function (t, e, n) { O.hasOwnProperty(e) || (O[e] = {}), O[e][n] = t; }, at = function (t, e, n, r) { var i = "F" + (Object.keys(E).length + 1).toString(10), o = E[i] = { id: i, PostScriptName: t, fontName: e, fontStyle: n, encoding: r, metadata: {} }; return ot(i, e, n), W.publish("addFont", o), i }, st = function (t, e) { var n, r, i, o, a, s, c, l, u; if (e = e || {}, i = e.sourceEncoding || "Unicode", a = e.outputEncoding, (e.autoencode || a) && E[d].metadata && E[d].metadata[i] && E[d].metadata[i].encoding && (o = E[d].metadata[i].encoding, !a && E[d].encoding && (a = E[d].encoding), !a && o.codePages && (a = o.codePages[0]), "string" == typeof a && (a = o[a]), a)) { for (c = !1, s = [], n = 0, r = t.length; n < r; n++)(l = a[t.charCodeAt(n)]) ? s.push(String.fromCharCode(l)) : s.push(t[n]), s[n].charCo
vendor: 31,894 bytes, lines 7551-7558
7551deAt(0) >> 8 && (c = !0); t = s.join(""); } for (n = t.length; void 0 === c && 0 !== n;)t.charCodeAt(n - 1) >> 8 && (c = !0), n--; if (!c) return t; for (s = e.noBOM ? [] : [254, 255], n = 0, r = t.length; n < r; n++) { if (l = t.charCodeAt(n), (u = l >> 8) >> 8) throw new Error("Character at position " + n + " of string '" + t + "' exceeds 16bits. Cannot be encoded into UCS-2 BE"); s.push(u), s.push(l - (u << 8)); } return String.fromCharCode.apply(void 0, s) }, ct = function (t, e) { return st(t, e).replace(/\\/g, "\\\\").replace(/\(/g, "\\(").replace(/\)/g, "\\)") }, lt = function () { J("/Producer (jsPDF " + i.version + ")"); for (var t in U) U.hasOwnProperty(t) && U[t] && J("/" + t.substr(0, 1).toUpperCase() + t.substr(1) + " (" + ct(U[t]) + ")"); var e = new Date, n = e.getTimezoneOffset(), r = n < 0 ? "+" : "-", o = Math.floor(Math.abs(n / 60)), a = Math.abs(n % 60), s = [r, Y(o), "'", Y(a), "'"].join(""); J(["/CreationDate (D:", e.getFullYear(), Y(e.getMonth() + 1), Y(e.getDate()), Y(e.getHours()), Y(e.getMinutes()), Y(e.getSeconds()), s, ")"].join("")); }, ut = function () { switch (J("/Type /Catalog"), J("/Pages 1 0 R"), b || (b = "fullwidth"), b) { case "fullwidth": J("/OpenAction [3 0 R /FitH null]"); break; case "fullheight": J("/OpenAction [3 0 R /FitV null]"); break; case "fullpage": J("/OpenAction [3 0 R /Fit]"); break; case "original": J("/OpenAction [3 0 R /XYZ null null 1]"); break; default: var t = "" + b; "%" === t.substr(t.length - 1) && (b = parseInt(b) / 100), "number" == typeof b && J("/OpenAction [3 0 R /XYZ null null " + V(b) + "]"); }switch (x || (x = "continuous"), x) { case "continuous": J("/PageLayout /OneColumn"); break; case "single": J("/PageLayout /SinglePage"); break; case "two": case "twoleft": J("/PageLayout /TwoColumnLeft"); break; case "tworight": J("/PageLayout /TwoColumnRight"); }v && J("/PageMode /" + v), W.publish("putCatalog"); }, ht = function () { J("/Size " + (T + 1)), J("/Root " + T + " 0 R"), J("/Info " + (T - 1) + " 0 R"); }, ft = function (t, e) { var n = "string" == typeof e && e.toLowerCase(); if ("string" == typeof t) { var r = t.toLowerCase(); s.hasOwnProperty(r) && (t = s[r][0] / p, e = s[r][1] / p); } if (Array.isArray(t) && (e = t[1], t = t[0]), n) { switch (n.substr(0, 1)) { case "l": e > t && (n = "s"); break; case "p": t > e && (n = "s"); }"s" === n && (m = t, t = e, e = m); } P = !0, B[++F] = [], D[F] = { width: Number(t) || w, height: Number(e) || y }, R[F] = {}, mt(F); }, dt = function () { ft.apply(this, arguments), J(V(q * p) + " w"), J(C), 0 !== N && J(N + " J"), 0 !== L && J(L + " j"), W.publish("addPage", { pageNumber: F }); }, pt = function (t) { t > 0 && t <= F && (B.splice(t, 1), D.splice(t, 1), g > --F && (g = F), this.setPage(g)); }, mt = function (t) { t > 0 && t <= F && (g = t, w = D[t].width, y = D[t].height); }, gt = function (t, e) { var n; switch (t = void 0 !== t ? t : E[d].fontName, e = void 0 !== e ? e : E[d].fontStyle, void 0 !== t && (t = t.toLowerCase()), t) { case "sans-serif": case "verdana": case "arial": case "helvetica": t = "helvetica"; break; case "fixed": case "monospace": case "terminal": case "courier": t = "courier"; break; case "serif": case "cursive": case "fantasy": default: t = "times"; }try { n = O[t][e]; } catch (t) { } return n || null == (n = O.times[e]) && (n = O.times.normal), n }, wt = function () { P = !1, T = 2, M = 0, j = [], I = [], z = [], W.publish("buildDocument"), J("%PDF-" + a), $(), it(), rt(), Q(), J("<<"), lt(), J(">>"), J("endobj"), Q(), J("<<"), ut(), J(">>"), J("endobj"); var t, e = M, n = "0000000000"; for (J("xref"), J("0 " + (T + 1)), J(n + " 65535 f "), t = 1; t <= T; t++) { var r = I[t]; J("function" == typeof r ? (n + I[t]()).slice(-10) + " 00000 n " : (n + I[t]).slice(-10) + " 00000 n "); } return J("trailer"), J("<<"), ht(), J(">>"), J("startxref"), J("" + e), J("%%EOF"), P = !0, j.join("\n") }, yt = function (t) { var e = "S"; return "F" === t ? e = "f" : "FD" === t || "DF" === t ? e = "B" : "f" !== t && "f*" !== t && "B" !== t && "B*" !== t || (e = t), e }, vt = function () { for (var t = wt(), e = t.length, n = new ArrayBuffer(e), r = new Uint8Array(n); e--;)r[e] = t.charCodeAt(e); return n }, bt = function () { return new Blob([vt()], { type: "application/pdf" }) }, xt = function (t) { return t.foo = function () { try { return t.apply(this, arguments) } catch (t) { var n = t.stack || ""; ~n.indexOf(" at ") && (n = n.split(" at ")[1]); var r = "Error in function " + n.split("\n")[0].split("<")[0] + ": " + t.message; if (!e.console) throw new Error(r); e.console.error(r, t), e.alert && alert(r); } }, t.foo.bar = t, t.foo }(function (t, n) { var i = "dataur" === ("" + t).substr(0, 6) ? "data:application/pdf;base64," + btoa(wt()) : 0; switch (t) { case void 0: return wt(); case "save": if (navigator.getUserMedia && (void 0 === e.URL || void 0 === e.URL.createObjectURL)) return H.output("dataurlnewwindow"); r(bt(), n), "function" == typeof r.unload && e.setTimeout && setTimeout(r.unload, 911); break; case "arraybuffer": return vt(); case "blob": return bt(); case "bloburi": case "bloburl": return e.URL && e.URL.createObjectURL(bt()) || void 0; case "datauristring": case "dataurlstring": return i; case "dataurlnewwindow": var o = e.open(i); if (o || "undefined" == typeof safari) return o; case "datauri": case "dataurl": return e.document.location.href = i; default: throw new Error('Output type "' + t + '" is not supported.') } }), kt = function (t) { return !0 === Array.isArray(X) && X.indexOf(t) > -1 }; switch (l) { case "pt": p = 1; break; case "mm": p = 72 / 25.4000508; break; case "cm": p = 72 / 2.54000508; break; case "in": p = 72; break; case "px": p = 1 == kt("px_scaling") ? .75 : 96 / 72; break; case "pc": case "em": p = 12; break; case "ex": p = 6; break; default: throw "Invalid unit: " + l }H.internal = { pdfEscape: ct, getStyle: yt, getFont: function () { return E[gt.apply(H, arguments)] }, getFontSize: function () { return A }, getLineHeight: function () { return A * S }, write: function (t) { J(1 === arguments.length ? t : Array.prototype.join.call(arguments, " ")); }, getCoordinateString: function (t) { return V(t * p) }, getVerticalCoordinateString: function (t) { return V((y - t) * p) }, collections: {}, newObject: Q, newAdditionalObject: function () { var t = 2 * B.length + 1, e = { objId: t += z.length, content: "" }; return z.push(e), e }, newObjectDeferred: function () { return T++, I[T] = function () { return M }, T }, newObjectDeferredBegin: function (t) { I[t] = M; }, putStream: K, events: W, scaleFactor: p, pageSize: { get width() { return w }, get height() { return y } }, output: function (t, e) { return xt(t, e) }, getNumberOfPages: function () { return B.length - 1 }, pages: B, out: J, f2: V, getPageInfo: function (t) { return { objId: 2 * (t - 1) + 3, pageNumber: t, pageContext: R[t] } }, getCurrentPageInfo: function () { return { objId: 2 * (g - 1) + 3, pageNumber: g, pageContext: R[g] } }, getPDFVersion: function () { return a }, hasHotfix: kt }, H.addPage = function () { return dt.apply(this, arguments), this }, H.setPage = function () { return mt.apply(this, arguments), this }, H.insertPage = function (t) { return this.addPage(), this.movePage(g, t), this }, H.movePage = function (t, e) { if (t > e) { for (var n = B[t], r = D[t], i = R[t], o = t; o > e; o--)B[o] = B[o - 1], D[o] = D[o - 1], R[o] = R[o - 1]; B[e] = n, D[e] = r, R[e] = i, this.setPage(e); } else if (t < e) { for (var n = B[t], r = D[t], i = R[t], o = t; o < e; o++)B[o] = B[o + 1], D[o] = D[o + 1], R[o] = R[o + 1]; B[e] = n, D[e] = r, R[e] = i, this.setPage(e); } return this }, H.deletePage = function () { return pt.apply(this, arguments), this }, H.setDisplayMode = function (t, e, n) { if (b = t, x = e, v = n, -1 == [void 0, null, "UseNone", "UseOutlines", "UseThumbs", "FullScreen"].indexOf(n)) throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "' + n + '" is not recognized.'); return this }, H.text = function (t, e, n, r, i, o) { function a(t) { return t = t.split("\t").join(Array(f.TabLen || 9).join(" ")), ct(t, r) } "number" == typeof t && (m = n, n = e, e = t, t = m), "string" == typeof t && (t = t.match(/[\n\r]/) ? t.split(/\r\n|\r|\n/g) : [t]), "string" == typeof i && (o = i, i = null), "string" == typeof r && (o = r, r = null), "number" == typeof r && (i = r, r = null); var s = "", c = "Td"; if (i) { i *= Math.PI / 180; var l = Math.cos(i), u = Math.sin(i); s = [V(l), V(u), V(-1 * u), V(l), ""].join(" "), c = "Tm"; } "noBOM" in (r = r || {}) || (r.noBOM = !0), "autoencode" in r || (r.autoencode = !0); var h = "", g = this.internal.getCurrentPageInfo().pageContext; if (!0 === r.stroke ? !0 !== g.lastTextWasStroke && (h = "1 Tr\n", g.lastTextWasStroke = !0) : (g.lastTextWasStroke && (h = "0 Tr\n"), g.lastTextWasStroke = !1), void 0 === this._runningPageHeight && (this._runningPageHeight = 0), "string" == typeof t) t = a(t); else { if ("[object Array]" !== Object.prototype.toString.call(t)) throw new Error('Type of text must be string or Array. "' + t + '" is not recognized.'); for (var w = t.concat(), v = [], b = w.length; b--;)v.push(a(w.shift())); if (o) { var x, k, C, q = A * S, T = t.map(function (t) { return this.getStringUnitWidth(t) * A / p }, this); if (C = Math.max.apply(Math, T), "center" === o) x = e - C / 2, e -= T[0] / 2; else { if ("right" !== o) throw new Error('Unrecognized alignment option, use "center" or "right".'); x = e - C, e -= T[0]; } k = e, t = v[0]; for (var P = 1, b = v.length; P < b; P++) { var I = C - T[P]; "center" === o && (I /= 2), t += ") Tj\n" + (x - k + I) + " -" + q + " Td (" + v[P], k = x + I; } } else t = v.join(") Tj\nT* ("); } var E; return E = V((y - n) * p), J("BT\n/" + d + " " + A + " Tf\n" + A * S + " TL\n" + h + _ + "\n" + s + V(e * p) + " " + E + " " + c + "\n(" + t + ") Tj\nET"), this }, H.lstext = function (t, e, n, r) { console.warn("jsPDF.lstext is deprecated"); for (var i = 0, o = t.length; i < o; i++, e += r)this.text(t[i], e, n); return this }, H.line = function (t, e, n, r) { return this.lines([[n - t, r - e]], t, e) }, H.clip = function () { J("W"), J("S"); }, H.clip_fixed = function (t) { J("evenodd" === t ? "W*" : "W"), J("n"); }, H.lines = function (t, e, n, r, i, o) { var a, s, c, l, u, h, f, d, g, w, v; for ("number" == typeof t && (m = n, n = e, e = t, t = m), r = r || [1, 1], J(G(e * p) + " " + G((y - n) * p) + " m "), a = r[0], s = r[1], l = t.length, w = e, v = n, c = 0; c < l; c++)2 === (u = t[c]).length ? (w = u[0] * a + w, v = u[1] * s + v, J(G(w * p) + " " + G((y - v) * p) + " l")) : (h = u[0] * a + w, f = u[1] * s + v, d = u[2] * a + w, g = u[3] * s + v, w = u[4] * a + w, v = u[5] * s + v, J(G(h * p) + " " + G((y - f) * p) + " " + G(d * p) + " " + G((y - g) * p) + " " + G(w * p) + " " + G((y - v) * p) + " c")); return o && J(" h"), null !== i && J(yt(i)), this }, H.rect = function (t, e, n, r, i) { yt(i); return J([V(t * p), V((y - e) * p), V(n * p), V(-r * p), "re"].join(" ")), null !== i && J(yt(i)), this }, H.triangle = function (t, e, n, r, i, o, a) { return this.lines([[n - t, r - e], [i - n, o - r], [t - i, e - o]], t, e, [1, 1], a, !0), this }, H.roundedRect = function (t, e, n, r, i, o, a) { var s = 4 / 3 * (Math.SQRT2 - 1); return this.lines([[n - 2 * i, 0], [i * s, 0, i, o - o * s, i, o], [0, r - 2 * o], [0, o * s, -i * s, o, -i, o], [2 * i - n, 0], [-i * s, 0, -i, -o * s, -i, -o], [0, 2 * o - r], [0, -o * s, i * s, -o, i, -o]], t + i, e, [1, 1], a), this }, H.ellipse = function (t, e, n, r, i) { var o = 4 / 3 * (Math.SQRT2 - 1) * n, a = 4 / 3 * (Math.SQRT2 - 1) * r; return J([V((t + n) * p), V((y - e) * p), "m", V((t + n) * p), V((y - (e - a)) * p), V((t + o) * p), V((y - (e - r)) * p), V(t * p), V((y - (e - r)) * p), "c"].join(" ")), J([V((t - o) * p), V((y - (e - r)) * p), V((t - n) * p), V((y - (e - a)) * p), V((t - n) * p), V((y - e) * p), "c"].join(" ")), J([V((t - n) * p), V((y - (e + a)) * p), V((t - o) * p), V((y - (e + r)) * p), V(t * p), V((y - (e + r)) * p), "c"].join(" ")), J([V((t + o) * p), V((y - (e + r)) * p), V((t + n) * p), V((y - (e + a)) * p), V((t + n) * p), V((y - e) * p), "c"].join(" ")), null !== i && J(yt(i)), this }, H.circle = function (t, e, n, r) { return this.ellipse(t, e, n, n, r) }, H.setProperties = function (t) { for (var e in U) U.hasOwnProperty(e) && t[e] && (U[e] = t[e]); return this }, H.setFontSize = function (t) { return A = t, this }, H.setFont = function (t, e) { return d = gt(t, e), this }, H.setFontStyle = H.setFontType = function (t) { return d = gt(void 0, t), this }, H.getFontList = function () { var t, e, n, r = {}; for (t in O) if (O.hasOwnProperty(t)) { r[t] = n = []; for (e in O[t]) O[t].hasOwnProperty(e) && n.push(e); } return r }, H.addFont = function (t, e, n) { at(t, e, n, "StandardEncoding"); }, H.setLineWidth = function (t) { return J((t * p).toFixed(2) + " w"), this }, H.setDrawColor = function (t, e, n, r) { var i; return i = void 0 === e || void 0 === r && t === e === n ? "string" == typeof t ? t + " G" : V(t / 255) + " G" : void 0 === r ? "string" == typeof t ? [t, e, n, "RG"].join(" ") : [V(t / 255), V(e / 255), V(n / 255), "RG"].join(" ") : "string" == typeof t ? [t, e, n, r, "K"].join(" ") : [V(t), V(e), V(n), V(r), "K"].join(" "), J(i), this }, H.setFillColor = function (e, n, r, i) { var o; return void 0 === n || void 0 === i && e === n === r ? o = "string" == typeof e ? e + " g" : V(e / 255) + " g" : void 0 === i || "object" === (void 0 === i ? "undefined" : t(i)) ? (o = "string" == typeof e ? [e, n, r, "rg"].join(" ") : [V(e / 255), V(n / 255), V(r / 255), "rg"].join(" "), i && 0 === i.a && (o = ["255", "255", "255", "rg"].join(" "))) : o = "string" == typeof e ? [e, n, r, i, "k"].join(" ") : [V(e), V(n), V(r), V(i), "k"].join(" "), J(o), this }, H.setTextColor = function (t, e, n) { if ("string" == typeof t && /^#[0-9A-Fa-f]{6}$/.test(t)) { var r = parseInt(t.substr(1), 16); t = r >> 16 & 255, e = r >> 8 & 255, n = 255 & r; } return _ = 0 === t && 0 === e && 0 === n || void 0 === e ? G(t / 255) + " g" : [G(t / 255), G(e / 255), G(n / 255), "rg"].join(" "), this }, H.CapJoinStyles = { 0: 0, butt: 0, but: 0, miter: 0, 1: 1, round: 1, rounded: 1, circle: 1, 2: 2, projecting: 2, project: 2, square: 2, bevel: 2 }, H.setLineCap = function (t) { var e = this.CapJoinStyles[t]; if (void 0 === e) throw new Error("Line cap style of '" + t + "' is not recognized. See or extend .CapJoinStyles property for valid styles"); return N = e, J(e + " J"), this }, H.setLineJoin = function (t) { var e = this.CapJoinStyles[t]; if (void 0 === e) throw new Error("Line join style of '" + t + "' is not recognized. See or extend .CapJoinStyles property for valid styles"); return L = e, J(e + " j"), this }, H.output = xt, H.save = function (t) { H.output("save", t); }; for (var _t in i.API) i.API.hasOwnProperty(_t) && ("events" === _t && i.API.events.length ? function (t, e) { var n, r, i; for (i = e.length - 1; -1 !== i; i--)n = e[i][0], r = e[i][1], t.subscribe.apply(t, [n].concat("function" == typeof r ? [r] : r)); }(W, i.API.events) : H[_t] = i.API[_t]); return function () { for (var t = [["Helvetica", "helvetica", "normal"], ["Helvetica-Bold", "helvetica", "bold"], ["Helvetica-Oblique", "helvetica", "italic"], ["Helvetica-BoldOblique", "helvetica", "bolditalic"], ["Courier", "courier", "normal"], ["Courier-Bold", "courier", "bold"], ["Courier-Oblique", "courier", "italic"], ["Courier-BoldOblique", "courier", "bolditalic"], ["Times-Roman", "times", "normal"], ["Times-Bold", "times", "bold"], ["Times-Italic", "times", "italic"], ["Times-BoldItalic", "times", "bolditalic"], ["ZapfDingbats", "zapfdingbats"]], e = 0, n = t.length; e < n; e++) { var r = at(t[e][0], t[e][1], t[e][2], "StandardEncoding"), i = t[e][0].split("-"); ot(r, i[0], i[1] || ""); } W.publish("addFonts", { fonts: E, dictionary: O }); }(), d = "F1", dt(u, c), W.publish("initialized"), H } var a = "1.3", s = { a0: [2383.94, 3370.39], a1: [1683.78, 2383.94], a2: [1190.55, 1683.78], a3: [841.89, 1190.55], a4: [595.28, 841.89], a5: [419.53, 595.28], a6: [297.64, 419.53], a7: [209.76, 297.64], a8: [147.4, 209.76], a9: [104.88, 147.4], a10: [73.7, 104.88], b0: [2834.65, 4008.19], b1: [2004.09, 2834.65], b2: [1417.32, 2004.09], b3: [1000.63, 1417.32], b4: [708.66, 1000.63], b5: [498.9, 708.66], b6: [354.33, 498.9], b7: [249.45, 354.33], b8: [175.75, 249.45], b9: [124.72, 175.75], b10: [87.87, 124.72], c0: [2599.37, 3676.54], c1: [1836.85, 2599.37], c2: [1298.27, 1836.85], c3: [918.43, 1298.27], c4: [649.13, 918.43], c5: [459.21, 649.13], c6: [323.15, 459.21], c7: [229.61, 323.15], c8: [161.57, 229.61], c9: [113.39, 161.57], c10: [79.37, 113.39], dl: [311.81, 623.62], letter: [612, 792], "government-letter": [576, 756], legal: [612, 1008], "junior-legal": [576, 360], ledger: [1224, 792], tabloid: [792, 1224], "credit-card": [153, 243] }; return i.API = { events: [] }, i.version = "1.x-master", "function" == typeof undefined && undefined.amd ? undefined("jsPDF", function () { return i }) : "undefined" != 'object' && module.exports ? module.exports = i : e.jsPDF = i, i }("undefined" != typeof self && self || "undefined" != typeof window && window || void 0));/**
7552 * jsPDF AcroForm Plugin
7553 * Copyright (c) 2016 Alexander Weidt, https://github.com/BiggA94
7554 *
7555 * Licensed under the MIT License.
7556 * http://opensource.org/licenses/mit-license
7557 */
7558            (window.AcroForm = function (t) { var n = window.AcroForm; n.scale = function (t) { return t * (r.internal.scaleFactor / 1) }, n.antiScale = function (t) { return 1 / r.internal.scaleFactor * t }; var r = { fields: [], xForms: [], acroFormDictionaryRoot: null, printedOut: !1, internal: null }; e.API.acroformPlugin = r; var i = function () { for (var t in this.acroformPlugin.acroFormDictionaryRoot.Fields) { var e = this.acroformPlugin.acroFormDictionaryRoot.Fields[t]; e.hasAnnotation && a.call(this, e); } }, o = function () { if (this.acroformPlugin.acroFormDictionaryRoot) throw new Error("Exception while creating AcroformDictionary"); this.acroformPlugin.acroFormDictionaryRoot = new n.AcroFormDictionary, this.acroformPlugin.internal = this.internal, this.acroformPlugin.acroFormDictionaryRoot._eventID = this.internal.events.subscribe("postPutResources", l), this.internal.events.subscribe("buildDocument", i), this.internal.events.subscribe("putCatalog", c), this.internal.events.subscribe("postPutPages", u); }, a = function (t) { var n = { type: "reference", object: t }; e.API.annotationPlugin.annotations[this.internal.getPageInfo(t.page).pageNumber].push(n); }, s = function (t) { this.acroformPlugin.printedOut && (this.acroformPlugin.printedOut = !1, this.acroformPlugin.acroFormDictionaryRoot = null), this.acroformPlugin.acroFormDictionaryRoot || o.call(this), this.acroformPlugin.acroFormDictionaryRoot.Fields.push(t); }, c = function () { void 0 !== this.acroformPlugin.acroFormDictionaryRoot ? this.internal.write("/AcroForm " + this.acroformPlugin.acroFormDictionaryRoot.objId + " 0 R") : console.log("Root missing..."); }, l = function () { this.internal.events.unsubscribe(this.acroformPlugin.acroFormDictionaryRoot._eventID), delete this.acroformPlugin.acroFormDictionaryRoot._eventID, this.acroformPlugin.printedOut = !0; }, u = function (t) { var e = !t; t || (this.internal.newObjectDeferredBegin(this.acroformPlugin.acroFormDictionaryRoot.objId), this.internal.out(this.acroformPlugin.acroFormDictionaryRoot.getString())); var t = t || this.acroformPlugin.acroFormDictionaryRoot.Kids; for (var r in t) { var i = t[r], o = i.Rect; i.Rect && (i.Rect = n.internal.calculateCoordinates.call(this, i.Rect)), this.internal.newObjectDeferredBegin(i.objId); var a = ""; if (a += i.objId + " 0 obj\n", a += "<<\n" + i.getContent(), i.Rect = o, i.hasAppearanceStream && !i.appearanceStreamContent) { var s = n.internal.calculateAppearanceStream.call(this, i); a += "/AP << /N " + s + " >>\n", this.acroformPlugin.xForms.push(s); } if (i.appearanceStreamContent) { a += "/AP << "; for (var c in i.appearanceStreamContent) { var l = i.appearanceStreamContent[c]; if (a += "/" + c + " ", a += "<< ", Object.keys(l).length >= 1 || Array.isArray(l)) for (var r in l) "function" == typeof (u = l[r]) && (u = u.call(this, i)), a += "/" + r + " " + u + " ", this.acroformPlugin.xForms.indexOf(u) >= 0 || this.acroformPlugin.xForms.push(u); else { var u = l; "function" == typeof u && (u = u.call(this, i)), a += "/" + r + " " + u + " \n", this.acroformPlugin.xForms.indexOf(u) >= 0 || this.acroformPlugin.xForms.push(u); } a += " >>\n"; } a += ">>\n"; } a += ">>\nendobj\n", this.internal.out(a); } e && h.call(this, this.acroformPlugin.xForms); }, h = function (t) { for (var e in t) { var n = e, r = t[e]; this.internal.newObjectDeferredBegin(r && r.objId); var i = ""; i += r ? r.getString() : "", this.internal.out(i), delete t[n]; } }; t.addField = function (t) { return t instanceof n.TextField ? d.call(this, t) : t instanceof n.ChoiceField ? p.call(this, t) : t instanceof n.Button ? f.call(this, t) : t instanceof n.ChildClass ? s.call(this, t) : t && s.call(this, t), t.page = this.acroformPlugin.internal.getCurrentPageInfo().pageNumber, this }; var f = function (t) { (t = t || new n.Field).FT = "/Btn"; var e = t.Ff || 0; t.pushbutton && (e = n.internal.setBitPosition(e, 17), delete t.pushbutton), t.radio && (e = n.internal.setBitPosition(e, 16), delete t.radio), t.noToggleToOff && (e = n.internal.setBitPosition(e, 15)), t.Ff = e, s.call(this, t); }, d = function (t) { (t = t || new n.Field).FT = "/Tx"; var e = t.Ff || 0; t.multiline && (e |= 4096), t.password && (e |= 8192), t.fileSelect && (e |= 1 << 20), t.doNotSpellCheck && (e |= 1 << 22), t.doNotScroll && (e |= 1 << 23), t.Ff = t.Ff || e, s.call(this, t); }, p = function (t) { var e = t || new n.Field; e.FT = "/Ch"; var r = e.Ff || 0; e.combo && (r = n.internal.setBitPosition(r, 18), delete e.combo), e.edit && (r = n.internal.setBitPosition(r, 19), delete e.edit), e.sort && (r = n.internal.setBitPosition(r, 20), delete e.sort), e.multiSelect && this.internal.getPDFVersion() >= 1.4 && (r = n.internal.setBitPosition(r, 22), delete e.multiSelect), e.doNotSpellCheck && this.internal.getPDFVersion() >= 1.4 && (r = n.internal.setBitPosition(r, 23), delete e.doNotSpellCheck), e.Ff = r, s.call(this, e); }; })(e.API); var n = window.AcroForm; n.internal = {}, n.createFormXObject = function (t) { var e = new n.FormXObject, r = n.Appearance.internal.getHeight(t) || 0, i = n.Appearance.internal.getWidth(t) || 0; return e.BBox = [0, 0, i, r], e }, n.Appearance = { CheckBox: { createAppearanceStream: function () { return { N: { On: n.Appearance.CheckBox.YesNormal }, D: { On: n.Appearance.CheckBox.YesPushDown, Off: n.Appearance.CheckBox.OffPushDown } } }, createMK: function () { return "<< /CA (3)>>" }, YesPushDown: function (t) { var e = n.createFormXObject(t), r = ""; t.Q = 1; var i = n.internal.calculateX(t, "3", "ZapfDingbats", 50); return r += "0.749023 g\n             0 0 " + n.Appearance.internal.getWidth(t) + " " + n.Appearance.internal.getHeight(t) + " re\n             f\n             BMC\n             q\n             0 0 1 rg\n             /F13 " + i.fontSize + " Tf 0 g\n             BT\n", r += i.text, r += "ET\n             Q\n             EMC\n", e.stream = r, e }, YesNormal: function (t) { var e = n.createFormXObject(t), r = ""; t.Q = 1; var i = n.internal.calculateX(t, "3", "ZapfDingbats", .9 * n.Appearance.internal.getHeight(t)); return r += "1 g\n0 0 " + n.Appearance.internal.getWidth(t) + " " + n.Appearance.internal.getHeight(t) + " re\nf\nq\n0 0 1 rg\n0 0 " + (n.Appearance.internal.getWidth(t) - 1) + " " + (n.Appearance.internal.getHeight(t) - 1) + " re\nW\nn\n0 g\nBT\n/F13 " + i.fontSize + " Tf 0 g\n", r += i.text, r += "ET\n             Q\n", e.stream = r, e }, OffPushDown: function (t) { var e = n.createFormXObject(t), r = ""; return r += "0.749023 g\n            0 0 " + n.Appearance.internal.getWidth(t) + " " + n.Appearance.internal.getHeight(t) + " re\n            f\n", e.stream = r, e } }, RadioButton: { Circle: { createAppearanceStream: function (t) { var e = { D: { Off: n.Appearance.RadioButton.Circle.OffPushDown }, N: {} }; return e.N[t] = n.Appearance.RadioButton.Circle.YesNormal, e.D[t] = n.Appearance.RadioButton.Circle.YesPushDown, e }, createMK: function () { return "<< /CA (l)>>" }, YesNormal: function (t) { var e = n.createFormXObject(t), r = "", i = n.Appearance.internal.getWidth(t) <= n.Appearance.internal.getHeight(t) ? n.Appearance.internal.getWidth(t) / 4 : n.Appearance.internal.getHeight(t) / 4; i *= .9; var o = n.Appearance.internal.Bezier_C; return r += "q\n1 0 0 1 " + n.Appearance.internal.getWidth(t) / 2 + " " + n.Appearance.internal.getHeight(t) / 2 + " cm\n" + i + " 0 m\n" + i + " " + i * o + " " + i * o + " " + i + " 0 " + i + " c\n-" + i * o + " " + i + " -" + i + " " + i * o + " -" + i + " 0 c\n-" + i + " -" + i * o + " -" + i * o + " -" + i + " 0 -" + i + " c\n" + i * o + " -" + i + " " + i + " -" + i * o + " " + i + " 0 c\nf\nQ\n", e.stream = r, e }, YesPushDown: function (t) { var e = n.createFormXObject(t), r = "", i = n.Appearance.internal.getWidth(t) <= n.Appearance.internal.getHeight(t) ? n.Appearance.internal.getWidth(t) / 4 : n.Appearance.internal.getHeight(t) / 4, o = 2 * (i *= .9), a = o * n.Appearance.internal.Bezier_C, s = i * n.Appearance.internal.Bezier_C; return r += "0.749023 g\n            q\n           1 0 0 1 " + n.Appearance.internal.getWidth(t) / 2 + " " + n.Appearance.internal.getHeight(t) / 2 + " cm\n" + o + " 0 m\n" + o + " " + a + " " + a + " " + o + " 0 " + o + " c\n-" + a + " " + o + " -" + o + " " + a + " -" + o + " 0 c\n-" + o + " -" + a + " -" + a + " -" + o + " 0 -" + o + " c\n" + a + " -" + o + " " + o + " -" + a + " " + o + " 0 c\n            f\n            Q\n            0 g\n            q\n            1 0 0 1 " + n.Appearance.internal.getWidth(t) / 2 + " " + n.Appearance.internal.getHeight(t) / 2 + " cm\n" + i + " 0 m\n" + i + " " + s + " " + s + " " + i + " 0 " + i + " c\n-" + s + " " + i + " -" + i + " " + s + " -" + i + " 0 c\n-" + i + " -" + s + " -" + s + " -" + i + " 0 -" + i + " c\n" + s + " -" + i + " " + i + " -" + s + " " + i + " 0 c\n            f\n            Q\n", e.stream = r, e }, OffPushDown: function (t) { var e = n.createFormXObject(t), r = "", i = n.Appearance.internal.getWidth(t) <= n.Appearance.internal.getHeight(t) ? n.Appearance.internal.getWidth(t) / 4 : n.Appearance.internal.getHeight(t) / 4, o = 2 * (i *= .9), a = o * n.Appearance.internal.Bezier_C; return r += "0.749023 g\n            q\n 1 0 0 1 " + n.Appearance.internal.getWidth(t) / 2 + " " + n.Appearance.internal.getHeight(t) / 2 + " cm\n" + o + " 0 m\n" + o + " " + a + " " + a + " " + o + " 0 " + o + " c\n-" + a + " " + o + " -" + o + " " + a + " -" + o + " 0 c\n-" + o + " -" + a + " -" + a + " -" + o + " 0 -" + o + " c\n" + a + " -" + o + " " + o + " -" + a + " " + o + " 0 c\n            f\n            Q\n", e.stream = r, e } }, Cross: { createAppearanceStream: function (t) { var e = { D: { Off: n.Appearance.RadioButton.Cross.OffPushDown }, N: {} }; return e.N[t] = n.Appearance.RadioButton.Cross.YesNormal, e.D[t] = n.Appearance.RadioButton.Cross.YesPushDown, e }, createMK: function () { return "<< /CA (8)>>" }, YesNormal: function (t) { var e = n.createFormXObject(t), r = "", i = n.Appearance.internal.calculateCross(t); return r += "q\n            1 1 " + (n.Appearance.internal.getWidth(t) - 2) + " " + (n.Appearance.internal.getHeight(t) - 2) + " re\n            W\n            n\n            " + i.x1.x + " " + i.x1.y + " m\n            " + i.x2.x + " " + i.x2.y + " l\n            " + i.x4.x + " " + i.x4.y + " m\n            " + i.x3.x + " " + i.x3.y + " l\n            s\n            Q\n", e.stream = r, e }, YesPushDown: function (t) { var e = n.createFormXObject(t), r = n.Appearance.internal.calculateCross(t), i = ""; return i += "0.749023 g\n            0 0 " + n.Appearance.internal.getWidth(t) + " " + n.Appearance.internal.getHeight(t) + " re\n            f\n            q\n            1 1 " + (n.Appearance.internal.getWidth(t) - 2) + " " + (n.Appearance.internal.getHeight(t) - 2) + " re\n            W\n            n\n            " + r.x1.x + " " + r.x1.y + " m\n            " + r.x2.x + " " + r.x2.y + " l\n            " + r.x4.x + " " + r.x4.y + " m\n            " + r.x3.x + " " + r.x3.y + " l\n            s\n            Q\n", e.stream = i, e }, OffPushDown: function (t) { var e = n.createFormXObject(t), r = ""; return r += "0.749023 g\n            0 0 " + n.Appearance.internal.getWidth(t) + " " + n.Appearance.internal.getHeight(t) + " re\n            f\n", e.stream = r, e } } }, createDefaultAppearanceStream: function (t) { var e = ""; return e += "/Helv 0 Tf 0 g" } }, n.Appearance.internal = { Bezier_C: .551915024494, calculateCross: function (t) { var e = n.Appearance.internal.getWidth(t), r = n.Appearance.internal.getHeight(t), i = function (t, e) { return t > e ? e : t }(e, r); return { x1: { x: (e - i) / 2, y: (r - i) / 2 + i }, x2: { x: (e - i) / 2 + i, y: (r - i) / 2 }, x3: { x: (e - i) / 2, y: (r - i) / 2 }, x4: { x: (e - i) / 2 + i, y: (r - i) / 2 + i } } } }, n.Appearance.internal.getWidth = function (t) { return t.Rect[2] }, n.Appearance.internal.getHeight = function (t) { return t.Rect[3] }, n.internal.inherit = function (t, e) { t.prototype = Object.create(e.prototype), t.prototype.constructor = t; }, n.internal.arrayToPdfArray = function (t) { if (Array.isArray(t)) { var e = " ["; for (var n in t) e += t[n].toString(), e += n < t.length - 1 ? " " : ""; return e += "]" } }, n.internal.toPdfString = function (t) { return 0 !== (t = t || "").indexOf("(") && (t = "(" + t), ")" != t.substring(t.length - 1) && (t += "("), t }, n.PDFObject = function () { var t; Object.defineProperty(this, "objId", { get: function () { return t || (this.internal ? t = this.internal.newObjectDeferred() : e.API.acroformPlugin.internal && (t = e.API.acroformPlugin.internal.newObjectDeferred())), t || console.log("Couldn't create Object ID"), t }, configurable: !1 }); }, n.PDFObject.prototype.toString = function () { return this.objId + " 0 R" }, n.PDFObject.prototype.getString = function () { var t = this.objId + " 0 obj\n<<"; return t += this.getContent() + ">>\n", this.stream && (t += "stream\n", t += this.stream, t += "endstream\n"), t += "endobj\n" }, n.PDFObject.prototype.getContent = function () { var t = ""; return t += function (t) { var e = "", r = Object.keys(t).filter(function (t) { return "content" != t && "appearanceStreamContent" != t && "_" != t.substring(0, 1) }); for (var i in r) { var o = r[i], a = t[o]; a && (Array.isArray(a) ? e += "/" + o + " " + n.internal.arrayToPdfArray(a) + "\n" : a instanceof n.PDFObject ? e += "/" + o + " " + a.objId + " 0 R\n" : e += "/" + o + " " + a + "\n"); } return e }(this) }, n.FormXObject = function () { n.PDFObject.call(this), this.Type = "/XObject", this.Subtype = "/Form", this.FormType = 1, this.BBox, this.Matrix, this.Resources = "2 0 R", this.PieceInfo; var t; Object.defineProperty(this, "Length", { enumerable: !0, get: function () { return void 0 !== t ? t.length : 0 } }), Object.defineProperty(this, "stream", { enumerable: !1, set: function (e) { t = e; }, get: function () { return t || null } }); }, n.internal.inherit(n.FormXObject, n.PDFObject), n.AcroFormDictionary = function () { n.PDFObject.call(this); var t = []; Object.defineProperty(this, "Kids", { enumerable: !1, configurable: !0, get: function () { return t.length > 0 ? t : void 0 } }), Object.defineProperty(this, "Fields", { enumerable: !0, configurable: !0, get: function () { return t } }), this.DA; }, n.internal.inherit(n.AcroFormDictionary, n.PDFObject), n.Field = function () { n.PDFObject.call(this); var t; Object.defineProperty(this, "Rect", { enumerable: !0, configurable: !1, get: function () { if (t) return t }
7558, set: function (e) { t = e; } }); var e = ""; Object.defineProperty(this, "FT", { enumerable: !0, set: function (t) { e = t; }, get: function () { return e } }); var r; Object.defineProperty(this, "T", { enumerable: !0, configurable: !1, set: function (t) { r = t; }, get: function () { if (!r || r.length < 1) { if (this instanceof n.ChildClass) return; return "(FieldObject" + n.Field.FieldNum++ + ")" } return "(" == r.substring(0, 1) && r.substring(r.length - 1) ? r : "(" + r + ")" } }); var i; Object.defineProperty(this, "DA", { enumerable: !0, get: function () { if (i) return "(" + i + ")" }, set: function (t) { i = t; } }); var o; Object.defineProperty(this, "DV", { enumerable: !0, configurable: !0, get: function () { if (o) return o }, set: function (t) { o = t; } }), Object.defineProperty(this, "Type", { enumerable: !0, get: function () { return this.hasAnnotation ? "/Annot" : null } }), Object.defineProperty(this, "Subtype", { enumerable: !0, get: function () { return this.hasAnnotation ? "/Widget" : null } }), this.BG, Object.defineProperty(this, "hasAnnotation", { enumerable: !1, get: function () { return !!(this.Rect || this.BC || this.BG) } }), Object.defineProperty(this, "hasAppearanceStream", { enumerable: !1, configurable: !0, writable: !0 }), Object.defineProperty(this, "page", { enumerable: !1, configurable: !0, writable: !0 }); }, n.Field.FieldNum = 0, n.internal.inherit(n.Field, n.PDFObject), n.ChoiceField = function () { n.Field.call(this), this.FT = "/Ch", this.Opt = [], this.V = "()", this.TI = 0, this.combo = !1, Object.defineProperty(this, "edit", { enumerable: !0, set: function (t) { 1 == t ? (this._edit = !0, this.combo = !0) : this._edit = !1; }, get: function () { return !!this._edit && this._edit }, configurable: !1 }), this.hasAppearanceStream = !0, Object.defineProperty(this, "V", { get: function () { n.internal.toPdfString(); } }); }, n.internal.inherit(n.ChoiceField, n.Field), window.ChoiceField = n.ChoiceField, n.ListBox = function () { n.ChoiceField.call(this); }, n.internal.inherit(n.ListBox, n.ChoiceField), window.ListBox = n.ListBox, n.ComboBox = function () { n.ListBox.call(this), this.combo = !0; }, n.internal.inherit(n.ComboBox, n.ListBox), window.ComboBox = n.ComboBox, n.EditBox = function () { n.ComboBox.call(this), this.edit = !0; }, n.internal.inherit(n.EditBox, n.ComboBox), window.EditBox = n.EditBox, n.Button = function () { n.Field.call(this), this.FT = "/Btn"; }, n.internal.inherit(n.Button, n.Field), window.Button = n.Button, n.PushButton = function () { n.Button.call(this), this.pushbutton = !0; }, n.internal.inherit(n.PushButton, n.Button), window.PushButton = n.PushButton, n.RadioButton = function () { n.Button.call(this), this.radio = !0; var t = []; Object.defineProperty(this, "Kids", { enumerable: !0, get: function () { if (t.length > 0) return t } }), Object.defineProperty(this, "__Kids", { get: function () { return t } }); var e; Object.defineProperty(this, "noToggleToOff", { enumerable: !1, get: function () { return e }, set: function (t) { e = t; } }); }, n.internal.inherit(n.RadioButton, n.Button), window.RadioButton = n.RadioButton, n.ChildClass = function (t, e) { n.Field.call(this), this.Parent = t, this._AppearanceType = n.Appearance.RadioButton.Circle, this.appearanceStreamContent = this._AppearanceType.createAppearanceStream(e), this.F 
vendor: 6,350 bytes, line 7558
7558= n.internal.setBitPosition(this.F, 3, 1), this.MK = this._AppearanceType.createMK(), this.AS = "/Off", this._Name = e; }, n.internal.inherit(n.ChildClass, n.Field), n.RadioButton.prototype.setAppearance = function (t) { if ("createAppearanceStream" in t && "createMK" in t) for (var e in this.__Kids) { var n = this.__Kids[e]; n.appearanceStreamContent = t.createAppearanceStream(n._Name), n.MK = t.createMK(); } else console.log("Couldn't assign Appearance to RadioButton. Appearance was Invalid!"); }, n.RadioButton.prototype.createOption = function (t) { var r = this, i = new n.ChildClass(r, t); return this.__Kids.push(i), e.API.addField(i), i }, n.CheckBox = function () { Button.call(this), this.appearanceStreamContent = n.Appearance.CheckBox.createAppearanceStream(), this.MK = n.Appearance.CheckBox.createMK(), this.AS = "/On", this.V = "/On"; }, n.internal.inherit(n.CheckBox, n.Button), window.CheckBox = n.CheckBox, n.TextField = function () { n.Field.call(this), this.DA = n.Appearance.createDefaultAppearanceStream(), this.F = 4; var t; Object.defineProperty(this, "V", { get: function () { return t ? "(" + t + ")" : t }, enumerable: !0, set: function (e) { t = e; } }); var e; Object.defineProperty(this, "DV", { get: function () { return e ? "(" + e + ")" : e }, enumerable: !0, set: function (t) { e = t; } }); var r = !1; Object.defineProperty(this, "multiline", { enumerable: !1, get: function () { return r }, set: function (t) { r = t; } }); var i = !1; Object.defineProperty(this, "MaxLen", { enumerable: !0, get: function () { return i }, set: function (t) { i = t; } }), Object.defineProperty(this, "hasAppearanceStream", { enumerable: !1, get: function () { return this.V || this.DV } }); }, n.internal.inherit(n.TextField, n.Field), window.TextField = n.TextField, n.PasswordField = function () { TextField.call(this), Object.defineProperty(this, "password", { value: !0, enumerable: !1, configurable: !1, writable: !1 }); }, n.internal.inherit(n.PasswordField, n.TextField), window.PasswordField = n.PasswordField, n.internal.calculateFontSpace = function (t, e, r) { var r = r || "helvetica", i = n.internal.calculateFontSpace.canvas || (n.internal.calculateFontSpace.canvas = document.createElement("canvas")); (s = i.getContext("2d")).save(); var o = e + " " + r; s.font = o; var a = s.measureText(t); s.fontcolor = "black"; var s = i.getContext("2d"); return a.height = 1.5 * s.measureText("3").width, s.restore(), a }, n.internal.calculateX = function (t, e, r, i) { var i = i || 12, r = r || "helvetica", o = { text: "", fontSize: "" }, a = (e = ")" == (e = "(" == e.substr(0, 1) ? e.substr(1) : e).substr(e.length - 1) ? e.substr(0, e.length - 1) : e).split(" "), s = i, c = n.Appearance.internal.getHeight(t) || 0; c = c < 0 ? -c : c; var l = n.Appearance.internal.getWidth(t) || 0; l = l < 0 ? -l : l; s++; t: for (; ;) { var e = ""; s--; var u = n.internal.calculateFontSpace("3", s + "px", r).height, h = t.multiline ? c - s : (c - u) / 2, f = -2, d = h += 2, p = 0, m = 0, g = 0; if (0 == s) { s = 12, e = "(...) Tj\n", e += "% Width of Text: " + n.internal.calculateFontSpace(e, "1px").width + ", FieldWidth:" + l + "\n"; break } g = n.internal.calculateFontSpace(a[0] + " ", s + "px", r).width; var w = "", y = 0; for (var v in a) { w = " " == (w += a[v] + " ").substr(w.length - 1) ? w.substr(0, w.length - 1) : w; var b = parseInt(v); g = n.internal.calculateFontSpace(w + " ", s + "px", r).width; var x = function (t, e, i) { if (t + 1 < a.length) { var o = e + " " + a[t + 1]; return n.internal.calculateFontSpace(o, i + "px", r).width <= l - 4 } return !1 }(b, w, s), k = v >= a.length - 1; if (!x || k) { if (x || k) { if (k) m = b; else if (t.multiline && (u + 2) * (y + 2) + 2 > c) continue t } else { if (!t.multiline) continue t; if ((u + 2) * (y + 2) + 2 > c) continue t; m = b; } for (var _ = "", C = p; C <= m; C++)_ += a[C] + " "; switch (_ = " " == _.substr(_.length - 1) ? _.substr(0, _.length - 1) : _, g = n.internal.calculateFontSpace(_, s + "px", r).width, t.Q) { case 2: f = l - g - 2; break; case 1: f = (l - g) / 2; break; case 0: default: f = 2; }e += f + " " + d + " Td\n", e += "(" + _ + ") Tj\n", e += -f + " 0 Td\n", d = -(s + 2), g = 0, p = m + 1, y++, w = ""; } else w += " "; } break } return o.text = e, o.fontSize = s, o }, n.internal.calculateAppearanceStream = function (t) { if (t.appearanceStreamContent) return t.appearanceStreamContent; if (t.V || t.DV) { var e = "", r = t.V || t.DV, i = n.internal.calculateX(t, r); e += "/Tx BMC\nq\n/F1 " + i.fontSize + " Tf\n1 0 0 1 0 0 Tm\n", e += "BT\n", e += i.text, e += "ET\n", e += "Q\nEMC\n"; var o = new n.createFormXObject(t); return o.stream = e, o } }, n.internal.calculateCoordinates = function (t, e, r, i) { var o = {}; if (this.internal) { var a = function (t) { return t * this.internal.scaleFactor }; Array.isArray(t) ? (t[0] = n.scale(t[0]), t[1] = n.scale(t[1]), t[2] = n.scale(t[2]), t[3] = n.scale(t[3]), o.lowerLeft_X = t[0] || 0, o.lowerLeft_Y = a.call(this, this.internal.pageSize.height) - t[3] - t[1] || 0, o.upperRight_X = t[0] + t[2] || 0, o.upperRight_Y = a.call(this, this.internal.pageSize.height) - t[1] || 0) : (t = n.scale(t), e = n.scale(e), r = n.scale(r), i = n.scale(i), o.lowerLeft_X = t || 0, o.lowerLeft_Y = this.internal.pageSize.height - e || 0, o.upperRight_X = t + r || 0, o.upperRight_Y = this.internal.pageSize.height - e + i || 0); } else Array.isArray(t) ? (o.lowerLeft_X = t[0] || 0, o.lowerLeft_Y = t[1] || 0, o.upperRight_X = t[0] + t[2] || 0, o.upperRight_Y = t[1] + t[3] || 0) : (o.lowerLeft_X = t || 0, o.lowerLeft_Y = e || 0, o.upperRight_X = t + r || 0, o.upperRight_Y = e + i || 0); return [o.lowerLeft_X, o.lowerLeft_Y, o.upperRight_X, o.upperRight_Y] }, n.internal.calculateColor = function (t, e, n) { var r = new Array(3); return r.r = 0 | t, r.g = 0 | e, r.b = 0 | n, r }, n.internal.getBitPosition = function (t, e) { var n = 1; return n <<= e - 1, (t = t || 0) | n }, n.internal.setBitPosition = function (t, e, n) { t = t || 0; var r = 1; if (r <<= e - 1, 1 == (n = n || 1)) t = t | r; else var t = t & ~r; return t }, e.API.addHTML = function (t, e, n, r, i) { if ("undefined" == typeof html2canvas && "undefined" == typeof rasterizeHTML) throw new Error("You need either https://github.com/niklasvh/html2canvas or https://github.com/cburgmer/rasterizeHTML.js");
7558 "number" != typeof e && (r = e, i = n), "function" == typeof r && (i = r, r = null); var o = this.internal, a = o.scaleFactor, s = o.pageSize.width, c = o.pageSize.height; if (r = r || {}, r.onrendered = function (t) { e = parseInt(e) || 0, n = parseInt(n) || 0; var o = r.dim || {}, l = o.h || 0, u = o.w || Math.min(s, t.width / a) - e, h = "JPEG"; if (r.format && (h = r.format), t.height > c && r.pagesplit) { var f = function () { for (var r = 0; ;) { var o = document.createElement("canvas"); o.width = Math.min(s * a, t.width), o.height = Math.min(c * a, t.height - r), o.getContext("2d").drawImage(t, 0, r, t.width, o.height, 0, 0, o.width, o.height); var l = [o, e, r ? 0 : n, o.width / a, o.height / a, h, null, "SLOW"]; if (this.addImage.apply(this, l), (r += o.height) >= t.height) break; this.addPage(); } i(u, r, null, l); }.bind(this); if ("CANVAS" === t.nodeName) { var d = new Image; d.onload = f, d.src = t.toDataURL("image/png"), t = d; } else f(); } else { var p = Math.random().toString(35), m = [t, e, n, u, l, h, p, "SLOW"]; this.addImage.apply(this, m), i(u, l, p, m); } }.bind(this), "undefined" != typeof html2canvas && !r.rstz) return html2canvas(t, r); if ("undefined" != typeof rasterizeHTML) { var l = "drawDocument"; return "string" == typeof t && (l = /^http/.test(t) ? "drawURL" : "drawHTML"), r.width = r.width || s * a, rasterizeHTML[l](t, void 0, r).then(function (t) { r.onrendered(t.image); }, function (t) { i(null, t); }) } return null }, function (e) { var n = ["jpeg", "jpg", "png"], r = function t(e) { var n = this.internal.newObject(), r = this.internal.write, i = this.internal.putStream; if (e.n = n, r("<</Type /XObject"), r("/Subtype /Image"), r("/Width " + e.w), r("/Height " + e.h), e.cs === this.color_spaces.INDEXED ? r("/ColorSpace [/Indexed /DeviceRGB " + (e.pal.length / 3 - 1) + " " + ("smask" in e ? n + 2 : n + 1) + " 0 R]") : (r("/ColorSpace /" + e.cs), e.cs === this.color_spaces.DEVICE_CMYK && r("/Decode [1 0 1 0 1 0 1 0]")), r("/BitsPerComponent " + e.bpc), "f" in e && r("/Filter /" + e.f), "dp" in e && r("/DecodeParms <<" + e.dp + ">>"), "trns" in e && e.trns.constructor == Array) { for (var o = "", a = 0, s = e.trns.length; a < s; a++)o += e.trns[a] + " " + e.trns[a] + " "; r("/Mask [" + o + "]"); } if ("smask" in e && r("/SMask " + (n + 1) + " 0 R"), r("/Length " + e.data.length + ">>"), i(e.data), r("endobj"), "smask" in e) { var c = "/Predictor " + e.p + " /Colors 1 /BitsPerComponent " + e.bpc + " /Columns " + e.w, l = { w: e.w, h: e.h, cs: "DeviceGray", bpc: e.bpc, dp: c, data: e.smask }; "f" in e && (l.f = e.f), t.call(this, l); } e.cs === this.color_spaces.INDEXED && (this.internal.newObject(), r("<< /Length " + e.pal.length + ">>"), i(this.arrayBufferToBinaryString(new Uint8Array(e.pal))), r("endobj")); }, i = function () { var t = this.internal.collections.addImage_images; for (var e in t) r.call(this, t[e]); }, o = function () { var t, e = this.internal.collections.addImage_images, n = this.internal.write; for (var r in e) n("/I" + (t = e[r]).i, t.n, "0", "R"); }, a = function (t) { return t && "string" == typeof t && (t = t.toUpperCase()), t in e.image_compression ? t : e.image_compression.NONE }, s = function () { var t = this.internal.collections.addImage_images; return t || (this.internal.collections.addImage_images = t = {}, this.internal.events.subscribe("putResources", i), this.internal.events.subscribe("putXobjectDict", o)), t }, c = function (t) { var e = 0; return t && (e = Object.keys ? Object.keys(t).length : function (t) { var e = 0; for (var n in t) t.hasOwnProperty(n) && e++; return e }(t)), e }, l = function (t) { return void 0 === t || null === t }, u = function (t) { return "string" == typeof t && e.sHashCode(t) }, h = function (t) { return -1 === n.indexOf(t) }, f = function (t) { return "function" != typeof e["process" + t.toUpperCase()] }, d = function (e) { return "object" === (void 0 === e ? "undefined" : t(e)) && 1 === e.nodeType }, p = function (e, n, r) { if ("IMG" === e.nodeName && e.hasAttribute("src")) { var i = "" + e.getAttribute("src"); if (!r && 0 === i.indexOf("data:image/")) return i; !n && /\.png(?:[?#].*)?$/i.test(i) && (n = "png"); }
vendor: 5,069 bytes, line 7558
7558 if ("CANVAS" === e.nodeName) var o = e; else { (o = document.createElement("canvas")).width = e.clientWidth || e.width, o.height = e.clientHeight || e.height; var a = o.getContext("2d"); if (!a) throw "addImage requires canvas to be supported by browser."; if (r) { var s, c, l, u, h, f, d, p, m = Math.PI / 180; "object" === (void 0 === r ? "undefined" : t(r)) && (s = r.x, c = r.y, l = r.bg, r = r.angle), p = r * m, u = Math.abs(Math.cos(p)), h = Math.abs(Math.sin(p)), f = o.width, d = o.height, o.width = d * h + f * u, o.height = d * u + f * h, isNaN(s) && (s = o.width / 2), isNaN(c) && (c = o.height / 2), a.clearRect(0, 0, o.width, o.height), a.fillStyle = l || "white", a.fillRect(0, 0, o.width, o.height), a.save(), a.translate(s, c), a.rotate(p), a.drawImage(e, -f / 2, -d / 2), a.rotate(-p), a.translate(-s, -c), a.restore(); } else a.drawImage(e, 0, 0, o.width, o.height); } return o.toDataURL("png" == ("" + n).toLowerCase() ? "image/png" : "image/jpeg") }, m = function (t, e) { var n; if (e) for (var r in e) if (t === e[r].alias) { n = e[r]; break } return n }, g = function (t, e, n) { return t || e || (t = -96, e = -96), t < 0 && (t = -1 * n.w * 72 / t / this.internal.scaleFactor), e < 0 && (e = -1 * n.h * 72 / e / this.internal.scaleFactor), 0 === t && (t = e * n.w / n.h), 0 === e && (e = t * n.h / n.w), [t, e] }, w = function (t, e, n, r, i, o, a) { var s = g.call(this, n, r, i), c = this.internal.getCoordinateString, l = this.internal.getVerticalCoordinateString; n = s[0], r = s[1], a[o] = i, this.internal.write("q", c(n), "0 0", c(r), c(t), l(e + r), "cm /I" + i.i, "Do Q"); }; e.color_spaces = { DEVICE_RGB: "DeviceRGB", DEVICE_GRAY: "DeviceGray", DEVICE_CMYK: "DeviceCMYK", CAL_GREY: "CalGray", CAL_RGB: "CalRGB", LAB: "Lab", ICC_BASED: "ICCBased", INDEXED: "Indexed", PATTERN: "Pattern", SEPARATION: "Separation", DEVICE_N: "DeviceN" }, e.decode = { DCT_DECODE: "DCTDecode", FLATE_DECODE: "FlateDecode", LZW_DECODE: "LZWDecode", JPX_DECODE: "JPXDecode", JBIG2_DECODE: "JBIG2Decode", ASCII85_DECODE: "ASCII85Decode", ASCII_HEX_DECODE: "ASCIIHexDecode", RUN_LENGTH_DECODE: "RunLengthDecode", CCITT_FAX_DECODE: "CCITTFaxDecode" }, e.image_compression = { NONE: "NONE", FAST: "FAST", MEDIUM: "MEDIUM", SLOW: "SLOW" }, e.sHashCode = function (t) { return Array.prototype.reduce && t.split("").reduce(function (t, e) { return (t = (t << 5) - t + e.charCodeAt(0)) & t }, 0) }, e.isString = function (t) { return "string" == typeof t }, e.extractInfoFromBase64DataURI = function (t) { return /^data:([\w]+?\/([\w]+?));base64,(.+?)$/g.exec(t) }, e.supportsArrayBuffer = function () { return "undefined" != typeof ArrayBuffer && "undefined" != typeof Uint8Array }, e.isArrayBuffer = function (t) { return !!this.supportsArrayBuffer() && t instanceof ArrayBuffer }, e.isArrayBufferView = function (t) { return !!this.supportsArrayBuffer() && ("undefined" != typeof Uint32Array && (t instanceof Int8Array || t instanceof Uint8Array || "undefined" != typeof Uint8ClampedArray && t instanceof Uint8ClampedArray || t instanceof Int16Array || t instanceof Uint16Array || t instanceof Int32Array || t instanceof Uint32Array || t instanceof Float32Array || t instanceof Float64Array)) }, e.binaryStringToUint8Array = function (t) { for (var e = t.length, n = new Uint8Array(e), r = 0; r < e; r++)n[r] = t.charCodeAt(r); return n }, e.arrayBufferToBinaryString = function (t) { if ("function" == typeof window.atob) return atob(this.arrayBufferToBase64(t)); for (var e = this.isArrayBuffer(t) ? t : new Uint8Array(t), n = "", r = Math.round(e.byteLength / 20480), i = 0; i < r; i++)n += String.fromCharCode.apply(null, e.slice(20480 * i, 20480 * i + 20480)); return n }, e.arrayBufferToBase64 = function (t) { for (var e, n, r, i, o = "", a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", s = new Uint8Array(t), c = s.byteLength, l = c % 3, u = c - l, h = 0; h < u; h += 3)e = (258048 & (i = s[h] << 16 | s[h + 1] << 8 | s[h + 2])) >> 12, n = (4032 & i) >> 6, r = 63 & i, o += a[(16515072 & i) >> 18] + a[e] + a[n] + a[r]; return 1 == l ? (e = (3 & (i = s[u])) << 4, o += a[(252 & i) >> 2] + a[e] + "==") : 2 == l && (e = (1008 & (i = s[u] << 8 | s[u + 1])) >> 4, n = (15 & i) << 2, o += a[(64512 & i) >> 10] + a[e] + a[n] + "="), o }, e.createImageInfo = function (t, e, n, r, i, o, a, s, c, l, u, h, f) { var d = { alias: s, w: e, h: n, cs: r, bpc: i, i: a, data: t }; return o && (d.f = o), c && (d.dp = c), l && (d.trns = l), u && (d.pal = u), h && (d.smask = h), f && (d.p = f), d }, e.addImage = function (e, r, i, o, g, y, v, b, x) { if ("string" != typeof r) { var k = y; y = g, g = o, o = i, i = r, r = k; } if ("object" === (void 0 === e ? "undefined" : t(e)) && !d(e) && "imageData" in e) { var _ = e; e = _.imageData, r = _.format || r, i = _.x || i || 0, o = _.y || o || 0, g = _.w || g, y = _.h || y, v = _.alias || v, b = _.compression || b, x = _.rotation || _.angle || x; } if (isNaN(i) || isNaN(o)) throw console.error("jsPDF.addImage: Invalid coordinates", arguments), new Error("Invalid coordinates passed to 
7558jsPDF.addImage"); var C, A = s.call(this); if (!(C = m(e, A))) { var S; if (d(e) && (e = p(e, r, x)), l(v) && (v = u(e)), !(C = m(v, A))) { if (this.isString(e)) { var q = this.extractInfoFromBase64DataURI(e); q ? (r = q[2], e = atob(q[3])) : 137 === e.charCodeAt(0) && 80 === e.charCodeAt(1) && 78 === e.charCodeAt(2) && 71 === e.charCodeAt(3) && (r = "png"); } if (r = (r || "JPEG").toLowerCase(), h(r)) throw new Error("addImage currently only supports formats " + n + ", not '" + r + "'"); if (f(r)) throw new Error("please ensure that the plugin for '" + r + "' support is added"); if (this.supportsArrayBuffer() && (e instanceof Uint8Array || (S = e, e = this.binaryStringToUint8Array(e))), !(C = this["process" + r.toUpperCase()](e, c(A), v, a(b), S))) throw new Error("An unkwown error occurred whilst processing the image") } } return w.call(this, i, o, g, y, C, C.i, A), this }; var y = function (t) { var e, n, r; if (255 === !t.charCodeAt(0) || 216 === !t.charCodeAt(1) || 255 === !t.charCodeAt(2) || 224 === !t.charCodeAt(3) || !t.charCodeAt(6) === "J".charCodeAt(0) || !t.charCodeAt(7) === "F".charCodeAt(0) || !t.charCodeAt(8) === "I".charCodeAt(0) || !t.charCodeAt(9) === "F".charCodeAt(0) || 0 === !t.charCodeAt(10)) throw new Error("getJpegSize requires a binary string jpeg file"); for (var i = 256 * t.charCodeAt(4) + t.charCodeAt(5), o = 4, a = t.length; o < a;) { if (o += i, 255 !== t.charCodeAt(o)) throw new Error("getJpegSize could not find the size of the image"); if (192 === t.charCodeAt(o + 1) || 193 === t.charCodeAt(o + 1) || 194 === t.charCodeAt(o + 1) || 195 === t.charCodeAt(o + 1) || 196 === t.charCodeAt(o + 1) || 197 === t.charCodeAt(o + 1) || 198 === t.charCodeAt(o + 1) || 199 === t.charCodeAt(o + 1)) return n = 256 * t.charCodeAt(o + 5) + t.charCodeAt(o + 6), e = 256 * t.charCodeAt(o + 7) + t.charCodeAt(o + 8), r = t.charCodeAt(o + 9), [e, n, r]; o += 2, i = 256 * t.charCodeAt(o) + t.charCodeAt(o + 1); } }, v = function (t) { if (65496 !== (t[0] << 8 | t[1])) throw new Error("Supplied data is not a JPEG"); for (var e, n, r, i, o = t.length, a = (t[4] << 8) + t[5], s = 4; s < o;) { if (s += a, e = b(t, s), a = (e[2] << 8) + e[3], (192 === e[1] || 194 === e[1]) && 255 === e[0] && a > 7) return e = b(t, s + 5), n = (e[2] << 8) + e[3], r = (e[0] << 8) + e[1], i = e[4], { width: n, height: r, numcomponents: i }; s += 2; } throw new Error("getJpegSizeFromBytes could not find the size of the image") }, b = function (t, e) { return t.subarray(e, e + 5) }; e.processJPEG = function (t, e, n, r, i) { var o, a = this.color_spaces.DEVICE_RGB, s = this.decode.DCT_DECODE; return this.isString(t) ? (o = y(t), this.createImageInfo(t, o[0], o[1], 1 == o[3] ? this.color_spaces.DEVICE_GRAY : a, 8, s, e, n)) : (this.isArrayBuffer(t) && (t = new Uint8Array(t)), this.isArrayBufferView(t) ? (o = v(t), t = i || this.arrayBufferToBinaryString(t), this.createImageInfo(t, o.width, o.height, 1 == o.numcomponents ? this.color_spaces.DEVICE_GRAY : a, 8, s, e, n)) : null) }, e.processJPG = function () { return this.processJPEG.apply(this, arguments) }; }(e.API), function (t) { var n = { annotations: [], f2: function (t) { return t.toFixed(2) }, notEmpty: function (t) { if (void 0 !== t && "" != t) return !0 } }; e.API.annotationPlugin = n, e.API.events.push(["addPage", function (t) { this.annotationPlugin.annotations[t.pageNumber] = []; }]), t.events.push(["putPage", function (t) { for (var e = this.annotationPlugin.annotations[t.pageNumber], r = !1, i = 0; i < e.length && !r; i++)switch ((l = e[i]).type) { case "link": if (n.notEmpty(l.options.url) || n.notEmpty(l.options.pageNumber)) { r = !0; break } case "reference": case "text": case "freetext": r = !0; }if (0 != r) { this.internal.write("/Annots ["); for (var o = this.annotationPlugin.f2, a = this.internal.scaleFactor, s = this.internal.pageSize.height, c = this.internal.getPageInfo(t.pageNumber), i = 0; i < e.length; i++) { var l = e[i]; switch (l.type) { case "reference": this.internal.write(" " + l.object.objId + " 0 R "); break; case "text": var u = this.internal.newAdditionalObject(), h = this.internal.newAdditionalObject(), f = l.title || "Note"; w = "<</Type /Annot /Subtype /Text " + (p = "/Rect [" + o(l.bounds.x * a) + " " + o(s - (l.bounds.y + l.boun
7558ds.h) * a) + " " + o((l.bounds.x + l.bounds.w) * a) + " " + o((s - l.bounds.y) * a) + "] ") + "/Contents (" + l.contents + ")", w += " /Popup " + h.objId + " 0 R", w += " /P " + c.objId + " 0 R", w += " /T (" + f + ") >>", u.content = w; var d = u.objId + " 0 R"; w = "<</Type /Annot /Subtype /Popup " + (p = "/Rect [" + o((l.bounds.x + 30) * a) + " " + o(s - (l.bounds.y + l.bounds.h) * a) + " " + o((l.bounds.x + l.bounds.w + 30) * a) + " " + o((s - l.bounds.y) * a) + "] ") + " /Parent " + d, l.open && (w += " /Open true"), w += " >>", h.content = w, this.internal.write(u.objId, "0 R", h.objId, "0 R"); break; case "freetext": var p = "/Rect [" + o(l.bounds.x * a) + " " + o((s - l.bounds.y) * a) + " " + o(l.bounds.x + l.bounds.w * a) + " " + o(s - (l.bounds.y + l.bounds.h) * a) + "] ", m = l.color || "#000000"; w = "<</Type /Annot /Subtype /FreeText " + p + "/Contents (" + l.contents + ")", w += " /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#" + m + ")", w += " /Border [0 0 0]", w += " >>", this.internal.write(w); break; case "link": if (l.options.name) { var g = this.annotations._nameMap[l.options.name]; l.options.pageNumber = g.page, l.options.top = g.y; } else l.options.top || (l.options.top = 0); var p = "/Rect [" + o(l.x * a) + " " + o((s - l.y) * a) + " " + o((l.x + l.w) * a) + " " + o((s - (l.y + l.h)) * a) + "] ", w = ""; if (l.options.url) w = "<</Type /Annot /Subtype /Link " + p + "/Border [0 0 0] /A <</S /URI /URI (" + l.options.url + ") >>"; else if (l.options.pageNumber) switch (w = "<</Type /Annot /Subtype /Link " + p + "/Border [0 0 0] /Dest [" + (t = this.internal.getPageInfo(l.options.pageNumber)).objId + " 0 R", l.options.magFactor = l.options.magFactor || "XYZ", l.options.magFactor) { case "Fit": w += " /Fit]"; break; case "FitH": w += " /FitH " + l.options.top + "]"; break; case "FitV": l.options.left = l.options.left || 0, w += " /FitV " + l.options.left + "]"; break; case "XYZ": default: var y = o((s - l.options.top) * a); l.options.left = l.options.left || 0, void 0 === l.options.zoom && (l.options.zoom = 0), w += " /XYZ " + l.options.left + " " + y + " " + l.options.zoom + "]"; }"" != w && (w += " >>", this.internal.write(w)); } } this.internal.write("]"); } }]), t.createAnnotation = function (t) { switch (t.type) { case "link": this.link(t.bounds.x, t.bounds.y, t.bounds.w, t.bounds.h, t); break; case "text": case "freetext": this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push(t); } }, t.link = function (t, e, n, r, i) { this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({ x: t, y: e, w: n, h: r, options: i, type: "link" }); }, t.textWithLink = function (t, e, n, r) { var i = this.getTextWidth(t), o = this.internal.getLineHeight() / this.internal.scaleFactor; return this.text(t, e, n), n += .2 * o, this.link(e, n - o, i, o, r), i }, t.getTextWidth = function (t) { var e = this.internal.getFontSize(); return this.getStringUnitWidth(t) * e / this.internal.scaleFactor }, t.getLineHeight = function () { return this.internal.getLineHeight() }; }(e.API), e.API.autoPrint = function () { var t; return this.internal.events.subscribe("postPutResources", function () { t = this.internal.newObject(), this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj"); }), this.internal.events.subscribe("putCatalog", function () { this.internal.write("/OpenAction " + t + " 0 R"); }), this }, function (t) { t.events.push(["initialized", function () { this.canvas.pdf = this; }]), t.canvas = { getContext: function (t) { return this.pdf.context2d._canvas = this, this.pdf.context2d }, style: {} }, Object.defineProperty(t.canvas, "width", { get: function () { return this._width }, set: function (t) { this._width = t, this.getContext("2d").pageWrapX = t + 1; } }), Object.defineProperty(t.canvas, "height", { get: function () { return this._height }, set: function (t) { this._height = t, this.getContext("2d").pageWrapY = t + 1; } }); }(e.API), function (t) { var e, n, r, i, o = { x: void 0, y: void 0, w: void 0, h: void 0, ln: void 0 }, a = 1, s = function (t, e, n, r, i) { o = { x: t, y: e, w: n, h: r, ln: i }; }, c = function () { return o }, l = { left: 0, top: 0, bottom: 0 }; t.setHeaderFunction = function (t) { i = t; }, t.getTextDimensions = function (t) { e = this.internal.getFont().fontName, n = this.table_font_size || this.internal.getFontSize(), r = this.internal.getFont().fontStyle; var i, o; (o = document.createElement("font")).id = "jsPDFCell"; try { o.style.fontStyle = r; } catch (t) { o.style.fontWeight = r; } o.style.fontName = e, o.style.fontSize = n + "pt"; try { o.textContent = t; } catch (e) { o.innerText = t; } return document.body.appendChild(o), i = { w: (o.offsetWidth + 1) * (19.049976 / 25.4), h: (o.offsetHeight + 1) * (19.049976 / 25.4) }, document.body.removeChild(o), i }, t.cellAddPage = function () { var t = this.margins || l; this.addPage(), s(t.left, t.top, void 0, void 0), a += 1; }, t.cellInitialize = function () { o = { x: void 0, y: void 0, w: void 0, h: void 0, ln: void 0 }, a = 1; }, t.cell = function (t, e, n, r, i, o, a) { var u = c(), h = !1; if (void 0 !== u.ln) if (u.ln === o) t = u.x + u.w, e = u.y; else { var f = this.margins || l; u.y + u.h + r + 13 >= this.internal.pageSize.height - f.bottom && (this.cellAddPage(), h = !0, this.printHeaders && this.tableHeaderRow && this.printHeaderRow(o, !0)), e = c().y + c().h, h && (e = 23); } if (void 0 !== i[0]) if (this.printingHeaderRow ? this.rect(t, e, n, r, "FD") : this.rect(t, e, n, r), "right" === a) { i instanceof Array || (i = [i]); for (var d = 0; d < i.length;
7558 d++) { var p = i[d], m = this.getStringUnitWidth(p) * this.internal.getFontSize(); this.text(p, t + n - m - 3, e + this.internal.getLineHeight() * (d + 1)); } } else this.text(i, t + 3, e + this.internal.getLineHeight()); return s(t, e, n, r, o), this }, t.arrayMax = function (t, e) { var n, r, i, o = t[0]; for (n = 0, r = t.length; n < r; n += 1)i = t[n], e ? -1 === e(o, i) && (o = i) : i > o && (o = i); return o }, t.table = function (e, n, r, i, s) { if (!r) throw "No data for PDF table"; var c, u, h, f, d, p, m, g, w, y, v = [], b = [], x = {}, k = {}, _ = [], C = [], A = !1, S = !0, q = 12, T = l; if (T.width = this.internal.pageSize.width, s && (!0 === s.autoSize && (A = !0), !1 === s.printHeaders && (S = !1), s.fontSize && (q = s.fontSize), s.css && void 0 !== s.css["font-size"] && (q = 16 * s.css["font-size"]), s.margins && (T = s.margins)), this.lnMod = 0, o = { x: void 0, y: void 0, w: void 0, h: void 0, ln: void 0 }, a = 1, this.printHeaders = S, this.margins = T, this.setFontSize(q), this.table_font_size = q, void 0 === i || null === i) v = Object.keys(r[0]); else if (i[0] && "string" != typeof i[0]) { for (u = 0, h = i.length; u < h; u += 1)c = i[u], v.push(c.name), b.push(c.prompt), k[c.name] = c.width * (19.049976 / 25.4); } else v = i; if (A) for (y = function (t) { return t[c] }, u = 0, h = v.length; u < h; u += 1) { for (x[c = v[u]] = r.map(y), _.push(this.getTextDimensions(b[u] || c).w), m = 0, f = (p = x[c]).length; m < f; m += 1)d = p[m], _.push(this.getTextDimensions(d).w); k[c] = t.arrayMax(_), _ = []; } if (S) { P = this.calculateLineHeight(v, k, b.length ? b : v); for (u = 0, h = v.length; u < h; u += 1)c = v[u], C.push([e, n, k[c], P, String(b.length ? b[u] : c)]); this.setTableHeaderRow(C), this.printHeaderRow(1, !1); } for (u = 0, h = r.length; u < h; u += 1) { var P; for (g = r[u], P = this.calculateLineHeight(v, k, g), m = 0, w = v.length; m < w; m += 1)c = v[m], this.cell(e, n, k[c], P, g[c], u + 2, c.align); } return this.lastCellPos = o, this.table_x = e, this.table_y = n, this }, t.calculateLineHeight = function (t, e, n) { for (var r, i = 0, o = 0; o < t.length; o++) { n[r = t[o]] = this.splitTextToSize(String(n[r]), e[r] - 3); var a = this.internal.getLineHeight() * n[r].length + 3; a > i && (i = a); } return i }, t.setTableHeaderRow = function (t) { this.tableHeaderRow = t; }, t.printHeaderRow = function (t, e) { if (!this.tableHeaderRow) throw "Property tableHeaderRow does not exist."; var n, r, o, c; if (this.printingHeaderRow = !0, void 0 !== i) { var l = i(this, a); s(l[0], l[1], l[2], l[3], -1); } this.setFontStyle("bold"); var u = []; for (o = 0, c = this.tableHeaderRow.length; o < c; o += 1)this.setFillColor(200, 200, 200), n = this.tableHeaderRow[o], e && (this.margins.top = 13, n[1] = this.margins && this.margins.top || 0, u.push(n)), r = [].concat(n), this.cell.apply(this, r.concat(t)); u.length > 0 && this.setTableHeaderRow(u), this.setFontStyle("normal"), this.printingHeaderRow = !1; }; }(e.API), function (t) { function e() { this._isStrokeTransparent = !1, this._strokeOpacity = 1, this.strokeStyle = "#000000", this.fillStyle = "#000000", this._isFillTransparent = !1, this._fillOpacity = 1, this.font = "12pt times", this.textBaseline = "alphabetic", this.textAlign = "start", this.lineWidth = 1, this.lineJoin = "miter", this.lineCap = "butt", this._transform = [1, 0, 0, 1, 0, 0], this.globalCompositeOperation = "normal", this.globalAlpha = 1, this._clip_path = [], this.ignoreClearRect = !1, this.copy = function (t) { this._isStrokeTransparent = t._isStrokeTransparent, this._strokeOpacity = t._strokeOpacity, this.strokeStyle = t.strokeStyle, this._isFillTransparent = t._isFillTransparent, this._fillOpacity = t._fillOpacity, this.fillStyle = t.fillStyle, this.font = t.font, this.lineWidth = t.lineWidth, this.lineJoin = t.lineJoin, this.lineCap = t.lineCap, this.textBaseline = t.textBaseline, this.textAlign = t.textAlign, this._fontSize = t._fontSize, this._transform = t._transform.slice(0), this.globalCompositeOperation = t.globalCompositeOperation, this.globalAlpha = t.globalAlpha, this._clip_path = t._clip_path.slice(0), this.ignoreClearRect = t.ignoreClearRect; }; } t.events.push(["initialized", function () { this.context2d.pdf = this, this.context2d.internal.pdf = this, this.context2d.ctx = new e, this.context2d.ctxStack = [], this.context2d.path = []; }]), t.context2d = { pageWrapXEnabled: !1, pageWrapYEnabled: !1, pageWrapX: 9999999, pageWrapY: 9999999, ctx: new e, f2: function (t) { return t.toFixed(2) }, fillRect: function (t, e, n, r) { if (!this._isFillTransparent
7558()) { t = this._wrapX(t), e = this._wrapY(e); var i = this._matrix_map_rect(this.ctx._transform, { x: t, y: e, w: n, h: r }); this.pdf.rect(i.x, i.y, i.w, i.h, "f"); } }, strokeRect: function (t, e, n, r) { if (!this._isStrokeTransparent()) { t = this._wrapX(t), e = this._wrapY(e); var i = this._matrix_map_rect(this.ctx._transform, { x: t, y: e, w: n, h: r }); this.pdf.rect(i.x, i.y, i.w, i.h, "s"); } }, clearRect: function (t, e, n, r) { if (!this.ctx.ignoreClearRect) { t = this._wrapX(t), e = this._wrapY(e); var i = this._matrix_map_rect(this.ctx._transform, { x: t, y: e, w: n, h: r }); this.save(), this.setFillStyle("#ffffff"), this.pdf.rect(i.x, i.y, i.w, i.h, "f"), this.restore(); } }, save: function () { this.ctx._fontSize = this.pdf.internal.getFontSize(); var t = new e; t.copy(this.ctx), this.ctxStack.push(this.ctx), this.ctx = t; }, restore: function () { this.ctx = this.ctxStack.pop(), this.setFillStyle(this.ctx.fillStyle), this.setStrokeStyle(this.ctx.strokeStyle), this.setFont(this.ctx.font), this.pdf.setFontSize(this.ctx._fontSize), this.setLineCap(this.ctx.lineCap), this.setLineWidth(this.ctx.lineWidth), this.setLineJoin(this.ctx.lineJoin); }, rect: function (t, e, n, r) { this.moveTo(t, e), this.lineTo(t + n, e), this.lineTo(t + n, e + r), this.lineTo(t, e + r), this.lineTo(t, e), this.closePath(); }, beginPath: function () { this.path = []; }, closePath: function () { this.path.push({ type: "close" }); }, _getRGBA: function (t) { var e, n, r, o; if (!t) return { r: 0, g: 0, b: 0, a: 0, style: t }; if (this.internal.rxTransparent.test(t)) e = 0, n = 0, r = 0, o = 0; else { var a = this.internal.rxRgb.exec(t); null != a ? (e = parseInt(a[1]), n = parseInt(a[2]), r = parseInt(a[3]), o = 1) : null != (a = this.internal.rxRgba.exec(t)) ? (e = parseInt(a[1]), n = parseInt(a[2]), r = parseInt(a[3]), o = parseFloat(a[4])) : (o = 1, "#" != t.charAt(0) && ((t = i.colorNameToHex(t)) || (t = "#000000")), 4 === t.length ? (e = t.substring(1, 2), e += e, n = t.substring(2, 3), n += n, r = t.substring(3, 4), r += r) : (e = t.substring(1, 3), n = t.substring(3, 5), r = t.substring(5, 7)), e = parseInt(e, 16), n = parseInt(n, 16), r = parseInt(r, 16)); } return { r: e, g: n, b: r, a: o, style: t } }, setFillStyle: function (t) { var e = this._getRGBA(t); this.ctx.fillStyle = t, this.ctx._isFillTransparent = 0 === e.a, this.ctx._fillOpacity = e.a, this.pdf.setFillColor(e.r, e.g, e.b, { a: e.a }), this.pdf.setTextColor(e.r, e.g, e.b, { a: e.a }); }, setStrokeStyle: function (t) { var e = this._getRGBA(t); this.ctx.strokeStyle = e.style, this.ctx._isStrokeTransparent = 0 === e.a, this.ctx._strokeOpacity = e.a, 0 === e.a ? this.pdf.setDrawColor(255, 255, 255) : (e.a, this.pdf.setDrawColor(e.r, e.g, e.b)); }, fillText: function (t, e, n, r) { if (!this._isFillTransparent()) { e = this._wrapX(e), n = this._wrapY(n); var i = this._matrix_map_point(this.ctx._transform, [e, n]); e = i[0], n = i[1]; var o = 57.2958 * this._matrix_rotation(this.ctx._transform); if (this.ctx._clip_path.length > 0) { var a; (a = window.outIntercept ? "group" === window.outIntercept.type ? window.outIntercept.stream : window.outIntercept : this.internal.getCurrentPage()).push("q"); var s = this.path; this.path = this.ctx._clip_path, this.ctx._clip_path = [], this._fill(null, !0), this.ctx._clip_path = this.path, this.path = s; } var c = 1; try { c = this._matrix_decompose(this._getTransform()).scale[0]; } catch (t) { console.warn(t); } if (c < .01) this.pdf.text(t, e, this._getBaseline(n), null, o); else { var l = this.pdf.internal.getFontSize(); this.pdf.setFontSize(l * c), this.pdf.text(t, e, this._getBaseline(n), null, o), this.pdf.setFontSize(l); } this.ctx._clip_path.length > 0 && a.push("Q"); } }, strokeText: function (t, e, n, r) { if (!this._isStrokeTransparent
7558()) { e = this._wrapX(e), n = this._wrapY(n); var i = this._matrix_map_point(this.ctx._transform, [e, n]); e = i[0], n = i[1]; var o = 57.2958 * this._matrix_rotation(this.ctx._transform); if (this.ctx._clip_path.length > 0) { var a; (a = window.outIntercept ? "group" === window.outIntercept.type ? window.outIntercept.stream : window.outIntercept : this.internal.getCurrentPage()).push("q"); var s = this.path; this.path = this.ctx._clip_path, this.ctx._clip_path = [], this._fill(null, !0), this.ctx._clip_path = this.path, this.path = s; } var c = 1; try { c = this._matrix_decompose(this._getTransform()).scale[0]; } catch (t) { console.warn(t); } if (1 === c) this.pdf.text(t, e, this._getBaseline(n), { stroke: !0 }, o); else { var l = this.pdf.internal.getFontSize(); this.pdf.setFontSize(l * c), this.pdf.text(t, e, this._getBaseline(n), { stroke: !0 }, o), this.pdf.setFontSize(l); } this.ctx._clip_path.length > 0 && a.push("Q"); } }, setFont: function (t) { this.ctx.font = t; var e = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+(.*)?/; if (null != (u = e.exec(t))) { var n = u[1], r = u[3], i = u[4], o = u[5], a = u[6]; i = "px" === o ? Math.floor(parseFloat(i)) : "em" === o ? Math.floor(parseFloat(i) * this.pdf.getFontSize()) : Math.floor(parseFloat(i)), this.pdf.setFontSize(i), "bold" === r || "700" === r ? this.pdf.setFontStyle("bold") : "italic" === n ? this.pdf.setFontStyle("italic") : this.pdf.setFontStyle("normal"); var s, c = (f = a).toLowerCase().split(/\s*,\s*/); s = -1 != c.indexOf("arial") ? "Arial" : -1 != c.indexOf("verdana") ? "Verdana" : -1 != c.indexOf("helvetica") ? "Helvetica" : -1 != c.indexOf("sans-serif") ? "sans-serif" : -1 != c.indexOf("fixed") ? "Fixed" : -1 != c.indexOf("monospace") ? "Monospace" : -1 != c.indexOf("terminal") ? "Terminal" : -1 != c.indexOf("courier") ? "Courier" : -1 != c.indexOf("times") ? "Times" : -1 != c.indexOf("cursive") ? "Cursive" : -1 != c.indexOf("fantasy") ? "Fantasy" : (c.indexOf("serif"), "Serif"); var l; l = "bold" === r ? "bold" : "normal", this.pdf.setFont(s, l); } else { var u = (e = /\s*(\d+)(pt|px|em)\s+([\w "]+)\s*([\w "]+)?/).exec(t); if (null != u) { var h = u[1], f = u[3]; (l = u[4]) || (l = "normal"), h = "em" === o ? Math.floor(parseFloat(i) * this.pdf.getFontSize()) : Math.floor(parseFloat(h)), this.pdf.setFontSize(h), this.pdf.setFont(f, l); } } }, setTextBaseline: function (t) { this.ctx.textBaseline = t; }, getTextBaseline: function () { return this.ctx.textBaseline }, setTextAlign: function (t) { this.ctx.textAlign = t; }, getTextAlign: function () { return this.ctx.textAlign }, setLineWidth: function (t) { this.ctx.lineWidth = t, this.pdf.setLineWidth(t); }, setLineCap: function (t) { this.ctx.lineCap = t, this.pdf.setLineCap(t); }, setLineJoin: function (t) { this.ctx.lineJoin = t, this.pdf.setLineJoin(t); }, moveTo: function (t, e) { t = this._wrapX(t), e = this._wrapY(e); var n = this._matrix_map_point(this.ctx._transform, [t, e]), r = { type: "mt", x: t = n[0], y: e = n[1] }; this.path.push(r); }, _wrapX: function (t) { return this.pageWrapXEnabled ? t % this.pageWrapX : t }, _wrapY: function (t) { return this.pageWrapYEnabled ? (this._gotoPage(this._page(t)), (t - this.lastBreak) % this.pageWrapY) : t }, transform: function (t, e, n, r, i, o) { this.ctx._transform = [t, e, n, r, i, o]; }, setTransform: function (t, e, n, r, i, o) { this.ctx._transform = [t, e, n, r, i, o]; }, _getTransform: function () { return this.ctx._transform }, lastBreak: 0, pageBreaks: [], _page: function (t) { if (this.pageWrapYEnabled) { this.lastBreak = 0; for (var e = 0, n = 0, r = 0; r < this.pageBreaks.length; r++)if (t >= this.pageBreaks[r]) { e++, 0 === this.lastBreak && n++; var i = this.pageBreaks[r] - this.lastBreak; this.lastBreak = this.pageBreaks[r], n += o = Math.floor(i / this.pageWrapY); } if (0 === this.lastBreak) { var o = Math.floor(t / this.pageWrapY) + 1; n += o; } return n + e } return this.pdf.internal.getCurrentPageInfo().pageNumber }, _gotoPage: function (t) { }, lineTo: function (t, e) { t = this._wrapX(t), e = this._wrapY(e); var n = this._matrix_map_point(this.ctx._transform, [t, e]), r = { type: "lt", x: t = n[0], y: e = n[1] }; this.path.push(r); }, bezierCurveTo: function (t, e, n, r, i, o) { t = this._wrapX(t), e = this._wrapY(e), n = this._wrapX(n), r = this._wrapY(r), i = this._wrapX(i), o = this._wrapY(o); var a; i = (a = this._matrix_map_point(this.ctx._transform, [i, o]))[0], o = a[1]; var s = { type: "bct", x1: t = (a = this._matrix_map_point(this.ctx._transform, [t, e]))[0], y1: e = a[1], x2: n = (a = this._matrix_map_point(this.ctx._transform, [n, r]))[0], y2: r = a[1], x: i, y: o }; this.path.push(s); }, quadraticCurveTo: function (t, e, n, r) { t = this._wrapX(t), e = this._wrapY(e), n = this._wrapX(n), r = this._wrapY(r); var i; n = (i = this._matrix_map_point(this.ctx._transform, [n, r]))[0], r = i[
vendor: 8,358 bytes, line 7558
75581]; var o = { type: "qct", x1: t = (i = this._matrix_map_point(this.ctx._transform, [t, e]))[0], y1: e = i[1], x: n, y: r }; this.path.push(o); }, arc: function (t, e, n, r, i, o) { if (t = this._wrapX(t), e = this._wrapY(e), !this._matrix_is_identity(this.ctx._transform)) { var a = this._matrix_map_point(this.ctx._transform, [t, e]); t = a[0], e = a[1]; var s = this._matrix_map_point(this.ctx._transform, [0, 0]), c = this._matrix_map_point(this.ctx._transform, [0, n]); n = Math.sqrt(Math.pow(c[0] - s[0], 2) + Math.pow(c[1] - s[1], 2)); } var l = { type: "arc", x: t, y: e, radius: n, startAngle: r, endAngle: i, anticlockwise: o }; this.path.push(l); }, drawImage: function (t, e, n, r, i, o, a, s, c) { void 0 !== o && (e = o, n = a, r = s, i = c), e = this._wrapX(e), n = this._wrapY(n); var l, u = this._matrix_map_rect(this.ctx._transform, { x: e, y: n, w: r, h: i }), h = (this._matrix_map_rect(this.ctx._transform, { x: o, y: a, w: s, h: c }), /data:image\/(\w+).*/i.exec(t)); l = null != h ? h[1] : "png", this.pdf.addImage(t, l, u.x, u.y, u.w, u.h); }, _matrix_multiply: function (t, e) { var n = e[0], r = e[1], i = e[2], o = e[3], a = e[4], s = e[5], c = n * t[0] + r * t[2], l = i * t[0] + o * t[2], u = a * t[0] + s * t[2] + t[4]; return r = n * t[1] + r * t[3], o = i * t[1] + o * t[3], s = a * t[1] + s * t[3] + t[5], n = c, i = l, a = u, [n, r, i, o, a, s] }, _matrix_rotation: function (t) { return Math.atan2(t[2], t[0]) }, _matrix_decompose: function (t) { var e = t[0], n = t[1], r = t[2], i = t[3], o = Math.sqrt(e * e + n * n), a = (e /= o) * r + (n /= o) * i; r -= e * a, i -= n * a; var s = Math.sqrt(r * r + i * i); return r /= s, i /= s, a /= s, e * i < n * r && (e = -e, n = -n, a = -a, o = -o), { scale: [o, 0, 0, s, 0, 0], translate: [1, 0, 0, 1, t[4], t[5]], rotate: [e, n, -n, e, 0, 0], skew: [1, 0, a, 1, 0, 0] } }, _matrix_map_point: function (t, e) { var n = t[0], r = t[1], i = t[2], o = t[3], a = t[4], s = t[5], c = e[0], l = e[1]; return [c * n + l * i + a, c * r + l * o + s] }, _matrix_map_point_obj: function (t, e) { var n = this._matrix_map_point(t, [e.x, e.y]); return { x: n[0], y: n[1] } }, _matrix_map_rect: function (t, e) { var n = this._matrix_map_point(t, [e.x, e.y]), r = this._matrix_map_point(t, [e.x + e.w, e.y + e.h]); return { x: n[0], y: n[1], w: r[0] - n[0], h: r[1] - n[1] } }, _matrix_is_identity: function (t) { return 1 == t[0] && (0 == t[1] && (0 == t[2] && (1 == t[3] && (0 == t[4] && 0 == t[5])))) }, rotate: function (t) { var e = [Math.cos(t), Math.sin(t), -Math.sin(t), Math.cos(t), 0, 0]; this.ctx._transform = this._matrix_multiply(this.ctx._transform, e); }, scale: function (t, e) { var n = [t, 0, 0, e, 0, 0]; this.ctx._transform = this._matrix_multiply(this.ctx._transform, n); }, translate: function (t, e) { var n = [1, 0, 0, 1, t, e]; this.ctx._transform = this._matrix_multiply(this.ctx._transform, n); }, stroke: function () { if (this.ctx._clip_path.length > 0) { var t; (t = window.outIntercept ? "group" === window.outIntercept.type ? window.outIntercept.stream : window.outIntercept : this.internal.getCurrentPage()).push("q"); var e = this.path; this.path = this.ctx._clip_path, this.ctx._clip_path = [], this._stroke(!0), this.ctx._clip_path = this.path, this.path = e, this._stroke(!1), t.push("Q"); } else this._stroke(!1); }, _stroke: function (t) { if (t || !this._isStrokeTransparent()) { for (var e = [], n = this.path, r = 0; r < n.length; r++) { var i = n[r]; switch (i.type) { case "mt": e.push({ start: i, deltas: [], abs: [] }); break; case "lt": h = [i.x - n[r - 1].x, i.y - n[r - 1].y]; e[e.length - 1].deltas.push(h), e[e.length - 1].abs.push(i); break; case "bct": h = [i.x1 - n[r - 1].x, i.y1 - n[r - 1].y, i.x2 - n[r - 1].x, i.y2 - n[r - 1].y, i.x - n[r - 1].x, i.y - n[r - 1].y]; e[e.length - 1].deltas.push(h); break; case "qct": var o = n[r - 1].x + 2 / 3 * (i.x1 - n[r - 1].x), a = n[r - 1].y + 2 / 3 * (i.y1 - n[r - 1].y), s = i.x + 2 / 3 * (i.x1 - i.x), c = i.y + 2 / 3 * (i.y1 - i.y), l = i.x, u = i.y, h = [o - n[r - 1].x, a - n[r - 1].y, s - n[r - 1].x, c - n[r - 1].y, l - n[r - 1].x, u - n[r - 1].y]; e[e.length - 1].deltas.push(h); break; case "arc": 0 == e.length && e.push({ start: { x: 0, y: 0 }, deltas: [], abs: [] }), e[e.length - 1].arc = !0, e[e.length - 1].abs.push(i); } } for (r = 0; r < e.length; r++) { var f; if (f = r == e.length - 1 ? "s" : null, e[r].arc) for (var d = e[r].abs, p = 0; p < d.length; p++) { var m = d[p], g = 360 * m.startAngle / (2 * Math.PI), w = 360 * m.endAngle / (2 * Math.PI), y = m.x, v = m.y; this.internal.arc2(this, y, v, m.radius, g, w, m.anticlockwise, f, t); } else { var y = e[r].start.x, v = e[r].start.y; t ? (this.pdf.lines(e[r].deltas, y, v, null, null), this.pdf.clip_fixed()) : this.pdf.lines(e[r].deltas, y, v, null, f); } } } }, _isFillTransparent: function () { return this.ctx._isFillTransparent || 0 == this.globalAlpha }, _isStrokeTransparent: function () { return this.ctx._isStrokeTransparent || 0 == this.globalAlpha }, fill: function (t) { if (this.ctx._clip_path.length > 0) { var e; (e = window.outIntercept ? "group" === window.outIntercept.type ? window.outIntercept.stream : window.outIntercept : this.internal.getCurrentPage()).push("q"); var n = this.path; this.path = this.ctx._clip_path, this.ctx._clip_path = [], this._fill(t, !0), this.ctx._clip_path = this.path, this.path = n, this._fill(t, !1), e.push("Q"); } else this._fill(t, !1); }, _fill: function (t, e) { if (!this._isFillTransparent()) { var r, i = "function" == typeof this.pdf.internal.newObject2; r = window.outIntercept ? "group" === window.outIntercept.type ? window.outIntercept.stream : window.outIntercept : this.internal.getCurrentPage(); var o = [], a = window.outIntercept; if (i) switch (this.ctx.globalCompositeOperation) { case "normal": case "source-over": break; case "destination-in": case "destination-out": var s = this.pdf.internal.newStreamObject(), c = this.pdf.internal.newObject2(); c.push("<</Type /ExtGState"), c.push("/SMask <</S /Alpha /G " + s.objId + " 0 R>>"), c.push(">>"); d = "MASK" + c.objId; this.pdf.internal.addGraphicsState(d, c.objId); var l = "/" + d + " gs"; r.splice(0, 0, "q"), r.splice(1, 0, l), r.push("Q"), window.outIntercept = s; break; default: var u = "/" + this.pdf.internal.blendModeMap[this.ctx.globalCompositeOperation.toUpperCase()]; u && this.pdf.internal.out(u + " gs"); }var h = this.ctx.globalAlpha; if (this.ctx._fillOpacity < 1 && (h = this.ctx._fillOpacity), i) { var f = this.pdf.internal.newObject2(); f.push("<</Type /ExtGState"), f.push("/CA " + h), f.push("/ca " + h), f.push(">>"); var d = "GS_O_" + f.objId; this.pdf.internal.addGraphicsState(d, f.objId), this.pdf.internal.out("/" + d + " gs"); } for (var p = this.path, m = 0; m < p.length; m++) { var g = p[m]; switch (g.type) { case "mt": o.push({ start: g, deltas: [], abs: [] }); break; case "lt": _ = [g.x - p[m - 1].x, g.y - p[m - 1].y]; o[o.length - 1].deltas.push(_), o[o.length - 1].abs.push(g); break; case "bct": _ = [g.x1 - p[m - 1].x, g.y1 - p[m - 1].y, g.x2 - p[m - 1].x, g.y2 - p[m - 1].y, g.x - p[m - 1].x, g.y - p[m - 1].y]; o[o.length - 1].deltas.push(_); break; case "qct": var w = p[m - 1].x + 2 / 3 * (g.x1 - p[m - 1].x), y = p[m - 1].y + 2 / 3 * (g.y1 - p[m - 1].y), v = g.x + 2 / 3 * (g.x1 - g.x), b = g.y + 2 / 3 * (g.y1 - g.y), x = g.x, k = g.y, _ = [w - p[m - 1].x, y - p[m - 1].y, v - p[m - 1].x, b - p[m - 1].y, x - p[m - 1].x, k - p[m - 1].y]; o[o.length - 1].deltas.push(_); break; case "arc": 0 === o.length && o.push({ deltas: [], abs: [] }), o[o.length - 1].arc = !0, o[o.length - 1].abs.push(g); break; case "close": o.push({ close: !0 }); } } for (m = 0; m < o.length; m++) { var C; if (m == o.length - 1 ? (C = "f", "evenodd" === t && (C += "*")) : C = null, o[m].close) this.pdf.internal.out("h"), this.pdf.internal.out("f"); else if (o[m].arc) { o[m].start && this.internal.move2(this, o[m].start.x, o[m].start.y); for (var A = o[m].abs, S = 0; S < A.length; S++) { var q = A[S]; if (void 0 !== q.startAngle) { var T = 360 * q.startAngle / (2 * Math.PI), P = 360 * q.endAngle / (2 * Math.PI), I = q.x, E = q.y; if (0 === S && this.internal.move2(this, I, E), this.internal.arc2(this, I, E, q.radius, T, P, q.anticlockwise, null, e), S === A.length - 1 && o[m].start) { var I = o[m].start.x, E = o[m].start.y; this.internal.line2(n, I, E); } }
7558 else this.internal.line2(n, q.x, q.y); } } else { var I = o[m].start.x, E = o[m].start.y; e ? (this.pdf.lines(o[m].deltas, I, E, null, null), this.pdf.clip_fixed()) : this.pdf.lines(o[m].deltas, I, E, null, C); } } window.outIntercept = a; } }, pushMask: function () { if ("function" == typeof this.pdf.internal.newObject2) { var t = this.pdf.internal.newStreamObject(), e = this.pdf.internal.newObject2(); e.push("<</Type /ExtGState"), e.push("/SMask <</S /Alpha /G " + t.objId + " 0 R>>"), e.push(">>"); var n = "MASK" + e.objId; this.pdf.internal.addGraphicsState(n, e.objId); var r = "/" + n + " gs"; this.pdf.internal.out(r); } else console.log("jsPDF v2 not enabled"); }, clip: function () { if (this.ctx._clip_path.length > 0) for (var t = 0; t < this.path.length; t++)this.ctx._clip_path.push(this.path[t]); else this.ctx._clip_path = this.path; this.path = []; }, measureText: function (t) { var e = this.pdf; return { getWidth: function () { var n = e.internal.getFontSize(), r = e.getStringUnitWidth(t) * n / e.internal.scaleFactor; return r *= 1.3333 }, get width() { return this.getWidth(t) } } }, _getBaseline: function (t) { var e = parseInt(this.pdf.internal.getFontSize()), n = .25 * e; switch (this.ctx.textBaseline) { case "bottom": return t - n; case "top": return t + e; case "hanging": return t + e - n; case "middle": return t + e / 2 - n; case "ideographic": return t; case "alphabetic": default: return t } } }; var n = t.context2d; Object.defineProperty(n, "fillStyle", { set: function (t) { this.setFillStyle(t); }, get: function () { return this.ctx.fillStyle } }), Object.defineProperty(n, "strokeStyle", { set: function (t) { this.setStrokeStyle(t); }, get: function () { return this.ctx.strokeStyle } }), Object.defineProperty(n, "lineWidth", { set: function (t) { this.setLineWidth(t); }, get: function () { return this.ctx.lineWidth } }), Object.defineProperty(n, "lineCap", { set: function (t) { this.setLineCap(t); }, get: function () { return this.ctx.lineCap } }), Object.defineProperty(n, "lineJoin", { set: function (t) { this.setLineJoin(t); }, get: function () { return this.ctx.lineJoin } }), Object.defineProperty(n, "miterLimit", { set: function (t) { this.ctx.miterLimit = t; }, get: function () { return this.ctx.miterLimit } }), Object.defineProperty(n, "textBaseline", { set: function (t) { this.setTextBaseline(t); }, get: function () { return this.getTextBaseline() } }), Object.defineProperty(n, "textAlign", { set: function (t) { this.setTextAlign(t); }, get: function () { return this.getTextAlign() } }), Object.defineProperty(n, "font", { set: function (t) { this.setFont(t); }, get: function () { return this.ctx.font } }), Object.defineProperty(n, "globalCompositeOperation", { set: function (t) { this.ctx.globalCompositeOperation = t; }, get: function () { return this.ctx.globalCompositeOperation } }), Object.defineProperty(n, "globalAlpha", { set: function (t) { this.ctx.globalAlpha = t; }, get: function () { return this.ctx.globalAlpha } }
vendor: 17,590 bytes, line 7558
7558), Object.defineProperty(n, "ignoreClearRect", { set: function (t) { this.ctx.ignoreClearRect = t; }, get: function () { return this.ctx.ignoreClearRect } }), n.internal = {}, n.internal.rxRgb = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/, n.internal.rxRgba = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/, n.internal.rxTransparent = /transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/, n.internal.arc = function (t, e, n, r, i, o, a, s) { for (var c = this.pdf.internal.scaleFactor, l = this.pdf.internal.pageSize.height, u = this.pdf.internal.f2, h = i * (Math.PI / 180), f = o * (Math.PI / 180), d = this.createArc(r, h, f, a), p = 0; p < d.length; p++) { var m = d[p]; 0 === p ? this.pdf.internal.out([u((m.x1 + e) * c), u((l - (m.y1 + n)) * c), "m", u((m.x2 + e) * c), u((l - (m.y2 + n)) * c), u((m.x3 + e) * c), u((l - (m.y3 + n)) * c), u((m.x4 + e) * c), u((l - (m.y4 + n)) * c), "c"].join(" ")) : this.pdf.internal.out([u((m.x2 + e) * c), u((l - (m.y2 + n)) * c), u((m.x3 + e) * c), u((l - (m.y3 + n)) * c), u((m.x4 + e) * c), u((l - (m.y4 + n)) * c), "c"].join(" ")), t._lastPoint = { x: e, y: n }; } null !== s && this.pdf.internal.out(this.pdf.internal.getStyle(s)); }, n.internal.arc2 = function (t, e, n, r, i, o, a, s, c) { var l = e, u = n; c ? (this.arc(t, l, u, r, i, o, a, null), this.pdf.clip_fixed()) : this.arc(t, l, u, r, i, o, a, s); }, n.internal.move2 = function (t, e, n) { var r = this.pdf.internal.scaleFactor, i = this.pdf.internal.pageSize.height, o = this.pdf.internal.f2; this.pdf.internal.out([o(e * r), o((i - n) * r), "m"].join(" ")), t._lastPoint = { x: e, y: n }; }, n.internal.line2 = function (t, e, n) { var r = this.pdf.internal.scaleFactor, i = this.pdf.internal.pageSize.height, o = this.pdf.internal.f2, a = { x: e, y: n }; this.pdf.internal.out([o(a.x * r), o((i - a.y) * r), "l"].join(" ")), t._lastPoint = a; }, n.internal.createArc = function (t, e, n, r) { var i = 2 * Math.PI, o = Math.PI / 2, a = e; for ((a < i || a > i) && (a %= i), a < 0 && (a = i + a); e > n;)e -= i; var s = Math.abs(n - e); s < i && r && (s = i - s); for (var c = [], l = r ? -1 : 1, u = a; s > 1e-5;) { var h = u + l * Math.min(s, o); c.push(this.createSmallArc(t, u, h)), s -= Math.abs(h - u), u = h; } return c }, n.internal.getCurrentPage = function () { return this.pdf.internal.pages[this.pdf.internal.getCurrentPageInfo().pageNumber] }, n.internal.createSmallArc = function (t, e, n) { var r = (n - e) / 2, i = t * Math.cos(r), o = t * Math.sin(r), a = i, s = -o, c = a * a + s * s, l = c + a * i + s * o, u = 4 / 3 * (Math.sqrt(2 * c * l) - l) / (a * o - s * i), h = a - u * s, f = s + u * a, d = h, p = -f, m = r + e, g = Math.cos(m), w = Math.sin(m); return { x1: t * Math.cos(e), y1: t * Math.sin(e), x2: h * g - f * w, y2: h * w + f * g, x3: d * g - p * w, y3: d * w + p * g, x4: t * Math.cos(n), y4: t * Math.sin(n) } }; }(e.API), function (e) { var n, r, o, a, s, c, l, u, h, f, d, p, m, g, w, y, v, b, x, k; n = function () { function t() { } return function (e) { return t.prototype = e, new t } }(), f = function (t) { var e, n, r, i, o, a, s; for (n = 0, r = t.length, e = void 0, i = !1, a = !1; !i && n !== r;)(e = t[n] = t[n].trimLeft()) && (i = !0), n++; for (n = r - 1; r && !a && -1 !== n;)(e = t[n] = t[n].trimRight()) && (a = !0), n--; for (o = /\s+$/g, s = !0, n = 0; n !== r;)"\u2028" != t[n] && (e = t[n].replace(/\s+/g, " "), s && (e = e.trimLeft()), e && (s = o.test(e)), t[n] = e), n++; return t }, p = function (t) { var e, n, r; for (e = void 0, n = (r = t.split(",")).shift(); !e && n;)e = o[n.trim().toLowerCase()], n = r.shift(); return e }, m = function (t) { (t = "auto" === t ? "0px" : t).indexOf("em") > -1 && !isNaN(Number(t.replace("em", ""))) && (t = 18.719 * Number(t.replace("em", "")) + "px"), t.indexOf("pt") > -1 && !isNaN(Number(t.replace("pt", ""))) && (t = 1.333 * Number(t.replace("pt", "")) + "px"); var e; return (e = g[t]) ? e : void 0 !== (e = { "xx-small": 9, "x-small": 11, small: 13, medium: 16, large: 19, "x-large": 23, "xx-large": 28, auto: 0 }[{ css_line_height_string: t }]) ? g[t] = e / 16 : (e = parseFloat(t)) ? g[t] = e / 16 : 3 === (e = t.match(/([\d\.]+)(px)/)).length ? g[t] = parseFloat(e[1]) / 16 : g[t] = 1 }, h = function (t) { var e, n, r; return r = function (e) { var n; return n = function (t) { return document.defaultView && document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(t, null) : t.currentStyle ? t.currentStyle : t.style }(t), function (t) { return t = t.replace(/-\D/g, function (t) { return t.charAt(1).toUpperCase() }), n[t] } }(), e = {}, n = void 0, e["font-family"] = p(r("font-family")) || "times", e["font-style"] = a[r("font-style")] || "normal", e["text-align"] = s[r("text-align")] || "left", "bold" === (n = c[r("font-weight")] || "normal") && ("normal" === e["font-style"] ? e["font-style"] = n : e["font-style"] = n + e["font-style"]), e["font-size"] = m(r("font-size")) || 1, e["line-height"] = m(r("line-height")) || 1, e.display = "inline" === r("display") ? "inline" : "block", n = "block" === e.display, e["margin-top"] = n && m(r("margin-top")) || 0, e["margin-bottom"] = n && m(r("margin-bottom")) || 0, e["padding-top"] = n && m(r("padding-top")) || 0, e["padding-bottom"] = n && m(r("padding-bottom")) || 0, e["margin-left"] = n && m(r("margin-left")) || 0, e["margin-right"] = n && m(r("margin-right")) || 0, e["padding-left"] = n && m(r("padding-left")) || 0, e["padding-right"] = n && m(r("padding-right")) || 0, e["page-break-before"] = r("page-break-before") || "auto", e.float = l[r("cssFloat")] || "none", e.clear = u[r("clear")] || "none", e.color = r("color"), e }, w = function (t, e, n) { var r, i, o, a, s; if (o = !1, i = void 0, a = void 0, r = n["#" + t.id]) if ("function" == typeof r) o = r(t, e); else for (i = 0, a = r.length; !o && i !== a;)o = r[i](t, e), i++; if (r = n[t.nodeName], !o && r) if ("function" == typeof r) o = r(t, e); else for (i = 0, a = r.length; !o && i !== a;)o = r[i](t, e), i++; for (s = t.className ? t.className.split(" ") : [], i = 0; i < s.length; i++)if (r = n["." + s[i]], !o && r) if ("function" == typeof r) o = r(t, e); else for (i = 0, a = r.length; !o && i !== a;)o = r[i](t, e), i++; return o }, k = function (t, e) { var n, r, i, o, a, s, c, l, u; for (n = [], r = [], i = 0, u = t.rows[0].cells.length, c = t.clientWidth; i < u;)l = t.rows[0].cells[i], r[i] = { name: l.textContent.toLowerCase().replace(/\s+/g, ""), prompt: l.textContent.replace(/\r?\n/g, ""), width: l.clientWidth / c * e.pdf.internal.pageSize.width }, i++; for (i = 1; i < t.rows.length;) { for (s = t.rows[i], a = {}, o = 0; o < s.cells.length;)a[r[o].name] = s.cells[o].textContent.replace(/\r?\n/g, ""), o++; n.push(a), i++; } return { rows: n, headers: r } }; var _ = { SCRIPT: 1, STYLE: 1, NOSCRIPT: 1, OBJECT: 1, EMBED: 1, SELECT: 1 }, C = 1; r = function (e, i, o) { var a, s, c, l, u, f, d, p; for (s = e.childNodes, a = void 0, (u = "block" === (c = h(e)).display) && (i.setBlockBoundary(), i.setBlockStyle(c)), l = 0, f = s.length; l < f;) { if ("object" === (void 0 === (a = s[l]) ? "undefined" : t(a))) { if (i.executeWatchFunctions(a), 1 === a.nodeType && "HEADER" === a.nodeName) { var m = a, g = i.pdf.margins_doc.top; i.pdf.internal.events.subscribe("addPage", function (t) { i.y = g, r(m, i, o), i.pdf.margins_doc.top = i.y + 10, i.y += 10; }, !1); } if (8 === a.nodeType && "#comment" === a.nodeName) ~a.textContent.indexOf("ADD_PAGE") && (i.pdf.addPage(), i.y = i.pdf.margins_doc.top); else if (1 !== a.nodeType || _[a.nodeName]) if (3 === a.nodeType) { var v = a.nodeValue; if (a.nodeValue && "LI" === a.parentNode.nodeName) if ("OL" === a.parentNode.parentNode.nodeName) v = C++ + ". " + v; else { var b = c["font-size"], x = (3 - .75 * b) * i.pdf.internal.scaleFactor, A = .75 * b * i.pdf.internal.scaleFactor, S = 1.74 * b / i.pdf.internal.scaleFactor; p = function (t, e) { this.pdf.circle(t + x, e + A, S, "FD"); }; } 16 & a.ownerDocument.body.compareDocumentPosition(a) && i.addText(v, c); } else "string" == typeof a && i.addText(a, c); else { var q; if ("IMG" === a.nodeName) { var T = a.getAttribute("src"); q = y[i.pdf.sHashCode(T) || T]; } if (q) { i.pdf.internal.pageSize.height - i.pdf.margins_doc.bottom < i.y + a.height && i.y > i.pdf.margins_doc.top && (i.pdf.addPage(), i.y = i.pdf.margins_doc.top, i.executeWatchFunctions(a)); var P = h(a), I = i.x, E = 12 / i.pdf.internal.scaleFactor, O = (P["margin-left"] + P["padding-left"]) * E, F = (P["margin-right"] + P["padding-right"]) * E, B = (P["margin-top"] + P["padding-top"]) * E, R = (P["margin-bottom"] + P["padding-bottom"]) * E; void 0 !== P.float && "right" === P.float ? I += i.settings.width - a.width - F : I += O, i.pdf.addImage(q, I, i.y + B, a.width, a.height), q = void 0, "right" === P.float || "left" === P.float ? (i.watchFunctions.push(function (t, e, n, r) { return i.y >= e ? (i.x += t, i.settings.width += n, !0) : !!(r && 1 === r.nodeType && !_[r.nodeName] && i.x + r.width > i.pdf.margins_doc.left + i.pdf.margins_doc.width) && (i.x += t, i.y = e, i.settings.width += n, !0) }.bind(this, "left" === P.float ? -a.width - O - F : 0, i.y + a.height + B + R, a.width)), i.watchFunctions.push(function (t, e, n) { return !(i.y < t && e === i.pdf.internal.getNumberOfPages()) || 1 === n.nodeType && "both" === h(n).clear && (i.y = t, !0) }.bind(this, i.y + a.height, i.pdf.internal.getNumberOfPages())), i.settings.width -= a.width + O + F, "left" === P.float && (i.x += a.width + O + F)) : i.y += a.height + B + R; } else if ("TABLE" === a.nodeName) d = k(a, i), i.y += 10, i.pdf.table(i.x, i.y, d.rows, d.headers, { autoSize: !1, printHeaders: o.printHeaders, margins: i.pdf.margins_doc, css: h(a) }), i.y = i.pdf.lastCellPos.y + i.pdf.lastCellPos.h + 20; else if ("OL" === a.nodeName || "UL" === a.nodeName) C = 1, w(a, i, o) || r(a, i, o), i.y += 10; else if ("LI" === a.nodeName) { var D = i.x; i.x += 20 / i.pdf.internal.scaleFactor, i.y += 3, w(a, i, o) || r(a, i, o), i.x = D; } else "BR" === a.nodeName ? (i.y += c["font-size"] * i.pdf.internal.scaleFactor, i.addText("\u2028", n(c))) : w(a, i, o) || r(a, i, o); } } l++; } if (o.outY = i.y, u) return i.setBlockBoundary(p) }, y = {}, v = function (t, e, n, r) { function i() { e.pdf.internal.events.publish("imagesLoaded"), r(o); } for (var o, a = t.getElementsByTagName("img"), s = a.length, c = 0; s--;)!function (t, n, r) { if (t) { var a = new Image; o = ++c, a.crossOrigin = "", a.onerror = a.onload = function () { if (a.complete && (0 === a.src.indexOf("data:image/") && (a.width = n || a.width || 0, a.height = r || a.height || 0), a.width + a.height)) { var o = e.pdf.sHashCode(t) || t; y[o] = y[o] || a; } --c || i(); }, a.src = t; } }(a[s].getAttribute("src"), a[s].width, a[s].height); return c || i() }, b = function (t, e, n) { var i = t.getElementsByTagName("footer"); if (i.length > 0) { i = i[0]; var o = e.pdf.internal.write, a = e.y; e.pdf.internal.write = function () { }, r(i, e, n); var s = Math.ceil(e.y - a) + 5; e.y = a, e.pdf.internal.write = o, e.pdf.margins_doc.bottom += s; for (var c = function (t) { var o = void 0 !== t ? t.pageNumber : 1, a = e.y; e.y = e.pdf.internal.pageSize.height - e.pdf.margins_doc.bottom, e.pdf.margins_doc.bottom -= s; for (var c = i.getElementsByTagName("span"), l = 0; l < c.length; ++l)(" " + c[l].className + " ").replace(/[\n\t]/g, " ").indexOf(" pageCounter ") > -1 && (c[l].innerHTML = o), (" " + c[l].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1 && (c[l].innerHTML = "###jsPDFVarTotalPages###"); r(i, e, n), e.pdf.margins_doc.bottom += s, e.y = a; }, l = i.getElementsByTagName("span"), u = 0; u < l.length; ++u)(" " + l[u].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1 && e.pdf.internal.events.subscribe("htmlRenderingFinished", e.pdf.putTotalPages.bind(e.pdf, "###jsPDFVarTotalPages###"), !0); e.pdf.internal.events.subscribe("addPage", c, !1), c(), _.FOOTER = 1; } }, x = function (t, e, n, i, o, a) { if (!e) return !1; "string" == typeof e || e.parentNode || (e = "" + e.innerHTML), "string" == typeof e && (e = function (t) { var e, n, r, i; return r = "jsPDFhtmlText" + Date.now().toString() + (1e3 * Math.random()).toFixed(0), i = "position: absolute !important;clip: rect(1px 1px 1px 1px); /* IE6, IE7 */clip: rect(1px, 1px, 1px, 1px);padding:0 !important;border:0 !important;height: 1px !important;width: 1px !important; top:auto;left:-100px;overflow: hidden;", n = document.createElement("div"), n.style.cssText = i, n.innerHTML = '<iframe style="height:1px;width:1px" name="' + r + '" />', document.body.appendChild(n), (e = window.frames[r]).document.open(), e.document.writeln(t), e.document.close(), e.document.body }(e.replace(/<\/?script[^>]*?>/gi, ""))); var s, c = new d(t, n, i, o); return v.call(this, e, c, o.elementHandlers, function (t) { b(e, c, o.elementHandlers), r(e, c, o.elementHandlers), c.pdf.internal.events.publish("htmlRenderingFinished"), s = c.dispose(), "function" == typeof a ? a(s) : t && console.error("jsPDF Warning: rendering issues? provide a callback to fromHTML!"); }), s || { x: c.x, y: c.y } }, (d = function (t, e, n, r) { return this.pdf = t, this.x = e, this.y = n, this.settings = r, this.watchFunctions = [], this.init(), this }).prototype.init = function () { return this.paragraph = { text: [], style: [] }, this.pdf.internal.write("q") }, d.prototype.dispose = function () { return this.pdf.internal.write("Q"), { x: this.x, y: this.y, ready: !0 } }, d.prototype.executeWatchFunctions = function (t) { var e = !1, n = []; if (this.watchFunctions.length > 0) { for (var r = 0; r < this.watchFunctions.length; ++r)!0 === this.watchFunctions[r](t) ? e = !0 : n.push(this.watchFunctions[r]); this.watchFunctions = n; } return e }, d.prototype.splitFragmentsIntoLines = function (t, e) { var r, i, o, a, s, c, l, u, h, f, d, p, m, g; for (f = this.pdf.internal.scaleFactor, a = {}, i = void 0, h = void 0, o = void 0, s = void 0, g = void 0, u = void 0, l = void 0, c = void 0, p = [d = []], r = 0, m = this.settings.width; t.length;)if (s = t.shift(), g = e.shift(), s) if (i = g["font-family"], h = g["font-style"], (o = a[i + h]) || (o = this.pdf.internal.getFont(i, h).metadata.Unicode, a[i + h] = o), u = { widths: o.widths, kerning: o.kerning, fontSize: 12 * g["font-size"], textIndent: r }, l = this.pdf.getStringUnitWidth(s, u) * u.fontSize / f, "\u2028" == s) d = [], p.push(d); else if (r + l > m) { for (c = this.pdf.splitTextToSize(s, m, u), d.push([c.shift(), g]); c.length;)d = [[c.shift(), g]], p.push(d); r = this.pdf.getStringUnitWidth(d[0][0], u) * u.fontSize / f; } else d.push([s, g]), r += l; if (void 0 !== g["text-align"] && ("center" === g["text-align"] || "right" === g["text-align"] || "justify" === g["text-align"])) for (var w = 0; w < p.length; ++w) { var y = this.pdf.getStringUnitWidth(p[w][0][0], u) * u.fontSize / f; w > 0 && (p[w][0][1] = n(p[w][0][1])); var v = m - y; if ("right" === g["text-align"]) p[w][0][1]["margin-left"] = v; else if ("center" === g["text-align"]) p[w][0][1]["margin-left"] = v / 2; else if ("justify" === g["text-align"]) { var b = p[w][0][0].split(" ").length - 1; p[w][0][1]["word-spacing"] = v / b, w === p.length - 1 && (p[w][0][1]["word-spacing"] = 0); } } return p }, d.prototype.RenderTextFragment = function (t, e) { var n, r; r = 0, this.pdf.internal.pageSize.height - this.pdf.margins_doc.bottom < this.y + this.pdf.internal.getFontSize() && (this.pdf.internal.write("ET", "Q"), this.pdf.addPage(), this.y = this.pdf.margins_doc.top, this.pdf.internal.write("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), e.color, "Td"), r = Math.max(r, e["line-height"], e["font-size"]), this.pdf.internal.write(0, (-12 * r).toFixed(2), "Td")), n = this.pdf.internal.getFont(e["font-family"], e["font-style"]); var i = this.getPdfColor(e.color); i !== this.lastTextColor && (this.pdf.internal.write(i), this.lastTextColor = i), void 0 !== e["word-spacing"] && e["word-spacing"] > 0 && this.pdf.internal.write(e["word-spacing"].toFixed(2), "Tw"), this.pdf.internal.write("/" + n.id, (12 * e["font-size"]).toFixed(2), "Tf", "(" + this.pdf.internal.pdfEscape(t) + ") Tj"), void 0 !== e["word-spacing"] && this.pdf.internal.write(0, "Tw"); }, d.prototype.getPdfColor = function (t) { var e, n, r, o = /rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/.exec(t); if (null != o ? (e = parseInt(o[1]), n = parseInt(o[2]), r = parseInt(o[3])) : ("#" != t.charAt(0) && ((t = i.colorNameToHex(t)) || (t = "#000000")), e = t.substring(1, 3), e = parseInt(e, 16), n = t.substring(3, 5), n = parseInt(n, 16), r = t.substring(5, 7), r = parseInt(r, 16)), "string" == typeof e && /^#[0-9A-Fa-f]{6}$/.test(e)) { var a = parseInt(e.substr(1), 16); e = a >> 16 & 255, n = a >> 8 & 255, r = 255 & a; } var s = this.f3; return 0 === e && 0 === n && 0 === r || void 0 === n ? s(e / 255) + " g" : [s(e / 255), s(n / 255), s(r / 255), "rg"].join(" ") }, d.prototype.f3 = function (t) { return t.toFixed(3) }, d.prototype.renderParagraph = function (t) { var e, n, r, i, o, a, s, c, l, u, h, d, p; if (r = f(this.paragraph.text), d = this.paragraph.style, e = this.paragraph.blockstyle, this.paragraph = { text: [], style: [], blockstyle: {}, priorblockstyle: e }, r.join("").trim()) { s = this.splitFragmentsIntoLines(r, d), a = void 0, c = void 0, n = 12 / this.pdf.internal.scaleFactor, this.priorMarginBottom = this.priorMarginBottom || 0, h = (Math.max((e["margin-top"] || 0) - this.priorMarginBottom, 0) + (e["padding-top"] || 0)) * 
7558n, u = ((e["margin-bottom"] || 0) + (e["padding-bottom"] || 0)) * n, this.priorMarginBottom = e["margin-bottom"] || 0, "always" === e["page-break-before"] && (this.pdf.addPage(), this.y = 0, h = ((e["margin-top"] || 0) + (e["padding-top"] || 0)) * n), l = this.pdf.internal.write, i = void 0, o = void 0, this.y += h, l("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td"); for (var m = 0; s.length;) { for (c = 0, i = 0, o = (a = s.shift()).length; i !== o;)a[i][0].trim() && (c = Math.max(c, a[i][1]["line-height"], a[i][1]["font-size"]), p = 7 * a[i][1]["font-size"]), i++; var g = 0, w = 0; for (void 0 !== a[0][1]["margin-left"] && a[0][1]["margin-left"] > 0 && (g = (w = this.pdf.internal.getCoordinateString(a[0][1]["margin-left"])) - m, m = w), l(g + Math.max(e["margin-left"] || 0, 0) * n, (-12 * c).toFixed(2), "Td"), i = 0, o = a.length; i !== o;)a[i][0] && this.RenderTextFragment(a[i][0], a[i][1]), i++; if (this.y += c * n, this.executeWatchFunctions(a[0][1]) && s.length > 0) { var y = [], v = []; s.forEach(function (t) { for (var e = 0, n = t.length; e !== n;)t[e][0] && (y.push(t[e][0] + " "), v.push(t[e][1])), ++e; }), s = this.splitFragmentsIntoLines(f(y), v), l("ET", "Q"), l("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td"); } } return t && "function" == typeof t && t.call(this, this.x - 9, this.y - p / 2), l("ET", "Q"), this.y += u } }, d.prototype.setBlockBoundary = function (t) { return this.renderParagraph(t) }, d.prototype.setBlockStyle = function (t) { return this.paragraph.blockstyle = t }, d.prototype.addText = function (t, e) { return this.paragraph.text.push(t), this.paragraph.style.push(e) }, o = { helvetica: "helvetica", "sans-serif": "helvetica", "times new roman": "times", serif: "times", times: "times", monospace: "courier", courier: "courier" }, c = { 100: "normal", 200: "normal", 300: "normal", 400: "normal", 500: "bold", 600: "bold", 700: "bold", 800: "bold", 900: "bold", normal: "normal", bold: "bold", bolder: "bold", lighter: "normal" }, a = { normal: "normal", italic: "italic", oblique: "italic" }, s = { left: "left", right: "right", center: "center", justify: "justify" }, l = { none: "none", right: "right", left: "left" }, u = { none: "none", both: "both" }, g = { normal: 1 }, e.fromHTML = function (t, e, n, r, i, o) { return this.margins_doc = o || { top: 0, bottom: 0 }, r || (r = {}), r.elementHandlers || (r.elementHandlers = {}), x(this, t, isNaN(e) ? 4 : e, isNaN(n) ? 4 : n, r, i) }; }(e.API), function (t) { var n, r, i; e.API.addJS = function (t) { return i = t, this.internal.events.subscribe("postPutResources", function (t) { n = this.internal.newObject(), this.internal.write("<< /Names [(EmbeddedJS) " + (n + 1) + " 0 R] >>", "endobj"), r = this.internal.newObject(), this.internal.write("<< /S /JavaScript /JS (", i, ") >>", "endobj"); }), this.internal.events.subscribe("putCatalog", function () { void 0 !== n && void 0 !== r && this.internal.write("/Names <</JavaScript " + n + " 0 R>>"); }), this }; }(), function (t) { t.events.push(["postPutResources", function () { var t = this, e = /^(\d+) 0 obj$/; if (this.outline.root.children.length > 0) for (var n = t.outline.render().split(/\r\n/), r = 0; r < n.length; r++) { var i = n[r], o = e.exec(i); if (null != o) { var a = o[1]; t.internal.newObjectDeferredBegin(a); } t.internal.write(i); } if (this.outline.createNamedDestinations) { for (var s = this.internal.pages.length, c = [], r = 0; r < s; r++) { var l = t.internal.newObject(); c.push(l); var u = t.internal.getPageInfo(r + 1); t.internal.write("<< /D[" + u.objId + " 0 R /XYZ null null null]>> endobj"); } var h = t.internal.newObject(); t.internal.write("<< /Names [ "); for (r = 0; r < c.length; r++)t.internal.write("(page_" + (r + 1) + ")" + c[r] + " 0 R"); t.internal.write(" ] >>", "endobj"); t.internal.newObject(); t.internal.write("<< /Dests " + h + " 0 R"), t.internal.write(">>", "endobj"); } }]), t.events.push(["putCatalog", function () { var t = this; t.outline.root.children.length > 0 && (t.internal.write("/Outlines", this.outline.makeRef(this.outline.root)), this.outline.createNamedDestinations && t.internal.write("/Names " + namesOid + " 0 R")); }]), t.events.push(["initialized", function () { var t = this; t.outline = { createNamedDestinations: !1, root: { children: [] } }, t.outline.add = function (t, e, n) { var r = { title: e, options: n, children: [] }; return null == t && (t = this.root), t.children.push(r), r }, t.outline.render = function () { return this.ctx = {}, this.ctx.val = "", this.ctx.pdf = t, this.genIds_r(this.root), this.renderRoot(this.root), this.renderItems(this.root), this.ctx.val }, t.outline.genIds_r = function (e) { e.id = t.internal.newObjectDeferred(); for (var n = 0; n < e.children.length; n++)this.genIds_r(e.children[n]); }, t.outline.renderRoot = function (t) { this.objStart(t), this.line("/Type /Outlines"), t.children.length > 0 && (this.line("/First " + this.makeRef(t.children[0])), this.line("/Last " + this.makeRef(t.children[t.children.length - 1]))), this.line("/Count " + this.count_r({ count: 0 }, t)), this.objEnd(); }, t.outline.renderItems = function (e) { for (i = 0; i < e.children.length; i++) { o = e.children[i]; this.objStart(o), this.line("/Title " + this.makeString(o.title)), this.line("/Parent " + this.makeRef(e)), i > 0 && this.line("/Prev " + this.makeRef(e.children[i - 1])), i < e.children.length - 1 && this.line("/Next " + this.makeRef(e.children[i + 1])
7558), o.children.length > 0 && (this.line("/First " + this.makeRef(o.children[0])), this.line("/Last " + this.makeRef(o.children[o.children.length - 1]))); var n = this.count = this.count_r({ count: 0 }, o); if (n > 0 && this.line("/Count " + n), o.options && o.options.pageNumber) { var r = t.internal.getPageInfo(o.options.pageNumber); this.line("/Dest [" + r.objId + " 0 R /XYZ 0 " + this.ctx.pdf.internal.pageSize.height + " 0]"); } this.objEnd(); } for (var i = 0; i < e.children.length; i++) { var o = e.children[i]; this.renderItems(o); } }, t.outline.line = function (t) { this.ctx.val += t + "\r\n"; }, t.outline.makeRef = function (t) { return t.id + " 0 R" }, t.outline.makeString = function (e) { return "(" + t.internal.pdfEscape(e) + ")" }, t.outline.objStart = function (t) { this.ctx.val += "\r\n" + t.id + " 0 obj\r\n<<\r\n"; }, t.outline.objEnd = function (t) { this.ctx.val += ">> \r\nendobj\r\n"; }, t.outline.count_r = function (t, e) { for (var n = 0; n < e.children.length; n++)t.count++, this.count_r(t, e.children[n]); return t.count }; }]); }(e.API), function (t) { var e = function () { return "function" != typeof PNG || "function" != typeof s }, n = function (e) { return e !== t.image_compression.NONE && r() }, r = function () { var t = "function" == typeof o; if (!t) throw new Error("requires deflate.js for compression"); return t }, i = function (e, n, r, i) { var s = 5, u = f; switch (i) { case t.image_compression.FAST: s = 3, u = h; break; case t.image_compression.MEDIUM: s = 6, u = d; break; case t.image_compression.SLOW: s = 9, u = p; }e = l(e, n, r, u); var m = new Uint8Array(a(s)), g = c(e), w = new o(s), y = w.append(e), v = w.flush(), b = m.length + y.length + v.length, x = new Uint8Array(b + 4); return x.set(m), x.set(y, m.length), x.set(v, m.length + y.length), x[b++] = g >>> 24 & 255, x[b++] = g >>> 16 & 255, x[b++] = g >>> 8 & 255, x[b++] = 255 & g, t.arrayBufferToBinaryString(x) }, a = function (t, e) { var n = Math.LOG2E * Math.log(32768) - 8 << 4 | 8, r = n << 8; return r |= Math.min(3, (e - 1 & 255) >> 1) << 6, r |= 0, r += 31 - r % 31, [n, 255 & r] }, c = function (t, e) { for (var n, r = 1, i = 0, o = t.length, a = 0; o > 0;) { o -= n = o > e ? e : o; do { i += r += t[a++]; } while (--n); r %= 65521, i %= 65521; } return (i << 16 | r) >>> 0 }, l = function (t, e, n, r) { for (var i, o, a, s = t.length / e, c = new Uint8Array(t.length + s), l = g(), u = 0; u < s; u++) { if (a = u * e, i = t.subarray(a, a + e), r) c.set(r(i, n, o), a + u); else { for (var h = 0, f = l.length, d = []; h < f; h++)d[h] = l[h](i, n, o); var p = w(d.concat()); c.set(d[p], a + u); } o = i; } return c }, u = function (t, e, n) { var r = Array.apply([], t); return r.unshift(0), r }, h = function (t, e, n) { var r, i = [], o = 0, a = t.length; for (i[0] = 1; o < a; o++)r = t[o - e] || 0, i[o + 1] = t[o] - r + 256 & 255; return i }, f = function (t, e, n) { var r, i = [], o = 0, a = t.length; for (i[0] = 2; o < a; o++)r = n && n[o] || 0, i[o + 1] = t[o] - r + 256 & 255; return i }, d = function (t, e, n) { var r, i, o = [], a = 0, s = t.length; for (o[0] = 3; a < s; a++)r = t[a - e] || 0, i = n && n[a] || 0, o[a + 1] = t[a] + 256 - (r + i >>> 1) & 255; return o }, p = function (t, e, n) { var r, i, o, a, s = [], c = 0, l = t.length; for (s[0] = 4; c < l; c++)r = t[c - e] || 0, i = n && n[c] || 0, o = n && n[c - e] || 0, a = m(r, i, o), s[c + 1] = t[c] - a + 256 & 255; return s }, m = function (t, e, n) { var r = t + e - n, i = Math.abs(r - t), o = Math.abs(r - e), a = Math.abs(r - n); return i <= o && i <= a ? t : o <= a ? e : n }, g = function () { return [u, h, f, d, p] }, w = function (t) { for (var e, n, r, i = 0, o = t.length; i < o;)((e = y(t[i].slice(1))) < n || !n) && (n = e, r = i), i++; return r }, y = function (t) { for (var e = 0, n = t.length, r = 0; e < n;)r += Math.abs(t[e++]); return r }, v = function (e) { var n; switch (e) { case t.image_compression.FAST: n = 11; break; case t.image_compression.MEDIUM: n = 13; break; case t.image_compression.SLOW: n = 14; break; default: n = 12; }return n }; t.processPNG = function (t, r, o, a, s) { var c, l, u, h, f, d, p 
vendor: 7,146 bytes, line 7558
7558= this.color_spaces.DEVICE_RGB, m = this.decode.FLATE_DECODE, g = 8; if (this.isArrayBuffer(t) && (t = new Uint8Array(t)), this.isArrayBufferView(t)) { if (e()) throw new Error("PNG support requires png.js and zlib.js"); if (c = new PNG(t), t = c.imgData, g = c.bits, p = c.colorSpace, h = c.colors, -1 !== [4, 6].indexOf(c.colorType)) { if (8 === c.bits) for (var w, y = (I = 32 == c.pixelBitlength ? new Uint32Array(c.decodePixels().buffer) : 16 == c.pixelBitlength ? new Uint16Array(c.decodePixels().buffer) : new Uint8Array(c.decodePixels().buffer)).length, b = new Uint8Array(y * c.colors), x = new Uint8Array(y), k = c.pixelBitlength - c.bits, _ = 0, C = 0; _ < y; _++) { for (A = I[_], w = 0; w < k;)b[C++] = A >>> w & 255, w += c.bits; x[_] = A >>> w & 255; } if (16 === c.bits) { for (var A, y = (I = new Uint32Array(c.decodePixels().buffer)).length, b = new Uint8Array(y * (32 / c.pixelBitlength) * c.colors), x = new Uint8Array(y * (32 / c.pixelBitlength)), S = c.colors > 1, _ = 0, C = 0, q = 0; _ < y;)A = I[_++], b[C++] = A >>> 0 & 255, S && (b[C++] = A >>> 16 & 255, A = I[_++], b[C++] = A >>> 0 & 255), x[q++] = A >>> 16 & 255; g = 8; } n(a) ? (t = i(b, c.width * c.colors, c.colors, a), d = i(x, c.width, 1, a)) : (t = b, d = x, m = null); } if (3 === c.colorType && (p = this.color_spaces.INDEXED, f = c.palette, c.transparency.indexed)) { for (var T = c.transparency.indexed, P = 0, _ = 0, y = T.length; _ < y; ++_)P += T[_]; if ((P /= 255) === y - 1 && -1 !== T.indexOf(0)) u = [T.indexOf(0)]; else if (P !== y) { for (var I = c.decodePixels(), x = new Uint8Array(I.length), _ = 0, y = I.length; _ < y; _++)x[_] = T[I[_]]; d = i(x, c.width, 1); } } var E = v(a); return l = m === this.decode.FLATE_DECODE ? "/Predictor " + E + " /Colors " + h + " /BitsPerComponent " + g + " /Columns " + c.width : "/Colors " + h + " /BitsPerComponent " + g + " /Columns " + c.width, (this.isArrayBuffer(t) || this.isArrayBufferView(t)) && (t = this.arrayBufferToBinaryString(t)), (d && this.isArrayBuffer(d) || this.isArrayBufferView(d)) && (d = this.arrayBufferToBinaryString(d)), this.createImageInfo(t, c.width, c.height, p, g, m, r, o, l, u, f, d, E) } throw new Error("Unsupported PNG image data, try using JPEG instead.") }; }(e.API), e.API.autoPrint = function () { var t; return this.internal.events.subscribe("postPutResources", function () { t = this.internal.newObject(), this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj"); }), this.internal.events.subscribe("putCatalog", function () { this.internal.write("/OpenAction " + t + " 0 R"); }), this }, function (t) { var e = t.getCharWidthsArray = function (t, e) { e || (e = {}); var n, r, i, o = e.widths ? e.widths : this.internal.getFont().metadata.Unicode.widths, a = o.fof ? o.fof : 1, s = e.kerning ? e.kerning : this.internal.getFont().metadata.Unicode.kerning, c = s.fof ? s.fof : 1, l = 0, u = o[0] || a, h = []; for (n = 0, r = t.length; n < r; n++)i = t.charCodeAt(n), h.push((o[i] || u) / a + (s[i] && s[i][l] || 0) / c), l = i; return h }, n = function (t) { for (var e = t.length, n = 0; e;)n += t[--e]; return n }, r = t.getStringUnitWidth = function (t, r) { return n(e.call(this, t, r)) }, i = function (t, e, n, r) { for (var i = [], o = 0, a = t.length, s = 0; o !== a && s + e[o] < n;)s += e[o], o++; i.push(t.slice(0, o)); var c = o; for (s = 0; o !== a;)s + e[o] > r && (i.push(t.slice(c, o)), s = 0, c = o), s += e[o], o++; return c !== o && i.push(t.slice(c, o)), i }, o = function (t, o, a) { a || (a = {}); var s, c, l, u, h, f, d = [], p = [d], m = a.textIndent || 0, g = 0, w = 0, y = t.split(" "), v = e(" ", a)[0]; if (f = -1 === a.lineIndent ? y[0].length + 2 : a.lineIndent || 0) { var b = Array(f).join(" "), x = []; y.map(function (t) { (t = t.split(/\s*\n/)).length > 1 ? x = x.concat(t.map(function (t, e) { return (e && t.length ? "\n" : "") + t })) : x.push(t[0]); }), y = x, f = r(b, a); } for (l = 0, u = y.length; l < u; l++) { var k = 0; if (s = y[l], f && "\n" == s[0] && (s = s.substr(1), k = 1), c = e(s, a), w = n(c), m + g + w > o || k) { if (w > o) { for (h = i(s, c, o - (m + g), o), d.push(h.shift()), d = [h.pop()]; h.length;)p.push([h.shift()]); w = n(c.slice(s.length - d[0].length)); } else d = [s]; p.push(d), m = w + f, g = v; } else d.push(s), m += g + w, g = v; } if (f) _ = function (t, e) { return (e ? b : "") + t.join(" ") }; else var _ = function (t) { return t.join(" ") }; return p.map(_) }; t.splitTextToSize = function (t, e, n) { n || (n = {}); var r, i = n.fontSize || this.internal.getFontSize(), a = function (t) { var e = { 0: 1 }, n = {}; if (t.widths && t.kerning) return { widths: t.widths, kerning: t.kerning }; var r = this.internal.getFont(t.fontName, t.fontStyle); return r.metadata.Unicode ? { widths: r.metadata.Unicode.widths || e, kerning: r.metadata.Unicode.kerning || n } : { widths: e, kerning: n } }.call(this, n); r = Array.isArray(t) ? t : t.split(/\r?\n/); var s = 1 * this.internal.scaleFactor * e / i; a.textIndent = n.textIndent ? 1 * n.textIndent * this.internal.scaleFactor / i : 0, a.lineIndent = n.lineIndent; var c, l, u = []; for (c = 0, l = r.length; c < l; c++)u = u.concat(o(r[c], s, a)); return u }; }(e.API), function (t) { var e = function (t) { for (var e = {}, n = 0; n < "klmnopqrstuvwxyz".length; n++)e["klmnopqrstuvwxyz"[n]] = "0123456789abcdef"[n]; var r, i, o, a, s = {}, c = 1, l = s, u = [], h = "", f = "", d = t.length - 1; for (n = 1; n != d;)a = t[n], n += 1, "'" == a ? r ? (o = r.join(""), r = void 0) : r = [] : r ? r.push(a) : "{" == a ? (u.push([l, o]), l = {}, o = void 0) : "}" == a ? ((i = u.pop())[0][i[1]] = l, o = void 0, l = i[0]) : "-" == a ? c = -1 : void 0 === o ? e.hasOwnProperty(a) ? (h += e[a], o = parseInt(h, 16) * c, c = 1, h = "") : h += a : e.hasOwnProperty(a) ? (f += e[a], l[o] = parseInt(f, 16) * c, c = 1, o = void 0, f = "") : f += a; return s }, n = { codePages: ["WinAnsiEncoding"], WinAnsiEncoding: e("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}") }, r = { Unicode: { Courier: n, "Courier-Bold": n, "Courier-BoldOblique": n, "Courier-Oblique": n, Helvetica: n, "Helvetica-Bold": n, "Helvetica-BoldOblique": n, "Helvetica-Oblique": n, "Times-Roman": n, "Times-Bold": n, "Times-BoldItalic": n, "Times-Italic": n } }, i = { Unicode: { "Courier-Oblique": e("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"), "Times-BoldItalic": e("{'widths'{k3o2q4ycx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2r202m2n2n3m2o3m2p5n202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5n4l4m4m4m4n4m4o4s4p4m4q4m4r4s4s4y4t2r4u3m4v4m4w3x4x5t4y4s4z4s5k3x5l4s5m4m5n3r5o3x5p4s5q4m5r5t5s4m5t3x5u3x5v2l5w1w5x2l5y3t5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q2l6r3m6s3r6t1w6u1w6v3m6w1w6x4y6y3r6z3m7k3m7l3m7m2r7n2r7o1w7p3r7q2w7r4m7s3m7t2w7u2r7v2n7w1q7x2n7y3t202l3mcl4mal2ram3man3mao3map3mar3mas2lat4uau1uav3maw3way4uaz2lbk2sbl3t'fof'6obo2lbp3tbq3mbr1tbs2lbu1ybv3mbz3mck4m202k3mcm4mcn4mco4mcp4mcq5ycr4mcs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3me
7558k3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz2w203k6o212m6o2dw2l2cq2l3t3m3u2l17s3x19m3m}'kerning'{cl{4qu5kt5qt5rs17ss5ts}201s{201ss}201t{cks4lscmscnscoscpscls2wu2yu201ts}201x{2wu2yu}2k{201ts}2w{4qx5kx5ou5qx5rs17su5tu}2x{17su5tu5ou}2y{4qx5kx5ou5qx5rs17ss5ts}'fof'-6ofn{17sw5tw5ou5qw5rs}7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qs}3v{17su5tu5os5qs}7p{17su5tu}ck{4qu5kt5qt5rs17ss5ts}4l{4qu5kt5qt5rs17ss5ts}cm{4qu5kt5qt5rs17ss5ts}cn{4qu5kt5qt5rs17ss5ts}co{4qu5kt5qt5rs17ss5ts}cp{4qu5kt5qt5rs17ss5ts}6l{4qu5ou5qw5rt17su5tu}5q{ckuclucmucnucoucpu4lu}5r{ckuclucmucnucoucpu4lu}7q{cksclscmscnscoscps4ls}6p{4qu5ou5qw5rt17sw5tw}ek{4qu5ou5qw5rt17su5tu}el{4qu5ou5qw5rt17su5tu}em{4qu5ou5qw5rt17su5tu}en{4qu5ou5qw5rt17su5tu}eo{4qu5ou5qw5rt17su5tu}ep{4qu5ou5qw5rt17su5tu}es{17ss5ts5qs4qu}et{4qu5ou5qw5rt17sw5tw}eu{4qu5ou5qw5rt17ss5ts}ev{17ss5ts5qs4qu}6z{17sw5tw5ou5qw5rs}fm{17sw5tw5ou5qw5rs}7n{201ts}fo{17sw5tw5ou5qw5rs}fp{17sw5tw5ou5qw5rs}fq{17sw5tw5ou5qw5rs}7r{cksclscmscnscoscps4ls}fs{17sw5tw5ou5qw5rs}ft{17su5tu}fu{17su5tu}fv{17su5tu}fw{17su5tu}fz{cksclscmscnscoscps4ls}}}"), "Helvetica-Bold": e("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4y
7558dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"), Courier: e("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"), "Courier-BoldOblique": e("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"), "Times-Bold": e("{'widths'{k3q2q5ncx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2l202m2n2n3m2o3m2p6o202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5x4l4s4m4m4n4s4o4s4p4m4q3x4r4y4s4y4t2r4u3m4v4y4w4m4x5y4y4s4z4y5k3x5l4y5m4s5n3r5o4m5p4s5q4s5r6o5s4s5t4s5u4m5v2l5w1w5x2l5y3u5z3m6k2l6l3m6m3r6n2w6o3r6p2w6q2l6r3m6s3r6t1w6u2l6v3r6w1w6x5n6y3r6z3m7k3r7l3r7m2w7n2r7o2l7p3r7q3m7r4s7s3m7t3m7u2w7v2r7w1q7x2r7y3o202l3mcl4sal2lam3man3mao3map3mar3mas2lat4uau1yav3maw3tay4uaz2lbk2sbl3t'fof'6obo2lbp3rbr1tbs2lbu2lbv3mbz3mck4s202k3mcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3rek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3m3u2l17s4s19m3m}'kerning'{cl{4qt5ks5ot5qy5rw17sv5tv}201t{cks4lscmscnscoscpscls4wv}2k{201ts}2w{4qu5ku7mu5os5qx5ru17su5tu}2x{17su5tu5ou5qs}2y{4qv5kv7mu5ot5qz5ru17su5tu}'fof'-6o7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qu}3v{17su5tu5os5qu}fu{17su5tu5ou5qu}7p{17su5tu5ou5qu}ck{4qt5ks5ot5qy5rw17sv5tv}4l{4qt5ks5ot5qy5rw17sv5tv}cm{4qt5ks5ot5qy5rw17sv5tv}cn{4qt5ks5ot5qy5rw17sv5tv}co{4qt5ks5ot5qy5rw17sv5tv}cp{4qt5ks5ot5qy5rw17sv5tv}6l{17st5tt5ou5qu}17s{ckuclucmucnucoucpu4lu4wu}5o{ckuclucmucnucoucpu4lu4wu}5q{ckzclzcmzcnzcozcpz4lz4wu}5r{ckxclxcmxcnxcoxcpx4lx4wu}5t{ckuclucmucnucoucpu4lu4wu}7q{ckuclucmucnucoucpu4lu}6p{17sw5tw5ou5qu}ek{17st5tt5qu}el{17st5tt5ou5qu}em{17st5tt5qu}en{17st5tt5qu}eo{17st5tt5qu}ep{17st5tt5ou5qu}es{17ss5ts5qu}et{17sw5tw5ou5qu}eu{17sw5tw5ou5qu}ev{17ss5ts5qu}6z{17sw5tw5ou5qu5rs}fm{17sw5tw5ou5qu5rs}fn{17sw5tw5ou5qu5rs}fo{17sw5tw5ou5qu5rs}fp{17sw5tw5ou5qu5rs}fq{17sw5tw5ou5qu5rs}7r{cktcltcmtcntcotcpt4lt5os}fs{17sw5tw5ou5qu5rs}ft{17su5tu5ou5qu}7m{5os}fv{17su5tu5ou5qu}fw{17su5tu5ou5qu}fz{cksclscmscnscoscps4ls}}}"), Helvetica: e("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4y
7558dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}"), "Helvetica-BoldOblique": e("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4y
7558dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"), "Courier-Bold": e("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"), "Times-Italic": e("{'widths'{k3n2q4ycx2l201n3m201o5t201s2l201t2l201u2l201w3r201x3r201y3r2k1t2l2l202m2n2n3m2o3m2p5n202q5t2r1p2s2l2t2l2u3m2v4n2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w4n3x4n3y4n3z3m4k5w4l3x4m3x4n4m4o4s4p3x4q3x4r4s4s4s4t2l4u2w4v4m4w3r4x5n4y4m4z4s5k3x5l4s5m3x5n3m5o3r5p4s5q3x5r5n5s3x5t3r5u3r5v2r5w1w5x2r5y2u5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q1w6r3m6s3m6t1w6u1w6v2w6w1w6x4s6y3m6z3m7k3m7l3m7m2r7n2r7o1w7p3m7q2w7r4m7s2w7t2w7u2r7v2s7w1v7x2s7y3q202l3mcl3xal2ram3man3mao3map3mar3mas2lat4wau1vav3maw4nay4waz2lbk2sbl4n'fof'6obo2lbp3mbq3obr1tbs2lbu1zbv3mbz3mck3x202k3mcm3xcn3xco3xcp3xcq5tcr4mcs3xct3xcu3xcv3xcw2l2m2ucy2lcz2ldl4mdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr4nfs3mft3mfu3mfv3mfw3mfz2w203k6o212m6m2dw2l2cq2l3t3m3u2l17s3r19m3m}'kerning'{cl{5kt4qw}201s{201sw}201t{201tw2wy2yy6q-t}201x{2wy2yy}2k{201tw}2w{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}2x{17ss5ts5os}2y{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}'fof'-6o6t{17ss5ts5qs}7t{5os}3v{5qs}7p{17su5tu5qs}ck{5kt4qw}4l{5kt4qw}cm{5kt4qw}cn{5kt4qw}co{5kt4qw}cp{5kt4qw}6l{4qs5ks5ou5qw5ru17su5tu}17s{2ks}5q{ckvclvcmvcnvcovcpv4lv}5r{ckuclucmucnucoucpu4lu}5t{2ks}6p{4qs5ks5ou5qw5ru17su5tu}ek{4qs5ks5ou5qw5ru17su5tu}el{4qs5ks5ou5qw5ru17su5tu}em{4qs5ks5ou5qw5ru17su5tu}en{4qs5ks5ou5qw5ru17su5tu}eo{4qs5ks5ou5qw5ru17su5tu}ep{4qs5ks5ou5qw5ru17su5tu}es{5ks5qs4qs}et{4qs5ks5ou5qw5ru17su5tu}eu{4qs5ks5qw5ru17su5tu}ev{5ks5qs4qs}ex{17ss5ts5qs}6z{4qv5ks5ou5qw5ru17su5tu}fm{4qv5ks5ou5qw5ru17su5tu}fn{4qv5ks5ou5qw5ru17su5tu}fo{4qv5ks5ou5qw5ru17su5tu}fp{4qv5ks5ou5qw5ru17su5tu}fq{4qv5ks5ou5qw5ru17su5tu}7r{5os}fs{4qv5ks5ou5qw5ru17su5tu}ft{17su5tu5qs}fu{17su5tu5qs}
7558fv{17su5tu5qs}fw{17su5tu5qs}}}"), "Times-Roman": e("{'widths'{k3n2q4ycx2l201n3m201o6o201s2l201t2l201u2l201w2w201x2w201y2w2k1t2l2l202m2n2n3m2o3m2p5n202q6o2r1m2s2l2t2l2u3m2v3s2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v1w3w3s3x3s3y3s3z2w4k5w4l4s4m4m4n4m4o4s4p3x4q3r4r4s4s4s4t2l4u2r4v4s4w3x4x5t4y4s4z4s5k3r5l4s5m4m5n3r5o3x5p4s5q4s5r5y5s4s5t4s5u3x5v2l5w1w5x2l5y2z5z3m6k2l6l2w6m3m6n2w6o3m6p2w6q2l6r3m6s3m6t1w6u1w6v3m6w1w6x4y6y3m6z3m7k3m7l3m7m2l7n2r7o1w7p3m7q3m7r4s7s3m7t3m7u2w7v3k7w1o7x3k7y3q202l3mcl4sal2lam3man3mao3map3mar3mas2lat4wau1vav3maw3say4waz2lbk2sbl3s'fof'6obo2lbp3mbq2xbr1tbs2lbu1zbv3mbz2wck4s202k3mcm4scn4sco4scp4scq5tcr4mcs3xct3xcu3xcv3xcw2l2m2tcy2lcz2ldl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek2wel2wem2wen2weo2wep2weq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr3sfs3mft3mfu3mfv3mfw3mfz3m203k6o212m6m2dw2l2cq2l3t3m3u1w17s4s19m3m}'kerning'{cl{4qs5ku17sw5ou5qy5rw201ss5tw201ws}201s{201ss}201t{ckw4lwcmwcnwcowcpwclw4wu201ts}2k{201ts}2w{4qs5kw5os5qx5ru17sx5tx}2x{17sw5tw5ou5qu}2y{4qs5kw5os5qx5ru17sx5tx}'fof'-6o7t{ckuclucmucnucoucpu4lu5os5rs}3u{17su5tu5qs}3v{17su5tu5qs}7p{17sw5tw5qs}ck{4qs5ku17sw5ou5qy5rw201ss5tw201ws}4l{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cm{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cn{4qs5ku17sw5ou5qy5rw201ss5tw201ws}co{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cp{4qs5ku17sw5ou5qy5rw201ss5tw201ws}6l{17su5tu5os5qw5rs}17s{2ktclvcmvcnvcovcpv4lv4wuckv}5o{ckwclwcmwcnwcowcpw4lw4wu}5q{ckyclycmycnycoycpy4ly4wu5ms}5r{cktcltcmtcntcotcpt4lt4ws}5t{2ktclvcmvcnvcovcpv4lv4wuckv}7q{cksclscmscnscoscps4ls}6p{17su5tu5qw5rs}ek{5qs5rs}el{17su5tu5os5qw5rs}em{17su5tu5os5qs5rs}en{17su5qs5rs}eo{5qs5rs}ep{17su5tu5os5qw5rs}es{5qs}et{17su5tu5qw5rs}eu{17su5tu5qs5rs}ev{5qs}6z{17sv5tv5os5qx5rs}fm{5os5qt5rs}fn{17sv5tv5os5qx5rs}fo{17sv5tv5os5qx5rs}fp{5os5qt5rs}fq{5os5qt5rs}7r{ckuclucmucnucoucpu4lu5os}fs{17sv5tv5os5qx5rs}ft{17ss5ts5qs}fu{17sw5tw5qs}fv{17sw5tw5qs}fw{17ss5ts5qs}fz{ckuclucmucnucoucpu4lu5os5rs}}}"), "Helvetica-Oblique": e("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4y
7558dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}") } }; t.events.push(["addFont", function (t) { var e, n, o; (e = i.Unicode[t.PostScriptName]) && ((n = t.metadata.Unicode ? t.metadata.Unicode : t.metadata.Unicode = {}).widths = e.widths, n.kerning = e.kerning), (o = r.Unicode[t.PostScriptName]) && ((n = t.metadata.Unicode ? t.metadata.Unicode : t.metadata.Unicode = {}).encoding = o, o.codePages && o.codePages.length && (t.encoding = o.codePages[0])); }]); }(e.API), e.API.addSVG = function (t, e, n, r, i) { function o(t, e) { var n = e.createElement("style"); n.type = "text/css", n.styleSheet ? n.styleSheet.cssText = t : n.appendChild(e.createTextNode(t)), e.getElementsByTagName("head")[0].appendChild(n); } if (void 0 === e || void 0 === n) throw new Error("addSVG needs values for 'x' and 'y'"); var a = function (t, e) { var n = (e.contentWindow || e.contentDocument).document; return n.write(t), n.close(), n.getElementsByTagName("svg")[0] }(t, function (t) { var e = t.createElement("iframe"); return o(".jsPDF_sillysvg_iframe {display:none;position:absolute;}", t), e.name = "childframe", e.setAttribute("width", 0), e.setAttribute("height", 0), e.setAttribute("frameborder", "0"), e.setAttribute("scrolling", "no"), e.setAttribute("seamless", "seamless"), e.setAttribute("class", "jsPDF_sillysvg_iframe"), t.body.appendChild(e), e }(document)), s = [1, 1], c = parseFloat(a.getAttribute("width")), l = parseFloat(a.getAttribute("height")); c && l && (r && i ? s = [r / c, i / l] : r ? s = [r / c, r / c] : i && (s = [i / l, i / l])); var u, h, f, d, p = a.childNodes; for (u = 0, h = p.length; u < h; u++)(f = p[u]).tagName && "PATH" === f.tagName.toUpperCase() && ((d = function (t) { for (var e = parseFloat(t[1]), n = parseFloat(t[2]), r = [], i = 3, o = t.length; i < o;)"c" === t[i] ? (r.push([parseFloat(t[i + 1]), parseFloat(t[i + 2]), parseFloat(t[i + 3]), parseFloat(t[i + 4]), parseFloat(t[i + 5]), parseFloat(t[i + 6])]), i += 7) : "l" === t[i] ? (r.push([parseFloat(t[i + 1]), parseFloat(t[i + 2])]), i += 3) : i += 1; return [e, n, r] }(f.getAttribute("d").split(" ")))[0] = d[0] * s[0] + e, d[1] = d[1] * s[1] + n, this.lines.call(this, d[2], d[0], d[1], s)); return this }, e.API.putTotalPages = function (t) { for (var e = new RegExp(t, "g"), n = 1; n <= this.internal.getNumberOfPages(); n++)for (var r = 0; r < this.internal.pages[n].length; r++)this.internal.pages[n][r] = this.internal.pages[n][r].replace(e, this.internal.getNumberOfPages()); return this }, function (t) { var n = "", r = "", i = ""; e.API.addMetadata = function (t, e) { return r = e || "http://jspdf.default.namespaceuri/", n = t, this.internal.events.subscribe("postPutResources", function () { if (n) { var t = '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:jspdf="' + r + '"><jspdf:metadata>', e = unescape(encodeURIComponent('<x:xmpmeta xmlns:x="adobe:ns:meta/">')), o = unescape(encodeURIComponent(t)), a = unescape(encodeURIComponent(n)), s = unescape(encodeURIComponent("</jspdf:metadata></rdf:Description></rdf:RDF>")), c = unescape(encodeURIComponent("</x:xmpmeta>")), l = o.length + a.length + s.length + e.length + c.length; i = this.internal.newObject(), this.internal.write("<< /Type /Metadata /Subtype /XML /Length " + l + " >>"), this.internal.write("stream"), this.internal.write(e + o + a + s + c), this.internal.write("endstream"), this.internal.write("endobj"); } else i = ""; }), this.internal.events.subscribe("putCatalog", function () { i && this.internal.write("/Metadata " + i + " 0 R"); }), this }; }(), function (t) { if (t.URL = t.URL || t.webkitURL, t.Blob && t.URL) try { return void new Blob } catch (t) { } var e = t.BlobBuilder || t.WebKitBlobBuilder || t.MozBlobBuilder || function (t) { var e = function (t) { return Object.prototype.toString.call(t).match(/^\[object\s(.*)\]$/)[1] }, n = function () { this.data = []; }, r = function (t, e, n) { this.data = t, this.size = t.length, this.type = e, this.encoding = n; }, i = n.prototype, o = r.prototype, a = t.FileReaderSync, s = function (t) { this.code = this[this.name = t]; }, c = "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR NO_MODIFICATION_ALLOWED_ER
7558R INVALID_STATE_ERR SYNTAX_ERR".split(" "), l = c.length, u = t.URL || t.webkitURL || t, h = u.createObjectURL, f = u.revokeObjectURL, d = u, p = t.btoa, m = t.atob, g = t.ArrayBuffer, w = t.Uint8Array, y = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/; for (r.fake = o.fake = !0; l--;)s.prototype[c[l]] = l + 1; return u.createObjectURL || (d = t.URL = function (t) { var e, n = document.createElementNS("http://www.w3.org/1999/xhtml", "a"); return n.href = t, "origin" in n || ("data:" === n.protocol.toLowerCase() ? n.origin = null : (e = t.match(y), n.origin = e && e[1])), n }), d.createObjectURL = function (t) { var e, n = t.type; return null === n && (n = "application/octet-stream"), t instanceof r ? (e = "data:" + n, "base64" === t.encoding ? e + ";base64," + t.data : "URI" === t.encoding ? e + "," + decodeURIComponent(t.data) : p ? e + ";base64," + p(t.data) : e + "," + encodeURIComponent(t.data)) : h ? h.call(u, t) : void 0 }, d.revokeObjectURL = function (t) { "data:" !== t.substring(0, 5) && f && f.call(u, t); }, i.append = function (t) { var n = this.data; if (w && (t instanceof g || t instanceof w)) { for (var i = "", o = new w(t), c = 0, l = o.length; c < l; c++)i += String.fromCharCode(o[c]); n.push(i); } else if ("Blob" === e(t) || "File" === e(t)) { if (!a) throw new s("NOT_READABLE_ERR"); var u = new a; n.push(u.readAsBinaryString(t)); } else t instanceof r ? "base64" === t.encoding && m ? n.push(m(t.data)) : "URI" === t.encoding ? n.push(decodeURIComponent(t.data)) : "raw" === t.encoding && n.push(t.data) : ("string" != typeof t && (t += ""), n.push(unescape(encodeURIComponent(t)))); }, i.getBlob = function (t) { return arguments.length || (t = null), new r(this.data.join(""), t, "raw") }, i.toString = function () { return "[object BlobBuilder]" }, o.slice = function (t, e, n) { var i = arguments.length; return i < 3 && (n = null), new r(this.data.slice(t, i > 1 ? e : this.data.length), n, this.encoding) }, o.toString = function () { return "[object Blob]" }, o.close = function () { this.size = 0, delete this.data; }, n }(t); t.Blob = function (t, n) { var r = n ? n.type || "" : "", i = new e; if (t) for (var o = 0, a = t.length; o < a; o++)Uint8Array && t[o] instanceof Uint8Array ? i.append(t[o].buffer) : i.append(t[o]); var s = i.getBlob(r); return !s.slice && s.webkitSlice && (s.slice = s.webkitSlice), s }; var n = Object.getPrototypeOf || function (t) { return t.__proto__ }; t.Blob.prototype = n(new t.Blob); }("undefined" != typeof self && self || "undefined" != typeof window && window || (void 0).content || void 0); var r = r || function (t) { if (!(void 0 === t || "undefined" != typeof navigator && /MSIE [1-9]\./.test(navigator.userAgent))) { var e = function () { return t.URL || t.webkitURL || t }, n = t.document.createElementNS("http://www.w3.org/1999/xhtml", "a"), r = "download" in n, i = function (t) { var e = new MouseEvent("click"); t.dispatchEvent(e); }, o = /constructor/i.test(t.HTMLElement) || t.safari, a = /CriOS\/[\d]+/.test(navigator.userAgent), s = function (e) { (t.setImmediate || t.setTimeout)(function () { throw e }, 0); }, c = function (t) { setTimeout(function () { "string" == typeof t ? e().revokeObjectURL(t) : t.remove(); }, 4e4); }, l = function (t, e, n) { for (var r = (e = [].concat(e)).length; r--;) { var i = t["on" + e[r]]; if ("function" == typeof i) try { i.call(t, n || t); } catch (t) { s(t); } } }, u = function (t) { return /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(t.type) ? new Blob([String.fromCharCode(65279), t], { type: t.type }) : t }, h = function (s, h, f) { f || (s = u(s)); var d, p = this, m = "application/octet-stream" === s.type, g = function () { l(p, "writestart progress write writeend".split(" ")); }; if (p.readyState = p.INIT, r) return d = e().createObjectURL(s), void setTimeout(function () { n.href = d, n.download = h, i(n), g(), c(d), p.readyState = p.DONE; }); !function () { if ((a || m && o) && t.FileReader) { var n = new FileReader; return n.onloadend = function () { var e = a ? n.result : n.result.replace(/^data:[^;]*;/, "data:attachment/file;"); t.open(e, "_blank") || (t.location.href = e), e = void 0, p.readyState = p.DONE, g(); }, n.readAsDataURL(s), void (p.readyState = p.INIT) } d || (d = e().createObjectURL(s)), m ? t.location.href = d : t.open(d, "_blank") || (t.location.href = d), p.readyState = p.DONE, g(), c(d); }(); }, f = h.prototype; return "undefined" != typeof navigator && navigator.msSaveOrOpenBlob ? function (t, e, n) { return e = e || t.name || "download", n || (t = u(t)), navigator.msSaveOrOpenBlob(t, e) } : (f.abort = function () { }, f.readyState = f.INIT = 0, f.WRITING = 1, f.DONE = 2, f.error = f.onwritestart = f.onprogress = f.onwrite = f.onabort = f.onerror = f.onwriteend = null, function (t, e, n) { return new h(t, e || t.name || "download", n) }) } }("undefined" != typeof self && self || "undefined" != typeof window && window || (void 0).content); "undefined" != 'object' && module.exports ? module.exports.saveAs = r : "undefined" != typeof undefined && null !== undefined && null !== undefined.amd && undefined("FileSaver.js", function () { return r }), function (t, e) { module.exports = e(); }(e, function () { var t = "function" == typeof ArrayBuffer && "function" == typeof Uint8Array, e = null, n = function () { if (!t) return function () { return !1 }; try { var n = {}; "function" == typeof n.Buffer && (e = n.Buffer); } catch (t) { } return function (t) { return t instanceof ArrayBuffer || null !== e && t instanceof e } }(), r = null !== e ? function (t) { return new e(t, "utf8").toString("binary") } : function (t) { return unescape(encodeURIComponent(t)) }, i = function (t, e) { for (var n = 65535 & t, r = t >>> 16, i = 0, o = e.length; i < o; i++)r = (r + (n = (n + (255 & e.charCodeAt(i))) % 65521)) % 65521; return (r << 16 | n) >>> 0 }, o = function (t, e) { for (var n = 65535 & t, r = t >>> 16, i = 0, o = e.length; i < o; i++)r = (r + (n = (n + e[i]) % 65521)) % 65521; return (r << 16 | n) >>> 0 }, a = {}, s = a.Adler32 = function () { var e = function (t) { if (!(this instanceof e)) throw new TypeError("Constructor cannot called be as a function."); if (!isFinite(t = null == t ? 1 : +t)) throw new Error("First arguments needs to be a finite number."); this.checksum = t >>> 0; }, a = e.prototype = {}; return a.constructor = e, e.from = function (t) { return t.prototype = a, t }(function (t) { if (!(this instanceof e)) throw new TypeError("Constructor cannot called be as a function."); if (null == t) throw new Error("First argument needs to be a string."); this.checksum = i(1, t.toString()); }), e.fromUtf8 = function (t) { return t.prototype = a, t }(function (t) { if (!(this instanceof e)) throw new TypeError("Constructor cannot called be as a function."); if (null == t) throw new Error("First argument needs to be a string."); var n = r(t.toString()); this.checksum = i(1, n); }), t && (e.fromBuffer = function (t) { return t.prototype = a, t }(function (t) { if (!(this instanceof e)) throw new TypeError("Constructor cannot called be as a function."); if (!n(t)) throw new Error("First argument needs to be ArrayBuffer."); var r = new Uint8Array(t); return this.checksum = o(1, r) })), a.update = function (t) { if (null == t) throw new Error("First argument needs to be a string."); return t = t.toString(), this.checksum = i(this.checksum, t) }, a.updateUtf8 = function (t) { if (null == t) throw new Error("First argument needs to be a string."); var e = r(t.toString()); return this.checksum = i(this.checksum, e) }, t && (a.updateBuffer = function (t) { if (!n(t)) throw new Error("First argument needs to be ArrayBuffer."); var e = new Uint8Array(t); return this.checksum = o(this.checksum, e) }), a.clone = function () { return new s(this.checksum) }, e }(); return a.from = function (t) { if (null == t) throw new Error("First argument needs to be a string."); return i(1, t.toString()) }, a.fromUtf8 = function (t) { if (null == t) throw new Error("First argument needs to be a string."); var e = r(t.toString()); return i(1, e) }, t && (a.fromBuffer = function (t) { if (!n(t)) throw new Error("First argument need to be ArrayBuffer."); var e = new Uint8Array(t); return o(1, e) }), a });/**
7559 * CssColors
7560 * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  [email protected]
7561 *
7562 * Licensed under the MIT License.
7563 * http://opensource.org/licenses/mit-license
7564 */
7565            var i = {}; i._colorsTable = { aliceblue: "#f0f8ff", antiquewhite: "#faebd7", aqua: "#00ffff", aquamarine: "#7fffd4", azure: "#f0ffff", beige: "#f5f5dc", bisque: "#ffe4c4", black: "#000000", blanchedalmond: "#ffebcd", blue: "#0000ff", blueviolet: "#8a2be2", brown: "#a52a2a", burlywood: "#deb887", cadetblue: "#5f9ea0", chartreuse: "#7fff00", chocolate: "#d2691e", coral: "#ff7f50", cornflowerblue: "#6495ed", cornsilk: "#fff8dc", crimson: "#dc143c", cyan: "#00ffff", darkblue: "#00008b", darkcyan: "#008b8b", darkgoldenrod: "#b8860b", darkgray: "#a9a9a9", darkgreen: "#006400", darkkhaki: "#bdb76b", darkmagenta: "#8b008b", darkolivegreen: "#556b2f", darkorange: "#ff8c00", darkorchid: "#9932cc", darkred: "#8b0000", darksalmon: "#e9967a", darkseagreen: "#8fbc8f", darkslateblue: "#483d8b", darkslategray: "#2f4f4f", darkturquoise: "#00ced1", darkviolet: "#9400d3", deeppink: "#ff1493", deepskyblue: "#00bfff", dimgray: "#696969", dodgerblue: "#1e90ff", firebrick: "#b22222", floralwhite: "#fffaf0", forestgreen: "#228b22", fuchsia: "#ff00ff", gainsboro: "#dcdcdc", ghostwhite: "#f8f8ff", gold: "#ffd700", goldenrod: "#daa520", gray: "#808080", green: "#008000", greenyellow: "#adff2f", honeydew: "#f0fff0", hotpink: "#ff69b4", "indianred ": "#cd5c5c", indigo: "#4b0082", ivory: "#fffff0", khaki: "#f0e68c", lavender: "#e6e6fa", lavenderblush: "#fff0f5", lawngreen: "#7cfc00", lemonchiffon: "#fffacd", lightblue: "#add8e6", lightcoral: "#f08080", lightcyan: "#e0ffff", lightgoldenrodyellow: "#fafad2", lightgrey: "#d3d3d3", lightgreen: "#90ee90", lightpink: "#ffb6c1", lightsalmon: "#ffa07a", lightseagreen: "#20b2aa", lightskyblue: "#87cefa", lightslategray: "#778899", lightsteelblue: "#b0c4de", lightyellow: "#ffffe0", lime: "#00ff00", limegreen: "#32cd32", linen: "#faf0e6", magenta: "#ff00ff", maroon: "#800000", mediumaquamarine: "#66cdaa", mediumblue: "#0000cd", mediumorchid: "#ba55d3", mediumpurple: "#9370d8", mediumseagreen: "#3cb371", mediumslateblue: "#7b68ee", mediumspringgreen: "#00fa9a", mediumturquoise: "#48d1cc", mediumvioletred: "#c71585", midnightblue: "#191970", mintcream: "#f5fffa", mistyrose: "#ffe4e1", moccasin: "#ffe4b5", navajowhite: "#ffdead", navy: "#000080", oldlace: "#fdf5e6", olive: "#808000", olivedrab: "#6b8e23", orange: "#ffa500", orangered: "#ff4500", orchid: "#da70d6", palegoldenrod: "#eee8aa", palegreen: "#98fb98", paleturquoise: "#afeeee", palevioletred: "#d87093", papayawhip: "#ffefd5", peachpuff: "#ffdab9", peru: "#cd853f", pink: "#ffc0cb", plum: "#dda0dd", powderblue: "#b0e0e6", purple: "#800080", red: "#ff0000", rosybrown: "#bc8f8f", royalblue: "#4169e1", saddlebrown: "#8b4513", salmon: "#fa8072", sandybrown: "#f4a460", seagreen: "#2e8b57", seashell: "#fff5ee", sienna: "#a0522d", silver: "#c0c0c0", skyblue: "#87ceeb", slateblue: "#6a5acd", slategray: "#708090", snow: "#fffafa", springgreen: "#00ff7f", steelblue: "#4682b4", tan: "#d2b48c", teal: "#008080", thistle: "#d8bfd8", tomato: "#ff6347", turquoise: "#40e0d0", violet: "#ee82ee", wheat: "#f5deb3", white: "#ffffff", whitesmoke: "#f5f5f5", yellow: "#ffff00", yellowgreen: "#9acd32" }
7565, i.colorNameToHex = function (t) { return t = t.toLowerCase(), void 0 !== this._colorsTable[t] && this._colorsTable[t] };/*
7566 Deflate.js - https://github.com/gildas-lormeau/zip.js
7567 Copyright (c) 2013 Gildas Lormeau. All rights reserved.
7568
7569 Redistribution and use in source and binary forms, with or without
7570 modification, are permitted provided that the following conditions are met:
7571
7572 1. Redistributions of source code must retain the above copyright notice,
7573 this list of conditions and the following disclaimer.
7574
7575 2. Redistributions in binary form must reproduce the above copyright 
7576 notice, this list of conditions and the following disclaimer in 
7577 the documentation and/or other materials provided with the distribution.
7578
7579 3. The names of the authors may not be used to endorse or promote products
7580 derived from this software without specific prior written permission.
7581
7582 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
7583 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
7584 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
7585 INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
7586 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7587 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
7588 OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
7589 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
7590 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
7591 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7592 */
7593            var o = function (t) { function e() { function t(t) { var e, n, i, o, a, c, l = r.dyn_tree, u = r.stat_desc.static_tree, h = r.stat_desc.extra_bits, d = r.stat_desc.extra_base, p = r.stat_desc.max_length, m = 0; for (o = 0; o <= s; o++)t.bl_count[o] = 0; for (l[2 * t.heap[t.heap_max] + 1] = 0, e = t.heap_max + 1; e < f; e++)(o = l[2 * l[2 * (n = t.heap[e]) + 1] + 1] + 1) > p && (o = p, m++), l[2 * n + 1] = o, n > r.max_code || (t.bl_count[o]++, a = 0, n >= d && (a = h[n - d]), c = l[2 * n], t.opt_len += c * (o + a), u && (t.static_len += c * (u[2 * n + 1] + a))); if (0 !== m) { do { for (o = p - 1; 0 === t.bl_count[o];)o--; t.bl_count[o]--, t.bl_count[o + 1] += 2, t.bl_count[p]--, m -= 2; } while (m > 0); for (o = p; 0 !== o; o--)for (n = t.bl_count[o]; 0 !== n;)(i = t.heap[--e]) > r.max_code || (l[2 * i + 1] != o && (t.opt_len += (o - l[2 * i + 1]) * l[2 * i], l[2 * i + 1] = o), n--); } } function e(t, e) { var n = 0; do { n |= 1 & t, t >>>= 1, n <<= 1; } while (--e > 0); return n >>> 1 } function n(t, n, r) { var i, o, a, c = [], l = 0; for (i = 1; i <= s; i++)c[i] = l = l + r[i - 1] << 1; for (o = 0; o <= n; o++)0 !== (a = t[2 * o + 1]) && (t[2 * o] = e(c[a]++, a)); } var r = this; r.build_tree = function (e) { var i, o, a, s = r.dyn_tree, c = r.stat_desc.static_tree, l = r.stat_desc.elems, u = -1; for (e.heap_len = 0, e.heap_max = f, i = 0; i < l; i++)0 !== s[2 * i] ? (e.heap[++e.heap_len] = u = i, e.depth[i] = 0) : s[2 * i + 1] = 0; for (; e.heap_len < 2;)s[2 * (a = e.heap[++e.heap_len] = u < 2 ? ++u : 0)] = 1, e.depth[a] = 0, e.opt_len--, c && (e.static_len -= c[2 * a + 1]); for (r.max_code = u, i = Math.floor(e.heap_len / 2); i >= 1; i--)e.pqdownheap(s, i); a = l; do { i = e.heap[1], e.heap[1] = e.heap[e.heap_len--], e.pqdownheap(s, 1), o = e.heap[1], e.heap[--e.heap_max] = i, e.heap[--e.heap_max] = o, s[2 * a] = s[2 * i] + s[2 * o], e.depth[a] = Math.max(e.depth[i], e.depth[o]) + 1, s[2 * i + 1] = s[2 * o + 1] = a, e.heap[1] = a++, e.pqdownheap(s, 1); } while (e.heap_len >= 2); e.heap[--e.heap_max] = e.heap[1], t(e), n(s, r.max_code, e.bl_count); }; } function n(t, e, n, r, i) { var o = this; o.static_tree = t, o.extra_bits = e, o.extra_base = n, o.elems = r, o.max_length = i; } function r(t, e, n, r, i) { var o = this; o.good_length = t, o.max_lazy = e, o.nice_length = n, o.max_chain = r, o.func = i; } function i(t, e, n, r) { var i = t[2 * e], o = t[2 * n]; return i < o || i == o && r[e] <= r[n] } function o() { function t() { var t; for (Pt = 2 * At, Et[Ft - 1] = 0, t = 0; t < Ft - 1; t++)Et[t] = 0; Vt = z[Gt].max_lazy, Jt = z[Gt].good_length, Qt = z[Gt].nice_length, Xt = z[Gt].max_chain, Mt = 0, jt = 0, Ht = 0, zt = Wt = $ - 1, Lt = 0, Ot = 0; } function r() { var t; for (t = 0; t < h; t++)Kt[2 * t] = 0; for (t = 0; t < c; t++)$t[2 * t] = 0; for (t = 0; t < l; t++)Zt[2 * t] = 0; Kt[2 * d] = 1, te.opt_len = te.static_len = 0, ae = ce = 0; } function o() { ee.dyn_tree = Kt, ee.stat_desc = n.static_l_desc, ne.dyn_tree = $t, ne.stat_desc = n.static_d_desc, re.dyn_tree = Zt, re.stat_desc = n.static_bl_desc, ue = 0, he = 0, le = 8, r(); } function a(t, e) { var n, r, i = -1, o = t[1], a = 0, s = 7, c = 4; for (0 === o && (s = 138, c = 3), t[2 * (e + 1) + 1] = 65535, n = 0; n <= e; n++)r = o, o = t[2 * (n + 1) + 1], ++a < s && r == o || (a < c ? Zt[2 * r] += a : 0 !== r ? (r != i && Zt[2 * r]++, Zt[2 * p]++) : a <= 10 ? Zt[2 * m]++ : Zt[2 * g]++, a = 0, i = r, 0 === o ? (s = 138, c = 3) : r == o ? (s = 6, c = 3) : (s = 7, c = 4)); } function s() { var t; for (a(Kt, ee.max_code), a($t, ne.max_code), re.build_tree(te), t = l - 1; t >= 3 && 0 === Zt[2 * e.bl_order[t] + 1]; t--); return te.opt_len += 3 * (t + 1) + 5 + 5 + 4, t } function f(t) { te.pending_buf[te.pending++] = t; } function O(t) { f(255 & t), f(t >>> 8 & 255); } function et(t) { f(t >> 8 & 255), f(255 & t); } function nt(t, e) { var n, r = e; he > w - r ? (O(ue |= (n = t) << he & 65535), ue = n >>> w - he, he += r - w) : (ue |= t << he & 65535, he += r); } function rt(t, e) { var n = 2 * t; nt(65535 & e[n], 65535 & e[n + 1]); } function it(t, e) { var n, r, i = -1, o = t[1], a = 0, s = 7, c = 4; for (0 === o && (s = 138, c = 3), n = 0; n <= e; n++)if (r = o, o = t[2 * (n + 1) + 1], !(++a < s && r == o)) { if (a < c) do { rt(r, Zt); } while (0 != --a); else 0 !== r ? (r != i && (rt(r, Zt), a--), rt(p, Zt), nt(a - 3, 2)) : a <= 10 ? (rt(m, Zt), nt(a - 3, 3)) : (rt(g, Zt), nt(a - 11, 7)); a = 0, i = r, 0 === o ? (s = 138, c = 3) : r == o ? (s = 6, c = 3) : (s = 7, c = 4); } } function ot(t, n, r) { var i; for (nt(t - 257, 5), nt(n - 1, 5), nt(r - 4, 4), i = 0; i < r; i++)nt(Zt[2 * e.bl_order[i] + 1], 3); it(Kt, t - 1), it($t, n - 1); } function at() { 16 == he ? (O(ue), ue = 0, he = 0) : he >= 8 && (f(255 & ue), ue >>>= 8, he -= 8); } function st() { nt(Q << 1, 3), rt(d, n.static_ltree), at(), 1 + le + 10 - he < 9 && (nt(Q << 1, 3), rt(d, n.static_ltree), at()), le = 7; } function ct(t, n) { var r, i, o; if (te.pending_buf[se + 2 * ae] = t >>>
7593 8 & 255, te.pending_buf[se + 2 * ae + 1] = 255 & t, te.pending_buf[ie + ae] = 255 & n, ae++, 0 === t ? Kt[2 * n]++ : (ce++, t--, Kt[2 * (e._length_code[n] + u + 1)]++, $t[2 * e.d_code(t)]++), 0 == (8191 & ae) && Gt > 2) { for (r = 8 * ae, i = Mt - jt, o = 0; o < c; o++)r += $t[2 * o] * (5 + e.extra_dbits[o]); if (r >>>= 3, ce < Math.floor(ae / 2) && r < Math.floor(i / 2)) return !0 } return ae == oe - 1 } function lt(t, n) { var r, i, o, a, s = 0; if (0 !== ae) do { r = te.pending_buf[se + 2 * s] << 8 & 65280 | 255 & te.pending_buf[se + 2 * s + 1], i = 255 & te.pending_buf[ie + s], s++, 0 === r ? rt(i, t) : (rt((o = e._length_code[i]) + u + 1, t), 0 !== (a = e.extra_lbits[o]) && nt(i -= e.base_length[o], a), r--, rt(o = e.d_code(r), n), 0 !== (a = e.extra_dbits[o]) && nt(r -= e.base_dist[o], a)); } while (s < ae); rt(d, t), le = t[2 * d + 1]; } function ut() { he > 8 ? O(ue) : he > 0 && f(255 & ue), ue = 0, he = 0; } function ht(t, e, n) { ut(), le = 8, n && (O(e), O(~e)), te.pending_buf.set(Tt.subarray(t, t + e), te.pending), te.pending += e; } function ft(t, e, n) { nt((J << 1) + (n ? 1 : 0), 3), ht(t, e, !0); } function dt(t, e, i) { var o, a, c = 0; Gt > 0 ? (ee.build_tree(te), ne.build_tree(te), c = s(), o = te.opt_len + 3 + 7 >>> 3, (a = te.static_len + 3 + 7 >>> 3) <= o && (o = a)) : o = a = e + 5, e + 4 <= o && -1 != t ? ft(t, e, i) : a == o ? (nt((Q << 1) + (i ? 1 : 0), 3), lt(n.static_ltree, n.static_dtree)) : (nt((K << 1) + (i ? 1 : 0), 3), ot(ee.max_code + 1, ne.max_code + 1, c + 1), lt(Kt, $t)), r(), i && ut(); } function pt(t) { dt(jt >= 0 ? jt : -1, Mt - jt, t), jt = Mt, xt.flush_pending(); } function mt() { var t, e, n, r; do { if (0 === (r = Pt - Ht - Mt) && 0 === Mt && 0 === Ht) r = At; else if (-1 == r) r--; else if (Mt >= At + At - tt) { Tt.set(Tt.subarray(At, At + At), 0), Ut -= At, Mt -= At, jt -= At, n = t = Ft; do { e = 65535 & Et[--n], Et[n] = e >= At ? e - At : 0; } while (0 != --t); n = t = At; do { e = 65535 & It[--n], It[n] = e >= At ? e - At : 0; } while (0 != --t); r += At; } if (0 === xt.avail_in) return; t = xt.read_buf(Tt, Mt + Ht, r), (Ht += t) >= $ && (Ot = 255 & Tt[Mt], Ot = (Ot << Dt ^ 255 & Tt[Mt + 1]) & Rt); } while (Ht < tt && 0 !== xt.avail_in) } function gt(t) { var e, n = 65535; for (n > _t - 5 && (n = _t - 5); ;) { if (Ht <= 1) { if (mt(), 0 === Ht && t == k) return L; if (0 === Ht) break } if (Mt += Ht, Ht = 0, e = jt + n, (0 === Mt || Mt >= e) && (Ht = Mt - e, Mt = e, pt(!1), 0 === xt.avail_out)) return L; if (Mt - jt >= At - tt && (pt(!1), 0 === xt.avail_out)) return L } return pt(t == A), 0 === xt.avail_out ? t == A ? U : L : t == A ? H : M } function wt(t) { var e, n, r = Xt, i = Mt, o = Wt, a = Mt > At - tt ? Mt - (At - tt) : 0, s = Qt, c = qt, l = Mt + Z, u = Tt[i + o - 1], h = Tt[i + o]; Wt >= Jt && (r >>= 2), s > Ht && (s = Ht); do { if (e = t, Tt[e + o] == h && Tt[e + o - 1] == u && Tt[e] == Tt[i] && Tt[++e] == Tt[i + 1]) { i += 2, e++; do { } while (Tt[++i] == Tt[++e] && Tt[++i] == Tt[++e] && Tt[++i] == Tt[++e] && Tt[++i] == Tt[++e] && Tt[++i] == Tt[++e] && Tt[++i] == Tt[++e] && Tt[++i] == Tt[++e] && Tt[++i] == Tt[++e] && i < l); if (n = Z - (l - i), i = l - Z, n > o) { if (Ut = t, o = n, n >= s) break; u = Tt[i + o - 1], h = Tt[i + o]; } } } while ((t = 65535 & It[t & c]) > a && 0 != --r); return o <= Ht ? o : Ht } function yt(t) { for (var e, n = 0; ;) { if (Ht < tt) { if (mt(), Ht < tt && t == k) return L; if (0 === Ht) break } if (Ht >= $ && (Ot = (Ot << Dt ^ 255 & Tt[Mt + ($ - 1)]) & Rt, n = 65535 & Et[Ot], It[Mt & qt] = Et[Ot], Et[Ot] = Mt), 0 !== n && (Mt - n & 65535) <= At - tt && Yt != b && (zt = wt(n)), zt >= $) if (e = ct(Mt - Ut, zt - $), Ht -= zt, zt <= Vt && Ht >= $) { zt--; do { Ot = (Ot << Dt ^ 255 & Tt[++Mt + ($ - 1)]) & Rt, n = 65535 & Et[Ot], It[Mt & qt] = Et[Ot], Et[Ot] = Mt; } while (0 != --zt); Mt++; } else Mt += zt, zt = 0, Ot = 255 & Tt[Mt], Ot = (Ot << Dt ^ 255 & Tt[Mt + 1]) & Rt; else e = ct(0, 255 & Tt[Mt]), Ht--, Mt++; if (e && (pt(!1), 0 === xt.avail_out)) return L } return pt(t == A), 0 === xt.avail_out ? t == A ? U : L : t == A ? H : M } function vt(t) { for (var e, n, r = 0; ;) { if (Ht < tt) { if (mt(), Ht < tt && t == k) return L; if (0 === Ht) break } if (Ht >
vendor: 4,184 bytes, line 7593
7593= $ && (Ot = (Ot << Dt ^ 255 & Tt[Mt + ($ - 1)]) & Rt, r = 65535 & Et[Ot], It[Mt & qt] = Et[Ot], Et[Ot] = Mt), Wt = zt, Nt = Ut, zt = $ - 1, 0 !== r && Wt < Vt && (Mt - r & 65535) <= At - tt && (Yt != b && (zt = wt(r)), zt <= 5 && (Yt == v || zt == $ && Mt - Ut > 4096) && (zt = $ - 1)), Wt >= $ && zt <= Wt) { n = Mt + Ht - $, e = ct(Mt - 1 - Nt, Wt - $), Ht -= Wt - 1, Wt -= 2; do { ++Mt <= n && (Ot = (Ot << Dt ^ 255 & Tt[Mt + ($ - 1)]) & Rt, r = 65535 & Et[Ot], It[Mt & qt] = Et[Ot], Et[Ot] = Mt); } while (0 != --Wt); if (Lt = 0, zt = $ - 1, Mt++, e && (pt(!1), 0 === xt.avail_out)) return L } else if (0 !== Lt) { if ((e = ct(0, 255 & Tt[Mt - 1])) && pt(!1), Mt++, Ht--, 0 === xt.avail_out) return L } else Lt = 1, Mt++, Ht--; } return 0 !== Lt && (e = ct(0, 255 & Tt[Mt - 1]), Lt = 0), pt(t == A), 0 === xt.avail_out ? t == A ? U : L : t == A ? H : M } function bt(e) { return e.total_in = e.total_out = 0, e.msg = null, te.pending = 0, te.pending_out = 0, kt = V, Ct = k, o(), t(), S } var xt, kt, _t, Ct, At, St, qt, Tt, Pt, It, Et, Ot, Ft, Bt, Rt, Dt, jt, zt, Nt, Lt, Mt, Ut, Ht, Wt, Xt, Vt, Gt, Yt, Jt, Qt, Kt, $t, Zt, te = this, ee = new e, ne = new e, re = new e; te.depth = []; var ie, oe, ae, se, ce, le, ue, he; te.bl_count = [], te.heap = [], Kt = [], $t = [], Zt = [], te.pqdownheap = function (t, e) { for (var n = te.heap, r = n[e], o = e << 1; o <= te.heap_len && (o < te.heap_len && i(t, n[o + 1], n[o], te.depth) && o++, !i(t, r, n[o], te.depth));)n[e] = n[o], e = o, o <<= 1; n[e] = r; }, te.deflateInit = function (t, e, n, r, i, o) { return r || (r = Y), i || (i = B), o || (o = x), t.msg = null, e == y && (e = 6), i < 1 || i > F || r != Y || n < 9 || n > 15 || e < 0 || e > 9 || o < 0 || o > b ? P : (t.dstate = te, St = n, At = 1 << St, qt = At - 1, Bt = i + 7, Ft = 1 << Bt, Rt = Ft - 1, Dt = Math.floor((Bt + $ - 1) / $), Tt = new Uint8Array(2 * At), It = [], Et = [], oe = 1 << i + 6, te.pending_buf = new Uint8Array(4 * oe), _t = 4 * oe, se = Math.floor(oe / 2), ie = 3 * oe, Gt = e, Yt = o, bt(t)) }, te.deflateEnd = function () { return kt != X && kt != V && kt != G ? P : (te.pending_buf = null, Et = null, It = null, Tt = null, te.dstate = null, kt == V ? I : S) }, te.deflateParams = function (t, e, n) { var r = S; return e == y && (e = 6), e < 0 || e > 9 || n < 0 || n > b ? P : (z[Gt].func != z[e].func && 0 !== t.total_in && (r = t.deflate(_)), Gt != e && (Vt = z[Gt = e].max_lazy, Jt = z[Gt].good_length, Qt = z[Gt].nice_length, Xt = z[Gt].max_chain), Yt = n, r) }, te.deflateSetDictionary = function (t, e, n) { var r, i = n, o = 0; if (!e || kt != X) return P; if (i < $) return S; for (i > At - tt && (o = n - (i = At - tt)), Tt.set(e.subarray(o, o + i), 0), Mt = i, jt = i, Ot = 255 & Tt[0], Ot = (Ot << Dt ^ 255 & Tt[1]) & Rt, r = 0; r <= i - $; r++)Ot = (Ot << Dt ^ 255 & Tt[r + ($ - 1)]) & Rt, It[r & qt] = Et[Ot], Et[Ot] = r; return S }, te.deflate = function (t, e) { var n, r, i, o, a; if (e > A || e < 0) return P; if (!t.next_out || !t.next_in && 0 !== t.avail_in || kt == G && e != A) return t.msg = N[T - P], P; if (0 === t.avail_out) return t.msg = N[T - E], E; if (xt = t, o = Ct, Ct = e, kt == X && (r = Y + (St - 8 << 4) << 8, (i = (Gt - 1 & 255) >> 1) > 3 && (i = 3), r |= i << 6, 0 !== Mt && (r |= W), kt = V, et(r += 31 - r % 31)), 0 !== te.pending) { if (xt.flush_pending(), 0 === xt.avail_out) return Ct = -1, S } else if (0 === xt.avail_in && e <= o && e != A) return xt.msg = N[T - E], E; if (kt == G && 0 !== xt.avail_in) return t.msg = N[T - E], E; if (0 !== xt.avail_in || 0 !== Ht || e != k && kt != G) { switch (a = -1, z[Gt].func) { case R: a = gt(e); break; case D: a = yt(e); break; case j: a = vt(e); }if (a != U && a != H || (kt = G), a == L || a == U) return 0 === xt.avail_out && (Ct = -1), S; if (a == M) { if (e == _) st(); else if (ft(0, 0, !1), e == C) for (n = 0; n < Ft; n++)Et[n] = 0; if (xt.flush_pending(), 0 === xt.avail_out) return Ct = -1, S } } return e != A ? S : q }; } function a() { var t = this; t.next_in_index = 0, t.next_out_index = 0, t.avail_in = 0, t.total_in = 0, t.avail_out = 0, t.total_out = 0; } var s = 15, c = 30, l = 19, u = 256, h = u + 1 + 29, f = 2 * h + 1, d = 256, p 
7593= 16, m = 17, g = 18, w = 16, y = -1, v = 1, b = 2, x = 0, k = 0, _ = 1, C = 3, A = 4, S = 0, q = 1, T = 2, P = -2, I = -3, E = -5, O = [0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29]; e._length_code = [0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28], e.base_length = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0], e.base_dist = [0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576], e.d_code = function (t) { return t < 256 ? O[t] : O[256 + (t >>> 7)] }, e.extra_lbits = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0], e.extra_dbits = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13], e.extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7], e.bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], n.static_ltree = [12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 27
vendor: 19,723 bytes, lines 7593-7599
75935, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8], n.static_dtree = [0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5], n.static_l_desc = new n(n.static_ltree, e.extra_lbits, u + 1, h, s), n.static_d_desc = new n(n.static_dtree, e.extra_dbits, 0, c, s), n.static_bl_desc = new n(null, e.extra_blbits, 0, l, 7); var F = 9, B = 8, R = 0, D = 1, j = 2, z = [new r(0, 0, 0, 0, R), new r(4, 4, 8, 4, D), new r(4, 5, 16, 8, D), new r(4, 6, 32, 32, D), new r(4, 4, 16, 16, j), new r(8, 16, 32, 32, j), new r(8, 16, 128, 128, j), new r(8, 32, 128, 256, j), new r(32, 128, 258, 1024, j), new r(32, 258, 258, 4096, j)], N = ["need dictionary", "stream end", "", "", "stream error", "data error", "", "buffer error", "", ""], L = 0, M = 1, U = 2, H = 3, W = 32, X = 42, V = 113, G = 666, Y = 8, J = 0, Q = 1, K = 2, $ = 3, Z = 258, tt = Z + $ + 1; return a.prototype = { deflateInit: function (t, e) { var n = this; return n.dstate = new o, e || (e = s), n.dstate.deflateInit(n, t, e) }, deflate: function (t) { var e = this; return e.dstate ? e.dstate.deflate(e, t) : P }, deflateEnd: function () { var t = this; if (!t.dstate) return P; var e = t.dstate.deflateEnd(); return t.dstate = null, e }, deflateParams: function (t, e) { var n = this; return n.dstate ? n.dstate.deflateParams(n, t, e) : P }, deflateSetDictionary: function (t, e) { var n = this; return n.dstate ? n.dstate.deflateSetDictionary(n, t, e) : P }, read_buf: function (t, e, n) { var r = this, i = r.avail_in; return i > n && (i = n), 0 === i ? 0 : (r.avail_in -= i, t.set(r.next_in.subarray(r.next_in_index, r.next_in_index + i), e), r.next_in_index += i, r.total_in += i, i) }, flush_pending: function () { var t = this, e = t.dstate.pending; e > t.avail_out && (e = t.avail_out), 0 !== e && (t.next_out.set(t.dstate.pending_buf.subarray(t.dstate.pending_out, t.dstate.pending_out + e), t.next_out_index), t.next_out_index += e, t.dstate.pending_out += e, t.total_out += e, t.avail_out -= e, t.dstate.pending -= e, 0 === t.dstate.pending && (t.dstate.pending_out = 0)); } }, function (t) { var e = this, n = new a, r = k, i = new Uint8Array(512); void 0 === t && (t = y), n.deflateInit(t), n.next_out = i, e.append = function (t, e) { var o, a = [], s = 0, c = 0, l = 0; if (t.length) { n.next_in_index = 0, n.next_in = t, n.avail_in = t.length; do { if (n.next_out_index = 0, n.avail_out = 512, n.deflate(r) != S) throw "deflating: " + n.msg; n.next_out_index && (512 == n.next_out_index ? a.push(new Uint8Array(i)) : a.push(new Uint8Array(i.subarray(0, n.next_out_index)))), l += n.next_out_index, e && n.next_in_index > 0 && n.next_in_index != s && (e(n.next_in_index), s = n.next_in_index); } while (n.avail_in > 0 || 0 === n.avail_out); return o = new Uint8Array(l), a.forEach(function (t) { o.set(t, c), c += t.length; }), o } }, e.flush = function () { var t, e, r = [], o = 0, a = 0; do { if (n.next_out_index = 0, n.avail_out = 512, (t = n.deflate(A)) != q && t != S) throw "deflating: " + n.msg; 512 - n.avail_out > 0 && r.push(new Uint8Array(i.subarray(0, n.next_out_index))), a += n.next_out_index; } while (n.avail_in > 0 || 0 === n.avail_out); return n.deflateEnd(), e = new Uint8Array(a), r.forEach(function (t) { e.set(t, o), o += t.length; }), e }; } }();/*
7594  html2canvas 0.5.0-beta3 <http://html2canvas.hertzen.com>
7595  Copyright (c) 2016 Niklas von Hertzen
7596
7597  Released under  License
7598*/
7599            !function (t) { module.exports = t(); }(function () { return function t(e, n, r) { function i(a, s) { if (!n[a]) { if (!e[a]) { var c = "function" == typeof commonjsRequire && commonjsRequire; if (!s && c) return c(a, !0); if (o) return o(a, !0); var l = new Error("Cannot find module '" + a + "'"); throw l.code = "MODULE_NOT_FOUND", l } var u = n[a] = { exports: {} }; e[a][0].call(u.exports, function (t) { var n = e[a][1][t]; return i(n || t) }, u, u.exports, t, e, n, r); } return n[a].exports } for (var o = "function" == typeof commonjsRequire && commonjsRequire, a = 0; a < r.length; a++)i(r[a]); return i }({ 1: [function (t, e, n) { (function (t) { !function (r) { function i(t) { throw RangeError(E[t]) } function o(t, e) { for (var n = t.length; n--;)t[n] = e(t[n]); return t } function a(t, e) { return o(t.split(I), e).join(".") } function s(t) { for (var e, n, r = [], i = 0, o = t.length; i < o;)(e = t.charCodeAt(i++)) >= 55296 && e <= 56319 && i < o ? 56320 == (64512 & (n = t.charCodeAt(i++))) ? r.push(((1023 & e) << 10) + (1023 & n) + 65536) : (r.push(e), i--) : r.push(e); return r } function c(t) { return o(t, function (t) { var e = ""; return t > 65535 && (e += B((t -= 65536) >>> 10 & 1023 | 55296), t = 56320 | 1023 & t), e += B(t) }).join("") } function l(t) { return t - 48 < 10 ? t - 22 : t - 65 < 26 ? t - 65 : t - 97 < 26 ? t - 97 : b } function u(t, e) { return t + 22 + 75 * (t < 26) - ((0 != e) << 5) } function h(t, e, n) { var r = 0; for (t = n ? F(t / C) : t >> 1, t += F(t / e); t > O * k >> 1; r += b)t = F(t / O); return F(r + (O + 1) * t / (t + _)) } function f(t) { var e, n, r, o, a, s, u, f, d, p, m = [], g = t.length, w = 0, y = S, _ = A; for ((n = t.lastIndexOf(q)) < 0 && (n = 0), r = 0; r < n; ++r)t.charCodeAt(r) >= 128 && i("not-basic"), m.push(t.charCodeAt(r)); for (o = n > 0 ? n + 1 : 0; o < g;) { for (a = w, s = 1, u = b; o >= g && i("invalid-input"), ((f = l(t.charCodeAt(o++))) >= b || f > F((v - w) / s)) && i("overflow"), w += f * s, d = u <= _ ? x : u >= _ + k ? k : u - _, !(f < d); u += b)s > F(v / (p = b - d)) && i("overflow"), s *= p; _ = h(w - a, e = m.length + 1, 0 == a), F(w / e) > v - y && i("overflow"), y += F(w / e), w %= e, m.splice(w++, 0, y); } return c(m) } function d(t) { var e, n, r, o, a, c, l, f, d, p, m, g, w, y, _, C = []; for (g = (t = s(t)).length, e = S, n = 0, a = A, c = 0; c < g; ++c)(m = t[c]) < 128 && C.push(B(m)); for (r = o = C.length, o && C.push(q); r < g;) { for (l = v, c = 0; c < g; ++c)(m = t[c]) >= e && m < l && (l = m); for (l - e > F((v - n) / (w = r + 1)) && i("overflow"), n += (l - e) * w, e = l, c = 0; c < g; ++c)if ((m = t[c]) < e && ++n > v && i("overflow"), m == e) { for (f = n, d = b; p = d <= a ? x : d >= a + k ? k : d - a, !(f < p); d += b)_ = f - p, y = b - p, C.push(B(u(p + _ % y, 0))), f = F(_ / y); C.push(B(u(f, 0))), a = h(n, w, r == o), n = 0, ++r; } ++n, ++e; } return C.join("") } var p = "object" == typeof n && n, m = "object" == typeof e && e && e.exports == p && e, g = "object" == typeof t && t; g.global !== g && g.window !== g || (r = g); var w, y, v = 2147483647, b = 36, x = 1, k = 26, _ = 38, C = 700, A = 72, S = 128, q = "-", T = /^xn--/, P = /[^ -~]/, I = /\x2E|\u3002|\uFF0E|\uFF61/g, E = { overflow: "Overflow: input needs wider integers to process", "not-basic": "Illegal input >= 0x80 (not a basic code point)", "invalid-input": "Invalid input" }, O = b - x, F = Math.floor, B = String.fromCharCode; if (w = { version: "1.2.4", ucs2: { decode: s, encode: c }, decode: f, encode: d, toASCII: function (t) { return a(t, function (t) { return P.test(t) ? "xn--" + d(t) : t }) }, toUnicode: function (t) { return a(t, function (t) { return T.test(t) ? f(t.slice(4).toLowerCase()) : t }) } }, p && !p.nodeType) if (m) m.exports = w; else for (y in w) w.hasOwnProperty(y) && (p[y] = w[y]); else r.punycode = w; }(this); }).call(this, "undefined" != typeof commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}); }, {}], 2: [function (t, e, n) { function r(t, e, n) { !t.defaultView || e === t.defaultView.pageXOffset && n === t.defaultView.pageYOffset || t.defaultView.scrollTo(e, n); } function i(t, e) { try { e && (e.width = t.width, e.height = t.height, e.getContext("2d").putImageData(t.getContext("2d").getImageData(0, 0, t.width, t.height), 0, 0)); } catch (e) { s("Unable to copy canvas content from", t, e); } } function o(t, e) { for (var n = 3 === t.nodeType ? document.createTextNode(t.nodeValue) : t.cloneNode(!1), r = t.firstChild; r;)!0 !== e && 1 === r.nodeType && "SCRIPT" === r.nodeName || n.appendChild(o(r, e)), r = r.nextSibling; return 1 === t.nodeType && (n._scrollTop = t.scrollTop, n._scrollLeft = t.scrollLeft, "CANVAS" === t.nodeName ? i(t, n) : "TEXTAREA" !== t.nodeName && "SELECT" !== t.nodeName || (n.value = t.value)), n } function a(t) { if (1 === t.nodeType) { t.scrollTop = t._scrollTop, t.scrollLeft = t._scrollLeft; for (var e = t.firstChild; e;)a(e), e = e.nextSibling; } } var s = t("./log"); e.exports = function (t, e, n, i, s, c, l) { var u = o(t.documentElement, s.javascriptEnabled), h = e.createElement("iframe"); return h.className = "html2canvas-container", h.style.visibility = "hidden", h.style.position = "fixed", h.style.left = "-10000px", h.style.top = "0px", h.style.border = "0", h.width = n, h.height = i, h.scrolling = "no", e.body.appendChild(h), new Promise(function (e) { var n = h.contentWindow.document; h.contentWindow.onload = h.onload = function () { var t = setInterval(function () { n.body.childNodes.length > 0 && (a(n.documentElement), clearInterval(t), "view" === s.type && (h.contentWindow.scrollTo(c, l), !/(iPad|iPhone|iPod)/g.test(navigator.userAgent) || h.contentWindow.scrollY === l && h.contentWindow.scrollX === c || (n.documentElement.style.top = -l + "px", n.documentElement.style.left = -c + "px", n.documentElement.style.position = "absolute")), e(h)); }, 50); }, n.open(), n.write("<!DOCTYPE html><html></html>"), r(t, c, l), n.replaceChild(n.adoptNode(u), n.documentElement), n.close(); }) }; }, { "./log": 13 }], 3: [function (t, e, n) { function r(t) { this.r = 0, this.g = 0, this.b = 0, this.a = null; this.fromArray(t) || this.namedColor(t) || this.rgb(t) || this.rgba(t) || this.hex6(t) || this.hex3(t); } r.prototype.darken = function (t) { var e = 1 - t; return new r([Math.round(this.r * e), Math.round(this.g * e), Math.round(this.b * e), this.a]) }, r.prototype.isTransparent = function () { return 0 === this.a }, r.prototype.isBlack = function () { return 0 === this.r && 0 === this.g && 0 === this.b }, r.prototype.fromArray = function (t) { return Array.isArray(t) && (this.r = Math.min(t[0], 255), this.g = Math.min(t[1], 255), this.b = Math.min(t[2], 255), t.length > 3 && (this.a = t[3])), Array.isArray(t) }; var i = /^#([a-f0-9]{3})$/i; r.prototype.hex3 = function (t) { var e = null; return null !== (e = t.match(i)) && (this.r = parseInt(e[1][0] + e[1][0], 16), this.g = parseInt(e[1][1] + e[1][1], 16), this.b = parseInt(e[1][2] + e[1][2], 16)), null !== e }; var o = /^#([a-f0-9]{6})$/i; r.prototype.hex6 = function (t) { var e = null; return null !== (e = t.match(o)) && (this.r = parseInt(e[1].substring(0, 2), 16), this.g = parseInt(e[1].substring(2, 4), 16), this.b = parseInt(e[1].substring(4, 6), 16)), null !== e }; var a = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/; r.prototype.rgb = function (t) { var e = null; return null !== (e = t.match(a)) && (this.r = Number(e[1]), this.g = Number(e[2]), this.b = Number(e[3])), null !== e }; var s = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/; r.prototype.rgba = function (t) { var e = null; return null !== (e = t.match(s)) && (this.r = Number(e[1]), this.g = Number(e[2]), this.b = Number(e[3]), this.a = Number(e[4])), null !== e }, r.prototype.toString = function () { return null !== this.a && 1 !== this.a ? "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" : "rgb(" + [this.r, this.g, this.b].join(",") + ")" }, r.prototype.namedColor = function (t) { t = t.toLowerCase(); var e = c[t]; if (e) this.r = e[0], this.g = e[1], this.b = e[2]; else if ("transparent" === t) return this.r = this.g = this.b = this.a = 0, !0; return !!e }, r.prototype.isColor = !0; var c = { aliceblue: [240, 248, 255], antiquewhite: [250, 235, 215], aqua: [0, 255, 255], aquamarine: [127, 255, 212], azure: [240, 255, 255], beige: [245, 245, 220], bisque: [255, 228, 196], black: [0, 0, 0], blanchedalmond: [255, 235, 205], blue: [0, 0, 255], blueviolet: [138, 43, 226], brown: [165, 42, 42], burlywood: [222, 184, 135], cadetblue: [95, 158, 160], chartreuse: [127, 255, 0], chocolate: [210, 105, 30], coral: [255, 127, 80], cornflowerblue: [100, 149, 237], cornsilk: [255, 248, 220], crimson: [220, 20, 60], cyan: [0, 255, 255], darkblue: [0, 0, 139], darkcyan: [0, 139, 139], darkgoldenrod: [184, 134, 11], darkgray: [169, 169, 169], darkgreen: [0, 100, 0], darkgrey: [169, 169, 169], darkkhaki: [189, 183, 107], darkmagenta: [139, 0, 139], darkolivegreen: [85, 107, 47], darkorange: [255, 140, 0], darkorchid: [153, 50, 204], darkred: [139, 0, 0], darksalmon: [233, 150, 122], darkseagreen: [143, 188, 143], darkslateblue: [72, 61, 139], darkslategray: [47, 79, 79], darkslategrey: [47, 79, 79], darkturquoise: [0, 206, 209], darkviolet: [148, 0, 211], deeppink: [255, 20, 147], deepskyblue: [0, 191, 255], dimgray: [105, 105, 105], dimgrey: [105, 105, 105], dodgerblue: [30, 144, 255], firebrick: [178, 34, 34], floralwhite: [255, 250, 240], forestgreen: [34, 139, 34], fuchsia: [255, 0, 255], gainsboro: [220, 220, 220], ghostwhite: [248, 248, 255], gold: [255, 215, 0], goldenrod: [218, 165, 32], gray: [128, 128, 128], green: [0, 128, 0], greenyellow: [173, 255, 47], grey: [128, 128, 128], honeydew: [240, 255, 240], hotpink: [255, 105, 180], indianred: [205, 92, 92], indigo: [75, 0, 130], ivory: [255, 255, 240], khaki: [240, 230, 140], lavender: [230, 230, 250], lavenderblush: [255, 240, 245], lawngreen: [124, 252, 0], lemonchiffon: [255, 250, 205], lightblue: [173, 216, 230], lightcoral: [240, 128, 128], lightcyan: [224, 255, 255], lightgoldenrodyellow: [250, 250, 210], lightgray: [211, 211, 211], lightgreen: [144, 238, 144], lightgrey: [211, 211, 211], lightpink: [255, 182, 193], lightsalmon: [255, 160, 122], lightseagreen: [32, 178, 170], lightskyblue: [135, 206, 250], lightslategray: [119, 136, 153], lightslategrey: [119, 136, 153], lightsteelblue: [176, 196, 222], lightyellow: [255, 255, 224], lime: [0, 255, 0], limegreen: [50, 205, 50], linen: [250, 240, 230], magenta: [255, 0, 255], maroon: [128, 0, 0], mediumaquamarine: [102, 205, 170], mediumblue: [0, 0, 205], mediumorchid: [186, 85, 211], mediumpurple: [147, 112, 219], mediumseagreen: [60, 179, 113], mediumslateblue: [123, 104, 238], mediumspringgreen: [0, 250, 154], mediumturquoise: [72, 209, 204], mediumvioletred: [199, 21, 133], midnightblue: [25, 25, 112], mintcream: [245, 255, 250], mistyrose: [255, 228, 225], moccasin: [255, 228, 181], navajowhite: [255, 222, 173], navy: [0, 0, 128], oldlace: [253, 245, 230], olive: [128, 128, 0], olivedrab: [107, 142, 35], orange: [255, 165, 0], orangered: [255, 69, 0], orchid: [218, 112, 214], palegoldenrod: [238, 232, 170], palegreen: [152, 251, 152], paleturquoise: [175, 238, 238], palevioletred: [219, 112, 147], papayawhip: [255, 239, 213], peachpuff: [255, 218, 185], peru: [205, 133, 63], pink: [255, 192, 203], plum: [221, 160, 221], powderblue: [176, 224, 230], purple: [128, 0, 128], rebeccapurple: [102, 51, 153], red: [255, 0, 0], rosybrown: [188, 143, 143], royalblue: [65, 105, 225], saddlebrown: [139, 69, 19], salmon: [250, 128, 114], sandybrown: [244, 164, 96], seagreen: [46, 139, 87], seashell: [255, 245, 238], sienna: [160, 82, 45], silver: [192, 192, 192], skyblue: [135, 206, 235], slateblue: [106, 90, 205], slategray: [112, 128, 144], slategrey: [112, 128, 144], snow: [255, 250, 250], springgreen: [0, 255, 127], steelblue: [70, 130, 180], tan: [210, 180, 140], teal: [0, 128, 128], thistle: [216, 191, 216], tomato: [255, 99, 71], turquoise: [64, 224, 208], violet: [238, 130, 238], wheat: [245, 222, 179], white: [255, 255, 255], whitesmoke: [245, 245, 245], yellow: [255, 255, 0], yellowgreen: [154, 205, 50] }; e.exports = r; }, {}], 4: [function (t, e, n) { function r(t, e) { var n = k++; if ((e = e || {}).logging && (g.options.logging = !0, g.options.start = Date.now()), e.async = void 0 === e.async || e.async, e.allowTaint = void 0 !== e.allowTaint && e.allowTaint, e.removeContainer = void 0 === e.removeContainer || e.removeContainer, e.javascriptEnabled = void 0 !== e.javascriptEnabled && e.javascriptEnabled, e.imageTimeout = void 0 === e.imageTimeout ? 1e4 : e.imageTimeout, e.renderer = "function" == typeof e.renderer ? e.renderer : f, e.strict = !!e.strict, "string" == typeof t) { if ("string" != typeof e.proxy) return Promise.reject("Proxy must be used when rendering url"); var r = null != e.width ? e.width : window.innerWidth, a = null != e.height ? e.height : window.innerHeight; return v(u(t), e.proxy, document, r, a, e).then(function (t) { return o(t.contentWindow.document.documentElement, t, e, r, a) }) } var s = (void 0 === t ? [document.documentElement] : t.length ? t : [t])[0]; return s.setAttribute(x + n, n), i(s.ownerDocument, e, s.ownerDocument.defaultView.innerWidth, s.ownerDocument.defaultView.innerHeight, n).then(function (t) { return "function" == typeof e.onrendered && (g("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas"), e.onrendered(t)), t }) } function i(t, e, n, r, i) { return y(t, t, n, r, e, t.defaultView.pageXOffset, t.defaultView.pageYOffset).then(function (a) { g("Document cloned"); var s = x + i, c = "[" + s + "='" + i + "']"; t.querySelector(c).removeAttribute(s); var l = a.contentWindow, u = l.document.querySelector(c); return ("function" == typeof e.onclone ? Promise.resolve(e.onclone(l.document)) : Promise.resolve(!0)).then(function () { return o(u, a, e, n, r) }) }) } function o(t, e, n, r, i) { var o = e.contentWindow, u = new h(o.document), f = new d(n, u), m = b(t), w = "view" === n.type ? r : c(o.document), y = "view" === n.type ? i : l(o.document), v = new n.renderer(w, y, f, n, document); return new p(t, v, u, f, n).ready.then(function () { g("Finished rendering"); var r; return r = "view" === n.type ? s(v.canvas, { width: v.canvas.width, height: v.canvas.height, top: 0, left: 0, x: 0, y: 0 }) : t === o.document.body || t === o.document.documentElement || null != n.canvas ? v.canvas : s(v.canvas, { width: null != n.width ? n.width : m.width, height: null != n.height ? n.height : m.height, top: m.top, left: m.left, x: 0, y: 0 }), a(e, n), r }) } function a(t, e) { e.removeContainer && (t.parentNode.removeChild(t), g("Cleaned up container")); } function s(t, e) { var n = document.createElement("canvas"), r = Math.min(t.width - 1, Math.max(0, e.left)), i = Math.min(t.width, Math.max(1, e.left + e.width)), o = Math.min(t.height - 1, Math.max(0, e.top)), a = Math.min(t.height, Math.max(1, e.top + e.height)); n.width = e.width, n.height = e.height;
7599 var s = i - r, c = a - o; return g("Cropping canvas at:", "left:", e.left, "top:", e.top, "width:", s, "height:", c), g("Resulting crop with width", e.width, "and height", e.height, "with x", r, "and y", o), n.getContext("2d").drawImage(t, r, o, s, c, e.x, e.y, s, c), n } function c(t) { return Math.max(Math.max(t.body.scrollWidth, t.documentElement.scrollWidth), Math.max(t.body.offsetWidth, t.documentElement.offsetWidth), Math.max(t.body.clientWidth, t.documentElement.clientWidth)) } function l(t) { return Math.max(Math.max(t.body.scrollHeight, t.documentElement.scrollHeight), Math.max(t.body.offsetHeight, t.documentElement.offsetHeight), Math.max(t.body.clientHeight, t.documentElement.clientHeight)) } function u(t) { var e = document.createElement("a"); return e.href = t, e.href = e.href, e } var h = t("./support"), f = t("./renderers/canvas"), d = t("./imageloader"), p = t("./nodeparser"), m = t("./nodecontainer"), g = t("./log"), w = t("./utils"), y = t("./clone"), v = t("./proxy").loadUrlDocument, b = w.getBounds, x = "data-html2canvas-node", k = 0; r.CanvasRenderer = f, r.NodeContainer = m, r.log = g, r.utils = w; var _ = "undefined" == typeof document || "function" != typeof Object.create || "function" != typeof document.createElement("canvas").getContext ? function () { return Promise.reject("No canvas support") } : r; e.exports = _; }, { "./clone": 2, "./imageloader": 11, "./log": 13, "./nodecontainer": 14, "./nodeparser": 15, "./proxy": 16, "./renderers/canvas": 20, "./support": 22, "./utils": 26 }], 5: [function (t, e, n) { function r(t) { if (this.src = t, i("DummyImageContainer for", t), !this.promise || !this.image) { i("Initiating DummyImageContainer"), r.prototype.image = new Image; var e = this.image; r.prototype.promise = new Promise(function (t, n) { e.onload = t, e.onerror = n, e.src = o(), !0 === e.complete && t(e); }); } } var i = t("./log"), o = t("./utils").smallImage; e.exports = r; }, { "./log": 13, "./utils": 26 }], 6: [function (t, e, n) { var r = t("./utils").smallImage; e.exports = function (t, e) { var n, i, o = document.createElement("div"), a = document.createElement("img"), s = document.createElement("span"); o.style.visibility = "hidden", o.style.fontFamily = t, o.style.fontSize = e, o.style.margin = 0, o.style.padding = 0, document.body.appendChild(o), a.src = r(), a.width = 1, a.height = 1, a.style.margin = 0, a.style.padding = 0, a.style.verticalAlign = "baseline", s.style.fontFamily = t, s.style.fontSize = e, s.style.margin = 0, s.style.padding = 0, s.appendChild(document.createTextNode("Hidden Text")), o.appendChild(s), o.appendChild(a), n = a.offsetTop - s.offsetTop + 1, o.removeChild(s), o.appendChild(document.createTextNode("Hidden Text")), o.style.lineHeight = "normal", a.style.verticalAlign = "super", i = a.offsetTop - o.offsetTop + 1, document.body.removeChild(o), this.baseline = n, this.lineWidth = 1, this.middle = i; }; }, { "./utils": 26 }], 7: [function (t, e, n) { function r() { this.data = {}; } var i = t("./font"); r.prototype.getMetrics = function (t, e) { return void 0 === this.data[t + "-" + e] && (this.data[t + "-" + e] = new i(t, e)), this.data[t + "-" + e] }, e.exports = r; }, { "./font": 6 }], 8: [function (t, e, n) { function r(e, n, r) { this.image = null, this.src = e; var o = this, a = i(e); this.promise = (n ? new Promise(function (t) { "about:blank" === e.contentWindow.document.URL || null == e.contentWindow.document.documentElement ? e.contentWindow.onload = e.onload = function () { t(e); } : t(e); }) : this.proxyLoad(r.proxy, a, r)).then(function (e) { return t("./core")(e.contentWindow.document.documentElement, { type: "view", width: e.width, height: e.height, proxy: r.proxy, javascriptEnabled: r.javascriptEnabled, removeContainer: r.removeContainer, allowTaint: r.allowTaint, imageTimeout: r.imageTimeout / 2 }) }).then(function (t) { return o.image = t }); } var i = t("./utils").getBounds, o = t("./proxy").loadUrlDocument; r.prototype.proxyLoad = function (t, e, n) { var r = this.src; return o(r.src, t, r.ownerDocument, e.width, e.height, n) }, e.exports = r; }, { "./core": 4, "./proxy": 16, "./utils": 26 }], 9: [function (t, e, n) { function r(t) { this.src = t.value, this.colorStops = [], this.type = null, this.x0 = .5, this.y0 = .5, this.x1 = .5, this.y1 = .5, this.promise = Promise.resolve(!0); } r.TYPES = { LINEAR: 1, RADIAL: 2 }, r.REGEXP_COLORSTOP = /^\s*(rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*[0-9\.]+)?\s*\)|[a-z]{3,20}|#[a-f0-9]{3,6})(?:\s+(\d{1,3}(?:\.\d+)?)(%|px)?)?(?:\s|$)/i, e.exports = r; }, {}], 10: [function (t, e, n) { e.exports = function (t, e) { this.src = t, this.image = new Image; var n = this; this.tainted = null, this.promise = new Promise(function (r, i) { n.image.onload = r, n.image.onerror = i, e && (n.image.crossOrigin = "anonymous"), n.image.src = t, !0 
7599=== n.image.complete && r(n.image); }); }; }, {}], 11: [function (t, e, n) { function r(t, e) { this.link = null, this.options = t, this.support = e, this.origin = this.getOrigin(window.location.href); } var i = t("./log"), o = t("./imagecontainer"), a = t("./dummyimagecontainer"), s = t("./proxyimagecontainer"), c = t("./framecontainer"), l = t("./svgcontainer"), u = t("./svgnodecontainer"), h = t("./lineargradientcontainer"), f = t("./webkitgradientcontainer"), d = t("./utils").bind; r.prototype.findImages = function (t) { var e = []; return t.reduce(function (t, e) { switch (e.node.nodeName) { case "IMG": return t.concat([{ args: [e.node.src], method: "url" }]); case "svg": case "IFRAME": return t.concat([{ args: [e.node], method: e.node.nodeName }]) }return t }, []).forEach(this.addImage(e, this.loadImage), this), e }, r.prototype.findBackgroundImage = function (t, e) { return e.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(t, this.loadImage), this), t }, r.prototype.addImage = function (t, e) { return function (n) { n.args.forEach(function (r) { this.imageExists(t, r) || (t.splice(0, 0, e.call(this, n)), i("Added image #" + t.length, "string" == typeof r ? r.substring(0, 100) : r)); }, this); } }, r.prototype.hasImageBackground = function (t) { return "none" !== t.method }, r.prototype.loadImage = function (t) { if ("url" === t.method) { var e = t.args[0]; return !this.isSVG(e) || this.support.svg || this.options.allowTaint ? e.match(/data:image\/.*;base64,/i) ? new o(e.replace(/url\(['"]{0,}|['"]{0,}\)$/gi, ""), !1) : this.isSameOrigin(e) || !0 === this.options.allowTaint || this.isSVG(e) ? new o(e, !1) : this.support.cors && !this.options.allowTaint && this.options.useCORS ? new o(e, !0) : this.options.proxy ? new s(e, this.options.proxy) : new a(e) : new l(e) } return "linear-gradient" === t.method ? new h(t) : "gradient" === t.method ? new f(t) : "svg" === t.method ? new u(t.args[0], this.support.svg) : "IFRAME" === t.method ? new c(t.args[0], this.isSameOrigin(t.args[0].src), this.options) : new a(t) }, r.prototype.isSVG = function (t) { return "svg" === t.substring(t.length - 3).toLowerCase() || l.prototype.isInline(t) }, r.prototype.imageExists = function (t, e) { return t.some(function (t) { return t.src === e }) }, r.prototype.isSameOrigin = function (t) { return this.getOrigin(t) === this.origin }, r.prototype.getOrigin = function (t) { var e = this.link || (this.link = document.createElement("a")); return e.href = t, e.href = e.href, e.protocol + e.hostname + e.port }, r.prototype.getPromise = function (t) { return this.timeout(t, this.options.imageTimeout).catch(function () { return new a(t.src).promise.then(function (e) { t.image = e; }) }) }, r.prototype.get = function (t) { var e = null; return this.images.some(function (n) { return (e = n).src === t }) ? e : null }, r.prototype.fetch = function (t) { return this.images = t.reduce(d(this.findBackgroundImage, this), this.findImages(t)), this.images.forEach(function (t, e) { t.promise.then(function () { i("Succesfully loaded image #" + (e + 1), t); }, function (n) { i("Failed loading image #" + (e + 1), t, n); }); }), this.ready = Promise.all(this.images.map(this.getPromise, this)), i("Finished searching images"), this }, r.prototype.timeout = function (t, e) { var n, r = Promise.race([t.promise, new Promise(function (r, o) { n = setTimeout(function () { i("Timed out loading image", t), o(t); }, e); })]).then(function (t) { return clearTimeout(n), t }); return r.catch(function () { clearTimeout(n); }), r }, e.exports = r; }, { "./dummyimagecontainer": 5, "./framecontainer": 8, "./imagecontainer": 10, "./lineargradientcontainer": 12, "./log": 13, "./proxyimagecontainer": 17, "./svgcontainer": 23, "./svgnodecontainer": 24, "./utils": 26, "./webkitgradientcontainer": 27 }], 12: [function (t, e, n) { function r(t) { i.apply(this, arguments), this.type = i.TYPES.LINEAR; var e = r.REGEXP_DIRECTION.test(t.args[0]) || !i.REGEXP_COLORSTOP.test(t.args[0]); e ? t.args[0].split(/\s+/).reverse().forEach(function (t, e) { switch (t) { case "left"
7599: this.x0 = 0, this.x1 = 1; break; case "top": this.y0 = 0, this.y1 = 1; break; case "right": this.x0 = 1, this.x1 = 0; break; case "bottom": this.y0 = 1, this.y1 = 0; break; case "to": var n = this.y0, r = this.x0; this.y0 = this.y1, this.x0 = this.x1, this.x1 = r, this.y1 = n; break; case "center": break; default: var i = .01 * parseFloat(t, 10); if (isNaN(i)) break; 0 === e ? (this.y0 = i, this.y1 = 1 - this.y0) : (this.x0 = i, this.x1 = 1 - this.x0); } }, this) : (this.y0 = 0, this.y1 = 1), this.colorStops = t.args.slice(e ? 1 : 0).map(function (t) { var e = t.match(i.REGEXP_COLORSTOP), n = +e[2], r = 0 === n ? "%" : e[3]; return { color: new o(e[1]), stop: "%" === r ? n / 100 : null } }), null === this.colorStops[0].stop && (this.colorStops[0].stop = 0), null === this.colorStops[this.colorStops.length - 1].stop && (this.colorStops[this.colorStops.length - 1].stop = 1), this.colorStops.forEach(function (t, e) { null === t.stop && this.colorStops.slice(e).some(function (n, r) { return null !== n.stop && (t.stop = (n.stop - this.colorStops[e - 1].stop) / (r + 1) + this.colorStops[e - 1].stop, !0) }, this); }, this); } var i = t("./gradientcontainer"), o = t("./color"); r.prototype = Object.create(i.prototype), r.REGEXP_DIRECTION = /^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i, e.exports = r; }, { "./color": 3, "./gradientcontainer": 9 }], 13: [function (t, e, n) { var r = function () { r.options.logging && window.console && window.console.log && Function.prototype.bind.call(window.console.log, window.console).apply(window.console, [Date.now() - r.options.start + "ms", "html2canvas:"].concat([].slice.call(arguments, 0))); }; r.options = { logging: !1 }, e.exports = r; }, {}], 14: [function (t, e, n) { function r(t, e) { this.node = t, this.parent = e, this.stack = null, this.bounds = null, this.borders = null, this.clip = [], this.backgroundClip = [], this.offsetBounds = null, this.visible = null, this.computedStyles = null, this.colors = {}, this.styles = {}, this.backgroundImages = null, this.transformData = null, this.transformMatrix = null, this.isPseudoElement = !1, this.opacity = null; } function i(t) { var e = t.options[t.selectedIndex || 0]; return e ? e.text || "" : "" } function o(t) { if (t && "matrix" === t[1]) return t[2].split(",").map(function (t) { return parseFloat(t.trim()) }); if (t && "matrix3d" === t[1]) { var e = t[2].split(",").map(function (t) { return parseFloat(t.trim()) }); return [e[0], e[1], e[4], e[5], e[12], e[13]] } } function a(t) { return -1 !== t.toString().indexOf("%") } function s(t) { return t.replace("px", "") } function c(t) { return parseFloat(t) } var l = t("./color"), u = t("./utils"), h = u.getBounds, f = u.parseBackgrounds, d = u.offsetBounds; r.prototype.cloneTo = function (t) { t.visible = this.visible, t.borders = this.borders, t.bounds = this.bounds, t.clip = this.clip, t.backgroundClip = this.backgroundClip, t.computedStyles = this.computedStyles, t.styles = this.styles, t.backgroundImages = this.backgroundImages, t.opacity = this.opacity; }, r.prototype.getOpacity = function () { return null === this.opacity ? this.opacity = this.cssFloat("opacity") : this.opacity }, r.prototype.assignStack = function (t) { this.stack = t, t.children.push(this); }, r.prototype.isElementVisible = function () { return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : "none" !== this.css("display") && "hidden" !== this.css("visibility") && !this.node.hasAttribute("data-html2canvas-ignore") && ("INPUT" !== this.node.nodeName || "hidden" !== this.node.getAttribute("type")) }, r.prototype.css = function (t) { return this.computedStyles || (this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null)), this.styles[t] || (this.styles[t] = this.computedStyles[t]) }, r.prototype.prefixedCss = function (t) { var e = ["webkit", "moz", "ms", "o"], n = this.css(t); return void 0 === n && e.some(function (e) { return void 0 !== (n = this.css(e + t.substr(0, 1).toUpperCase() + t.substr(1))) }, this), void 0 === n ? null : n }, r.prototype.computedStyle = function (t) { return this.node.ownerDocument.defaultView.getComputedStyle(this.node, t) }, r.prototype.cssInt = function (t) { var e = parseInt(this.css(t), 10); return isNaN(e) ? 0 : e }, r.prototype.color = function (t) { return this.colors[t] || (this.colors[t] = new l(this.css(t))) }, r.prototype.cssFloat = function (t) { var e = parseFloat(this.css(t)); return isNaN(e) ? 0 : e }, r.prototype.fontWeight = function () { var t = this.css("fontWeight"); switch (parseInt(t, 10)) { case 401: t = "bold"; break; case 400: t = "normal"; }return t }, r.prototype.parseClip = function () { var t = this.css("clip").match(this.CLIP); return t ? { top: parseInt(t[1], 10), right: parseInt(t[2], 10), bottom: parseInt(t[3], 10), left: parseInt(t[4], 10) } : null }
vendor: 11,921 bytes, line 7599
7599, r.prototype.parseBackgroundImages = function () { return this.backgroundImages || (this.backgroundImages = f(this.css("backgroundImage"))) }, r.prototype.cssList = function (t, e) { var n = (this.css(t) || "").split(","); return n = n[e || 0] || n[0] || "auto", 1 === (n = n.trim().split(" ")).length && (n = [n[0], a(n[0]) ? "auto" : n[0]]), n }, r.prototype.parseBackgroundSize = function (t, e, n) { var r, i, o = this.cssList("backgroundSize", n); if (a(o[0])) r = t.width * parseFloat(o[0]) / 100; else { if (/contain|cover/.test(o[0])) { var s = t.width / t.height, c = e.width / e.height; return s < c ^ "contain" === o[0] ? { width: t.height * c, height: t.height } : { width: t.width, height: t.width / c } } r = parseInt(o[0], 10); } return i = "auto" === o[0] && "auto" === o[1] ? e.height : "auto" === o[1] ? r / e.width * e.height : a(o[1]) ? t.height * parseFloat(o[1]) / 100 : parseInt(o[1], 10), "auto" === o[0] && (r = i / e.height * e.width), { width: r, height: i } }, r.prototype.parseBackgroundPosition = function (t, e, n, r) { var i, o, s = this.cssList("backgroundPosition", n); return i = a(s[0]) ? (t.width - (r || e).width) * (parseFloat(s[0]) / 100) : parseInt(s[0], 10), o = "auto" === s[1] ? i / e.width * e.height : a(s[1]) ? (t.height - (r || e).height) * parseFloat(s[1]) / 100 : parseInt(s[1], 10), "auto" === s[0] && (i = o / e.height * e.width), { left: i, top: o } }, r.prototype.parseBackgroundRepeat = function (t) { return this.cssList("backgroundRepeat", t)[0] }, r.prototype.parseTextShadows = function () { var t = this.css("textShadow"), e = []; if (t && "none" !== t) for (var n = t.match(this.TEXT_SHADOW_PROPERTY), r = 0; n && r < n.length; r++) { var i = n[r].match(this.TEXT_SHADOW_VALUES); e.push({ color: new l(i[0]), offsetX: i[1] ? parseFloat(i[1].replace("px", "")) : 0, offsetY: i[2] ? parseFloat(i[2].replace("px", "")) : 0, blur: i[3] ? i[3].replace("px", "") : 0 }); } return e }, r.prototype.parseTransform = function () { if (!this.transformData) if (this.hasTransform()) { var t = this.parseBounds(), e = this.prefixedCss("transformOrigin").split(" ").map(s).map(c); e[0] += t.left, e[1] += t.top, this.transformData = { origin: e, matrix: this.parseTransformMatrix() }; } else this.transformData = { origin: [0, 0], matrix: [1, 0, 0, 1, 0, 0] }; return this.transformData }, r.prototype.parseTransformMatrix = function () { if (!this.transformMatrix) { var t = this.prefixedCss("transform"), e = t ? o(t.match(this.MATRIX_PROPERTY)) : null; this.transformMatrix = e || [1, 0, 0, 1, 0, 0]; } return this.transformMatrix }, r.prototype.parseBounds = function () { return this.bounds || (this.bounds = this.hasTransform() ? d(this.node) : h(this.node)) }, r.prototype.hasTransform = function () { return "1,0,0,1,0,0" !== this.parseTransformMatrix().join(",") || this.parent && this.parent.hasTransform() }, r.prototype.getValue = function () { var t = this.node.value || ""; return "SELECT" === this.node.tagName ? t = i(this.node) : "password" === this.node.type && (t = Array(t.length + 1).join("•")), 0 === t.length ? this.node.placeholder || "" : t }, r.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/, r.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g, r.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g, r.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/, e.exports = r; }, { "./color": 3, "./utils": 26 }], 15: [function (t, e, n) { function r(t, e, n, r, i) { L("Starting NodeParser"), this.renderer = e, this.options = i, this.range = null, this.support = n, this.renderQueue = [], this.stack = new G(!0, 1, t.ownerDocument, null); var o = new U(t, null); if (i.background && e.rectangle(0, 0, e.width, e.height, new V(i.background)), t === t.ownerDocument.documentElement) { var a = new U(o.color("backgroundColor").isTransparent() ? t.ownerDocument.body : t.ownerDocument.documentElement, null); e.rectangle(0, 0, e.width, e.height, a.color("backgroundColor")); } o.visibile = o.isElementVisible(), this.createPseudoHideStyles(t.ownerDocument), this.disableAnimations(t.ownerDocument), this.nodes = R([o].concat(this.getChildren(o)).filter(function (t) { return t.visible = t.isElementVisible() }).map(this.getPseudoElements, this)), this.fontMetrics = new X, L("Fetched nodes, total:", this.nodes.length), L("Calculate overflow clips"), this.calculateOverflowClips(), L("Start fetching images"), this.images = r.fetch(this.nodes.filter(q)), this.ready = this.images.ready.then(J(function () { return L("Images loaded, starting parsing"), L("Creating stacking contexts"), this.createStackingContexts(), L("Sorting stacking contexts"), this.sortStackingContexts(this.stack), this.parse(this.stack), L("Render queue created with " + this.renderQueue.length + " items"), new Promise(J(function (t) { i.async ? "function" == typeof i.async ? i.async.call(this, this.renderQueue, t) : this.renderQueue.length > 0 ? (this.renderIndex = 0, this.asyncRenderer(this.renderQueue, t)) : t() : (this.renderQueue.forEach(this.paint, this), t()); }, this)) }, this)); } function i(t) { return t.parent && t.parent.clip.length } function o(t) { return t.replace(/(\-[a-z])/g, function (t) { return t.toUpperCase().replace("-", "") }) } function a() { } function s(t, e, n, r) { return t.map(function (i, o) { if (i.width > 0) { var a = e.left, s = e.top, c = e.width, l = e.height - t[2].width; switch (o) { case 0: l = t[0].width, i.args = h({ c1: [a, s], c2: [a + c, s], c3: [a + c - t[1].width, s + l], c4: [a + t[3].width, s + l] }, r[0], r[1], n.topLeftOuter, n.topLeftInner, n.topRightOuter, n.topRightInner); break; case 1: a = e.left + e.width - t[1].width, c = t[1].width, i.args = h({ c1: [a + c, s], c2: [a + c, s + l + t[2].width], c3: [a, s + l], c4: [a, s + t[0].width] }, r[1], r[2], n.topRightOuter, n.topRightInner, n.bottomRightOuter, n.bottomRightInner); break; case 2: s = s + e.height - t[2].width, l = t[2].width, i.args = h({ c1: [a + c, s + l], c2: [a, s + l], c3: [a + t[3].width, s], c4: [a + c - t[3].width, s] }, r[2], r[3], n.bottomRightOuter, n.bottomRightInner, n.bottomLeftOuter, n.bottomLeftInner); break; case 3: c = t[3].width, i.args = h({ c1: [a, s + l + t[2].width], c2: [a, s], c3: [a + c, s + t[0].width], c4: [a + c, s + l] }, r[3], r[0], n.bottomLeftOuter, n.bottomLeftInner, n.topLeftOuter, n.topLeftInner); } } return i }) } function c(t, e, n, r) { var i = (Math.sqrt(2) - 1) / 3 * 4, o = n * i, a = r * i, s = t + n, c = e + r; return { topLeft: u({ x: t, y: c }, { x: t, y: c - a }, { x: s - o, y: e }, { x: s, y: e }), topRight: u({ x: t, y: e }, { x: t + o, y: e }, { x: s, y: c - a }, { x: s, y: c }), bottomRight: u({ x: s, y: e }, { x: s, y: e + a }, { x: t + o, y: c }, { x: t, y: c }), bottomLeft: u({ x: s, y: c }, { x: s - o, y: c }, { x: t, y: e + a }, { x: t, y: e }) } } function l(t, e, n) { var r = t.left, i = t.top, o = t.width, a = t.height, s = e[0][0] < o / 2 ? e[0][0] : o / 2, l = e[0][1] < a / 2 ? e[0][1] : a / 2, u = e[1][0] < o / 2 ? e[1][0] : o / 2, h = e[1][1] < a / 2 ? e[1][1] : a / 2, f = e[2][0] < o / 2 ? e[2][0] : o / 2, d = e[2][1] < a / 2 ? e[2][1] : a / 2, p = e[3][0] < o / 2 ? e[3][0] : o / 2, m = e[3][1] < a / 2 ? e[3][1] : a / 2, g = o - u, w = a - d, y = o - f, v = a - m; return { topLeftOuter: c(r, i, s, l).topLeft.subdivide(.5), topLeftInner: c(r + n[3].width, i + n[0].width, Math.max(0, s - n[3].width), Math.max(0, l - n[0].width)).topLeft.subdivide(.5), topRightOuter: c(r + g, i, u, h).topRight.subdivide(.5), topRightInner: c(r + Math.min(g, o + n[3].width), i + n[0].width, g > o + n[3].width ? 0 : u - n[3].width, h - n[0].width).topRight.subdivide(.5), bottomRightOuter: c(r + y, i + w, f, d).bottomRight.subdivide(.5), bottomRightInner: c(r + Math.min(y, o - n[3].width), i + Math.min(w, a + n[0].width), Math.max(0, f - n[1].width), d - n[2].width).bottomRight.subdivide(.5), bottomLeftOuter: c(r, i + v, p, m).bottomLeft.subdivide(.5), bottomLeftInner: c(r + n[3].width, i + v, Math.max(0, p - n[3].width), m - n[2].width).bottomLeft.subdivide(.5) } } function u(t, e, n, r) { var i = function (t, e, n) { return { x: t.x + (e.x - t.x) * n, y: t.y + (e.y - t.y) * n } }; return { start: t, startControl: e, endControl: n, end: r, subdivide: function (o) { var a = i(t, e, o), s = i(e, n, o), c = i(n, r, o), l = i(a, s, o), h = i(s, c, o), f = i(l, h, o); return [u(t, a, l, f), u(f, h, c, r)] }, curveTo: function (t) { t.push(["bezierCurve", e.x, e.y, n.x, n.y, r.x, r.y]); }, curveToReversed: function (r) { r.push(["bezierCurve", n.x, n.y, e.x, e.y, t.x, t.y]); } } } function h(t, e, n, r, i, o, a) { var s = []; return e[0] > 0 || e[1] > 0 ? (s.push(["line", r[1].start.x, r[1].start.y]), r[1].curveTo(s)) : s.push(["line", t.c1[0], t.c1[1]]), n[0] > 0 || n[1] > 0 ? (s.push(["line", o[0].start.x, o[0].start.y]), o[0].curveTo(s), s.push(["line", a[0].end.x, a[0].end.y]), a[0].curveToReversed(s)) : (s.push(["line", t.c2[0], t.c2[1]]), s.push(["line", t.c3[0], t.c3[1]])), e[0] > 0 || e[1] > 0 ? (s.push(["line", i[1].end.x, i[1].end.y]), i[1].curveToReversed(s)) : s.push(["line", t.c4[0], t.c4[1]]), s } function f(t, e, n, r, i, o, a) { e[0] > 0 || e[1] > 0 ? (t.push(["line", r[0].start.x, r[0].start.y]), r[0].curveTo(t), r[1].curveTo(t)) : t.push(["line", o, a]), (n[0] > 0 || n[1] > 0) && t.push(["line", i[0].start.x, i[0].start.y]); } function d(t) { return t.cssInt("zIndex") < 0 } function p(t) { return t.cssInt("zIndex") > 0 } function m(t) { return 0 === t.cssInt("zIndex") } function g(t) { return -1 !== ["inline", "inline-block", "inline-table"].indexOf(t.css("display")) } function w(t) { return t instanceof G } function y(t) { return t.node.data.trim().length > 0 } function v(t) { return /^(normal|none|0px)$/.test(t.parent.css("letterSpacing")) } function b(t) { return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function (e) { var n = t.css("border" + e + "Radius").split(" "); return n.length <= 1 && (n[1] = n[0]), n.map(O) }) } function x(t) { return t.nodeType === Node.TEXT_NODE || t.nodeType === Node.ELEMENT_NODE } function k(t) { var e = t.css("position"); return "auto" !== (-1 !== ["absolute", "relative", "fixed"].indexOf(e) ? t.css("zIndex") : "auto") } function _(t) { return "static" !== t.css("position") } function C(t) { return "none" !== t.css("float") } function A(t) { return -1 !== ["inline-block", "inline-table"].indexOf(t.css("display")) } function S(t) { var e = this; return function () { return !t.apply(e, arguments) } } function q(t) { return t.node.nodeType === Node.ELEMENT_NODE } function T(t) { return !0 === t.isPseudoElement } function P(t) { return t.node.nodeType === Node.TEXT_NODE } function I(t) { return function (e, n) { return e.cssInt("zIndex") + t.indexOf(e) / t.length - (n.cssInt("zIndex") + t.indexOf(n) / t.length) } } function E(t) { return t.getOpacity() < 1 } function O(t) { return parseInt(t, 10) } function F(t) { return t.width } function B(t) { return t.node.nodeType !== Node.ELEMENT_NODE || -1 === ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(t.node.nodeName) } function R(t) { return [].concat.apply([], t) } function D(t) { var e = t.substr(0, 1); return e === t.substr(t.length - 1) && e.match(/'|"/) ? t.substr(1, t.length - 2) : t } function j(t) { for (var e, n = [], r = 0, i = !1; t.length;)z(t[r]) === i ? ((e = t.splice(0, r)).length && n.push(M.ucs2.encode(e)), i = !i, r = 0) : r++, r >= t.length && (e = t.splice(0, r)).length && n.push(M.ucs2.encode(e)); return n } function z(t) { return -1 !== [32, 13, 10, 9, 45].indexOf(t) } function N(t) { return /[^\u0000-\u00ff]/.test(t) } var L = t("./log"), M = t("punycode"), U = t("./nodecontainer"), H = t("./textcontainer"), W = t("./pseudoelementcontainer"), X = t("./fontmetrics"), V = t("./color"), G = t("./stackingcontext"), Y = t("./utils"), J = Y.bind, Q = Y.getBounds, K = Y.parseBackgroun
7599ds, $ = Y.offsetBounds; r.prototype.calculateOverflowClips = function () { this.nodes.forEach(function (t) { if (q(t)) { T(t) && t.appendToDOM(), t.borders = this.parseBorders(t); var e = "hidden" === t.css("overflow") ? [t.borders.clip] : [], n = t.parseClip(); n && -1 !== ["absolute", "fixed"].indexOf(t.css("position")) && e.push([["rect", t.bounds.left + n.left, t.bounds.top + n.top, n.right - n.left, n.bottom - n.top]]), t.clip = i(t) ? t.parent.clip.concat(e) : e, t.backgroundClip = "hidden" !== t.css("overflow") ? t.clip.concat([t.borders.clip]) : t.clip, T(t) && t.cleanDOM(); } else P(t) && (t.clip = i(t) ? t.parent.clip : []); T(t) || (t.bounds = null); }, this); }, r.prototype.asyncRenderer = function (t, e, n) { n = n || Date.now(), this.paint(t[this.renderIndex++]), t.length === this.renderIndex ? e() : n + 20 > Date.now() ? this.asyncRenderer(t, e, n) : setTimeout(J(function () { this.asyncRenderer(t, e); }, this), 0); }, r.prototype.createPseudoHideStyles = function (t) { this.createStyles(t, "." + W.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }.' + W.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }'); }, r.prototype.disableAnimations = function (t) { this.createStyles(t, "* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; -webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}"); }, r.prototype.createStyles = function (t, e) { var n = t.createElement("style"); n.innerHTML = e, t.body.appendChild(n); }, r.prototype.getPseudoElements = function (t) { var e = [[t]]; if (t.node.nodeType === Node.ELEMENT_NODE) { var n = this.getPseudoElement(t, ":before"), r = this.getPseudoElement(t, ":after"); n && e.push(n), r && e.push(r); } return R(e) }, r.prototype.getPseudoElement = function (t, e) { var n = t.computedStyle(e); if (!n || !n.content || "none" === n.content || "-moz-alt-content" === n.content || "none" === n.display) return null; for (var r = D(n.content), i = "url" === r.substr(0, 3), a = document.createElement(i ? "img" : "html2canvaspseudoelement"), s = new W(a, t, e), c = n.length - 1; c >= 0; c--) { var l = o(n.item(c)); a.style[l] = n[l]; } if (a.className = W.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + W.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER, i) return a.src = K(r)[0].args[0], [s]; var u = document.createTextNode(r); return a.appendChild(u), [s, new H(u, s)] }, r.prototype.getChildren = function (t) { return R([].filter.call(t.node.childNodes, x).map(function (e) { var n = [e.nodeType === Node.TEXT_NODE ? new H(e, t) : new U(e, t)].filter(B); return e.nodeType === Node.ELEMENT_NODE && n.length && "TEXTAREA" !== e.tagName ? n[0].isElementVisible() ? n.concat(this.getChildren(n[0])) : [] : n }, this)) }, r.prototype.newStackingContext = function (t, e) { var n = new G(e, t.getOpacity(), t.node, t.parent); t.cloneTo(n), (e ? n.getParentStack(this) : n.parent.stack).contexts.push(n), t.stack = n; }, r.prototype.createStackingContexts = function () { this.nodes.forEach(function (t) { q(t) && (this.isRootElement(t) || E(t) || k(t) || this.isBodyWithTransparentRoot(t) || t.hasTransform()) ? this.newStackingContext(t, !0) : q(t) && (_(t) && m(t) || A(t) || C(t)) ? this.newStackingContext(t, !1) : t.assignStack(t.parent.stack); }, this); }, r.prototype.isBodyWithTransparentRoot = function (t) { return "BODY" === t.node.nodeName && t.parent.color("backgroundColor").isTransparent() }, r.prototype.isRootElement = function (t) { return null === t.parent }, r.prototype.sortStackingContexts = function (t) { t.contexts.sort(I(t.contexts.slice(0))), t.contexts.forEac
vendor: 4,585 bytes, line 7599
7599h(this.sortStackingContexts, this); }, r.prototype.parseTextBounds = function (t) { return function (e, n, r) { if ("none" !== t.parent.css("textDecoration").substr(0, 4) || 0 !== e.trim().length) { if (this.support.rangeBounds && !t.parent.hasTransform()) { var i = r.slice(0, n).join("").length; return this.getRangeBounds(t.node, i, e.length) } if (t.node && "string" == typeof t.node.data) { var o = t.node.splitText(e.length), a = this.getWrapperBounds(t.node, t.parent.hasTransform()); return t.node = o, a } } else this.support.rangeBounds && !t.parent.hasTransform() || (t.node = t.node.splitText(e.length)); return {} } }, r.prototype.getWrapperBounds = function (t, e) { var n = t.ownerDocument.createElement("html2canvaswrapper"), r = t.parentNode, i = t.cloneNode(!0); n.appendChild(t.cloneNode(!0)), r.replaceChild(n, t); var o = e ? $(n) : Q(n); return r.replaceChild(i, n), o }, r.prototype.getRangeBounds = function (t, e, n) { var r = this.range || (this.range = t.ownerDocument.createRange()); return r.setStart(t, e), r.setEnd(t, e + n), r.getBoundingClientRect() }, r.prototype.parse = function (t) { var e = t.contexts.filter(d), n = t.children.filter(q), r = n.filter(S(C)), i = r.filter(S(_)).filter(S(g)), o = n.filter(S(_)).filter(C), s = r.filter(S(_)).filter(g), c = t.contexts.concat(r.filter(_)).filter(m), l = t.children.filter(P).filter(y), u = t.contexts.filter(p); e.concat(i).concat(o).concat(s).concat(c).concat(l).concat(u).forEach(function (t) { this.renderQueue.push(t), w(t) && (this.parse(t), this.renderQueue.push(new a)); }, this); }, r.prototype.paint = function (t) { try { t instanceof a ? this.renderer.ctx.restore() : P(t) ? (T(t.parent) && t.parent.appendToDOM(), this.paintText(t), T(t.parent) && t.parent.cleanDOM()) : this.paintNode(t); } catch (t) { if (L(t), this.options.strict) throw t } }, r.prototype.paintNode = function (t) { w(t) && (this.renderer.setOpacity(t.opacity), this.renderer.ctx.save(), t.hasTransform() && this.renderer.setTransform(t.parseTransform())), "INPUT" === t.node.nodeName && "checkbox" === t.node.type ? this.paintCheckbox(t) : "INPUT" === t.node.nodeName && "radio" === t.node.type ? this.paintRadio(t) : this.paintElement(t); }, r.prototype.paintElement = function (t) { var e = t.parseBounds(); this.renderer.clip(t.backgroundClip, function () { this.renderer.renderBackground(t, e, t.borders.borders.map(F)); }, this), this.renderer.clip(t.clip, function () { this.renderer.renderBorders(t.borders.borders); }, this), this.renderer.clip(t.backgroundClip, function () { switch (t.node.nodeName) { case "svg": case "IFRAME": var n = this.images.get(t.node); n ? this.renderer.renderImage(t, e, t.borders, n) : L("Error loading <" + t.node.nodeName + ">", t.node); break; case "IMG": var r = this.images.get(t.node.src); r ? this.renderer.renderImage(t, e, t.borders, r) : L("Error loading <img>", t.node.src); break; case "CANVAS": this.renderer.renderImage(t, e, t.borders, { image: t.node }); break; case "SELECT": case "INPUT": case "TEXTAREA": this.paintFormValue(t); } }, this); }, r.prototype.paintCheckbox = function (t) { var e = t.parseBounds(), n = Math.min(e.width, e.height), r = { width: n - 1, height: n - 1, top: e.top, left: e.left }, i = [3, 3], o = [i, i, i, i], a = [1, 1, 1, 1].map(function (t) { return { color: new V("#A5A5A5"), width: t } }), c = l(r, o, a); this.renderer.clip(t.backgroundClip, function () { this.renderer.rectangle(r.left + 1, r.top + 1, r.width - 2, r.height - 2, new V("#DEDEDE")), this.renderer.renderBorders(s(a, r, c, o)), t.node.checked && (this.renderer.font(new V("#424242"), "normal", "normal", "bold", n - 3 + "px", "arial"), this.renderer.text("✔", r.left + n / 6, r.top + n - 1)); }, this); }, r.prototype.paintRadio = function (t) { var e = t.parseBounds(), n = Math.min(e.width, e.height) - 2; this.renderer.clip(t.backgroundClip, function () { this.renderer.circleStroke(e.left + 1, e.top + 1, n, new V("#DEDEDE"), 1, new V("#A5A5A5")), t.node.checked && this.renderer.circle(Math.ceil(e.left + n / 4) + 1, Math.ceil(e.top + n / 4) + 1, Math.floor(n / 2), new V("#424242")); }, this); }, r.prototype.paintFormValue = function (t) { var e = t.getValue(); if (e.length > 0) { var n = t.node.ownerDocument, r = n.createElement("html2canvaswrapper");["lineHeight", "textAlign", "fontFamily", "fontWeight", "fontSize", "color", "paddingLeft", "paddingTop", "paddingRight", "paddingBottom", "width", "height", "borderLeftStyle", "borderTopStyle", "borderLeftWidth", "borderTopWidth", "boxSizing", "whiteSpace", "wordWrap"].forEach(function (e) { tr
7599y { r.style[e] = t.css(e); } catch (t) { L("html2canvas: Parse: Exception caught in renderFormValue: " + t.message); } }); var i = t.parseBounds(); r.style.position = "fixed", r.style.left = i.left + "px", r.style.top = i.top + "px", r.textContent = e, n.body.appendChild(r), this.paintText(new H(r.firstChild, t)), n.body.removeChild(r); } }, r.prototype.paintText = function (t) { t.applyTextTransform(); var e = M.ucs2.decode(t.node.data), n = this.options.letterRendering && !v(t) || N(t.node.data) ? e.map(function (t) { return M.ucs2.encode([t]) }) : j(e), r = t.parent.fontWeight(), i = t.parent.css("fontSize"), o = t.parent.css("fontFamily"), a = t.parent.parseTextShadows(); this.renderer.font(t.parent.color("color"), t.parent.css("fontStyle"), t.parent.css("fontVariant"), r, i, o), a.length ? this.renderer.fontShadow(a[0].color, a[0].offsetX, a[0].offsetY, a[0].blur) : this.renderer.clearShadow(), this.renderer.clip(t.parent.clip, function () { n.map(this.parseTextBounds(t), this).forEach(function (e, r) { e && (this.renderer.text(n[r], e.left, e.bottom), this.renderTextDecoration(t.parent, e, this.fontMetrics.getMetrics(o, i))); }, this); }, this); }, r.prototype.renderTextDecoration = function (t, e, n) { switch (t.css("textDecoration").split(" ")[0]) { case "underline": this.renderer.rectangle(e.left, Math.round(e.top + n.baseline + n.lineWidth), e.width, 1, t.color("color")); break; case "overline": this.renderer.rectangle(e.left, Math.round(e.top), e.width, 1, t.color("color")); break; case "line-through": this.renderer.rectangle(e.left, Math.ceil(e.top + n.middle + n.lineWidth), e.width, 1, t.color("color")); } }; var Z = { inset: [["darken", .6], ["darken", .1], ["darken", .1], ["darken", .6]] }; r.prototype.parseBorders = function (t) { var e = t.parseBounds(), n = b(t), r = ["Top", "Right", "Bottom", "Left"].map(function (e, n) { var r = t.css("border" + e + "Style"), i = t.color("border" + e + "Color"); "inset" === r && i.isBlack() && (i = new V([255, 255, 255, i.a])); var o = Z[r] ? Z[r][n] : null; return { width: t.cssInt("border" + e + "Width"), color: o ? i[o[0]](o[1]) : i, args: null } }), i = l(e, n, r); return { clip: this.parseBackgroundClip(t, i, r, n, e), borders: s(r, e, i, n) } }, r.prototype.parseBackgroundClip = function (t, e, n, r, i) { var o = []; switch (t.css("backgroundClip")) { case "content-box": case "padding-box": f(o, r[0], r[1], e.topLeftInner, e.topRightInner, i.left + n[3].width, i.top + n[0].width), f(o, r[1], r[2], e.topRightInner, e.bottomRightInner, i.left + i.width - n[1].width, i.top + n[0].width), f(o, r[2], r[3], e.bottomRightInner, e.bottomLeftInner, i.left + i.width - n[1].width, i.top + i.height - n[2].width), f(o, r[3], r[0], e.bottomLeftInner, e.topLeftInner, i.left + n[3].width, i.top + i.height - n[2].width); break; default: f(o, r[0], r[1], e.topLeftOuter, e.topRightOuter, i.left, i.top), f(o, r[1], r[2], e.topRightOuter, e.bottomRightOuter, i.left + i.width, i.top), f(o, r[2], r[3], e.bottomRightOuter, e.bottomLeftOuter, i.left + i.width, i.top + i.height), f(o, r[3], r[0], e.bottomLeftOuter, e.topLeftOuter, i.left, i.top + i.height); }return o }, e.exports = r; }, { "./color": 3, "./fontmetrics": 7, "./log": 13, "./nodecontainer": 14, "./pseudoelementcontainer": 18, "./stackingcontext": 21, "./textcontainer": 25, "./utils": 26, punycode: 1 }], 16: [function (t, e, n) { function r(t, e, n) { var r = "withCredentials" in new XMLHttpRequest; if (!e) return Promise.reject("No proxy configured"); var s = o(r), l = a(e, t, s); return r ? c(l) : i(n, l, s).then(function (t) { return f(t.content) }) } function i(t, e, n) { return new Promise(function (r, i) { var o = t.createElement("script"), a = function () { delete window.html2canvas.proxy[n], t.body.removeChild(o); }; window.html2canvas.proxy[n] = function (t) { a(), r(t); }, o.src = e, o.onerror = function (t) { a(), i(t); }, t.body.appendChild(o); }) } function o(t) { return t ? "" : "html2canvas_" + Date.now() + "_" + ++d + "_" + Math.round(1e5 * Math.random()) } function a(t, e, n) { return t + "?url=" + encodeURIComponent(e) + (n.length ? "&callback=html2canvas.proxy." + n : "") } function s(t) { return function (e) { var n, r = new DOMParser; try { n = r.parseFromString(e, "text/html"); } catch (t) { u("DOMParser not supported, falling back to createHTMLDocument"), n = document.implementation.createHTMLDocument(""); try { n.open(), n.write(e), n.close(); } catch (t) { u("createHTMLDocument write not supported, falling back to document.body.innerHTML"), n.body.innerHTML = e; } } var i = n.querySelector("base"); if (!i || !i.href.host) { var o = n.createElement("base"); o.href = t, n.head.insertBefore(o, n.head.firstChild); } return n } } var c = t("./xhr"), l = t("./utils"), u = t("./log"), h = t("./clone"), f = l.decode64, d = 0; n.Proxy = r, n.ProxyURL = function (t, e, n) { var r = "crossOrigin" in new Image, s = o(r), c = a(e, t, s); return r ? Promise.resolve(c) : i(n, c, s).then(function (t) { return "data:" + t.type + ";base64," + t.content }) }, n.loadUrlDocument = function (t, e, n, i, o, a) { return new r(t, e, window.document).then(s(t)).then(function (t) { return h(t, n, i, o, a, 0, 0) }) }; }, { "./clone": 2, "./log": 13, "./utils": 26, "./xhr": 28 }], 17: [function (t, e, n) { var r = t("./proxy").ProxyURL; e.exports = function (t, e) { var n = document.createElement("a"); n.href = t, t = n.href, this.src = t, this.image = new Image; var i = this; this.promise = new Promise(function (n, o) { i.image.crossOrigin = "Anonymous", i.image.onload = n, i.image.onerror = o, new r(t, e, document).then(function (t) { i.image.src = t; }).catch(o); }); }; }, { "./proxy": 16 }], 18: [function (t, e, n) { function r(t, e, n) { i.call(this, t, e), this.isPseudoElement = !0, this.before = ":before" === n; } var i = t("./nodecontainer"); r.prototype.cloneTo = function (t) { r.prototype.cloneTo.call(this, t), t.isPseudoElement = !0, t.before = this.before; }, (r.prototype = Object.create(i.prototype)).appendToDOM = function () { this.before ? this.parent.node.insertBefore(this.node, this.parent.node.firstChild) : this.parent.node.appendChild(this.node), this.parent.node.className += " " + this.getHideClass(); }, r.prototype.cleanDOM = function () { this.node.parentNode.removeChild(this.node), this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), ""); }, r.prototype.getHideClass = function () { return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")] }, r.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before", r.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after", e.exports = r; }, { "./nodecontainer": 14 }], 19: [function (t, e, n) { function r(t, e, n, r, i) { this.width = t, this.height = e, this.images = n, this.options = r, this.document = i; } var i = t("./log"); r.prototype.renderImage = function (t, e, n, r) { var i = t.cssInt("paddingLeft"), o = t.cssInt("paddingTop"), a = t.cssInt("paddingRight"), s = t.cssInt("paddingBottom"), c = n.borders, l = e.width - (c[1].width + c[3].width + i + a), u = e.height - (c[0].width + c[2].width + o + s); this.drawImage(r, 0, 0, r.image.width || l, r.image.height || u, e.left + i + c[3].width, e.top + o + c[0].width, l, u); }
7599, r.prototype.renderBackground = function (t, e, n) { e.height > 0 && e.width > 0 && (this.renderBackgroundColor(t, e), this.renderBackgroundImage(t, e, n)); }, r.prototype.renderBackgroundColor = function (t, e) { var n = t.color("backgroundColor"); n.isTransparent() || this.rectangle(e.left, e.top, e.width, e.height, n); }, r.prototype.renderBorders = function (t) { t.forEach(this.renderBorder, this); }, r.prototype.renderBorder = function (t) { t.color.isTransparent() || null === t.args || this.drawShape(t.args, t.color); }, r.prototype.renderBackgroundImage = function (t, e, n) { t.parseBackgroundImages().reverse().forEach(function (r, o, a) { switch (r.method) { case "url": var s = this.images.get(r.args[0]); s ? this.renderBackgroundRepeating(t, e, s, a.length - (o + 1), n) : i("Error loading background-image", r.args[0]); break; case "linear-gradient": case "gradient": var c = this.images.get(r.value); c ? this.renderBackgroundGradient(c, e, n) : i("Error loading background-image", r.args[0]); break; case "none": break; default: i("Unknown background-image type", r.args[0]); } }, this); }, r.prototype.renderBackgroundRepeating = function (t, e, n, r, i) { var o = t.parseBackgroundSize(e, n.image, r), a = t.parseBackgroundPosition(e, n.image, r, o); switch (t.parseBackgroundRepeat(r)) { case "repeat-x": case "repeat no-repeat": this.backgroundRepeatShape(n, a, o, e, e.left + i[3], e.top + a.top + i[0], 99999, o.height, i); break; case "repeat-y": case "no-repeat repeat": this.backgroundRepeatShape(n, a, o, e, e.left + a.left + i[3], e.top + i[0], o.width, 99999, i); break; case "no-repeat": this.backgroundRepeatShape(n, a, o, e, e.left + a.left + i[3], e.top + a.top + i[0], o.width, o.height, i); break; default: this.renderBackgroundRepeat(n, a, o, { top: e.top, left: e.left }, i[3], i[0]); } }, e.exports = r; }, { "./log": 13 }], 20: [function (t, e, n) { function r(t, e) { o.apply(this, arguments), this.canvas = this.options.canvas || this.document.createElement("canvas"), this.options.canvas || (this.canvas.width = t, this.canvas.height = e), this.ctx = this.canvas.getContext("2d"), this.taintCtx = this.document.createElement("canvas").getContext("2d"), this.ctx.textBaseline = "bottom", this.variables = {}, s("Initialized CanvasRenderer with size", t, "x", e); } function i(t) { return t.length > 0 } var o = t("../renderer"), a = t("../lineargradientcontainer"), s = t("../log"); (r.prototype = Object.create(o.prototype)).setFillStyle = function (t) { return this.ctx.fillStyle = "object" == typeof t && t.isColor ? t.toString() : t, this.ctx }, r.prototype.rectangle = function (t, e, n, r, i) { this.setFillStyle(i).fillRect(t, e, n, r); }, r.prototype.circle = function (t, e, n, r) { this.setFillStyle(r), this.ctx.beginPath(), this.ctx.arc(t + n / 2, e + n / 2, n / 2, 0, 2 * Math.PI, !0), this.ctx.closePath(), this.ctx.fill(); }, r.prototype.circleStroke = function (t, e, n, r, i, o) { this.circle(t, e, n, r), this.ctx.strokeStyle = o.toString(), this.ctx.stroke(); }, r.prototype.drawShape = function (t, e) { this.shape(t), this.setFillStyle(e).fill(); }, r.prototype.taints = function (t) { if (null === t.tainted) { this.taintCtx.drawImage(t.image, 0, 0); try { this.taintCtx.getImageData(0, 0, 1, 1), t.tainted = !1; } catch (e) { this.taintCtx = document.createElement("canvas").getContext("2d"), t.tainted = !0; } } return t.tainted }, r.prototype.drawImage = function (t, e, n, r, i, o, a, s, c) { this.taints(t) && !this.options.allowTaint || this.ctx.drawImage(t.image, e, n, r, i, o, a, s, c); }, r.prototype.clip = function (t, e, n) { this.ctx.save(), t.filter(i).forEach(function (t) { this.shape(t).clip(); }, this), e.call(n), this.ctx.restore(); }, r.prototype.shape = function (t) { return this.ctx.beginPath(), t.forEach(function (t, e) { "rect" === t[0] ? this.ctx.rect.apply(this.ctx, t.slice(1)) : this.ctx[0 === e ? "moveTo" : t[0] + "To"].apply(this.ctx, t.slice(1)); }, this), this.ctx.closePath(), this.ctx }, r.prototype.font = function (t, e, n, r, i, o) { this.setFillStyle(t).font = [e, n, r, i, o].join(" ").split(",")[0]; }, r.prototype.fontShadow = function (t, e, n, r) { this.setVariable("shadowColor", t.toString()).setVariable("shadowOffsetY", e).setVariable("shadowOffsetX", n).setVariable("shadowBlur", r); }, r.prototype.clearShadow = function () { this.setVariable("shadowColor", "rgba(0,0,0,0)"); }, r.prototype.setOpacity = function (t) { this.ctx.globalAlpha = t; }, r.prototype.setTransform = function (t) { this.ctx.translate(t.origin[0], t.origin[1]), this.ctx.transform.apply(this.ctx, t.matrix), this.ctx.translate(-t.origin[0], -t.origin[1]); }, r.prototype.setVariable = function (t, e) { return this.variables[t] !== e && (this.variables[t] = this.ctx[t] = e), this }, r.prototype.text = function (t, e, n) { this.ctx.fillText(t, e, n); }, r.prototype.backgroundRepeatShape = function (t, e, n, r, i, o, a, s, c) { var l = [["line", Math.round(i), Math.round(o)], ["line", Math.round(i + a), Math.round(o)], ["line", Math.round(i + a), Math.round(s + o)], ["line", Math.round(i), Math.round(s + o)]];
7599 this.clip([l], function () { this.renderBackgroundRepeat(t, e, n, r, c[3], c[0]); }, this); }, r.prototype.renderBackgroundRepeat = function (t, e, n, r, i, o) { var a = Math.round(r.left + e.left + i), s = Math.round(r.top + e.top + o); this.setFillStyle(this.ctx.createPattern(this.resizeImage(t, n), "repeat")), this.ctx.translate(a, s), this.ctx.fill(), this.ctx.translate(-a, -s); }, r.prototype.renderBackgroundGradient = function (t, e) { if (t instanceof a) { var n = this.ctx.createLinearGradient(e.left + e.width * t.x0, e.top + e.height * t.y0, e.left + e.width * t.x1, e.top + e.height * t.y1); t.colorStops.forEach(function (t) { n.addColorStop(t.stop, t.color.toString()); }), this.rectangle(e.left, e.top, e.width, e.height, n); } }, r.prototype.resizeImage = function (t, e) { var n = t.image; if (n.width === e.width && n.height === e.height) return n; var r = document.createElement("canvas"); return r.width = e.width, r.height = e.height, r.getContext("2d").drawImage(n, 0, 0, n.width, n.height, 0, 0, e.width, e.height), r }, e.exports = r; }, { "../lineargradientcontainer": 12, "../log": 13, "../renderer": 19 }], 21: [function (t, e, n) { function r(t, e, n, r) { i.call(this, n, r), this.ownStacking = t, this.contexts = [], this.children = [], this.opacity = (this.parent ? this.parent.stack.opacity : 1) * e; } var i = t("./nodecontainer"); (r.prototype = Object.create(i.prototype)).getParentStack = function (t) { var e = this.parent ? this.parent.stack : null; return e ? e.ownStacking ? e : e.getParentStack(t) : t.stack }, e.exports = r; }, { "./nodecontainer": 14 }], 22: [function (t, e, n) { function r(t) { this.rangeBounds = this.testRangeBounds(t), this.cors = this.testCORS(), this.svg = this.testSVG(); } r.prototype.testRangeBounds = function (t) { var e, n, r = !1; return t.createRange && (e = t.createRange()).getBoundingClientRect && ((n = t.createElement("boundtest")).style.height = "123px", n.style.display = "block", t.body.appendChild(n), e.selectNode(n), 123 === e.getBoundingClientRect().height && (r = !0), t.body.removeChild(n)), r }, r.prototype.testCORS = function () { return void 0 !== (new Image).crossOrigin }, r.prototype.testSVG = function () { var t = new Image, e = document.createElement("canvas"), n = e.getContext("2d"); t.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>"; try { n.drawImage(t, 0, 0), e.toDataURL(); } catch (t) { return !1 } return !0 }, e.exports = r; }, {}], 23: [function (t, e, n) { function r(t) { this.src = t, this.image = null; var e = this; this.promise = this.hasFabric().then(function () { return e.isInline(t) ? Promise.resolve(e.inlineFormatting(t)) : i(t) }).then(function (t) { return new Promise(function (n) { window.html2canvas.svg.fabric.loadSVGFromString(t, e.createCanvas.call(e, n)); }) }); } var i = t("./xhr"), o = t("./utils").decode64; r.prototype.hasFabric = function () { return window.html2canvas.svg && window.html2canvas.svg.fabric ? Promise.resolve() : Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) }, r.prototype.inlineFormatting = function (t) { return /^data:image\/svg\+xml;base64,/.test(t) ? this.decode64(this.removeContentType(t)) : this.removeContentType(t) }, r.prototype.removeContentType = function (t) { return t.replace(/^data:image\/svg\+xml(;base64)?,/, "") }, r.prototype.isInline = function (t) { return /^data:image\/svg\+xml/i.test(t) }, r.prototype.createCanvas = function (t) { var e = this; return function (n, r) { var i = new window.html2canvas.svg.fabric.StaticCanvas("c"); e.image = i.lowerCanvasEl, i.setWidth(r.width).setHeight(r.height).add(window.html2canvas.svg.fabric.util.groupSVGElements(n, r)).renderAll(), t(i.lowerCanvasEl); } }, r.prototype.decode64 = function (t) { return "function" == typeof window.atob ? window.atob(t) : o(t) }, e.exports = r; }, { "./utils": 26, "./xhr": 28 }], 24: [function (t, e, n) { function r(t, e) { this.src = t, this.image = null; var n = this; this.promise = e ? new Promise(function (e, r) { n.image = new Image, n.image.onload = e, n.image.onerror = r, n.image.src = "data:image/svg+xml," + (ne
vendor: 11,984 bytes, lines 7599-7600
7599w XMLSerializer).serializeToString(t), !0 === n.image.complete && e(n.image); }) : this.hasFabric().then(function () { return new Promise(function (e) { window.html2canvas.svg.fabric.parseSVGDocument(t, n.createCanvas.call(n, e)); }) }); } var i = t("./svgcontainer"); r.prototype = Object.create(i.prototype), e.exports = r; }, { "./svgcontainer": 23 }], 25: [function (t, e, n) { function r(t, e) { o.call(this, t, e); } function i(t, e, n) { if (t.length > 0) return e + n.toUpperCase() } var o = t("./nodecontainer"); (r.prototype = Object.create(o.prototype)).applyTextTransform = function () { this.node.data = this.transform(this.parent.css("textTransform")); }, r.prototype.transform = function (t) { var e = this.node.data; switch (t) { case "lowercase": return e.toLowerCase(); case "capitalize": return e.replace(/(^|\s|:|-|\(|\))([a-z])/g, i); case "uppercase": return e.toUpperCase(); default: return e } }, e.exports = r; }, { "./nodecontainer": 14 }], 26: [function (t, e, n) { n.smallImage = function () { return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" }, n.bind = function (t, e) { return function () { return t.apply(e, arguments) } }, n.decode64 = function (t) { var e, n, r, i, o, a, s, c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", l = t.length, u = ""; for (e = 0; e < l; e += 4)o = c.indexOf(t[e]) << 2 | (n = c.indexOf(t[e + 1])) >> 4, a = (15 & n) << 4 | (r = c.indexOf(t[e + 2])) >> 2, s = (3 & r) << 6 | (i = c.indexOf(t[e + 3])), u += 64 === r ? String.fromCharCode(o) : 64 === i || -1 === i ? String.fromCharCode(o, a) : String.fromCharCode(o, a, s); return u }, n.getBounds = function (t) { if (t.getBoundingClientRect) { var e = t.getBoundingClientRect(), n = null == t.offsetWidth ? e.width : t.offsetWidth; return { top: e.top, bottom: e.bottom || e.top + e.height, right: e.left + n, left: e.left, width: n, height: null == t.offsetHeight ? e.height : t.offsetHeight } } return {} }, n.offsetBounds = function (t) { var e = t.offsetParent ? n.offsetBounds(t.offsetParent) : { top: 0, left: 0 }; return { top: t.offsetTop + e.top, bottom: t.offsetTop + t.offsetHeight + e.top, right: t.offsetLeft + e.left + t.offsetWidth, left: t.offsetLeft + e.left, width: t.offsetWidth, height: t.offsetHeight } }, n.parseBackgrounds = function (t) { var e, n, r, i, o, a, s, c = [], l = 0, u = 0, h = function () { e && ('"' === n.substr(0, 1) && (n = n.substr(1, n.length - 2)), n && s.push(n), "-" === e.substr(0, 1) && (i = e.indexOf("-", 1) + 1) > 0 && (r = e.substr(0, i), e = e.substr(i)), c.push({ prefix: r, method: e.toLowerCase(), value: o, args: s, image: null })), s = [], e = r = n = o = ""; }; return s = [], e = r = n = o = "", t.split("").forEach(function (t) { if (!(0 === l && " \r\n\t".indexOf(t) > -1)) { switch (t) { case '"': a ? a === t && (a = null) : a = t; break; case "(": if (a) break; if (0 === l) return l = 1, void (o += t); u++; break; case ")": if (a) break; if (1 === l) { if (0 === u) return l = 0, o += t, void h(); u--; } break; case ",": if (a) break; if (0 === l) return void h(); if (1 === l && 0 === u && !e.match(/^url$/i)) return s.push(n), n = "", void (o += t) }o += t, 0 === l ? e += t : n += t; } }), h(), c }; }, {}], 27: [function (t, e, n) { function r(t) { i.apply(this, arguments), this.type = "linear" === t.args[0] ? i.TYPES.LINEAR : i.TYPES.RADIAL; } var i = t("./gradientcontainer"); r.prototype = Object.create(i.prototype), e.exports = r; }, { "./gradientcontainer": 9 }], 28: [function (t, e, n) { e.exports = function (t) { return new Promise(function (e, n) { var r = new XMLHttpRequest; r.open("GET", t), r.onload = function () { 200 === r.status ? e(r.responseText) : n(new Error(r.statusText)); }, r.onerror = function () { n(new Error("Network Error")); }, r.send(); }) }; }, {}] }, {}, [4])(4) }), function (t) { var e; e = function () { function e(t) { var e, n, r, i, o, a, s, c, l, u, h, f, d, p, m; for (this.data = t, this.pos = 8, this.palette = [], this.imgData = [], this.transparency = {}, this.animation = null, this.text = {}, a = null; ;) { switch (e = this.readUInt32(), u = function () { var t, e; for (e = [], s = t = 0; t < 4; s = ++t)e.push(String.fromCharCode(this.data[this.pos++])); return e }.call(this).join("")) { case "IHDR": this.width = this.readUInt32(), this.height = this.readUInt32(), this.bits = this.data[this.pos++], this.colorType = this.data[this.pos++], this.compressionMethod = this.data[this.pos++], this.filterMethod = this.data[this.pos++], this.interlaceMethod = this.data[this.pos++]; break; case "acTL": this.animation = { numFrames: this.readUInt32(), numPlays: this.readUInt32() || 1 / 0, frames: [] }; break; case "PLTE": this.palette = this.read(e); break; case "fcTL": a && this.animation.frames.push(a), this.pos += 4, a = { width: this.readUInt32(), height: this.readUInt32(), xOffset: this.readUInt32(), yOffset: this.readUInt32() }, o = this.readUInt16(), i = this.readUInt16() || 100, a.delay = 1e3 * o / i, a.disposeOp = this.data[this.pos++], a.blendOp = this.data[this.pos++], a.data = []; break; case "IDAT": case "fdAT": for ("fdAT" === u && (this.pos += 4, e -= 4), t = (null != a ? a.data : void 0) || this.imgData, s = d = 0; 0 <= e ? d < e : d > e; s = 0 <= e ? ++d : --d)t.push(this.data[this.pos++]); break; case "tRNS": switch (this.transparency = {}, this.colorType) { case 3: if (r = this.palette.length / 3, this.transparency.indexed = this.read(e), this.transparency.indexed.length > r) throw new Error("More transparent colors than palette size"); if ((h = r - this.transparency.indexed.length) > 0) for (s = p = 0; 0 <= h ? p < h : p > h; s = 0 <= h ? ++p : --p)this.transparency.indexed.push(255); break; case 0: this.transparency.grayscale = this.read(e)[0]; break; case 2: this.transparency.rgb = this.read(e); }break; case "tEXt": c = (f = this.read(e)).indexOf(0), l = String.fromCharCode.apply(String, f.slice(0, c)), this.text[l] = String.fromCharCode.apply(String, f.slice(c + 1)); break; case "IEND": return a && this.animation.frames.push(a), this.colors = function () { switch (this.colorType) { case 0: case 3: case 4: return 1; case 2: case 6: return 3 } }.call(this), this.hasAlphaChannel = 4 === (m = this.colorType) || 6 === m, n = this.colors + (this.hasAlphaChannel ? 1 : 0), this.pixelBitlength = this.bits * n, this.colorSpace = function () { switch (this.colors) { case 1: return "DeviceGray"; case 3: return "DeviceRGB" } }.call(this), void (this.imgData = new Uint8Array(this.imgData)); default: this.pos += e; }if (this.pos += 4, this.pos > this.data.length) throw new Error("Incomplete or corrupt PNG file") } } var n, r, i; e.load = function (t, n, r) { var i; return "function" == typeof n && (r = n), (i = new XMLHttpRequest).open("GET", t, !0), i.responseType = "arraybuffer", i.onload = function () { var t, o; return t = new Uint8Array(i.response || i.mozResponseArrayBuffer), o = new e(t), "function" == typeof (null != n ? n.getContext : void 0) && o.render(n), "function" == typeof r ? r(o) : void 0 }, i.send(null) }, e.prototype.read = function (t) { var e, n; for (n = [], e = 0; 0 <= t ? e < t : e > t; 0 <= t ? ++e : --e)n.push(this.data[this.pos++]); return n }, e.prototype.readUInt32 = function () { var t, e, n, r; return t = this.data[this.pos++] << 24, e = this.data[this.pos++] << 16, n = this.data[this.pos++] << 8, r = this.data[this.pos++], t | e | n | r }, e.prototype.readUInt16 = function () { var t, e; return t = this.data[this.pos++] << 8, e = this.data[this.pos++], t | e }, e.prototype.decodePixels = function (t) { var e, n, r, i, o, a, c, l, u, h, f, d, p, m, g, w, y, v, b, x, k, _, C; if (null == t && (t = this.imgData), 0 === t.length) return new Uint8Array(0); for (t = (t = new s(t)).getBytes(), w = (d = this.pixelBitlength / 8) * this.width, p = new Uint8Array(w * this.height), a = t.length, g = 0, m = 0, n = 0; m < a;) { switch (t[m++]) { case 0: for (i = b = 0; b < w; i = b += 1)p[n++] = t[m++]; break; case 1: for (i = x = 0; x < w; i = x += 1)e = t[m++], o = i < d ? 0 : p[n - d], p[n++] = (e + o) % 256; break; case 2: for (i = k = 0; k < w; i = k += 1)e = t[m++], r = (i - i % d) / d, y = g && p[(g - 1) * w + r * d + i % d], p[n++] = (y + e) % 256; break; case 3: for (i = _ = 0; _ < w; i = _ += 1)e = t[m++], r = (i - i % d) / d, o = i < d ? 0 : p[n - d], y = g && p[(g - 1) * w + r * d + i % d], p[n++] = (e + Math.floor((o + y) / 2)) % 256; break; case 4: for (i = C = 0; C < w; i = C += 1)e = t[m++], r = (i - i % d) / d, o = i < d ? 0 : p[n - d], 0 === g ? y = v = 0 : (y = p[(g - 1) * w + r * d + i % d], v = r && p[(g - 1) * w + (r - 1) * d + i % d]), c = o + y - v, l = Math.abs(c - o), h = Math.abs(c - y), f = Math.abs(c - v), u = l <= h && l <= f ? o : h <= f ? y : v, p[n++] = (e + u) % 256; break; default: throw new Error("Invalid filter algorithm: " + t[m - 1]) }g++; } return p }, e.prototype.decodePalette = function () { var t, e, n, r, i, o, a, s, c; for (n = this.palette, o = this.transparency.indexed || [], i = new Uint8Array((o.length || 0) + n.length), r = 0, t = 0, e = a = 0, s = n.length; a < s; e = a += 3)i[r++] = n[e], i[r++] = n[e + 1], i[r++] = n[e + 2], i[r++] = null != (c = o[t++]) ? c : 255; return i }, e.prototype.copyToImageData = function (t, e) { var n, r, i, o, a, s, c, l, u, h, f; if (r = this.colors, u = null, n = this.hasAlphaChannel, this.palette.length && (u = null != (f = this._decodedPalette) ? f : this._decodedPalette = this.decodePalette(), r = 4, n = !0), i = t.data || t, l = i.length, a = u || e, o = s = 0, 1 === r) for (; o < l;)c = u ? 4 * e[o / 4] : s, h = a[c++], i[o++] = h, i[o++] = h, i[o++] = h, i[o++] = n ? a[c++] : 255, s = c; else for (; o < l;)c = u ? 4 * e[o / 4] : s, i[o++] = a[c++], i[o++] = a[c++], i[o++] = a[c++], i[o++] = n ? a[c++] : 255, s = c; }, e.prototype.decode = function () { var t; return t = new Uint8Array(this.width * this.height * 4), this.copyToImageData(t, this.decodePixels()), t }; try { r = t.document.createElement("canvas"), i = r.getContext("2d"); } catch (t) { return -1 } return n = function (t) { var e; return i.width = t.width, i.height = t.height, i.clearRect(0, 0, t.width, t.height), i.putImageData(t, 0, 0), e = new Image, e.src = r.toDataURL(), e }, e.prototype.decodeFrames = function (t) { var e, r, i, o, a, s, c, l; if (this.animation) { for (l = [], r = a = 0, s = (c = this.animation.frames).length; a < s; r = ++a)e = c[r], i = t.createImageData(e.width, e.height), o = this.decodePixels(new Uint8Array(e.data)), this.copyToImageData(i, o), e.imageData = i, l.push(e.image = n(i)); return l } }, e.prototype.renderFrame = function (t, e) { var n, r, i; return r = this.animation.frames, n = r[e], i = r[e - 1], 0 === e && t.clearRect(0, 0, this.width, this.height), 1 === (null != i ? i.disposeOp : void 0) ? t.clearRect(i.xOffset, i.yOffset, i.width, i.height) : 2 === (null != i ? i.disposeOp : void 0) && t.putImageData(i.imageData, i.xOffset, i.yOffset), 0 === n.blendOp && t.clearRect(n.xOffset, n.yOffset, n.width, n.height), t.drawImage(n.image, n.xOffset, n.yOffset) }, e.prototype.animate = function (t) { var e, n, r, i, o, a, s = this; return n = 0, a = this.animation, i = a.numFrames, r = a.frames, o = a.numPlays, (e = function () { var a, c; if (a = n++ % i, c = r[a], s.renderFrame(t, a), i > 1 && n / i < o) return s.animation._timeout = setTimeout(e, c.delay) })() }, e.prototype.stopAnimation = function () { var t; return clearTimeout(null != (t = this.animation) ? t._timeout : void 0) }, e.prototype.render = function (t) { var e, n; return t._png && t._png.stopAnimation(), t._png = this, t.width = this.width, t.height = this.height, e = t.getContext("2d"), this.animation ? (this.decodeFrames(e), this.animate(e)) : (n = e.createImageData(this.width, this.height), this.copyToImageData(n, this.decodePixels()), e.putImageData(n, 0, 0)) }, e }(), t.PNG = e; }("undefined" != typeof window && window || void 0);/*
7600 * Extracted from pdf.js
7601 * https://github.com/andreasgal/pdf.js
7602 *
7603 * Copyright (c) 2011 Mozilla Foundation
7604 *
7605 * Contributors: Andreas Gal <[email protected]>
7606 *               Chris G Jones <[email protected]>
7607 *               Shaon Barman <[email protected]>
7608 *               Vivien Nicolas <[email protected]>
7609 *               Justin D'Arcangelo <[email protected]>
7610 *               Yury Delendik
7611 *
7612 * 
7613 */
7614            var a = function () { function t() { this.pos = 0, this.bufferLength = 0, this.eof = !1, this.buffer = null; } return t.prototype = { ensureBuffer: function (t) { var e = this.buffer, n = e ? e.byteLength : 0; if (t < n) return e; for (var r = 512; r < t;)r <<= 1; for (var i = new Uint8Array(r), o = 0; o < n; ++o)i[o] = e[o]; return this.buffer = i }, getByte: function () { for (var t = this.pos; this.bufferLength <= t;) { if (this.eof) return null; this.readBlock(); } return this.buffer[this.pos++] }, getBytes: function (t) { var e = this.pos; if (t) { this.ensureBuffer(e + t); for (r = e + t; !this.eof && this.bufferLength < r;)this.readBlock(); var n = this.bufferLength; r > n && (r = n); } else { for (; !this.eof;)this.readBlock(); var r = this.bufferLength; } return this.pos = r, this.buffer.subarray(e, r) }, lookChar: function () { for (var t = this.pos; this.bufferLength <= t;) { if (this.eof) return null; this.readBlock(); } return String.fromCharCode(this.buffer[this.pos]) }, getChar: function () { for (var t = this.pos; this.bufferLength <= t;) { if (this.eof) return null; this.readBlock(); } return String.fromCharCode(this.buffer[this.pos++]) }, makeSubStream: function (t, e, n) { for (var r = t + e; this.bufferLength <= r && !this.eof;)this.readBlock(); return new Stream(this.buffer, t, e, n) }, skip: function (t) { t || (t = 1), this.pos += t; }, reset: function () { this.pos = 0; } }, t }(), s = function () { function t(t) { throw new Error(t) } function e(e) { var n = 0, r = e[n++], i = e[n++]; -1 != r && -1 != i || t("Invalid header in flate stream"), 8 != (15 & r) && t("Unknown compression method in flate stream"), ((r << 8) + i) % 31 != 0 && t("Bad FCHECK in flate stream"), 32 & i && t("FDICT bit set in flate stream"), this.bytes = e, this.bytesPos = n, this.codeSize = 0, this.codeBuf = 0, a.call(this); } if ("undefined" != typeof Uint32Array) { var n = new Uint32Array([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]), r = new Uint32Array([3, 4, 5, 6, 7, 8, 9, 10, 65547, 65549, 65551, 65553, 131091, 131095, 131099, 131103, 196643, 196651, 196659, 196667, 262211, 262227, 262243, 262259, 327811, 327843, 327875, 327907, 258, 258, 258]), i = new Uint32Array([1, 2, 3, 4, 65541, 65543, 131081, 131085, 196625, 196633, 262177, 262193, 327745, 327777, 393345, 393409, 459009, 459137, 524801, 525057, 590849, 591361, 657409, 658433, 724993, 727041, 794625, 798721, 868353, 876545]), o = [new Uint32Array([459008, 524368, 524304, 524568, 459024, 524400, 524336, 590016, 459016, 524384, 524320, 589984, 524288, 524416, 524352, 590048, 459012, 524376, 524312, 589968, 459028, 524408, 524344, 590032, 459020, 524392, 524328, 59e4, 524296, 524424, 524360, 590064, 459010, 524372, 524308, 524572, 459026, 524404, 524340, 590024, 459018, 524388, 524324, 589992, 524292, 524420, 524356, 590056, 459014, 524380, 524316, 589976, 459030, 524412, 524348, 590040, 459022, 524396, 524332, 590008, 524300, 524428, 524364, 590072, 459009, 524370, 524306, 524570, 459025, 524402, 524338, 590020, 459017, 524386, 524322, 589988, 524290, 524418, 524354, 590052, 459013, 524378, 524314, 589972, 459029, 524410, 524346, 590036, 459021, 524394, 524330, 590004, 524298, 524426, 524362, 590068, 459011, 524374, 524310, 524574, 459027, 524406, 524342, 590028, 459019, 524390, 524326, 589996, 524294, 524422, 524358, 590060, 459015, 524382, 524318, 589980, 459031, 524414, 524350, 590044, 459023, 524398, 524334, 590012, 524302, 524430, 524366, 590076, 459008, 524369, 524305, 524569, 459024, 524401, 524337, 590018, 459016, 524385, 524321, 589986, 524289, 524417, 524353, 590050, 459012, 524377, 524313, 589970, 459028, 524409, 524345, 590034, 459020, 524393, 524329, 590002, 524297, 524425, 524361, 590066, 459010, 524373, 524309, 524573, 459026, 524405, 524341, 590026, 459018, 524389, 524325, 589994, 524293, 524421, 524357, 590058, 459014, 524381, 524317, 589978, 459030, 524413, 524349, 590042, 459022, 524397, 524333, 590010, 524301, 524429, 524365, 590074, 459009, 524371, 524307, 524571, 459025, 524403, 524339, 590022, 459017, 524387, 524323, 589990, 524291, 524419, 524355, 590054, 459013, 524379, 524315, 589974, 459029, 524411, 524347, 590038, 459021, 524395, 524331, 590006, 524299, 524427, 524363, 590070, 459011, 524375, 524311, 524575, 459027, 524407, 524343, 590030, 459019, 524391, 524327, 589998, 524295, 524423, 524359, 590062, 459015, 524383, 524319, 589982, 459031, 524415, 524351, 590046, 459023, 524399, 524335, 590014, 524303, 524431, 524367, 590078, 459008, 524368, 524304, 524568, 459024, 524400, 524336, 590017, 459016, 524384, 524320, 589985, 524288, 524416, 524352, 590049, 459012, 524376, 524312, 589969, 459028, 524408, 524344, 590033, 459020, 524392, 524328, 590001, 524296, 524424, 524360, 590065, 459010, 524372, 524308, 524572, 459026, 524404, 524340, 590025, 459018, 524388, 524324, 589993, 524292, 524420, 524356, 590057, 459014, 524380, 524316, 589977, 459030, 524412, 524348, 590041, 459022, 524396, 524332, 590009, 524300, 524428, 524364, 590073, 459009, 524370, 524306, 524570, 459025, 524402, 524338, 590021, 459017, 524386, 524322, 589989, 524290, 524418, 524354, 590053, 459013, 524378, 524314, 589973, 459029, 524410, 524346, 590037, 459021, 524394, 524330, 590005, 524298, 524426, 524362, 590069, 459011, 524374, 524310, 524574, 459027, 524406, 524342, 590029, 459019, 524390, 524326, 589997, 524294, 524422, 524358, 590061, 459015, 524382, 524318, 589981, 459031, 524414, 524350, 590045, 459023, 524398, 524334, 590013, 524302, 524430, 524366, 590077, 459008, 524369, 524305, 524569, 459024, 524401, 524337, 590019, 459016, 524385, 524321, 589987, 524289, 524417, 524353, 590051, 459012, 524377, 524313, 589971, 459028, 524409, 524345, 590035, 459020, 524393, 524329, 590003, 524297, 524425, 524361, 590067, 459010, 524373, 524309, 524573, 459026, 524405, 524341, 590027, 459018, 524389, 524325, 589995, 524293, 524421, 524357, 590059, 459014, 524381, 524317, 589979, 459030, 524413, 524349, 590043, 459022, 524397, 524333, 590011, 524301, 524429, 524365, 590075, 459009, 524371, 524307, 524571, 459025, 524403, 524339, 590023, 459017, 524387, 524323, 589991, 524291, 524419, 524355, 590055, 459013, 524379, 524315, 589975, 459029, 524411, 524347, 590039, 459021, 524395, 524331, 590007, 524299, 524427, 524363, 590071, 459011, 524375, 524311, 524575, 459027, 524407, 524343, 590031, 459019, 524391, 524327, 589999, 524295, 524423, 524359, 590063, 459015, 524383, 524319, 589983, 459031, 524415, 524351, 590047, 459023, 524399, 524335, 590015, 524303, 524431, 524367, 590079]), 9], s = [
vendor: 4,769 bytes, line 7614
7614new Uint32Array([327680, 327696, 327688, 327704, 327684, 327700, 327692, 327708, 327682, 327698, 327690, 327706, 327686, 327702, 327694, 0, 327681, 327697, 327689, 327705, 327685, 327701, 327693, 327709, 327683, 327699, 327691, 327707, 327687, 327703, 327695, 0]), 5]; return e.prototype = Object.create(a.prototype), e.prototype.getBits = function (e) { for (var n, r = this.codeSize, i = this.codeBuf, o = this.bytes, a = this.bytesPos; r < e;)void 0 === (n = o[a++]) && t("Bad encoding in flate stream"), i |= n << r, r += 8; return n = i & (1 << e) - 1, this.codeBuf = i >> e, this.codeSize = r -= e, this.bytesPos = a, n }, e.prototype.getCode = function (e) { for (var n = e[0], r = e[1], i = this.codeSize, o = this.codeBuf, a = this.bytes, s = this.bytesPos; i < r;) { var c; void 0 === (c = a[s++]) && t("Bad encoding in flate stream"), o |= c << i, i += 8; } var l = n[o & (1 << r) - 1], u = l >> 16, h = 65535 & l; return (0 == i || i < u || 0 == u) && t("Bad encoding in flate stream"), this.codeBuf = o >> u, this.codeSize = i - u, this.bytesPos = s, h }, e.prototype.generateHuffmanTable = function (t) { for (var e = t.length, n = 0, r = 0; r < e; ++r)t[r] > n && (n = t[r]); for (var i = 1 << n, o = new Uint32Array(i), a = 1, s = 0, c = 2; a <= n; ++a, s <<= 1, c <<= 1)for (var l = 0; l < e; ++l)if (t[l] == a) { for (var u = 0, h = s, r = 0; r < a; ++r)u = u << 1 | 1 & h, h >>= 1; for (r = u; r < i; r += c)o[r] = a << 16 | l; ++s; } return [o, n] }, e.prototype.readBlock = function () { function e(t, e, n, r, i) { for (var o = t.getBits(n) + r; o-- > 0;)e[p++] = i; } var a = this.getBits(3); if (1 & a && (this.eof = !0), 0 != (a >>= 1)) { var c, l; if (1 == a) c = o, l = s; else if (2 == a) { for (var u = this.getBits(5) + 257, h = this.getBits(5) + 1, f = this.getBits(4) + 4, d = Array(n.length), p = 0; p < f;)d[n[p++]] = this.getBits(3); for (var m = this.generateHuffmanTable(d), g = 0, p = 0, w = u + h, y = new Array(w); p < w;) { var v = this.getCode(m); 16 == v ? e(this, y, 2, 3, g) : 17 == v ? e(this, y, 3, 3, g = 0) : 18 == v ? e(this, y, 7, 11, g = 0) : y[p++] = g = v; } c = this.generateHuffmanTable(y.slice(0, u)), l = this.generateHuffmanTable(y.slice(u, w)); } else t("Unknown block type in flate stream"); for (var b = (O = this.buffer) ? O.length : 0, x = this.bufferLength; ;) { var k = this.getCode(c); if (k < 256) x + 1 >= b && (b = (O = this.ensureBuffer(x + 1)).length), O[x++] = k; else { if (256 == k) return void (this.bufferLength = x); var _ = (k = r[k -= 257]) >> 16; _ > 0 && (_ = this.getBits(_)); g = (65535 & k) + _; k = this.getCode(l), (_ = (k = i[k]) >> 16) > 0 && (_ = this.getBits(_)); var C = (65535 & k) + _; x + g >= b && (b = (O = this.ensureBuffer(x + g)).length); for (var A = 0; A < g; ++A, ++x)O[x] = O[x - C]; } } } else { var S, q = this.bytes, T = this.bytesPos; void 0 === (S = q[T++]) && t("Bad block header in flate stream"); var P = S; void 0 === (S = q[T++]) && t("Bad block header in flate stream"), P |= S << 8, void 0 === (S = q[T++]) && t("Bad block header in flate stream"); var I = S; void 0 === (S = q[T++]) && t("Bad block header in flate stream"), (I |= S << 8) != (65535 & ~P) && t("Bad uncompressed block length in flate stream"), this.codeBuf = 0, this.codeSize = 0; var E = this.bufferLength, O = this.ensureBuffer(E + P), F = E + P; this.bufferLength = F; for (var B = E; B < F; ++B) { if (void 0 === (S = q[T++])) { this.eof = !0; break } O[B] = S; } this.bytesPos = T; } }, e } }(); return function (t) { var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; void 0 === t.btoa && (t.btoa = function (t) { var n, r, i, o, a, s = 0, c = 0, l = "", u = []; if (!t) return t; do { n = (a = t.charCodeAt(s++) << 16 | t.charCodeAt(s++) << 8 | t.charCodeAt(s++)) >> 18 & 63, r = a >> 12 & 63, i = a >> 6 & 63, o = 63 & a, u[c++] = e.charAt(n) + e.charAt(r) + e.charAt(i) + e.charAt(o); } while (s < t.length); l = u.join(""); var h = t.length % 3; return (h ? l.slice(0, h - 3) : l) + "===".slice(h || 3) }), void 0 === t.atob && (t.atob = function (t) { var n, r, i, o, a, s, c = 0, l = 0, u = []; if (!t) return t; t += ""; do { n = (s = e.indexOf(t.charAt(c++)) << 18 | e.indexOf(t.charAt(c++)) << 12 | (o = e.indexOf(t.charAt(c++))) << 6 | (a = e.indexOf(t.charAt(c++)))) >> 16 & 255, r = s >> 8 & 255, i = 255 & s, u[l++] = 64 == o ? String.fromCharCode(n) : 64 == a ? String.fromCharCode(n, r) : String.fromCharCode(n, r, i); } while (c < t.length); return u.join("") }), Array.prototype.map || (Array.prototype.map = function (t) { if (void 0 === this || null === this || "function" != typeof t) throw new TypeError; for (var e = Object(this), n = e.length >>> 0, r = new Array(n), i = arguments.length > 1 ? arguments[1] : void 0, o = 0; o < n;
7614 o++)o in e && (r[o] = t.call(i, e[o], o, e)); return r }), Array.isArray || (Array.isArray = function (t) { return "[object Array]" === Object.prototype.toString.call(t) }), Array.prototype.forEach || (Array.prototype.forEach = function (t, e) { if (void 0 === this || null === this || "function" != typeof t) throw new TypeError; for (var n = Object(this), r = n.length >>> 0, i = 0; i < r; i++)i in n && t.call(e, n[i], i, n); }), Object.keys || (Object.keys = function () { var t = Object.prototype.hasOwnProperty, e = !{ toString: null }.propertyIsEnumerable("toString"), n = ["toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor"], r = n.length; return function (i) { if ("object" != typeof i && ("function" != typeof i || null === i)) throw new TypeError; var o, a, s = []; for (o in i) t.call(i, o) && s.push(o); if (e) for (a = 0; a < r; a++)t.call(i, n[a]) && s.push(n[a]); return s } }()), String.prototype.trim || (String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, "") }), String.prototype.trimLeft || (String.prototype.trimLeft = function () { return this.replace(/^\s+/g, "") }), String.prototype.trimRight || (String.prototype.trimRight = function () { return this.replace(/\s+$/g, "") }); }("undefined" != typeof self && self || "undefined" != typeof window && window || void 0), e
7615        });
7616    });
7617
7618    var jspdf_min_1 = jspdf_min.saveAs;
7619
7620    var html2canvas$1 = createCommonjsModule(function (module, exports) {
7621        /*
7622          html2canvas 0.5.0-beta4 <http://html2canvas.hertzen.com>
7623          Copyright (c) 2017 Niklas von Hertzen
7624          2017-06-14 Custom build by Erik Koopmans, featuring latest bugfixes and features
7625        
7626          Released under MIT License
7627        */
7628
7629        (function (f) { { module.exports = f(); } })(function () {
7630            var define; return (function e(t, n, r) { function s(o, u) { if (!n[o]) { if (!t[o]) { var a = typeof commonjsRequire == "function" && commonjsRequire; if (!u && a) return a(o, !0); if (i) return i(o, !0); var f = new Error("Cannot find module '" + o + "'"); throw f.code = "MODULE_NOT_FOUND", f } var l = n[o] = { exports: {} }; t[o][0].call(l.exports, function (e) { var n = t[o][1][e]; return s(n ? n : e) }, l, l.exports, e, t, n, r); } return n[o].exports } var i = typeof commonjsRequire == "function" && commonjsRequire; for (var o = 0; o < r.length; o++)s(r[o]); return s })({
7631                1: [function (_dereq_, module, exports) {
7632                    (function (global) {
7633                        /*! https://mths.be/punycode v1.4.1 by @mathias */
7634                        (function (root) {
7635
7636                            /** Detect free variables */
7637                            var freeExports = typeof exports == 'object' && exports &&
7638                                !exports.nodeType && exports;
7639                            var freeModule = typeof module == 'object' && module &&
7640                                !module.nodeType && module;
7641                            var freeGlobal = typeof global == 'object' && global;
7642                            if (
7643                                freeGlobal.global === freeGlobal ||
7644                                freeGlobal.window === freeGlobal ||
7645                                freeGlobal.self === freeGlobal
7646                            ) {
7647                                root = freeGlobal;
7648                            }
7649
7650                            /**
7651                             * The `punycode` object.
7652                             * @name punycode
7653                             * @type Object
7654                             */
7655                            var punycode,
7656
7657                                /** Highest positive signed 32-bit float value */
7658                                maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
7659
7660                                /** Bootstring parameters */
7661                                base = 36,
7662                                tMin = 1,
7663                                tMax = 26,
7664                                skew = 38,
7665                                damp = 700,
7666                                initialBias = 72,
7667                                initialN = 128, // 0x80
7668                                delimiter = '-', // '\x2D'
7669
7670                                /** Regular expressions */
7671                                regexPunycode = /^xn--/,
7672                                regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
7673                                regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
7674
7675                                /** Error messages */
7676                                errors = {
7677                                    'overflow': 'Overflow: input needs wider integers to process',
7678                                    'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
7679                                    'invalid-input': 'Invalid input'
7680                                },
7681
7682                                /** Convenience shortcuts */
7683                                baseMinusTMin = base - tMin,
7684                                floor = Math.floor,
vendor: 5,062 bytes, lines 7685-7770
7685                                stringFromCharCode = String.fromCharCode,
7686
7687                                /** Temporary variable */
7688                                key;
7689
7690                            /*--------------------------------------------------------------------------*/
7691
7692                            /**
7693                             * A generic error utility function.
7694                             * @private
7695                             * @param {String} type The error type.
7696                             * @returns {Error} Throws a `RangeError` with the applicable error message.
7697                             */
7698                            function error(type) {
7699                                throw new RangeError(errors[type]);
7700                            }
7701
7702                            /**
7703                             * A generic `Array#map` utility function.
7704                             * @private
7705                             * @param {Array} array The array to iterate over.
7706                             * @param {Function} callback The function that gets called for every array
7707                             * item.
7708                             * @returns {Array} A new array of values returned by the callback function.
7709                             */
7710                            function map(array, fn) {
7711                                var length = array.length;
7712                                var result = [];
7713                                while (length--) {
7714                                    result[length] = fn(array[length]);
7715                                }
7716                                return result;
7717                            }
7718
7719                            /**
7720                             * A simple `Array#map`-like wrapper to work with domain name strings or email
7721                             * addresses.
7722                             * @private
7723                             * @param {String} domain The domain name or email address.
7724                             * @param {Function} callback The function that gets called for every
7725                             * character.
7726                             * @returns {Array} A new string of characters returned by the callback
7727                             * function.
7728                             */
7729                            function mapDomain(string, fn) {
7730                                var parts = string.split('@');
7731                                var result = '';
7732                                if (parts.length > 1) {
7733                                    // In email addresses, only the domain name should be punycoded. Leave
7734                                    // the local part (i.e. everything up to `@`) intact.
7735                                    result = parts[0] + '@';
7736                                    string = parts[1];
7737                                }
7738                                // Avoid `split(regex)` for IE8 compatibility. See #17.
7739                                string = string.replace(regexSeparators, '\x2E');
7740                                var labels = string.split('.');
7741                                var encoded = map(labels, fn).join('.');
7742                                return result + encoded;
7743                            }
7744
7745                            /**
7746                             * Creates an array containing the numeric code points of each Unicode
7747                             * character in the string. While JavaScript uses UCS-2 internally,
7748                             * this function will convert a pair of surrogate halves (each of which
7749                             * UCS-2 exposes as separate characters) into a single code point,
7750                             * matching UTF-16.
7751                             * @see `punycode.ucs2.encode`
7752                             * @see <https://mathiasbynens.be/notes/javascript-encoding>
7753                             * @memberOf punycode.ucs2
7754                             * @name decode
7755                             * @param {String} string The Unicode input string (UCS-2).
7756                             * @returns {Array} The new array of code points.
7757                             */
7758                            function ucs2decode(string) {
7759                                var output = [],
7760                                    counter = 0,
7761                                    length = string.length,
7762                                    value,
7763                                    extra;
7764                                while (counter < length) {
7765                                    value = string.charCodeAt(counter++);
7766                                    if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
7767                                        // high surrogate, and there is a next character
7768                                        extra = string.charCodeAt(counter++);
7769                                        if ((extra & 0xFC00) == 0xDC00) { // low surrogate
7770                                            output.push(((value & 0x3FF) << 10) + (extra & 0x3F
7770F) + 0x10000);
7771                                        } else {
7772                                            // unmatched surrogate; only append this code unit, in case the next
7773                                            // code unit is the high surrogate of a surrogate pair
7774                                            output.push(value);
7775                                            counter--;
7776                                        }
7777                                    } else {
7778                                        output.push(value);
7779                                    }
7780                                }
7781                                return output;
7782                            }
7783
7784                            /**
7785                             * Creates a string based on an array of numeric code points.
7786                             * @see `punycode.ucs2.decode`
7787                             * @memberOf punycode.ucs2
7788                             * @name encode
7789                             * @param {Array} codePoints The array of numeric code points.
7790                             * @returns {String} The new Unicode string (UCS-2).
7791                             */
7792                            function ucs2encode(array) {
7793                                return map(array, function (value) {
7794                                    var output = '';
7795                                    if (value > 0xFFFF) {
7796                                        value -= 0x10000;
7797                                        output += stringFromCharCode(value >>>
vendor: 17,332 bytes, lines 7797-8118
7797 10 & 0x3FF | 0xD800);
7798                                        value = 0xDC00 | value & 0x3FF;
7799                                    }
7800                                    output += stringFromCharCode(value);
7801                                    return output;
7802                                }).join('');
7803                            }
7804
7805                            /**
7806                             * Converts a basic code point into a digit/integer.
7807                             * @see `digitToBasic()`
7808                             * @private
7809                             * @param {Number} codePoint The basic numeric code point value.
7810                             * @returns {Number} The numeric value of a basic code point (for use in
7811                             * representing integers) in the range `0` to `base - 1`, or `base` if
7812                             * the code point does not represent a value.
7813                             */
7814                            function basicToDigit(codePoint) {
7815                                if (codePoint - 48 < 10) {
7816                                    return codePoint - 22;
7817                                }
7818                                if (codePoint - 65 < 26) {
7819                                    return codePoint - 65;
7820                                }
7821                                if (codePoint - 97 < 26) {
7822                                    return codePoint - 97;
7823                                }
7824                                return base;
7825                            }
7826
7827                            /**
7828                             * Converts a digit/integer into a basic code point.
7829                             * @see `basicToDigit()`
7830                             * @private
7831                             * @param {Number} digit The numeric value of a basic code point.
7832                             * @returns {Number} The basic code point whose value (when used for
7833                             * representing integers) is `digit`, which needs to be in the range
7834                             * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
7835                             * used; else, the lowercase form is used. The behavior is undefined
7836                             * if `flag` is non-zero and `digit` has no uppercase form.
7837                             */
7838                            function digitToBasic(digit, flag) {
7839                                //  0..25 map to ASCII a..z or A..Z
7840                                // 26..35 map to ASCII 0..9
7841                                return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
7842                            }
7843
7844                            /**
7845                             * Bias adaptation function as per section 3.4 of RFC 3492.
7846                             * https://tools.ietf.org/html/rfc3492#section-3.4
7847                             * @private
7848                             */
7849                            function adapt(delta, numPoints, firstTime) {
7850                                var k = 0;
7851                                delta = firstTime ? floor(delta / damp) : delta >> 1;
7852                                delta += floor(delta / numPoints);
7853                                for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
7854                                    delta = floor(delta / baseMinusTMin);
7855                                }
7856                                return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
7857                            }
7858
7859                            /**
7860                             * Converts a Punycode string of ASCII-only symbols to a string of Unicode
7861                             * symbols.
7862                             * @memberOf punycode
7863                             * @param {String} input The Punycode string of ASCII-only symbols.
7864                             * @returns {String} The resulting string of Unicode symbols.
7865                             */
7866                            function decode(input) {
7867                                // Don't use UCS-2
7868                                var output = [],
7869                                    inputLength = input.length,
7870                                    out,
7871                                    i = 0,
7872                                    n = initialN,
7873                                    bias = initialBias,
7874                                    basic,
7875                                    j,
7876                                    index,
7877                                    oldi,
7878                                    w,
7879                                    k,
7880                                    digit,
7881                                    t,
7882                                    /** Cached calculation results */
7883                                    baseMinusT;
7884
7885                                // Handle the basic code points: let `basic` be the number of input code
7886                                // points before the last delimiter, or `0` if there is none, then copy
7887                                // the first basic code points to the output.
7888
7889                                basic = input.lastIndexOf(delimiter);
7890                                if (basic < 0) {
7891                                    basic = 0;
7892                                }
7893
7894                                for (j = 0; j < basic; ++j) {
7895                                    // if it's not a basic code point
7896                                    if (input.charCodeAt(j) >= 0x80) {
7897                                        error('not-basic');
7898                                    }
7899                                    output.push(input.charCodeAt(j));
7900                                }
7901
7902                                // Main decoding loop: start just after the last delimiter if any basic code
7903                                // points were copied; start at the beginning otherwise.
7904
7905                                for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
7906
7907                                    // `index` is the index of the next character to be consumed.
7908                                    // Decode a generalized variable-length integer into `delta`,
7909                                    // which gets added to `i`. The overflow checking is easier
7910                                    // if we increase `i` as we go, then subtract off its starting
7911                                    // value at the end to obtain `delta`.
7912                                    for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
7913
7914                                        if (index >= inputLength) {
7915                                            error('invalid-input');
7916                                        }
7917
7918                                        digit = basicToDigit(input.charCodeAt(index++));
7919
7920                                        if (digit >= base || digit > floor((maxInt - i) / w)) {
7921                                            error('overflow');
7922                                        }
7923
7924                                        i += digit * w;
7925                                        t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
7926
7927                                        if (digit < t) {
7928                                            break;
7929                                        }
7930
7931                                        baseMinusT = base - t;
7932                                        if (w > floor(maxInt / baseMinusT)) {
7933                                            error('overflow');
7934                                        }
7935
7936                                        w *= baseMinusT;
7937
7938                                    }
7939
7940                                    out = output.length + 1;
7941                                    bias = adapt(i - oldi, out, oldi == 0);
7942
7943                                    // `i` was supposed to wrap around from `out` to `0`,
7944                                    // incrementing `n` each time, so we'll fix that now:
7945                                    if (floor(i / out) > maxInt - n) {
7946                                        error('overflow');
7947                                    }
7948
7949                                    n += floor(i / out);
7950                                    i %= out;
7951
7952                                    // Insert `n` at position `i` of the output
7953                                    output.splice(i++, 0, n);
7954
7955                                }
7956
7957                                return ucs2encode(output);
7958                            }
7959
7960                            /**
7961                             * Converts a string of Unicode symbols (e.g. a domain name label) to a
7962                             * Punycode string of ASCII-only symbols.
7963                             * @memberOf punycode
7964                             * @param {String} input The string of Unicode symbols.
7965                             * @returns {String} The resulting Punycode string of ASCII-only symbols.
7966                             */
7967                            function encode(input) {
7968                                var n,
7969                                    delta,
7970                                    handledCPCount,
7971                                    basicLength,
7972                                    bias,
7973                                    j,
7974                                    m,
7975                                    q,
7976                                    k,
7977                                    t,
7978                                    currentValue,
7979                                    output = [],
7980                                    /** `inputLength` will hold the number of code points in `input`. */
7981                                    inputLength,
7982                                    /** Cached calculation results */
7983                                    handledCPCountPlusOne,
7984                                    baseMinusT,
7985                                    qMinusT;
7986
7987                                // Convert the input in UCS-2 to Unicode
7988                                input = ucs2decode(input);
7989
7990                                // Cache the length
7991                                inputLength = input.length;
7992
7993                                // Initialize the state
7994                                n = initialN;
7995                                delta = 0;
7996                                bias = initialBias;
7997
7998                                // Handle the basic code points
7999                                for (j = 0; j < inputLength; ++j) {
8000                                    currentValue = input[j];
8001                                    if (currentValue < 0x80) {
8002                                        output.push(stringFromCharCode(currentValue));
8003                                    }
8004                                }
8005
8006                                handledCPCount = basicLength = output.length;
8007
8008                                // `handledCPCount` is the number of code points that have been handled;
8009                                // `basicLength` is the number of basic code points.
8010
8011                                // Finish the basic string - if it is not empty - with a delimiter
8012                                if (basicLength) {
8013                                    output.push(delimiter);
8014                                }
8015
8016                                // Main encoding loop:
8017                                while (handledCPCount < inputLength) {
8018
8019                                    // All non-basic code points < n have been handled already. Find the next
8020                                    // larger one:
8021                                    for (m = maxInt, j = 0; j < inputLength; ++j) {
8022                                        currentValue = input[j];
8023                                        if (currentValue >= n && currentValue < m) {
8024                                            m = currentValue;
8025                                        }
8026                                    }
8027
8028                                    // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
8029                                    // but guard against overflow
8030                                    handledCPCountPlusOne = handledCPCount + 1;
8031                                    if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
8032                                        error('overflow');
8033                                    }
8034
8035                                    delta += (m - n) * handledCPCountPlusOne;
8036                                    n = m;
8037
8038                                    for (j = 0; j < inputLength; ++j) {
8039                                        currentValue = input[j];
8040
8041                                        if (currentValue < n && ++delta > maxInt) {
8042                                            error('overflow');
8043                                        }
8044
8045                                        if (currentValue == n) {
8046                                            // Represent delta as a generalized variable-length integer
8047                                            for (q = delta, k = base; /* no condition */; k += base) {
8048                                                t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
8049                                                if (q < t) {
8050                                                    break;
8051                                                }
8052                                                qMinusT = q - t;
8053                                                baseMinusT = base - t;
8054                                                output.push(
8055                                                    stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
8056                                                );
8057                                                q = floor(qMinusT / baseMinusT);
8058                                            }
8059
8060                                            output.push(stringFromCharCode(digitToBasic(q, 0)));
8061                                            bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
8062                                            delta = 0;
8063                                            ++handledCPCount;
8064                                        }
8065                                    }
8066
8067                                    ++delta;
8068                                    ++n;
8069
8070                                }
8071                                return output.join('');
8072                            }
8073
8074                            /**
8075                             * Converts a Punycode string representing a domain name or an email address
8076                             * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
8077                             * it doesn't matter if you call it on a string that has already been
8078                             * converted to Unicode.
8079                             * @memberOf punycode
8080                             * @param {String} input The Punycoded domain name or email address to
8081                             * convert to Unicode.
8082                             * @returns {String} The Unicode representation of the given Punycode
8083                             * string.
8084                             */
8085                            function toUnicode(input) {
8086                                return mapDomain(input, function (string) {
8087                                    return regexPunycode.test(string)
8088                                        ? decode(string.slice(4).toLowerCase())
8089                                        : string;
8090                                });
8091                            }
8092
8093                            /**
8094                             * Converts a Unicode string representing a domain name or an email address to
8095                             * Punycode. Only the non-ASCII parts of the domain name will be converted,
8096                             * i.e. it doesn't matter if you call it with a domain that's already in
8097                             * ASCII.
8098                             * @memberOf punycode
8099                             * @param {String} input The domain name or email address to convert, as a
8100                             * Unicode string.
8101                             * @returns {String} The Punycode representation of the given domain name or
8102                             * email address.
8103                             */
8104                            function toASCII(input) {
8105                                return mapDomain(input, function (string) {
8106                                    return regexNonASCII.test(string)
8107                                        ? 'xn--' + encode(string)
8108                                        : string;
8109                                });
8110                            }
8111
8112                            /*--------------------------------------------------------------------------*/
8113
8114                            /** Define the public API */
8115                            punycode = {
8116                                /**
8117                                 * A string representing the current Punycode.js version number.
8118                                 * @memberOf punycode
8119                                 * @type String
8120                                 */
8121                                'version': '1.4.1',
8122                                /**
8123                                 * An object of methods to convert from JavaScript's internal character
8124                                 * representation (UCS-2) to Unicode code points, and back.
8125                                 * @see <https://mathiasbynens.be/notes/javascript-encoding>
8126                                 * @memberOf punycode
8127                                 * @type Object
8128                                 */
8129                                'ucs2': {
8130                                    'decode': ucs2decode,
8131                                    'encode': ucs2encode
8132                                },
8133                                'decode': decode,
8134                                'encode': encode,
8135                                'toASCII': toASCII,
8136                                'toUnicode': toUnicode
8137                            };
8138
8139                            /** Expose `punycode` */
8140                            // Some AMD build optimizers, like r.js, check for specific condition patterns
8141                            // like the following:
8142                            if (
8143                                typeof define == 'function' &&
8144                                typeof define.amd == 'object' &&
8145                                define.amd
8146                            ) {
8147                                define('punycode', function () {
8148                                    return punycode;
8149                                });
8150                            } else if (freeExports && freeModule) {
8151                                if (module.exports == freeExports) {
8152                                    // in Node.js, io.js, or RingoJS v0.8.0+
8153                                    freeModule.exports = punycode;
8154                                } else {
8155                                    // in Narwhal or RingoJS v0.7.0-
8156                                    for (key in punycode) {
8157                                        punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
8158                                    }
8159                                }
8160                            } else {
8161                                // in Rhino or a web browser
8162                                root.punycode = punycode;
8163                            }
8164
8165                        }(this));
8166
8167                    }).call(this, typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
8168                }, {}], 2: [function (_dereq_, module, exports) {
8169                    var log = _dereq_('./log');
8170
8171                    function restoreOwnerScroll(ownerDocument, x, y) {
8172                        if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
8173                            ownerDocument.defaultView.scrollTo(x, y);
8174                        }
8175                    }
8176
8177                    function cloneCanvasContents(canvas, clonedCanvas) {
8178                        try {
8179                            if (clonedCanvas) {
8180                                clonedCanvas.width = canvas.width;
8181                                clonedCanvas.height = canvas.height;
8182                                clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
8183                            }
8184                        } catch (e) {
8185                            log("Unable to copy canvas content from", canvas, e);
8186                        }
8187                    }
8188
8189                    function cloneNode(node, javascriptEnabled) {
8190                        var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
8191
8192                        var child = node.firstChild;
8193                        while (child) {
8194                            if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
8195                                clone.appendChild(cloneNode(child, javascriptEnabled));
8196                            }
8197                            child = child.nextSibling;
8198                        }
8199
8200                        if (node.nodeType === 1) {
8201                            clone._scrollTop = node.scrollTop;
8202                            clone._scrollLeft = node.scrollLeft;
8203                            if (node.nodeName === "CANVAS") {
8204                                cloneCanvasContents(node, clone);
8205                            } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
8206                                clone.value = node.value;
8207                            }
8208                        }
8209
8210                        return clone;
8211                    }
8212
8213                    function initNode(node) {
8214                        if (node.nodeType === 1) {
8215                            node.scrollTop = node._scrollTop;
8216                            node.scrollLeft = node._scrollLeft;
8217
8218                            var child = node.firstChild;
8219                            while (child) {
8220                                initNode(child);
8221                                child = child.nextSibling;
8222                            }
8223                        }
8224                    }
8225
8226                    module.exports = function (ownerDocument, containerDocument, width, height, options, x, y) {
8227                        var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
8228                        var container = containerDocument.createElement("iframe");
8229
8230                        container.className = "html2canvas-container";
8231                        container.style.visibility = "hidden";
8232                        container.style.position = "fixed";
8233                        container.style.left = "-10000px";
8234                        container.style.top = "0px";
8235                        container.style.border = "0";
8236                        container.width = width;
8237                        container.height = height;
8238                        container.scrolling = "no"; // ios won't scroll without it
8239                        containerDocument.body.appendChild(container);
8240
8241                        return new Promise(function (resolve) {
8242                            var documentClone = container.contentWindow.document;
8243
8244                            /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
8245                             if window url is about:blank, we can assign the url to current by writing onto the document
8246                             */
8247                            container.contentWindow.onload = container.onload = function () {
8248                                var interval = setInterval(function () {
8249                                    if (documentClone.body.childNodes.length > 0) {
8250                                        initNode(documentClone.documentElement);
8251                                        clearInterval(interval);
8252                                        if (options.type === "view") {
8253                                            container.contentWindow.scrollTo(x, y);
8254                                            if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
8255                                                documentClone.documentElement.style.top = (-y) + "px";
8256                                                documentClone.documentElement.style.left = (-x) + "px";
8257                                                documentClone.documentElement.style.position = 'absolute';
8258                                            }
8259                                        }
8260                                        resolve(container);
8261                                    }
8262                                }, 50);
8263                            };
8264
8265                            documentClone.open();
8266                            documentClone.write("<!DOCTYPE html><html></html>");
8267                            // Chrome scrolls the parent document for some reason after the write to the cloned window???
8268                            restoreOwnerScroll(ownerDocument, x, y);
8269                            documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
8270                            documentClone.close();
8271                        });
8272                    };
8273
8274                }, { "./log": 13 }
8274], 3: [function (_dereq_, module, exports) {
8275                    // http://dev.w3.org/csswg/css-color/
8276
8277                    function Color(value) {
8278                        this.r = 0;
8279                        this.g = 0;
8280                        this.b = 0;
8281                        this.a = null;
8282                        var result = this.fromArray(value) ||
8283                            this.namedColor(value) ||
8284                            this.rgb(value) ||
8285                            this.rgba(value) ||
8286                            this.hex6(value) ||
8287                            this.hex3(value);
8288                    }
8289
8290                    Color.prototype.darken = function (amount) {
8291                        var a = 1 - amount;
8292                        return new Color([
8293                            Math.round(this.r * a),
8294                            Math.round(this.g * a),
8295                            Math.round(this.b * a),
8296                            this.a
8297                        ]);
8298                    };
8299
8300                    Color.prototype.isTransparent = function () {
8301                        return this.a === 0;
8302                    };
8303
8304                    Color.prototype.isBlack = function () {
8305                        return this.r === 0 && this.g === 0 && this.b === 0;
8306                    };
8307
8308                    Color.prototype.fromArray = function (array) {
8309                        if (Array.isArray(array)) {
8310                            this.r = Math.min(array[0], 255);
8311                            this.g = Math.min(array[1], 255);
8312                            this.b = Math.min(array[2], 255);
8313                            if (array.length > 3) {
8314                                this.a = array[3];
8315                            }
8316                        }
8317
8318                        return (Array.isArray(array));
8319                    };
8320
8321                    var _hex3 = /^#([a-f0-9]{3})$/i;
8322
8323                    Color.prototype.hex3 = function (value) {
8324                        var match = null;
8325                        if ((match = value.match(_hex3)) !== null) {
8326                            this.r = parseInt(match[1][0] + match[1][0], 16);
8327                            this.g = parseInt(match[1][1] + match[1][1], 16);
8328                            this.b = parseInt(match[1][2] + match[1][2], 16);
8329                        }
8330                        return match !== null;
8331                    };
8332
8333                    var _hex6 = /^#([a-f0-9]{6})$/i;
8334
8335                    Color.prototype.hex6 = function (value) {
8336                        var match = null;
8337                        if ((match = value.match(_hex6)) !== null) {
8338                            this.r = parseInt(match[1].substring(0, 2), 16);
8339                            this.g = parseInt(match[1].substring(2, 4), 16);
8340                            this.b = parseInt(match[1].substring(4, 6), 16);
8341                        }
8342                        return match !== null;
8343                    };
8344
8345
8346                    var _rgb = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
8347
8348                    Color.prototype.rgb = function (value) {
8349                        var match = null;
8350                        if ((match = value.match(_rgb)) !== null) {
8351                            this.r = Number(match[1]);
8352                            this.g = Number(match[2]);
8353                            this.b = Number(match[3]);
8354                        }
8355                        return match !== null;
8356                    };
8357
8358                    var _rgba = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
8359
8360                    Color.prototype.rgba = function (value) {
8361                        var match = null;
8362                        if ((match = value.match(_rgba)) !== null) {
8363                            this.r = Number(match[1]);
8364                            this.g = Number(match[2]);
8365                            this.b = Number(match[3]);
8366                            this.a = Number(match[4]);
8367                        }
8368                        return match !== null;
8369                    };
8370
8371                    Color.prototype.toString = function () {
8372                        return this.a !== null && this.a !== 1 ?
8373                            "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
8374                            "rgb(" + [this.r, this.g, this.b].join(",") + ")";
8375                    };
8376
8377                    Color.prototype.namedColor = function (value) {
8378                        value = value.toLowerCase();
8379                        var color = colors[value];
8380                        if (color) {
8381                            this.r = color[0];
8382                            this.g = color[1];
8383                            this.b = color[2];
8384                        } else if (value === "transparent") {
8385                            this.r = this.g = this.b = this.a = 0;
8386                            return true;
8387                        }
8388
8389                        return !!color;
8390                    };
8391
8392                    Color.prototype.isColor = true;
8393
8394                    // JSON.stringify([].slice.call($$('.named-color-table tr'), 1).map(function(row) { return [row.childNodes[3].textContent, row.childNodes[5].textContent.trim().split(",").map(Number)] }).reduce(function(data, row) {data[row[0]] = row[1]; return data}, {}))
8395                    var colors = {
8396                        "aliceblue": [240, 248, 255],
8397                        "antiquewhite": [250, 235, 215],
8398                        "aqua": [0, 255, 255],
8399                        "aquamarine": [127, 255, 212],
8400                        "azure": [240, 255, 255],
8401                        "beige": [245, 245, 220],
8402                        "bisque": [255, 228, 196],
8403                        "black": [0, 0, 0],
8404                        "blanchedalmond": [255, 235, 205],
8405                        "blue": [0, 0, 255],
8406                        "blueviolet": [138, 43, 226],
8407                        "brown": [165, 42, 42],
8408                        "burlywood": [222, 184, 135],
8409                        "cadetblue": [95, 158, 160],
8410                        "chartreuse": [127, 255, 0],
8411                        "chocolate": [210, 105, 30],
8412                        "coral": [255, 127, 80],
8413                        "cornflowerblue": [100, 149, 237],
8414                        "cornsilk": [255, 248, 220],
8415                        "crimson": [220, 20, 60],
8416                        "cyan": [0, 255, 255],
8417                        "darkblue": [0, 0, 139],
8418                        "darkcyan": [0, 139, 139],
8419                        "darkgoldenrod": [184, 134, 11],
8420                        "darkgray": [169, 169, 169],
8421                        "darkgreen": [0, 100, 0],
8422                        "darkgrey": [169, 169, 169],
8423                        "darkkhaki": [189, 183, 107],
8424                        "darkmagenta": [139, 0, 139],
8425                        "darkolivegreen": [85, 107, 47],
8426                        "darkorange": [255, 140, 0],
8427                        "darkorchid": [153, 50, 204],
8428                        "darkred": [139, 0, 0],
8429                        "darksalmon": [233, 150, 122],
8430                        "darkseagreen": [143, 188, 143],
8431                        "darkslateblue": [72, 61, 139],
8432                        "darkslategray": [47, 79, 79],
8433                        "darkslategrey": [47, 79, 79],
8434                        "darkturquoise": [0, 206, 209],
8435                        "darkviolet": [148, 0, 211],
8436                        "deeppink": [255, 20, 147],
8437                        "deepskyblue": [0, 191, 255],
8438                        "dimgray": [105, 105, 105],
8439                        "dimgrey": [105, 105, 105],
8440                        "dodgerblue": [30, 144, 255],
8441                        "firebrick": [178, 34, 34],
8442                        "floralwhite": [255, 250, 240],
8443                        "forestgreen": [34, 139, 34],
8444                        "fuchsia": [255, 0, 255],
8445                        "gainsboro": [220, 220, 220],
8446                        "ghostwhite": [248, 248, 255],
8447                        "gold": [255, 215, 0],
8448                        "goldenrod": [218, 165, 32],
8449                        "gray": [128, 128, 128],
8450                        "green": [0, 128, 0],
8451                        "greenyellow": [173, 255, 47],
8452                        "grey": [128, 128, 128],
8453                        "honeydew": [240, 255, 240],
8454                        "hotpink": [255, 105, 180],
8455                        "indianred": [205, 92, 92],
8456                        "indigo": [75, 0, 130],
8457                        "ivory": [255, 255, 240],
8458                        "khaki": [240, 230, 140],
8459                        "lavender": [230, 230, 250],
8460                        "lavenderblush": [255, 240, 245],
8461                        "lawngreen": [124, 252, 0],
8462                        "lemonchiffon": [255, 250, 205],
8463                        "lightblue": [173, 216, 230],
8464                        "lightcoral": [240, 128, 128],
8465                        "lightcyan": [224, 255, 255],
8466                        "lightgoldenrodyellow": [250, 250, 210],
8467                        "lightgray": [211, 211, 211],
8468                        "lightgreen": [144, 238, 144],
8469                        "lightgrey": [211, 211, 211],
8470                        "lightpink": [255, 182, 193],
8471                        "lightsalmon": [255, 160, 122],
8472                        "lightseagreen": [32, 178, 170],
8473                        "lightskyblue": [135, 206, 250],
8474                        "lightslategray": [119, 136, 153],
8475                        "lightslategrey": [119, 136, 153],
8476                        "lightsteelblue": [176, 196, 222],
8477                        "lightyellow": [255, 255, 224],
8478                        "lime": [0, 255, 0],
8479                        "limegreen": [50, 205, 50],
8480                        "linen": [250, 240, 230],
8481                        "magenta": [255, 0, 255],
8482                        "maroon": [128, 0, 0],
8483                        "mediumaquamarine": [102, 205, 170],
8484                        "mediumblue": [0, 0, 205],
8485                        "mediumorchid": [186, 85, 211],
8486                        "mediumpurple": [147, 112, 219],
8487                        "mediumseagreen": [60, 179, 113],
8488                        "mediumslateblue": [123, 104, 238],
8489                        "mediumspringgreen": [0, 250, 154],
8490                        "mediumturquoise": [72, 209, 204],
8491                        "mediumvioletred": [199, 21, 133],
8492                        "midnightblue": [25, 25, 112],
8493                        "mintcream": [245, 255, 250],
8494                        "mistyrose": [255, 228, 225],
8495                        "moccasin": [255, 228, 181],
8496                        "navajowhite": [255, 222, 173],
8497                        "navy": [0, 0, 128],
8498                        "oldlace": [253, 245, 230],
8499                        "olive": [128, 128, 0],
8500                        "olivedrab": [107, 142, 35],
8501                        "orange": [255, 165, 0],
8502                        "orangered": [255, 69, 0],
8503                        "orchid": [218, 112, 214],
8504                        "palegoldenrod": [238, 232, 170],
8505                        "palegreen": [152, 251, 152],
8506                        "paleturquoise": [175, 238, 238],
8507                        "palevioletred": [219, 112, 147],
8508                        "papayawhip": [255, 239, 213],
8509                        "peachpuff": [255, 218, 185],
8510                        "peru": [205, 133, 63],
8511                        "pink": [255, 192, 203],
8512                        "plum": [221, 160, 221],
8513                        "powderblue": [176, 224, 230],
8514                        "purple": [128, 0, 128],
8515                        "rebeccapurple": [102, 51, 153],
8516                        "red": [255, 0, 0],
8517                        "rosybrown": [188, 143, 143],
8518                        "royalblue": [65, 105, 225],
8519                        "saddlebrown": [139, 69, 19],
8520                        "salmon": [250, 128, 114],
8521                        "sandybrown": [244, 164, 96],
8522                        "seagreen": [46, 139, 87],
8523                        "seashell": [255, 245, 238],
8524                        "sienna": [160, 82, 45],
8525                        "silver": [192, 192, 192],
8526                        "skyblue": [135, 206, 235],
8527                        "slateblue": [106, 90, 205],
8528                        "slategray": [112, 128, 144],
8529                        "slategrey": [112, 128, 144],
8530                        "snow": [255, 250, 250],
8531                        "springgreen": [0, 255, 127],
8532                        "steelblue": [70, 130, 180],
8533                        "tan": [210, 180, 140],
8534                        "teal": [0, 128, 128],
8535                        "thistle": [216, 191, 216],
8536                        "tomato": [255, 99, 71],
8537                        "turquoise": [64, 224, 208],
8538                        "violet": [238, 130, 238],
8539                        "wheat": [245, 222, 179],
8540                        "white": [255, 255, 255],
8541                        "whitesmoke": [245, 245, 245],
8542                        "yellow": [255, 255, 0],
8543                        "yellowgreen": [154, 205, 50]
8544                    };
8545
8546                    module.exports = Color;
8547
8548                }, {}], 4: [function (_dereq_, module, exports) {
8549                    var Support = _dereq_('./support');
8550                    var CanvasRenderer = _dereq_('./renderers/canvas');
8551                    var ImageLoader = _dereq_('./imageloader');
8552                    var NodeParser = _dereq_('./nodeparser');
8553                    var NodeContainer = _dereq_('./nodecontainer');
8554                    var log = _dereq_('./log');
8555                    var utils = _dereq_('./utils');
8556                    var createWindowClone = _dereq_('./clone');
8557                    var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
8558                    var getBounds = utils.getBounds;
8559
8560                    var html2canvasNodeAttribute = "data-html2canvas-node";
8561                    var html2canvasCloneIndex = 0;
8562
8563                    function html2canvas(nodeList, options) {
8564                        var index = html2canvasCloneIndex++;
8565                        options = options || {};
8566                        if (options.logging) {
8567                            log.options.logging = true;
8568                            log.options.start = Date.now();
8569                        }
8570
8571                        options.async = typeof (options.async) === "undefined" ? true : options.async;
8572                        options.allowTaint = typeof (options.allowTaint) === "undefined" ? false : options.allowTaint;
8573                        options.removeContainer = typeof (options.removeContainer) === "undefined" ? true : options.removeContainer;
8574                        options.javascriptEnabled = typeof (options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
8575                        options.imageTimeout = typeof (options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
8576                        options.renderer = typeof (options.renderer) === "function" ? options.renderer : CanvasRenderer;
8577                        options.strict = !!options.strict;
8578
8579                        if (typeof (nodeList) === "string") {
8580                            if (typeof (options.proxy) !== "string") {
8581                                return Promise.reject("Proxy must be used when rendering url");
8582                            }
8583                            var width = options.width != null ? options.width : window.innerWidth;
8584                            var height = options.height != null ? options.height : window.innerHeight;
8585                            return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function (container) {
8586                                return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
8587                            });
8588                        }
8589
8590                        var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
8591                        node.setAttribute(html2canvasNodeAttribute + index, index);
8592                        return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function (canvas) {
8593                            if (typeof (options.onrendered) === "function") {
8594                                log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
8595                                options.onrendered(canvas);
8596                            }
8597                            return canvas;
8598                        });
8599                    }
8600
8601                    html2canvas.CanvasRenderer = CanvasRenderer;
8602                    html2canvas.NodeContainer = NodeContainer;
8603                    html2canvas.log = log;
8604                    html2canvas.utils = utils;
8605
8606                    var html2canvasExport = (typeof (document) === "undefined" || typeof (Object.create) !== "function" || typeof (document.createElement("canvas").getContext) !== "function") ? function () {
8607                        return Promise.reject("No canvas support");
8608                    } : html2canvas;
8609
8610                    module.exports = html2canvasExport;
8611
8612                    if (typeof (define) === 'function' && define.amd) {
8613                        define('html2canvas', [], function () {
8614                            return html2canvasExport;
8615                        });
8616                    }
8617
8618                    function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
8619                        return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function (container) {
8620                            log("Document cloned");
8621                            var attributeName = html2canvasNodeAttribute + html2canvasIndex;
8622                            var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
8623                            document.querySelector(selector).removeAttribute(attributeName);
8624                            var clonedWindow = container.contentWindow;
8625                            var node = clonedWindow.document.querySelector(selector);
8626                            var oncloneHandler = (typeof (options.onclone) 
8626=== "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
8627                            return oncloneHandler.then(function () {
8628                                return renderWindow(node, container, options, windowWidth, windowHeight);
8629                            });
8630                        });
8631                    }
8632
8633                    function renderWindow(node, container, options, windowWidth, windowHeight) {
8634                        var clonedWindow = container.contentWindow;
8635                        var support = new Support(clonedWindow.document);
8636                        var imageLoader = new ImageLoader(options, support);
8637                        var bounds = getBounds(node);
8638                        var width = options.type === "view" ? windowWidth : bounds.right + 1;
8639                        var height = options.type === "view" ? windowHeight : bounds.bottom + 1;
8640                        var renderer = new options.renderer(width, height, imageLoader, options, document);
8641                        var parser = new NodeParser(node, renderer, support, imageLoader, options);
8642                        return parser.ready.then(function () {
8643                            log("Finished rendering");
8644                            var canvas;
8645
8646                            if (options.type === "view") {
8647                                canvas = crop(renderer.canvas, { width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0 });
8648                            } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
8649                                canvas = renderer.canvas;
8650                            } else if (options.scale) {
8651                                var origBounds = { width: options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: 0, y: 0 };
8652                                var cropBounds = {};
8653                                for (var key in origBounds) {
8654                                    if (origBounds.hasOwnProperty(key)) { cropBounds[key] = origBounds[key] * options.scale; }
8655                                }
8656                                canvas = crop(renderer.canvas, cropBounds);
8657                                canvas.style.width = origBounds.width + 'px';
8658                                canvas.style.height = origBounds.height + 'px';
8659                            } else {
8660                                canvas = crop(renderer.canvas, { width: options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: 0, y: 0 });
8661                            }
8662
8663                            cleanupContainer(container, options);
8664                            return canvas;
8665                        });
8666                    }
8667
8668                    function cleanupContainer(container, options) {
8669                        if (options.removeContainer) {
8670                            container.parentNode.removeChild(container);
8671                            log("Cleaned up container");
8672                        }
8673                    }
8674
8675                    function crop(canvas, bounds) {
8676                        var croppedCanvas = document.createElement("canvas");
8677                        var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
8678                        var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
8679                        var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
8680                        var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
8681                        croppedCanvas.width = bounds.width;
8682                        croppedCanvas.height = bounds.height;
8683                        var width = x2 - x1;
8684                        var height = y2 - y1;
8685                        log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", width, "he
8685ight:", height);
8686                        log("Resulting crop with width", bounds.width, "and height", bounds.height, "with x", x1, "and y", y1);
8687                        croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, width, height, bounds.x, bounds.y, width, height);
8688                        return croppedCanvas;
8689                    }
8690
8691                    function absoluteUrl(url) {
8692                        var link = document.createElement("a");
8693                        link.href = url;
8694                        link.href = link.href;
8695                        return link;
8696                    }
8697
8698                }, { "./clone": 2, "./imageloader": 11, "./log": 13, "./nodecontainer": 14, "./nodeparser": 15, "./proxy": 16, "./renderers/canvas": 20, "./support": 22, "./utils": 26 }], 5: [function (_dereq_, module, exports) {
8699                    var log = _dereq_('./log');
8700                    var smallImage = _dereq_('./utils').smallImage;
8701
8702                    function DummyImageContainer(src) {
8703                        this.src = src;
8704                        log("DummyImageContainer for", src);
8705                        if (!this.promise || !this.image) {
8706                            log("Initiating DummyImageContainer");
8707                            DummyImageContainer.prototype.image = new Image();
8708                            var image = this.image;
8709                            DummyImageContainer.prototype.promise = new Promise(function (resolve, reject) {
8710                                image.onload = resolve;
8711                                image.onerror = reject;
8712                                image.src = smallImage();
8713                                if (image.complete === true) {
8714                                    resolve(image);
8715                                }
8716                            });
8717                        }
8718                    }
8719
8720                    module.exports = DummyImageContainer;
8721
8722                }, { "./log": 13, "./utils": 26 }], 6: [function (_dereq_, module, exports) {
8723                    var smallImage = _dereq_('./utils').smallImage;
8724
8725                    function Font(family, size) {
8726                        var container = document.createElement('div'),
8727                            img = document.createElement('img'),
8728                            span = document.createElement('span'),
8729                            sampleText = 'Hidden Text',
8730                            baseline,
8731                            middle;
8732
8733                        container.style.visibility = "hidden";
8734                        container.style.fontFamily = family;
8735                        container.style.fontSize = size;
8736                        container.style.margin = 0;
8737                        container.style.padding = 0;
8738
8739                        document.body.appendChild(container);
8740
8741                        img.src = smallImage();
8742                        img.width = 1;
8743                        img.height = 1;
8744
8745                        img.style.margin = 0;
8746                        img.style.padding = 0;
8747                        img.style.verticalAlign = "baseline";
8748
8749                        span.style.fontFamily = family;
8750                        span.style.fontSize = size;
8751                        span.style.margin = 0;
8752                        span.style.padding = 0;
8753
8754                        span.appendChild(document.createTextNode(sampleText));
8755                        container.appendChild(span);
8756                        container.appendChild(img);
8757                        baseline = (img.offsetTop - span.offsetTop) + 1;
8758
8759                        container.removeChild(span);
8760                        container.appendChild(document.createTextNode(sampleText));
8761
8762                        container.style.lineHeight = "normal";
8763                        img.style.verticalAlign = "super";
8764
8765                        middle = (img.offsetTop - container.offsetTop) + 1;
8766
8767                        document.body.removeChild(container);
8768
8769                        this.baseline = baseline;
8770                        this.lineWidth = 1;
8771                        this.middle = middle;
8772                    }
8773
8774                    module.exports = Font;
8775
8776                }, { "./utils": 26 }
8776], 7: [function (_dereq_, module, exports) {
8777                    var Font = _dereq_('./font');
8778
8779                    function FontMetrics() {
8780                        this.data = {};
8781                    }
8782
8783                    FontMetrics.prototype.getMetrics = function (family, size) {
8784                        if (this.data[family + "-" + size] === undefined) {
8785                            this.data[family + "-" + size] = new Font(family, size);
8786                        }
8787                        return this.data[family + "-" + size];
8788                    };
8789
8790                    module.exports = FontMetrics;
8791
8792                }, { "./font": 6 }], 8: [function (_dereq_, module, exports) {
8793                    var utils = _dereq_('./utils');
8794                    var getBounds = utils.getBounds;
8795                    var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
8796
8797                    function FrameContainer(container, sameOrigin, options) {
8798                        this.image = null;
8799                        this.src = container;
8800                        var self = this;
8801                        var bounds = getBounds(container);
8802                        this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function (resolve) {
8803                            if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
8804                                container.contentWindow.onload = container.onload = function () {
8805                                    resolve(container);
8806                                };
8807                            } else {
8808                                resolve(container);
8809                            }
8810                        })).then(function (container) {
8811                            var html2canvas = _dereq_('./core');
8812                            return html2canvas(container.contentWindow.document.documentElement, { type: 'view', width: container.width, height: container.height, proxy: options.proxy, javascriptEnabled: options.javascriptEnabled, removeContainer: options.removeContainer, allowTaint: options.allowTaint, imageTimeout: options.imageTimeout / 2 });
8813                        }).then(function (canvas) {
8814                            return self.image = canvas;
8815                        });
8816                    }
8817
8818                    FrameContainer.prototype.proxyLoad = function (proxy, bounds, options) {
8819                        var container = this.src;
8820                        return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
8821                    };
8822
8823                    module.exports = FrameContainer;
8824
8825                }, { "./core": 4, "./proxy": 16, "./utils": 26 }], 9: [function (_dereq_, module, exports) {
8826                    function GradientContainer(imageData) {
8827                        this.src = imageData.value;
8828                        this.colorStops = [];
8829                        this.type = null;
8830                        this.x0 = 0.5;
8831                        this.y0 = 0.5;
8832                        this.x1 = 0.5;
8833                        this.y1 = 0.5;
8834                        this.promise = Promise.resolve(true);
8835                    }
8836
8837                    GradientContainer.TYPES = {
8838                        LINEAR: 1,
8839                        RADIAL: 2
8840                    };
8841
8842                    // TODO: support hsl[a], negative %/length values
8843                    // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
8844                    GradientContainer.REGEXP_COLORSTOP = /^\s*(rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*[0-9\.]+)?\s*\)|[a-z]{3,20}|#[a-f0-9]{3,6})(?:\s+(\d{1,3}(?:\.\d+)?)(%|px)?)?(?:\s|$)/i;
8845
8846                    module.exports = GradientContainer;
8847
8848                }, {}], 10: [function (_dereq_, module, exports) {
8849                    function ImageContainer(src, cors) {
8850                        this.src = src;
8851                        this.image = new Image();
8852                        var self = this;
8853                        this.tainted = null;
8854                        this.promise = new Promise(function (resolve, reject) {
8855                            self.image.onload = resolve;
8856                            self.image.onerror = reject;
8857                            if (cors) {
8858                                self.image.crossOrigin = "anonymous";
8859                            }
8860                            self.image.src = src;
8861                            if (self.image.complete === true) {
8862                                resolve(self.image);
8863                            }
8864                        });
8865                    }
8866
8867                    module.exports = ImageContainer;
8868
8869                }, {}
8869], 11: [function (_dereq_, module, exports) {
8870                    var log = _dereq_('./log');
8871                    var ImageContainer = _dereq_('./imagecontainer');
8872                    var DummyImageContainer = _dereq_('./dummyimagecontainer');
8873                    var ProxyImageContainer = _dereq_('./proxyimagecontainer');
8874                    var FrameContainer = _dereq_('./framecontainer');
8875                    var SVGContainer = _dereq_('./svgcontainer');
8876                    var SVGNodeContainer = _dereq_('./svgnodecontainer');
8877                    var LinearGradientContainer = _dereq_('./lineargradientcontainer');
8878                    var WebkitGradientContainer = _dereq_('./webkitgradientcontainer');
8879                    var bind = _dereq_('./utils').bind;
8880
8881                    function ImageLoader(options, support) {
8882                        this.link = null;
8883                        this.options = options;
8884                        this.support = support;
8885                        this.origin = this.getOrigin(window.location.href);
8886                    }
8887
8888                    ImageLoader.prototype.findImages = function (nodes) {
8889                        var images = [];
8890                        nodes.reduce(function (imageNodes, container) {
8891                            switch (container.node.nodeName) {
8892                                case "IMG":
8893                                    return imageNodes.concat([{
8894                                        args: [container.node.src],
8895                                        method: "url"
8896                                    }]);
8897                                case "svg":
8898                                case "IFRAME":
8899                                    return imageNodes.concat([{
8900                                        args: [container.node],
8901                                        method: container.node.nodeName
8902                                    }]);
8903                            }
8904                            return imageNodes;
8905                        }, []).forEach(this.addImage(images, this.loadImage), this);
8906                        return images;
8907                    };
8908
8909                    ImageLoader.prototype.findBackgroundImage = function (images, container) {
8910                        container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
8911                        return images;
8912                    };
8913
8914                    ImageLoader.prototype.addImage = function (images, callback) {
8915                        return function (newImage) {
8916                            newImage.args.forEach(function (image) {
8917                                if (!this.imageExists(images, image)) {
8918                                    images.splice(0, 0, callback.call(this, newImage));
8919                                    log('Added image #' + (images.length), typeof (image) === "string" ? image.substring(0, 100) : image);
8920                                }
8921                            }, this);
8922                        };
8923                    };
8924
8925                    ImageLoader.prototype.hasImageBackground = function (imageData) {
8926                        return imageData.method !== "none";
8927                    };
8928
8929                    ImageLoader.prototype.loadImage = function (imageData) {
8930                        if (imageData.method === "url") {
8931                            var src = imageData.args[0];
8932                            if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
8933                                return new SVGContainer(src);
8934                            } else if (src.match(/data:image\/.*;base64,/i)) {
8935                                return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
8936                            } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
8937                                return new ImageContainer(src, false);
8938                            } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
8939                                return new ImageContainer(src, true);
8940                            } else if (this.options.proxy) {
8941                                return new ProxyImageContainer(src, this.options.proxy);
8942                            } else {
8943                                return new DummyImageContainer(src);
8944                            }
8945                        } else if (imageData.method === "linear-gradient") {
8946                            return new LinearGradientContainer(imageData);
8947                        } else if (imageData.method === "gradient") {
8948                            return new WebkitGradientContainer(imageData);
8949                        } else if (imageData.method === "svg") {
8950                            return new SVGNodeContainer(imageData.args[0], this.support.svg);
8951                        } else if (imageData.method === "IFRAME") {
8952                            return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
8953                        } else {
8954                            return new DummyImageContainer(imageData);
8955                        }
8956                    };
8957
8958                    ImageLoader.prototype.isSVG = function (src) {
8959                        return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
8960                    };
8961
8962                    ImageLoader.prototype.imageExists = function (images, src) {
8963                        return images.some(function (image) {
8964                            return image.src === src;
8965                        });
8966                    };
8967
8968                    ImageLoader.prototype.isSameOrigin = function (url) {
8969                        return (this.getOrigin(url) === this.origin);
8970                    };
8971
8972                    ImageLoader.prototype.getOrigin = function (url) {
8973                        var link = this.link || (this.link = document.createElement("a"));
8974                        link.href = url;
8975                        link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
8976                        return link.protocol + link.hostname + link.port;
8977                    };
8978
8979                    ImageLoader.prototype.getPromise = function (container) {
8980                        return this.timeout(container, this.options.imageTimeout)['catch'](function () {
8981                            var dummy = new DummyImageContainer(container.src);
8982                            return dummy.promise.then(function (image) {
8983                                container.image = image;
8984                            });
8985                        });
8986                    };
8987
8988                    ImageLoader.prototype.get = function (src) {
8989                        var found = null;
8990                        return this.images.some(function (img) {
8991                            return (found = img).src === src;
8992                        }) ? found : null;
8993                    };
8994
8995                    ImageLoader.prototype.fetch = function (nodes) {
8996                        this.images = nodes.reduce(bind(this.findBackgroun
8996dImage, this), this.findImages(nodes));
8997                        this.images.forEach(function (image, index) {
8998                            image.promise.then(function () {
8999                                log("Succesfully loaded image #" + (index + 1), image);
9000                            }, function (e) {
9001                                log("Failed loading image #" + (index + 1), image, e);
9002                            });
9003                        });
9004                        this.ready = Promise.all(this.images.map(this.getPromise, this));
9005                        log("Finished searching images");
9006                        return this;
9007                    };
9008
9009                    ImageLoader.prototype.timeout = function (container, timeout) {
9010                        var timer;
9011                        var promise = Promise.race([container.promise, new Promise(function (res, reject) {
9012                            timer = setTimeout(function () {
9013                                log("Timed out loading image", container);
9014                                reject(container);
9015                            }, timeout);
9016                        })]).then(function (container) {
9017                            clearTimeout(timer);
9018                            return container;
9019                        });
9020                        promise['catch'](function () {
9021                            clearTimeout(timer);
9022                        });
9023                        return promise;
9024                    };
9025
9026                    module.exports = ImageLoader;
9027
9028                }, { "./dummyimagecontainer": 5, "./framecontainer": 8, "./imagecontainer": 10, "./lineargradientcontainer": 12, "./log": 13, "./proxyimagecontainer": 17, "./svgcontainer": 23, "./svgnodecontainer": 24, "./utils": 26, "./webkitgradientcontainer": 27 }], 12: [function (_dereq_, module, exports) {
9029                    var GradientContainer = _dereq_('./gradientcontainer');
9030                    var Color = _dereq_('./color');
9031
9032                    function LinearGradientContainer(imageData) {
9033                        GradientContainer.apply(this, arguments);
9034                        this.type = GradientContainer.TYPES.LINEAR;
9035
9036                        var hasDirection = LinearGradientContainer.REGEXP_DIRECTION.test(imageData.args[0]) ||
9037                            !GradientContainer.REGEXP_COLORSTOP.test(imageData.args[0]);
9038
9039                        if (hasDirection) {
9040                            imageData.args[0].split(/\s+/).reverse().forEach(function (position, index) {
9041                                switch (position) {
9042                                    case "left":
9043                                        this.x0 = 0;
9044                                        this.x1 = 1;
9045                                        break;
9046                                    case "top":
9047                                        this.y0 = 0;
9048                                        this.y1 = 1;
9049                                        break;
9050                                    case "right":
9051                                        this.x0 = 1;
9052                                        this.x1 = 0;
9053                                        break;
9054                                    case "bottom":
9055                                        this.y0 = 1;
9056                                        this.y1 = 0;
9057                                        break;
9058                                    case "to":
9059                                        var y0 = this.y0;
9060                                        var x0 = this.x0;
9061                                        this.y0 = this.y1;
9062                                        this.x0 = this.x1;
9063                                        this.x1 = x0;
9064                                        this.y1 = y0;
9065                                        break;
9066                                    case "center":
9067                                        break; // centered by default
9068                                    // Firefox internally converts position keywords to percentages:
9069                                    // http://www.w3.org/TR/2010/WD-CSS2-20101207/colors.html#propdef-background-position
9070                                    default: // percentage or absolute length
9071                                        // TODO: support absolute start point positions (e.g., use bounds to convert px to a ratio)
9072                                        var ratio = parseFloat(position, 10) * 1e-2;
9073                                        if (isNaN(ratio)) { // invalid or unhandled value
9074                                            break;
9075                                        }
9076                                        if (index === 0) {
9077                                            this.y0 = ratio;
9078                                            this.y1 = 1 - this.y0;
9079                                        } else {
9080                                            this.x0 = ratio;
9081                                            this.x1 = 1 - this.x0;
9082                                        }
9083                                        break;
9084                                }
9085                            }, this);
9086                        } else {
9087                            this.y0 = 0;
9088                            this.y1 = 1;
9089                        }
9090
9091                        this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function (colorStop) {
9092                            var colorStopMatch = colorStop.match(GradientContainer.REGEXP_COLORSTOP);
9093                            var value = +colorStopMatch[2];
9094                            var unit = value === 0 ? "%" : colorStopMatch[3]; // treat "0" as "0%"
9095                            return {
9096                                color: new Color(colorStopMatch[1]),
9097                                // TODO: support absolute stop positions (e.g., compute gradient line length & convert px to ratio)
9098                                stop: unit === "%" ? value / 100 : null
9099                            };
9100                        });
9101
9102                        if (this.colorStops[0].stop === null) {
9103                            this.colorStops[0].stop = 0;
9104                        }
9105
9106                        if (this.colorStops[this.colorStops.length - 1].stop === null) {
9107                            this.colorStops[this.colorStops.length - 1].stop = 1;
9108                        }
9109
9110                        // calculates and fills-in explicit stop positions when omitted from rule
9111                        this.colorStops.forEach(function (colorStop, index) {
9112                            if (colorStop.stop === null) {
9113                                this.colorStops.slice(index).some(function (find, count) {
9114                                    if (find.stop !== null) {
9115                                        colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
9116                                        return true;
9117                                    } else {
9118                                        return false;
9119                                    }
9120                                }, this);
9121                            }
9122                        }, this);
9123                    }
9124
9125                    LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
9126
9127                    // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
9128                    LinearGradientContainer.REGEXP_DIRECTION = /^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i;
9129
9130                    module.exports = LinearGradientContainer;
9131
9132                }, { "./color": 3, "./gradientcontainer": 9 }], 13: [function (_dereq_, module, exports) {
9133                    var logger = function () {
9134                        if (logger.options.logging && window.console && window.console.log) {
9135                            Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - logger.options.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
9136                        }
9137                    };
9138
9139                    logger.options = { logging: false };
9140                    module.exports = logger;
9141
9142                }, {}], 14: [function (_dereq_, module, exports) {
9143                    var Color = _dereq_('./color');
9144                    var utils = _dereq_('./utils');
9145                    var getBounds = utils.getBounds;
9146                    var parseBackgrounds = utils.parseBackgrounds;
9147                    var offsetBounds = utils.offsetBounds;
9148
9149                    function NodeContainer(node, parent) {
9150                        this.node = node;
9151                        this.parent = parent;
9152                        this.stack = null;
9153                        this.bounds = null;
9154                        this.borders = null;
9155                        this.clip = [];
9156                        this.backgroundClip = [];
9157                        this.offsetBounds = null;
9158                        this.visible = null;
9159                        this.computedStyles = null;
9160                        this.colors = {};
9161                        this.styles = {};
9162                        this.backgroundImages = null;
9163                        this.transformData = null;
9164                        this.transformMatrix = null;
9165                        this.isPseudoElement = false;
9166                        this.opacity = null;
9167                    }
9168
9169                    NodeContainer.prototype.cloneTo = function (stack) {
9170                        stack.visible = this.visible;
9171                        stack.borders = this.borders;
9172                        stack.bounds = this.bounds;
9173                        stack.clip = this.clip;
9174                        stack.backgroundClip = this.backgroundClip;
9175                        stack.computedStyles = this.computedStyles;
9176                        stack.styles = this.styles;
9177                        stack.backgroundImages = this.backgroundImages;
9178                        stack.opacity = this.opacity;
9179                    };
9180
9181                    NodeContainer.prototype.getOpacity = function () {
9182                        return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
9183                    };
9184
9185                    NodeContainer.prototype.assignStack = function (stack) {
9186                        this.stack = stack;
9187                        stack.children.push(this);
9188                    };
9189
9190                    NodeContainer.prototype.isElementVisible = function () {
9191                        return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
9192                            this.css('display') !== "none" &&
9193                            this.css('visibility') !== "hidden" &&
9194                            !this.node.hasAttribute("data-html2canvas-ignore") &&
9195                            (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
9196                        );
9197                    };
9198
9199                    NodeContainer.prototype.css = function (attribute) {
9200                        if (!this.computedStyles) {
9201                            this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
9202                        }
9203
9204                        return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
9205                    };
9206
9207                    NodeContainer.prototype.prefixedCss = function (attribute) {
9208                        var prefixes = ["webkit", "moz", "ms", "o"];
9209                        var value = this.css(attribute);
9210                        if (value === undefined) {
9211                            prefixes.some(function (prefix) {
9212                                value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
9213                                return value !== undefined;
9214                            }, this);
9215                        }
9216                        return value === undefined ? null : value;
9217                    };
9218
9219                    NodeContainer.prototype.computedStyle = function (type) {
9220                        return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
9221                    };
9222
9223                    NodeContainer.prototype.cssInt = function (attribute) {
9224                        var value = parseInt(this.css(attribute), 10);
9225                        return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
9226                    };
9227
9228                    NodeContainer.prototype.color = function (attribute) {
9229                        return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
9230                    };
9231
9232                    NodeContainer.prototype.cssFloat = function (attribute) {
9233                        var value = parseFloat(this.css(attribute));
9234                        return (isNaN(value)) ? 0 : value;
9235                    };
9236
9237                    NodeContainer.prototype.fontWeight = function () {
9238                        var weight = this.css("fontWeight");
9239                        switch (parseInt(weight, 10)) {
9240                            case 401:
9241                                weight = "bold";
9242                                break;
9243                            case 400:
9244                                weight = "normal";
9245                                break;
9246                        }
9247                        return weight;
9248                    };
9249
9250                    NodeContainer.prototype.parseClip = function () {
9251                        var matches = this.css('clip').match(this.CLIP);
9252                        if (matches) {
9253                            return {
9254                                top: parseInt(matches[1], 10),
9255                                right: parseInt(matches[2], 10),
9256                                bottom: parseInt(matches[3], 10),
9257                                left: parseInt(matches[4], 10)
9258                            };
9259                        }
9260                        return null;
9261                    };
9262
9263                    NodeContainer.prototype.parseBackgroundImages = function () {
9264                        return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
9265                    };
9266
9267                    NodeContainer.prototype.cssList = function (property, index) {
9268                        var value = (this.css(property) || '').split(',');
9269                        value = value[index || 0] || value[0] || 'auto';
9270                        value = value.trim().split(' ');
9271                        if (value.length === 1) {
9272                            value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
9273                        }
9274                        return value;
9275                    };
9276
9277                    NodeContainer.prototype.parseBackgroundSize = function (bounds, image, index) {
9278                        var size = this.cssList("backgroundSize", index);
9279                        var width, height;
9280
9281                        if (isPercentage(size[0])) {
9282                            width = bounds.width * parseFloat(size[0]) / 100;
9283                        } else if (/contain|cover/.test(size[0])) {
9284                            var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
9285                            return (targetRatio < currentRatio ^ size[0] === 'contain') ? { width: bounds.height * currentRatio, height: bounds.height } : { width: bounds.width, height: bounds.width / currentRatio };
9286                        } else {
9287                            width = parseInt(size[0], 10);
9288                        }
9289
9290                        if (size[0] === 'auto' && size[1] === 'auto') {
9291                            height = image.height;
9292                        } else if (size[1] === 'auto') {
9293                            height = width / image.width * image.height;
9294                        } else if (isPercentage(size[1])) {
9295                            height = bounds.height * parseFloat(size[1]) / 100;
9296                        } else {
9297                            height = parseInt(size[1], 10);
9298                        }
9299
9300                        if (size[0] === 'auto') {
9301                            width = height / image.height * image.width;
9302                        }
9303
9304                        return { width: width, height: height };
9305                    };
9306
9307                    NodeContainer.prototype.parseBackgroundPosition = function (bounds, image, index, backgroundSize) {
9308                        var position = this.cssList('backgroundPosition', index);
9309                        var left, top;
9310
9311                        if (isPercentage(position[0])) {
9312                            left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
9313                        } else {
9314                            left = parseInt(position[0], 10);
9315                        }
9316
9317                        if (position[1] === 'auto') {
9318                            top = left / image.width * image.height;
9319                        } else if (isPercentage(position[1])) {
9320                            top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
9321                        } else {
9322                            top = parseInt(position[1], 10);
9323                        }
9324
9325                        if (position[0] === 'auto') {
9326                            left = top / image.height * image.width;
9327                        }
9328
9329                        return { left: left, top: top };
9330                    };
9331
9332                    NodeContainer.prototype.parseBackgroundRepeat = function (index) {
9333                        return this.cssList("backgroundRepeat", index)[0];
9334                    };
9335
9336                    NodeContainer.prototype.parseTextShadows = function () {
9337                        var textShadow = this.css("textShadow");
9338                        var results = [];
9339
9340                        if (textShadow && textShadow !== 'none') {
9341                            var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
9342                            for (var i = 0; shadows && (i < shadows.length); i++) {
9343                                var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
9344                                results.push({
9345                                    color: new Color(s[0]),
9346                                    offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
9347                                    offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
9348                                    blur: s[3] ? s[3].replace('px', '') 
9348: 0
9349                                });
9350                            }
9351                        }
9352                        return results;
9353                    };
9354
9355                    NodeContainer.prototype.parseTransform = function () {
9356                        if (!this.transformData) {
9357                            if (this.hasTransform()) {
9358                                var offset = this.parseBounds();
9359                                var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
9360                                origin[0] += offset.left;
9361                                origin[1] += offset.top;
9362                                this.transformData = {
9363                                    origin: origin,
9364                                    matrix: this.parseTransformMatrix()
9365                                };
9366                            } else {
9367                                this.transformData = {
9368                                    origin: [0, 0],
9369                                    matrix: [1, 0, 0, 1, 0, 0]
9370                                };
9371                            }
9372                        }
9373                        return this.transformData;
9374                    };
9375
9376                    NodeContainer.prototype.parseTransformMatrix = function () {
9377                        if (!this.transformMatrix) {
9378                            var transform = this.prefixedCss("transform");
9379                            var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
9380                            this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
9381                        }
9382                        return this.transformMatrix;
9383                    };
9384
9385                    NodeContainer.prototype.inverseTransform = function () {
9386                        var transformData = this.parseTransform();
9387                        return { origin: transformData.origin, matrix: matrixInverse(transformData.matrix) };
9388                    };
9389
9390                    NodeContainer.prototype.parseBounds = function () {
9391                        return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
9392                    };
9393
9394                    NodeContainer.prototype.hasTransform = function () {
9395                        return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
9396                    };
9397
9398                    NodeContainer.prototype.getValue = function () {
9399                        var value = this.node.value || "";
9400                        if (this.node.tagName === "SELECT") {
9401                            value = selectionValue(this.node);
9402                        } else if (this.node.type === "password") {
9403                            value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
9404                        }
9405                        return value.length === 0 ? (this.node.placeholder || "") : value;
9406                    };
9407
9408                    NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
9409                    NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
9410                    NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
9411                    NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
9412
9413                    function selectionValue(node) {
9414                        var option = node.options[node.selectedIndex || 0];
9415                        return option ? (option.text || "") : "";
9416                    }
9417
9418                    function parseMatrix(match) {
9419                        if (match && match[1] === "matrix") {
9420                            return match[2].split(",").map(function (s) {
9421                                return parseFloat(s.trim());
9422                            });
9423                        } else if (match && match[1] === "matrix3d") {
9424                            var matrix3d = match[2].split(",").map(function (s) {
9425                                return parseFloat(s.trim());
9426                            });
9427                            return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
9428                        }
9429                    }
9430
9431                    function matrixInverse(m) {
9432                        // This is programmed specifically for transform matrices, which have a fixed structure.
9433                        var a = m[0], b = m[2], c = m[4], d = m[1], e = m[3], f = m[5];
9434                        var det = a * e - b * d;
9435                        var M = [e, -d, -b, a, b * f - c * e, c * d - a * f].map(function (val) { return val / det; });
9436                        return M;
9437                    }
9438
9439                    function isPercentage(value) {
9440                        return value.toString().indexOf("%") !== -1;
9441                    }
9442
9443                    function removePx(str) {
9444                        return str.replace("px", "");
9445                    }
9446
9447                    function asFloat(str) {
9448                        return parseFloat(str);
9449                    }
9450
9451                    module.exports = NodeContainer;
9452
9453                }, { "./color": 3, "./utils": 26 }
9453], 15: [function (_dereq_, module, exports) {
9454                    var log = _dereq_('./log');
9455                    var punycode = _dereq_('punycode');
9456                    var NodeContainer = _dereq_('./nodecontainer');
9457                    var TextContainer = _dereq_('./textcontainer');
9458                    var PseudoElementContainer = _dereq_('./pseudoelementcontainer');
9459                    var FontMetrics = _dereq_('./fontmetrics');
9460                    var Color = _dereq_('./color');
9461                    var StackingContext = _dereq_('./stackingcontext');
9462                    var utils = _dereq_('./utils');
9463                    var bind = utils.bind;
9464                    var getBounds = utils.getBounds;
9465                    var parseBackgrounds = utils.parseBackgrounds;
9466                    var offsetBounds = utils.offsetBounds;
9467
9468                    function NodeParser(element, renderer, support, imageLoader, options) {
9469                        log("Starting NodeParser");
9470                        this.renderer = renderer;
9471                        this.options = options;
9472                        this.range = null;
9473                        this.support = support;
9474                        this.renderQueue = [];
9475                        this.stack = new StackingContext(true, 1, element.ownerDocument, null);
9476                        var parent = new NodeContainer(element, null);
9477                        if (options.background) {
9478                            renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
9479                        }
9480                        if (element === element.ownerDocument.documentElement) {
9481                            // http://www.w3.org/TR/css3-background/#special-backgrounds
9482                            var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
9483                            renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
9484                        }
9485                        parent.visibile = parent.isElementVisible();
9486                        this.createPseudoHideStyles(element.ownerDocument);
9487                        this.disableAnimations(element.ownerDocument);
9488                        this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function (container) {
9489                            return container.visible = container.isElementVisible();
9490                        }).map(this.getPseudoElements, this));
9491                        this.fontMetrics = new FontMetrics();
9492                        log("Fetched nodes, total:", this.nodes.length);
9493                        log("Calculate overflow clips");
9494                        this.calculateOverflowClips();
9495                        log("Start fetching images");
9496                        this.images = imageLoader.fetch(this.nodes.filter(isElement));
9497                        this.ready = this.images.ready.then(bind(function () {
9498                            log("Images loaded, starting parsing");
9499                            log("Creating stacking contexts");
9500                            this.createStackingContexts();
9501                            log("Sorting stacking contexts");
9502                            this.sortStackingContexts(this.stack);
9503                            this.parse(this.stack);
9504                            log("Render queue created with " + this.renderQueue.length + " items");
9505                            return new Promise(bind(function (resolve) {
9506                                if (!options.async) {
9507                                    this.renderQueue.forEach(this.paint, this);
9508                                    resolve();
9509                                } else if (typeof (options.async) === "function") {
9510                                    options.async.call(this, this.renderQueue, resolve);
9511                                } else if (this.renderQueue.length > 0) {
9512                                    this.renderIndex = 0;
9513                                    this.asyncRenderer(this.renderQueue, resolve);
9514                                } else {
9515                                    resolve();
9516                                }
9517                            }, this));
9518                        }, this));
9519                    }
9520
9521                    NodeParser.prototype.calculateOverflowClips = function () {
9522                        this.nodes.forEach(function (container) {
9523                            if (isElement(container)) {
9524                                if (isPseudoElement(container)) {
9525                                    container.appendToDOM();
9526                                }
9527                                container.borders = this.parseBorders(container);
9528                                var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
9529                                var cssClip = container.parseClip();
9530                                if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
9531                                    clip.push([["rect",
9532                                        container.bounds.left + cssClip.left,
9533                                        container.bounds.top + cssClip.top,
9534                                        cssClip.right - cssClip.left,
9535                                        cssClip.bottom - cssClip.top
9536                                    ]]);
9537                                }
9538                                container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
9539                                container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
9540                                if (isPseudoElement(container)) {
9541                                    container.cleanDOM();
9542                                }
9543                            } else if (isTextNode(container)) {
9544                                container.clip = hasParentClip(container) ? container.parent.clip : [];
9545                            }
9546                            if (!isPseudoElement(container)) {
9547                                container.bounds = null;
9548                            }
9549                        }, this);
9550                    };
9551
9552                    function hasParentClip(container) {
9553                        return container.parent && container.parent.clip.length;
9554                    }
9555
9556                    NodeParser.prototype.asyncRenderer = function (queue, resolve, asyncTimer) {
9557                        asyncTimer = asyncTimer || Date.now();
9558                        this.paint(queue[this.renderIndex++]);
9559                        if (queue.length === this.renderIndex) {
9560                            resolve();
9561                        } else if (asyncTimer + 20 > Date.now()) {
9562                            this.asyncRenderer(queue, resolve, asyncTimer);
9563                        } else {
9564                            setTimeout(bind(function () {
9565                                this.asyncRenderer(queue, resolve);
9566                            }, this), 0);
9567                        }
9568                    };
9569
9570                    NodeParser.prototype.createPseudoHideStyles = function (document) {
9571                        this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
9572                            '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
9573                    };
9574
9575                    NodeParser.prototype.disableAnimations = function (document) {
9576                        this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
9577                            '-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
9578                    };
9579
9580                    NodeParser.prototype.createStyles = function (document, styles) {
9581                        var hidePseudoElements = document.createElement('style');
9582                        hidePseudoElements.innerHTML = styles;
9583                        document.body.appendChild(hidePseudoElements);
9584                    };
9585
9586                    NodeParser.prototype.getPseudoElements = function (container) {
9587                        var nodes = [[container]];
9588                        if (container.node.nodeType === Node.ELEMENT_NODE) {
9589                            var before = this.getPseudoElement(container, ":before");
9590                            var after = this.getPseudoElement(container, ":after");
9591
9592                            if (before) {
9593                                nodes.push(before);
9594                            }
9595
9596                            if (after) {
9597                                nodes.push(after);
9598                            }
9599                        }
9600                        return flatten(nodes);
9601                    };
9602
9603                    function toCamelCase(str) {
9604                        return str.replace(/(\-[a-z])/g, function (match) {
9605                            return match.toUpperCase().replace('-', '');
9606                        });
9607                    }
9608
9609                    NodeParser.prototype.getPseudoElement = function (container, type) {
9610                        var style = container.computedStyle(type);
9611                        if (!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
9612                            return null;
9613                        }
9614
9615                        var content = stripQuotes(style.content);
9616                        var isImage = content.substr(0, 3) === 'url';
9617                        var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
9618                        var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
9619
9620                        for (var i = style.length - 1; i >= 0; i--) {
9621                            var property = toCamelCase(style.item(i));
9622                            pseudoNode.style[property] = style[property];
9623                        }
9624
9625                        pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
9626
9627                        if (isImage) {
9628                            pseudoNode.src = parseBackgrounds(content)[0].args[0];
9629                            return [pseudoContainer];
9630                        } else {
9631                            var text = document.createTextNode(content);
9632                            pseudoNode.appendChild(text);
9633                            return [pseudoContainer, new TextContainer(text, pseudoContainer)];
9634                        }
9635                    };
9636
9637
9638                    NodeParser.prototype.getChildren = function (parentContainer) {
9639                        return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function (node) {
9640                            var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
9641                            return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
9642                        }, this));
9643                    };
9644
9645                    NodeParser.prototype.newStackingContext = function (container, hasOwnStacking) {
9646                        var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
9647                        container.cloneTo(stack);
9648                        var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
9649                        parentStack.contexts.push(stack);
9650                        container.stack = stack;
9651                    };
9652
9653                    NodeParser.prototype.createStackingContexts = function () {
9654                        this.nodes.forEach(function (container) {
9655                            if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
9656                                this.newStackingContext(container, true);
9657                            } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
9658                                this.newStackingContext(container, false);
9659                            } else {
9660                                container.assignStack(container.parent.stack);
9661                            }
9662                        }, this);
9663                    };
9664
9665                    NodeParser.prototype.isBodyWithTransparentRoot = function (container) {
9666                        return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
9667                    };
9668
9669                    NodeParser.prototype.isRootElement = function (container) {
9670                        return container.parent === null;
9671                    };
9672
9673                    NodeParser.prototype.sortStackingContexts = function (stack) {
9674                        stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
9675                        stack.contexts.forEach(this.sortStackingContexts, this);
9676                    };
9677
9678                    NodeParser.prototype.parseTextBounds = function (container) {
9679                        return function (text, index, textList) {
9680                            if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
9681                                if (this.support.rangeBounds && !container.parent.hasTransform()) {
9682                                    var offset = textList.slice(0, index).join("").length;
9683                                    return this.getRangeBounds(container.node, offset, text.length);
9684                                } else if (container.node && typeof (container.node.data) === "string") {
9685                                    var replacementNode = container.node.splitText(text.length);
9686                                    var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
9687                                    container.node = replacementNode;
9688                                    return bounds;
9689                                }
9690                            } else if (!this.support.rangeBounds || container.parent.hasTransform()) {
9691                                container.node = container.node.splitText(text.length);
9692                            }
9693                            return {};
9694                        };
9695                    };
9696
9697                    NodeParser.prototype.getWrapperBounds = function (node, transform) {
9698                        var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
9699                        var parent = node.parentNode,
9700                            backupText = node.cloneNode(true);
9701
9702                        wrapper.appendChild(node.cloneNode(true));
9703                        parent.replaceChild(wrapper, node);
9704                        var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
9705                        parent.replaceChild(backupText, wrapper);
9706                        return bounds;
9707                    };
9708
9709                    NodeParser.prototype.getRangeBounds = function (node, offset, length) {
9710                        var range = this.range || (this.range = node.ownerDocument.createRange());
9711                        range.setStart(node, offset);
9712                        range.setEnd(node, offset + length);
9713                        return range.getBoundingClientRect();
9714                    };
9715
9716                    function ClearTransform() { }
9717
9718                    NodeParser.prototype.parse = function (stack) {
9719                        // http://www.w3.org/TR/CSS21/visuren.html#z-index
9720                        var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
9721                        var descendantElements = stack.children.filter(isElement);
9722                        var descendantNonFloats = descendantElements.filter(not(isFloating));
9723                        var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
9724                        var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
9725                        var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
9726                        var stackLevel0 = stack.contexts.concat(descendantNonFloats.filter(isPositioned)).filter(zIndex0); // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
9727                        var text = stack.children.filter(isTextNode).filter(hasText);
9728                        var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
9729                        negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
9730                            .concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEac
9730h(function (container) {
9731                                this.renderQueue.push(container);
9732                                if (isStackingContext(container)) {
9733                                    this.parse(container);
9734                                    this.renderQueue.push(new ClearTransform());
9735                                }
9736                            }, this);
9737                    };
9738
9739                    NodeParser.prototype.paint = function (container) {
9740                        try {
9741                            if (container instanceof ClearTransform) {
9742                                this.renderer.ctx.restore();
9743                            } else if (isTextNode(container)) {
9744                                if (isPseudoElement(container.parent)) {
9745                                    container.parent.appendToDOM();
9746                                }
9747                                this.paintText(container);
9748                                if (isPseudoElement(container.parent)) {
9749                                    container.parent.cleanDOM();
9750                                }
9751                            } else {
9752                                this.paintNode(container);
9753                            }
9754                        } catch (e) {
9755                            log(e);
9756                            if (this.options.strict) {
9757                                throw e;
9758                            }
9759                        }
9760                    };
9761
9762                    NodeParser.prototype.paintNode = function (container) {
9763                        if (isStackingContext(container)) {
9764                            this.renderer.setOpacity(container.opacity);
9765                            this.renderer.ctx.save();
9766                            if (container.hasTransform()) {
9767                                this.renderer.setTransform(container.parseTransform());
9768                            }
9769                        }
9770
9771                        if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
9772                            this.paintCheckbox(container);
9773                        } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
9774                            this.paintRadio(container);
9775                        } else {
9776                            this.paintElement(container);
9777                        }
9778                    };
9779
9780                    NodeParser.prototype.paintElement = function (container) {
9781                        var bounds = container.parseBounds();
9782                        this.renderer.clip(container.backgroundClip, function () {
9783                            this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
9784                        }, this, container);
9785
9786                        this.renderer.mask(container.backgroundClip, function () {
9787                            this.renderer.renderShadows(container, container.borders.clip);
9788                        }, this, container);
9789
9790                        this.renderer.clip(container.clip, function () {
9791                            this.renderer.renderBorders(container.borders.borders);
9792                        }, this, container);
9793
9794                        this.renderer.clip(container.backgroundClip, function () {
9795                            switch (container.node.nodeName) {
9796                                case "svg":
9797                                case "IFRAME":
9798                                    var imgContainer = this.images.get(container.node);
9799                                    if (imgContainer) {
9800                                        this.renderer.renderImage(container, bounds, container.borders, imgContainer);
9801                                    } else {
9802                                        log("Error loading <" + container.node.nodeName + ">", container.node);
9803                                    }
9804                                    break;
9805                                case "IMG":
9806                                    var imageContainer = this.images.get(container.node.src);
9807                                    if (imageContainer) {
9808                                        this.renderer.renderImage(container, bounds, container.borders, imageContainer);
9809                                    } else {
9810                                        log("Error loading <img>", container.node.src);
9811                                    }
9812                                    break;
9813                                case "CANVAS":
9814                                    this.renderer.renderImage(container, bounds, container.borders, { image: container.node });
9815                                    break;
9816                                case "SELECT":
9817                                case "INPUT":
9818                                case "TEXTAREA":
9819                                    this.paintFormValue(container);
9820                                    break;
9821                            }
9822                        }, this, container);
9823                    };
9824
9825                    NodeParser.prototype.paintCheckbox = function (container) {
9826                        var b = container.parseBounds();
9827
9828                        var size = Math.min(b.width, b.height);
9829                        var bounds = { width: size - 1, height: size - 1, top: b.top, left: b.left };
9830                        var r = [3, 3];
9831                        var radius = [r, r, r, r];
9832                        var borders = [1, 1, 1, 1].map(function (w) {
9833                            return { color: new Color('#A5A5A5'), width: w };
9834                        });
9835
9836                        var borderPoints = calculateCurvePoints(bounds, radius, borders);
9837
9838                        this.renderer.clip(container.backgroundClip, function () {
9839                            this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
9840                            this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
9841                            if (container.node.checked) {
9842                                this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
9843                                this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
9844                            }
9845                        }, this, container);
9846                    };
9847
9848                    NodeParser.prototype.paintRadio = function (container) {
9849                        var bounds = container.parseBounds();
9850
9851                        var size = Math.min(bounds.width, bounds.height) - 2;
9852
9853                        this.renderer.clip(container.backgroundClip, function () {
9854                            this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
9855                            if (container.node.checked) {
9856                                this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
9857                            }
9858                        }, this, container);
9859                    };
9860
9861                    NodeParser.prototype.paintFormValue = function (container) {
9862                        var value = container.getValue();
9863                        if (value.length > 0) {
9864                            var document = container.node.ownerDocument;
9865                            var wrapper = document.createElement('html2canvaswrapper');
9866                            var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
9867                                'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
9868                                'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
9869                                'boxSizing', 'whiteSpace', 'wordWrap'];
9870
9871                            properties.forEach(function (property) {
9872                                try {
9873                                    wrapper.style[property] = container.css(property);
9874                                } catch (e) {
9875                                    // Older IE has issues with "border"
9876                                    log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
9877                                }
9878                            });
9879                            var bounds = container.parseBounds();
9880                            wrapper.style.position = "fixed";
9881                            wrapper.style.left = bounds.left + "px";
9882                            wrapper.style.top = bounds.top + "px";
9883                            wrapper.textContent = value;
9884                            document.body.appendChild(wrapper);
9885                            this.paintText(new TextContainer(wrapper.firstChild, container));
9886                            document.body.removeChild(wrapper);
9887                        }
9888                    };
9889
9890                    NodeParser.prototype.paintText = function (container) {
9891                        container.applyTextTransform();
9892                        var characters = punycode.ucs2.decode(container.node.data);
9893                        var wordRendering = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data);
9894                        var textList = wordRendering ? getWords(characters) : characters.map(function (character) {
9895                            return punycode.ucs2.encode([character]);
9896                        });
9897                        if (!wordRendering) {
9898                            container.parent.node.style.fontVariantLigatures = 'none';
9899                        }
9900
9901                        var weight = container.parent.fontWeight();
9902                        var size = container.parent.css('fontSize');
9903                        var family = container.parent.css('fontFamily');
9904                        var shadows = container.parent.parseTextShadows();
9905
9906                        this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
9907                        if (shadows.length) {
9908                            // TODO: support multiple text shadows
9909                            this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
9910                        } else {
9911                            this.renderer.clearShadow();
9912                        }
9913
9914                        this.renderer.clip(container.parent.clip, function () {
9915                            textList.map(this.parseTextBounds(container), this).forEach(function (bounds, index) {
9916                                if (bounds) {
9917                                    this.renderer.text(textList[index], bounds.left, bounds.bottom);
9918                                    this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
9919                                }
9920                            }, this);
9921                        }, this, container.parent);
9922                    };
9923
9924                    NodeParser.prototype.renderTextDecoration = function (container, bounds, metrics) {
9925                        switch (container.css("textDecoration").split(" ")[0]) {
9926                            case "underline":
9927                                // Draws a line at the baseline of the font
9928                                // TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size
9929                                this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
9930                                break;
9931                            case "overline":
9932                                this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
9933                                break;
9934                            case "line-through":
9935                                // TODO try and find exact position for line-through
9936                                this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
9937                                break;
9938                        }
9939                    };
9940
9941                    var borderColorTransforms = {
9942                        inset: [
9943                            ["darken", 0.60],
9944                            ["darken", 0.10],
9945                            ["darken", 0.10],
9946                            ["darken", 0.60]
9947                        ]
9948                    };
9949
9950                    NodeParser.prototype.parseBorders = function (container) {
9951                        var nodeBounds = container.parseBounds();
9952                        var radius = getBorderRadiusData(container);
9953                        var borders = ["Top", "Right", "Bottom", "Left"].map(function (side, index) {
9954                            var style = container.css('border' + side + 'Style');
9955                            var color = container.color('border' + side + 'Color');
9956                            if (style === "inset" && color.isBlack()) {
9957                                color = new Color([255, 255, 255, color.a]); // this is wrong, but
9958                            }
9959                            var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
9960                            return {
9961                                width: container.cssInt('border' + side + 'Width'),
9962                                color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
9963                                style: style,
9964                                pathArgs: null,
9965                                args: null
9966                            };
9967                        });
9968                        var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
9969
9970                        return {
9971                            clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
9972                            borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
9973                        };
9974                    };
9975
9976                    function calculateBorders(borders, nodeBounds, borderPoints, radius) {
9977                        var pathBounds = {
9978                            top: nodeBounds.top + borders[0].width / 2,
9979                            right: nodeBounds.right - borders[1].width / 2,
9980                            bottom: nodeBounds.bottom - borders[2].width / 2,
9981                            left: nodeBounds.left + borders[3].width / 2
9982                        };
9983                        return borders.map(function (border, borderSide) {
9984                            if (border.width > 0) {
9985                                var bx = nodeBounds.left;
9986                                var by = nodeBounds.top;
9987                                var bw = nodeBounds.width;
9988                                var bh = nodeBounds.height - (borders[2].width);
9989
9990                                switch (borderSide) {
9991                                    case 0:
9992                                        // top border
9993                                        bh = borders[0].width;
9994                                        border.args = drawSide({
9995                                            c1: [bx, by],
9996                                            c2: [bx + bw, by],
9997                                            c3: [bx + bw - borders[1].width, by + bh],
9998                                            c4: [bx + borders[3].width, by + bh]
9999                                        }, radius[0], radius[1],
10000                                            borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
10001                                        border.pathArgs = drawSidePath({
10002                                            c1: [pathBounds.left, pathBounds.top],
10003                                            c2: [pathBounds.right, pathBounds.top]
10004                                        }, radius[0], radius[1],
10005                                            borderPoints.topLeft, borderPoints.topRight);
10006                                        break;
10007                                    case 1:
10008                                        // right border
10009                                        bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
10010                                        bw = borders[1].width;
10011
10012                                        border.args = drawSide({
10013                                            c1: [bx + bw, by],
10014                                            c2: [bx + bw, by + bh + borders[2].width],
10015                                            c3: [bx, by + bh],
10016                                            c4: [bx, by + borders[0].width]
10017                                        }, radius[1], radius[2],
10018                                            borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
10019                                        border.pathArgs = drawSidePath({
10020                                            c1: [pathBounds.right, pathBounds.top],
10021                                            c2: [pathBounds.right, pathBounds.bottom]
10022                                        }, radius[1], radius[2],
10023                                            borderPoints.topRight, borderPoints.bottomRight);
10024                                        break;
10025                                    case 2:
10026                                        // bottom border
10027                                        by = (by + nodeBounds.height) - (borders[2].width);
10028                                        bh = borders[2].width;
10029                                        border.args = drawSide({
10030                                            c1: [bx + bw, by + bh],
10031                                            c2: [bx, by + bh],
10032                                            c3: [bx + borders[3].width, by],
10033                                            c4: [bx + bw - borders[3].width, by]
10034                                        }, radius[2], radius[3],
10035                                            borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
10036                                        border.pathArgs = drawSidePath({
10037                                            c1: [pathBounds.right, pathBounds.bottom],
10038                                            c2: [pathBounds.left, pathBounds.bottom]
10039                                        }, radius[2], radius[3],
10040                                            borderPoints.bottomRight, borderPoints.bottomLeft);
10041                                        break;
10042                                    case 3:
10043                                        // left border
10044                                        bw = borders[3].width;
10045                                        border.args = drawSide({
10046                                            c1: [bx, by + bh + borders[2].width],
10047                                            c2: [bx, by],
10048                                            c3: [bx + bw, by + borders[0].width],
10049                                            c4: [bx + bw, by + bh]
10050                                        }, radius[3], radius[0],
10051                                            borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
10052                                        border.pathArgs = drawSidePath({
10053                                            c1: [pathBounds.left, pathBounds.bottom],
10054                                            c2: [pathBounds.left, pathBounds.top]
10055                                        }, radius[3], radius[0],
10056                                            borderPoints.bottomLeft, borderPoints.topLeft);
10057                                        break;
10058                                }
10059                            }
10060                            return border;
10061                        });
10062                    }
10063
10064                    NodeParser.prototype.parseBackgroundClip = function (container, borderPoints, borders, radius, bounds) {
10065                        var backgroundClip = container.css('backgroundClip'),
10066                            borderArgs = [];
10067
10068                        switch (backgroundClip) {
10069                            case "content-box":
10070                            case "padding-box":
10071                                parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
10072                                parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
10073                                parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
10074                                parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
10075                                break;
10076
10077                            default:
10078                                parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
10079                                parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
10080                                parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
10081                                parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
10082                                break;
10083                        }
10084
10085                        return borderArgs;
10086                    };
10087
10088                    function getCurvePoints(x, y, r1, r2) {
10089                        var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
10090                        var ox = (r1) * kappa, // control point offset horizontal
10091                            oy = (r2) * kappa, // control point offset vertical
10092                            xm = x + r1, // x-middle
10093                            ym = y + r2; // y-middle
10094                        return {
10095                            topLeft: bezierCurve({ x: x, y: ym }, { x: x, y: ym - oy }, { x: xm - ox, y: y }, { x: xm, y: y }),
10096                            topRight: bezierCurve({ x: x, y: y }, { x: x + ox, y: y }, { x: xm, y: ym - oy }, { x: xm, y: ym }),
10097                            bottomRight: bezierCurve({ x: xm, y: y }, { x: xm, y: y + oy }, { x: x + ox, y: ym }, { x: x, y: ym }),
10098                            bottomLeft: bezierCurve({ x: xm, y: ym }, { x: xm - ox, y: ym }, { x: x, y: y + oy }, { x: x, y: y })
10099                        };
10100                    }
10101
10102                    function calculateCurvePoints(bounds, borderRadius, borders) {
10103                        var x = bounds.left,
10104                            y = bounds.top,
10105                            width = bounds.width,
10106                            height = bounds.height,
10107
10108                            tlh = borderRadius[0][0] < width / 2 ? borderRadius[0][0] : width / 2,
10109                            tlv = borderRadius[0][1] < height / 2 ? borderRadius[0][1] : height / 2,
10110                            trh = borderRadius[1][0] < width / 2 ? borderRadius[1][0] : width / 2,
10111                            trv = borderRadius[1][1] < height / 2 ? borderRadius[1][1] : height / 2,
10112                            brh = borderRadius[2][0] < width / 2 ? borderRadius[2][0] : width / 2,
10113                            brv = borderRadius[2][1] < height / 2 ? borderRadius[2][1] : height / 2,
10114                            blh = borderRadius[3][0] < width / 2 ? borderRadius[3][0] : width / 2,
10115                            blv = borderRadius[3][1] < height / 2 ? borderRadius[3][1] : height / 2;
10116
10117                        var topWidth = width - trh,
10118                            rightHeight = height - brv,
10119                            bottomWidth = width - brh,
10120                            leftHeight = height - blv;
10121
10122                        return {
10123                            topLeft: getCurvePoints(x + borders[3].width / 2, y + borders[0].width / 2, Math.max(0, tlh - borders[3].width / 2), Math.max(0, tlv - borders[0].width / 2)).topLeft.subdivide(0.5),
10124                            topRight: getCurvePoints(x + Math.min(topWidth, width + borders[3].width / 2), y + borders[0].width / 2, (topWidth > width + borders[3].width / 2) ? 0 : trh - borders[3].width / 2, trv - borders[0].width / 2).topRight.subdivide(0.5),
10125                            bottomRight: getCurvePoints(x + Math.min(bottomWidth, width - borders[3].width / 2), y + Math.min(rightHeight, height + borders[0].width / 2), Math.max(0, brh - borders[1].width / 2), brv - borders[2].width / 2).bottomRight.subdivide(0.5),
10126                            bottomLeft: getCurvePoints(x + borders[3].width / 2, y + leftHeight, Math.max(0, blh - borders[3].width / 2), blv - borders[2].width / 2).bottomLeft.subdivide(0.5),
10127
10128                            topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
10129                            topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - borders[3].width), Math.max(0, tlv - borders[0].width)).topLeft.subdivide(0.5),
10130                            topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
10131                            topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (topWidth > width + borders[3].width) ? 0 : trh - borders[3].width, trv - borders[0].width).topRight.subdivide(0.5),
10132                            bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
10133                            bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width - borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - borders[1].width), brv - borders[2].width).bottomRight.subdivide(0.5),
10134                            bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
10135                            bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
10136                        };
10137                    }
10138
10139                    function bezierCurve(start, startControl, endControl, end) {
10140                        var lerp = function (a, b, t) {
10141                            return {
10142                                x: a.x + (b.x - a.x) * t,
10143                                y: a.y + (b.y - a.y) * t
10144                            };
10145                        };
10146
10147                        return {
10148                            start: start,
10149                            startControl: startControl,
10150                            endControl: endControl,
10151                            end: end,
10152                            subdivide: function (t) {
10153                                var ab = lerp(start, startControl, t),
10154                                    bc = lerp(startControl, endControl, t),
10155                                    cd = lerp(endControl, end, t),
10156                                    abbc = lerp(ab, bc, t),
10157                                    bccd = lerp(bc, cd, t),
10158                                    dest = lerp(abbc, bccd, t);
10159                                return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
10160                            },
10161                            curveTo: function (borderArgs) {
10162                                borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
10163                            },
10164                            curveToReversed: function (borderArgs) {
10165                                borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
10166                            }
10167                        };
10168                    }
10169
10170                    function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
10171                        var borderArgs = [];
10172
10173                        if (radius1[0] > 0 || radius1[1] > 0) {
10174                            borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
10175                            outer1[1].curveTo(borderArgs);
10176                        } else {
10177                            borderArgs.push(["line", borderData.c1[0], borderData.c1[1]]);
10178                        }
10179
10180                        if (radius2[0] > 0 || radius2[1] > 0) {
10181                            borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
10182                            outer2[0].curveTo(borderArgs);
10183                            borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
10184                            inner2[0].curveToReversed(borderArgs);
10185                        } else {
10186                            borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
10187                            borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
10188                        }
10189
10190                        if (radius1[0] > 0 || radius1[1] > 0) {
10191                            borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
10192                            inner1[1].curveToReversed(borderArgs);
10193                        } else {
10194                            borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
10195                        }
10196
10197                        return borderArgs;
10198                    }
10199
10200                    function drawSidePath(borderData, radius1, radius2, curve1, curve2) {
10201                        var borderArgs = [];
10202                        if (radius1[0] > 0 || radius1[1] > 0) {
10203                            borderArgs.push(["line", curve1[1].start.x, curve1[1].start.y]);
10204                            curve1[1].curveTo(borderArgs);
10205                        } else {
10206                            borderArgs.push(["line", borderData.c1[0], borderData.c1[1]]);
10207                        }
10208                        if (radius2[0] > 0 || radius2[1] > 0) {
10209                            borderArgs.push(["line", curve2[0].start.x, curve2[0].start.y]);
10210                            curve2[0].curveTo(borderArgs);
10211                        } else {
10212                            borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
10213                        }
10214
10215                        return borderArgs;
10216                    }
10217
10218                    function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
10219                        if (radius1[0] > 0 || radius1[1] > 0) {
10220                            borderArgs.push(["line", corner1[0].start.x, c
10220orner1[0].start.y]);
10221                            corner1[0].curveTo(borderArgs);
10222                            corner1[1].curveTo(borderArgs);
10223                        } else {
10224                            borderArgs.push(["line", x, y]);
10225                        }
10226
10227                        if (radius2[0] > 0 || radius2[1] > 0) {
10228                            borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
10229                        }
10230                    }
10231
10232                    function negativeZIndex(container) {
10233                        return container.cssInt("zIndex") < 0;
10234                    }
10235
10236                    function positiveZIndex(container) {
10237                        return container.cssInt("zIndex") > 0;
10238                    }
10239
10240                    function zIndex0(container) {
10241                        return container.cssInt("zIndex") === 0;
10242                    }
10243
10244                    function inlineLevel(container) {
10245                        return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
10246                    }
10247
10248                    function isStackingContext(container) {
10249                        return (container instanceof StackingContext);
10250                    }
10251
10252                    function hasText(container) {
10253                        return container.node.data.trim().length > 0;
10254                    }
10255
10256                    function noLetterSpacing(container) {
10257                        return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
10258                    }
10259
10260                    function getBorderRadiusData(container) {
10261                        return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function (side) {
10262                            var value = container.css('border' + side + 'Radius');
10263                            var arr = value.split(" ");
10264                            if (arr.length <= 1) {
10265                                arr[1] = arr[0];
10266                            }
10267                            return arr.map(asInt);
10268                        });
10269                    }
10270
10271                    function renderableNode(node) {
10272                        return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
10273                    }
10274
10275                    function isPositionedForStacking(container) {
10276                        var position = container.css("position");
10277                        var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
10278                        return zIndex !== "auto";
10279                    }
10280
10281                    function isPositioned(container) {
10282                        return container.css("position") !== "static";
10283                    }
10284
10285                    function isFloating(container) {
10286                        return container.css("float") !== "none";
10287                    }
10288
10289                    function isInlineBlock(container) {
10290                        return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
10291                    }
10292
10293                    function not(callback) {
10294                        var context = this;
10295                        return function () {
10296                            return !callback.apply(context, arguments);
10297                        };
10298                    }
10299
10300                    function isElement(container) {
10301                        return container.node.nodeType === Node.ELEMENT_NODE;
10302                    }
10303
10304                    function isPseudoElement(container) {
10305                        return container.isPseudoElement === true;
10306                    }
10307
10308                    function isTextNode(container) {
10309                        return container.node.nodeType === Node.TEXT_NODE;
10310                    }
10311
10312                    function zIndexSort(contexts) {
10313                        return function (a, b) {
10314                            return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
10315                        };
10316                    }
10317
10318                    function hasOpacity(container) {
10319                        return container.getOpacity() < 1;
10320                    }
10321
10322                    function asInt(value) {
10323                        return parseInt(value, 10);
10324                    }
10325
10326                    function getWidth(border) {
10327                        return border.width;
10328                    }
10329
10330                    function nonIgnoredElement(nodeContainer) {
10331                        return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
10332                    }
10333
10334                    function flatten(arrays) {
10335                        return [].concat.apply([], arrays);
10336                    }
10337
10338                    function stripQuotes(content) {
10339                        var first = content.substr(0, 1);
10340                        return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
10341                    }
10342
10343                    function getWords(characters) {
10344                        var words = [], i = 0, onWordBoundary = false, word;
10345                        while (characters.length) {
10346                            if (isWordBoundary(characters[i]) === onWordBoundary) {
10347                                word = characters.splice(0, i);
10348                                if (word.length) {
10349                                    words.push(punycode.ucs2.encode(word));
10350                                }
10351                                onWordBoundary = !onWordBoundary;
10352                                i = 0;
10353                            } else {
10354                                i++;
10355                            }
10356
10357                            if (i >= characters.length) {
10358                                word = characters.splice(0, i);
10359                                if (word.length) {
10360                                    words.push(punycode.ucs2.encode(word));
10361                                }
10362                            }
10363                        }
10364                        return words;
10365                    }
10366
10367                    function isWordBoundary(characterCode) {
10368                        return [
10369                            32, // <space>
10370                            13, // \r
10371                            10, // \n
10372                            9, // \t
10373                            45 // -
10374                        ].indexOf(characterCode) !== -1;
10375                    }
10376
10377                    function hasUnicode(string) {
10378                        return (/[^\u0000-\u00ff]/).test(string);
10379                    }
10380
10381                    module.exports = NodeParser;
10382
10383                }, { "./color": 3, "./fontmetrics": 7, "./log": 13, "./nodecontainer": 14, "./pseudoelementcontainer": 18, "./stackingcontext": 21, "./textcontainer": 25, "./utils": 26, "punycode": 1 }
10383], 16: [function (_dereq_, module, exports) {
10384                    var XHR = _dereq_('./xhr');
10385                    var utils = _dereq_('./utils');
10386                    var log = _dereq_('./log');
10387                    var createWindowClone = _dereq_('./clone');
10388                    var decode64 = utils.decode64;
10389
10390                    function Proxy(src, proxyUrl, document) {
10391                        var supportsCORS = ('withCredentials' in new XMLHttpRequest());
10392                        if (!proxyUrl) {
10393                            return Promise.reject("No proxy configured");
10394                        }
10395                        var callback = createCallback(supportsCORS);
10396                        var url = createProxyUrl(proxyUrl, src, callback);
10397
10398                        return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function (response) {
10399                            return decode64(response.content);
10400                        }));
10401                    }
10402                    var proxyCount = 0;
10403
10404                    function ProxyURL(src, proxyUrl, document) {
10405                        var supportsCORSImage = ('crossOrigin' in new Image());
10406                        var callback = createCallback(supportsCORSImage);
10407                        var url = createProxyUrl(proxyUrl, src, callback);
10408                        return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function (response) {
10409                            return "data:" + response.type + ";base64," + response.content;
10410                        }));
10411                    }
10412
10413                    function jsonp(document, url, callback) {
10414                        return new Promise(function (resolve, reject) {
10415                            var s = document.createElement("script");
10416                            var cleanup = function () {
10417                                delete window.html2canvas.proxy[callback];
10418                                document.body.removeChild(s);
10419                            };
10420                            window.html2canvas.proxy[callback] = function (response) {
10421                                cleanup();
10422                                resolve(response);
10423                            };
10424                            s.src = url;
10425                            s.onerror = function (e) {
10426                                cleanup();
10427                                reject(e);
10428                            };
10429                            document.body.appendChild(s);
10430                        });
10431                    }
10432
10433                    function createCallback(useCORS) {
10434                        return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
10435                    }
10436
10437                    function createProxyUrl(proxyUrl, src, callback) {
10438                        return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
10439                    }
10440
10441                    function documentFromHTML(src) {
10442                        return function (html) {
10443                            var parser = new DOMParser(), doc;
10444                            try {
10445                                doc = parser.parseFromString(html, "text/html");
10446                            } catch (e) {
10447                                log("DOMParser not supported, falling back to createHTMLDocument");
10448                                doc = document.implementation.createHTMLDocument("");
10449                                try {
10450                                    doc.open();
10451                                    doc.write(html);
10452                                    doc.close();
10453                                } catch (ee) {
10454                                    log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
10455                                    doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
10456                                }
10457                            }
10458
10459                            var b = doc.querySelector("base");
10460                            if (!b || !b.href.host) {
10461                                var base = doc.createElement("base");
10462                                base.href = src;
10463                                doc.head.insertBefore(base, doc.head.firstChild);
10464                            }
10465
10466                            return doc;
10467                        };
10468                    }
10469
10470                    function loadUrlDocument(src, proxy, document, width, height, options) {
10471                        return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function (doc) {
10472                            return createWindowClone(doc, document, width, height, options, 0, 0);
10473                        });
10474                    }
10475
10476                    exports.Proxy = Proxy;
10477                    exports.ProxyURL = ProxyURL;
10478                    exports.loadUrlDocument = loadUrlDocument;
10479
10480                }, { "./clone": 2, "./log": 13, "./utils": 26, "./xhr": 28 }
10480], 17: [function (_dereq_, module, exports) {
10481                    var ProxyURL = _dereq_('./proxy').ProxyURL;
10482
10483                    function ProxyImageContainer(src, proxy) {
10484                        var link = document.createElement("a");
10485                        link.href = src;
10486                        src = link.href;
10487                        this.src = src;
10488                        this.image = new Image();
10489                        var self = this;
10490                        this.promise = new Promise(function (resolve, reject) {
10491                            self.image.crossOrigin = "Anonymous";
10492                            self.image.onload = resolve;
10493                            self.image.onerror = reject;
10494
10495                            new ProxyURL(src, proxy, document).then(function (url) {
10496                                self.image.src = url;
10497                            })['catch'](reject);
10498                        });
10499                    }
10500
10501                    module.exports = ProxyImageContainer;
10502
10503                }, { "./proxy": 16 }], 18: [function (_dereq_, module, exports) {
10504                    var NodeContainer = _dereq_('./nodecontainer');
10505
10506                    function PseudoElementContainer(node, parent, type) {
10507                        NodeContainer.call(this, node, parent);
10508                        this.isPseudoElement = true;
10509                        this.before = type === ":before";
10510                    }
10511
10512                    PseudoElementContainer.prototype.cloneTo = function (stack) {
10513                        PseudoElementContainer.prototype.cloneTo.call(this, stack);
10514                        stack.isPseudoElement = true;
10515                        stack.before = this.before;
10516                    };
10517
10518                    PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
10519
10520                    PseudoElementContainer.prototype.appendToDOM = function () {
10521                        if (this.before) {
10522                            this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
10523                        } else {
10524                            this.parent.node.appendChild(this.node);
10525                        }
10526                        this.parent.node.className += " " + this.getHideClass();
10527                    };
10528
10529                    PseudoElementContainer.prototype.cleanDOM = function () {
10530                        this.node.parentNode.removeChild(this.node);
10531                        this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
10532                    };
10533
10534                    PseudoElementContainer.prototype.getHideClass = function () {
10535                        return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
10536                    };
10537
10538                    PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
10539                    PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
10540
10541                    module.exports = PseudoElementContainer;
10542
10543                }, { "./nodecontainer": 14 }], 19: [function (_dereq_, module, exports) {
10544                    var log = _dereq_('./log');
10545
10546                    function Renderer(width, height, images, options, document) {
10547                        this.width = width;
10548                        this.height = height;
10549                        this.images = images;
10550                        this.options = options;
10551                        this.document = document;
10552                    }
10553
10554                    Renderer.prototype.renderImage = function (container, bounds, borderData, imageContainer) {
10555                        var paddingLeft = container.cssInt('paddingLeft'),
10556                            paddingTop = container.cssInt('paddingTop'),
10557                            paddingRight = container.cssInt('paddingRight'),
10558                            paddingBottom = container.cssInt('paddingBottom'),
10559                            borders = borderData.borders;
10560
10561                        var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
10562                        var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
10563                        this.drawImage(
10564                            imageContainer,
10565                            0,
10566                            0,
10567                            imageContainer.image.width || width,
10568                            imageContainer.image.height || height,
10569                            bounds.left + paddingLeft + borders[3].width,
10570                            bounds.top + paddingTop + borders[0].width,
10571                            width,
10572                            height
10573                        );
10574                    };
10575
10576                    Renderer.prototype.renderBackground = function (container, bounds, borderData) {
10577                        if (bounds.height > 0 && bounds.width > 0) {
10578                            this.renderBackgroundColor(container, bounds);
10579                            this.renderBackgroundImage(container, bounds, borderData);
10580                        }
10581                    };
10582
10583                    Renderer.prototype.renderBackgroundColor = function (container, bounds) {
10584                        var color = container.color("backgroundColor");
10585                        if (!color.isTransparent()) {
10586                            this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
10587                        }
10588                    };
10589
10590                    Renderer.prototype.renderShadows = function (container, shape) {
10591                        var boxShadow = container.css('boxShadow');
10592                        if (boxShadow !== 'none') {
10593                            var shadows = boxShadow.split(/,(?![^(]*\))/);
10594                            this.shadow(shape, shadows);
10595                        }
10596                    };
10597
10598                    Renderer.prototype.renderBorders = function (borders) {
10599                        borders.forEach(this.renderBorder, this);
10600                    };
10601
10602                    Renderer.prototype.renderBorder = function (data) {
10603                        if (!data.color.isTransparent() && data.args !== null) {
10604                            if (data.style === 'dashed' || data.style === 'dotted') {
10605                                var dash = (data.style === 'dashed') ? 3 : data.width;
10606                                this.ctx.setLineDash([dash]);
10607                                this.path(data.pathArgs);
10608                                this.ctx.strokeStyle = data.color;
10609                                this.ctx.lineWidth = data.width;
10610                                this.ctx.stroke();
10611                            } else {
10612                                this.drawShape(data.args, data.color);
10613                            }
10614                        }
10615                    };
10616
10617                    Renderer.prototype.renderBackgroundImage = function (container, bounds, borderData) {
10618                        var backgroundImages = container.parseBackgroundImages();
10619                        backgroundImages.reverse().forEach(function (backgroundImage, index, arr) {
10620                            switch (backgroundImage.method) {
10621                                case "url":
10622                                    var image = this.images.get(backgroundImage.args[0]);
10623                                    if (image) {
10624                                        this.renderBackgroundRepeating(container, bounds, image, arr.length - (index + 1), borderData);
10625                                    } else {
10626                                        log("Error loading background-image", backgroundImage.args[0]);
10627                                    }
10628                                    break;
10629                                case "linear-gradient":
10630                                case "gradient":
10631                                    var gradientImage = this.images.get(backgroundImage.value);
10632                                    if (gradientImage) {
10633                                        this.renderBackgroundGradient(gradientImage, bounds, borderData);
10634                                    } else {
10635                                        log("Error loading background-image", backgroundImage.args[0]);
10636                                    }
10637                                    break;
10638                                case "none":
10639                                    break;
10640                                default:
10641                                    log("Unknown background-image type", backgroundImage.args[0]);
10642                            }
10643                        }, this);
10644                    };
10645
10646                    Renderer.prototype.renderBackgroundRepeating = function (container, bounds, imageContainer, index, borderData) {
10647                        var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
10648                        var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
10649                        var repeat = container.parseBackgroundRepeat(index);
10650                        switch (repeat) {
10651                            case "repeat-x":
10652                            case "repeat no-repeat":
10653                                this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
10654                                break;
10655                            case "repeat-y":
10656                            case "no-repeat repeat":
10657                                this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
10658                                break;
10659                            case "no-repeat":
10660                                this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
10661                                break;
10662                            default:
10663                                this.renderBackgroundRepeat(imageContainer, position, size, { top: bounds.top, left: bounds.left }, borderData[3], borderData[0]);
10664                                break;
10665                        }
10666                    };
10667
10668                    module.exports = Renderer;
10669
10670                }, { "./log": 13 }], 20: [function (_dereq_, module, exports) {
10671                    var Renderer = _dereq_('../renderer');
10672                    var LinearGradientContainer = _dereq_('../lineargradientcontainer');
10673                    var log = _dereq_('../log');
10674
10675                    function CanvasRenderer(width, height) {
10676                        Renderer.apply(this, arguments);
10677                        this.canvas = this.options.canvas || this.document.createElement("canvas");
10678                        this.ctx = this.canvas.getContext("2d");
10679                        if (!this.options.canvas) {
10680                            if (this.options.dpi) {
10681                                this.options.scale = this.options.dpi / 96;   // 1 CSS inch = 96px.
10682                            }
10683                            if (this.options.scale) {
10684                                this.canvas.style.width = width + 'px';
10685                                this.canvas.style.height = height + 'px';
10686                                this.canvas.width = Math.floor(width * this.options.scale);
10687                                this.canvas.height = Math.floor(height * this.options.scale);
10688                                this.ctx.scale(this.options.scale, this.options.scale);
10689                            } else {
10690                                this.canvas.width = width;
10691                                this.canvas.height = height;
10692                            }
10693                        }
10694                        this.taintCtx = this.document.createElement("canvas").getContext("2d");
10695                        this.ctx.textBaseline = "bottom";
10696                        this.variables = {};
10697                        log("Initialized CanvasRenderer with size", width, "x", height);
10698                    }
10699
10700                    CanvasRenderer.prototype = Object.create(Renderer.prototype);
10701
10702                    CanvasRenderer.prototype.setFillStyle = function (fillStyle) {
10703                        this.ctx.fillStyle = typeof (fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
10704                        return this.ctx;
10705                    };
10706
10707                    CanvasRenderer.prototype.rectangle = function (left, top, width, height, color) {
10708                        this.setFillStyle(color).fillRect(left, top, width, height);
10709                    };
10710
10711                    CanvasRenderer.prototype.circle = function (left, top, size, color) {
10712                        this.setFillStyle(color);
10713                        this.ctx.beginPath();
10714                        this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI * 2, true);
10715                        this.ctx.closePath();
10716                        this.ctx.fill();
10717                    };
10718
10719                    CanvasRenderer.prototype.circleStroke = function (left, top, size, color, stroke, strokeColor) {
10720                        this.circle(left, top, size, color);
10721                        this.ctx.strokeStyle = strokeColor.toString();
10722                        this.ctx.stroke();
10723                    };
10724
10725                    CanvasRenderer.prototype.shadow = function (shape, shadows) {
10726                        var parseShadow = function (str) {
10727                            var propertyFilters = { color: /^(#|rgb|hsl|(?!(inset|initial|inherit))\D+)/i, inset: /^inset/i, px: /px$/i };
10728                            var pxPropertyNames = ['x', 'y', 'blur', 'spread'];
10729                            var properties = str.split(/ (?![^(]*\))/);
10730                            var info = {};
10731                            for (var key in propertyFilters) {
10732                                info[key] = properties.filter(propertyFilters[key].test.bind(propertyFilters[key]));
10733                                info[key] = info[key].length === 0 ? null : info[key].length === 1 ? info[key][0] : info[key];
10734                            }
10735                            for (var i = 0; i < info.px.length; i++) {
10736                                info[pxPropertyNames[i]] = parseInt(info.px[i]);
10737                            }
10738                            return info;
10739                        };
10740                        var drawShadow = function (shadow) {
10741                            var info = parseShadow(shadow);
10742                            if (!info.inset) {
10743                                context.shadowOffsetX = info.x;
10744                                context.shadowOffsetY = info.y;
10745                                context.shadowColor = info.color;
10746                                context.shadowBlur = info.blur;
10747                                context.fill();
10748                            }
10749                        };
10750                        var context = this.setFillStyle('white');
10751                        context.save();
10752                        this.shape(shape);
10753                        shadows.forEach(drawShadow, this);
10754                        context.restore();
10755                    };
10756
10757                    CanvasRenderer.prototype.drawShape = function (shape, color) {
10758                        this.shape(shape);
10759                        this.setFillStyle(color).fill();
10760                    };
10761
10762                    CanvasRenderer.prototype.taints = function (imageContainer) {
10763                        if (imageContainer.tainted === null) {
10764                            this.taintCtx.drawImage(imageContainer.image, 0, 0);
10765                            try {
10766                                this.taintCtx.getImageData(0, 0, 1, 1);
10767                                imageContainer.tainted = false;
10768                            } catch (e) {
10769                                this.taintCtx = document.createElement("canvas").getContext("2d");
10770                                imageContainer.tainted = true;
10771                            }
10772                        }
10773
10774                        return imageContainer.tainted;
10775                    };
10776
10777                    CanvasRenderer.prototype.drawImage = function (imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
10778                        if (!this.taints(imageContainer) || this.options.allowTaint) {
10779                            this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
10780                        }
10781                    };
10782
10783                    CanvasRenderer.prototype.clip = function (shapes, callback, context, container) {
10784                        this.ctx.save();
10785                        if (container && container.hasTransform()) {
10786                            this.setTransform(container.inverseTransform());
10787                            shapes.filter(hasEntries).forEach(function (shape) {
10788                                this.shape(shape).clip();
10789                            }, this);
10790                            this.setTransform(container.parseTransform());
10791                        } else {
10792                            shapes.filter(hasEntries).forEach(function (shape) {
10793                                this.shape(shape).clip();
10794                            }, this);
10795                        }
10796                        callback.call(context);
10797                        this.ctx.restore();
10798                    };
10799
10800                    CanvasRenderer.prototype.mask = function (shapes, callback, context, container) {
10801                        var borderClip = shapes[shapes.length - 1];
10802                        if (borderClip && borderClip.length) {
10803                            var canvasBorderCCW = ["rect", this.canvas.width, 0, -this.canvas.width, this.canvas.height];
10804                            var maskShape = [canvasBorderCCW].concat(borderClip).concat([borderClip[0]]);
10805                            shapes = shapes.slice(0, -1).concat([maskShape]);
10806                        }
10807                        this.clip(shapes, callback, context, container);
10808                    };
10809
10810                    CanvasRenderer.prototype.shape = function (shape) {
10811                        this.ctx.beginPath();
10812                        shape.forEach(function (point, index) {
10813                            if (point[0] === "rect") {
10814                                this.ctx.rect.apply(this.ctx, point.slice(1));
10815                            } else {
10816                                this.ctx[(index === 0) ? "moveTo" : point[0] + "To"].apply(this.ctx, point.slice(1));
10817                            }
10818                        }, this);
10819                        this.ctx.closePath();
10820                        return this.ctx;
10821                    };
10822
10823                    CanvasRenderer.prototype.path = function (shape) {
10824                        this.ctx.beginPath();
10825                        shape.forEach(function (point, index) {
10826                            if (point[0] === "rect") {
10827                                this.ctx.rect.apply(this.ctx, point.slice(1));
10828                            } else {
10829                                this.ctx[(index === 0) ? "moveTo" : point[0] + "To"].apply(this.ctx, point.slice(1));
10830                            }
10831                        }, this);
10832                        return this.ctx;
10833                    };
10834
10835                    CanvasRenderer.prototype.font = function (color, style, variant, weight, size, family) {
10836                        variant = /^(normal|small-caps)$/i.test(variant) ? variant : '';
10837                        this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
10838                    };
10839
10840                    CanvasRenderer.prototype.fontShadow = function (color, offsetX, offsetY, blur) {
10841                        this.setVariable("shadowColor", color.toString())
10842                            .setVariable("shadowOffsetY", offsetX)
10843                            .setVariable("shadowOffsetX", offsetY)
10844                            .setVariable("shadowBlur", blur);
10845                    };
10846
10847                    CanvasRenderer.prototype.clearShadow = function () {
10848                        this.setVariable("shadowColor", "rgba(0,0,0,0)");
10849                    };
10850
10851                    CanvasRenderer.prototype.setOpacity = function (opacity) {
10852                        this.ctx.globalAlpha = opacity;
10853                    };
10854
10855                    CanvasRenderer.prototype.setTransform = function (transform) {
10856                        this.ctx.translate(transform.origin[0], transform.origin[1]);
10857                        this.ctx.transform.apply(this.ctx, transform.matrix);
10858                        this.ctx.translate(-transform.origin[0], -transform.origin[1]);
10859                    };
10860
10861                    CanvasRenderer.prototype.setVariable = function (property, value) {
10862                        if (this.variables[property] !== value) {
10863                            this.variables[property] = this.ctx[property] = value;
10864                        }
10865
10866                        return this;
10867                    };
10868
10869                    CanvasRenderer.prototype.text = function (text, left, bottom) {
10870                        this.ctx.fillText(text, left, bottom);
10871                    };
10872
10873                    CanvasRenderer.prototype.backgroundRepeatShape = function (imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
10874                        var shape = [
10875                            ["line", Math.round(left), Math.round(top)],
10876                            ["line", Math.round(left + width), Math.round(top)],
10877                            ["line", Math.round(left + width), Math.round(height + top)],
10878                            ["line", Math.round(left), Math.round(height + top)]
10879                        ];
10880                        this.clip([shape], function () {
10881                            this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
10882                        }, this);
10883                    };
10884
10885                    CanvasRenderer.prototype.renderBackgroundRepeat = function (imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
10886                        var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
10887                        this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
10888                        this.ctx.translate(offsetX, offsetY);
10889                        this.ctx.fill();
10890                        this.ctx.translate(-offsetX, -offsetY);
10891                    };
10892
10893                    CanvasRenderer.prototype.renderBackgroundGradient = function (gradientImage, bounds) {
10894                        if (gradientImage instanceof LinearGradientContainer) {
10895                            var gradient = this.ctx.createLinearGradient(
10896                                bounds.left + bounds.width * gradientImage.x0,
10897                                bounds.top + bounds.height * gradientImage.y0,
10898                                bounds.left + bounds.width * gradientImage.x1,
10899                                bounds.top + bounds.height * gradientImage.y1);
10900                            gradientImage.colorStops.forEach(function (colorStop) {
10901                                gradient.addColorStop(colorStop.stop, colorStop.color.toString());
10902                            });
10903                            this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
10904                        }
10905                    };
10906
10907                    CanvasRenderer.prototype.resizeImage = function (imageContainer, size) {
10908                        var image = imageContainer.image;
10909                        if (image.width === size.width && image.height === size.height) {
10910                            return image;
10911                        }
10912
10913                        var ctx, canvas = document.createElement('canvas');
10914                        canvas.width = size.width;
10915                        canvas.height = size.height;
10916                        ctx = canvas.getContext("2d");
10917                        ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height);
10918                        return canvas;
10919                    };
10920
10921                    function hasEntries(array) {
10922                        return array.length > 0;
10923                    }
10924
10925                    module.exports = CanvasRenderer;
10926
10927                }, { "../lineargradientcontainer": 12, "../log": 13, "../renderer": 19 }], 21: [function (_dereq_, module, exports) {
10928                    var NodeContainer = _dereq_('./nodecontainer');
10929
10930                    function StackingContext(hasOwnStacking, opacity, element, parent) {
10931                        NodeContainer.call(this, element, parent);
10932                        this.ownStacking = hasOwnStacking;
10933                        this.contexts = [];
10934                        this.children = [];
10935                        this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
10936                    }
10937
10938                    StackingContext.prototype = Object.create(NodeContainer.prototype);
10939
10940                    StackingContext.prototype.getParentStack = function (context) {
10941                        var parentStack = (this.parent) ? this.parent.stack : null;
10942                        return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
10943                    };
10944
10945                    module.exports = StackingContext;
10946
10947                }, { "./nodecontainer": 14 }], 22: [function (_dereq_, module, exports) {
10948                    function Support(document) {
10949                        this.rangeBounds = this.testRangeBounds(document);
10950                        this.cors = this.testCORS();
10951                        this.svg = this.testSVG();
10952                    }
10953
10954                    Support.prototype.testRangeBounds = function (document) {
10955                        var range, testElement, rangeBounds, rangeHeight, support = false;
10956
10957                        if (document.createRange) {
10958                            range = document.createRange();
10959                            if (range.getBoundingClientRect) {
10960                                testElement = document.createElement('boundtest');
10961                                testElement.style.height = "123px";
10962                                testElement.style.display = "block";
10963                                document.body.appendChild(testElement);
10964
10965                                range.selectNode(testElement);
10966                                rangeBounds = range.getBoundingClientRect();
10967                                rangeHeight = rangeBounds.height;
10968
10969                                if (rangeHeight === 123) {
10970                                    support = true;
10971                                }
10972                                document.body.removeChild(testElement);
10973                            }
10974                        }
10975
10976                        return support;
10977                    };
10978
10979                    Support.prototype.testCORS = function () {
10980                        return typeof ((new Image()).crossOrigin) !== "undefined";
10981                    };
10982
10983                    Support.prototype.testSVG = function () {
10984                        var img = new Image();
10985                        var canvas = document.createElement("canvas");
10986                        var ctx = canvas.getContext("2d");
10987                        img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
10988
10989                        try {
10990                            ctx.drawImage(img, 0, 0);
10991                            canvas.toDataURL();
10992                        } catch (e) {
10993                            return false;
10994                        }
10995                        return true;
10996                    };
10997
10998                    module.exports = Support;
10999
11000                }, {}], 23: [function (_dereq_, module, exports) {
11001                    var XHR = _dereq_('./xhr');
11002                    var decode64 = _dereq_('./utils').decode64;
11003
11004                    function SVGContainer(src) {
11005                        this.src = src;
11006                        this.image = null;
11007                        var self = this;
11008
11009                        this.promise = this.hasFabric().then(function () {
11010                            return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
11011                        }).then(function (svg) {
11012                            return new Promise(function (resolve) {
11013                                window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
11014                            });
11015                        });
11016                    }
11017
11018                    SVGContainer.prototype.hasFabric = function () {
11019                        return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
11020                    };
11021
11022                    SVGContainer.prototype.inlineFormatting = function (src) {
11023                        return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
11024                    };
11025
11026                    SVGContainer.prototype.removeContentType = function (src) {
11027                        return src.replace(/^data:image\/svg\+xml(;base64)?,/, '');
11028                    };
11029
11030                    SVGContainer.prototype.isInline = function (src) {
11031                        return (/^data:image\/svg\+xml/i.test(src));
11032                    };
11033
11034                    SVGContainer.prototype.createCanvas = function (resolve) {
11035                        var self = this;
11036                        return function (objects, options) {
11037                            var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
11038                            self.image = canvas.lowerCanvasEl;
11039                            canvas
11040                                .setWidth(options.width)
11041                                .setHeight(options.height)
11042                                .add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
11043                                .renderAll();
11044                            resolve(canvas.lowerCanvasEl);
11045                        };
11046                    };
11047
11048                    SVGContainer.prototype.decode64 = function (str) {
11049                        return (typeof (window.atob) === "function") ? window.atob(str) : decode64(str);
11050                    };
11051
11052                    module.exports = SVGContainer;
11053
11054                }, { "./utils": 26, "./xhr": 28 }
11054], 24: [function (_dereq_, module, exports) {
11055                    var SVGContainer = _dereq_('./svgcontainer');
11056
11057                    function SVGNodeContainer(node, _native) {
11058                        this.src = node;
11059                        this.image = null;
11060                        var self = this;
11061
11062                        this.promise = _native ? new Promise(function (resolve, reject) {
11063                            self.image = new Image();
11064                            self.image.onload = resolve;
11065                            self.image.onerror = reject;
11066                            self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
11067                            if (self.image.complete === true) {
11068                                resolve(self.image);
11069                            }
11070                        }) : this.hasFabric().then(function () {
11071                            return new Promise(function (resolve) {
11072                                window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
11073                            });
11074                        });
11075                    }
11076
11077                    SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
11078
11079                    module.exports = SVGNodeContainer;
11080
11081                }, { "./svgcontainer": 23 }], 25: [function (_dereq_, module, exports) {
11082                    var NodeContainer = _dereq_('./nodecontainer');
11083
11084                    function TextContainer(node, parent) {
11085                        NodeContainer.call(this, node, parent);
11086                    }
11087
11088                    TextContainer.prototype = Object.create(NodeContainer.prototype);
11089
11090                    TextContainer.prototype.applyTextTransform = function () {
11091                        this.node.data = this.transform(this.parent.css("textTransform"));
11092                    };
11093
11094                    TextContainer.prototype.transform = function (transform) {
11095                        var text = this.node.data;
11096                        switch (transform) {
11097                            case "lowercase":
11098                                return text.toLowerCase();
11099                            case "capitalize":
11100                                return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
11101                            case "uppercase":
11102                                return text.toUpperCase();
11103                            default:
11104                                return text;
11105                        }
11106                    };
11107
11108                    function capitalize(m, p1, p2) {
11109                        if (m.length > 0) {
11110                            return p1 + p2.toUpperCase();
11111                        }
11112                    }
11113
11114                    module.exports = TextContainer;
11115
11116                }, { "./nodecontainer": 14 }], 26: [function (_dereq_, module, exports) {
11117                    exports.smallImage = function smallImage() {
11118                        return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
11119                    };
11120
11121                    exports.bind = function (callback, context) {
11122                        return function () {
11123                            return callback.apply(context, arguments);
11124                        };
11125                    };
11126
11127                    /*
11128                     * base64-arraybuffer
11129                     * https://github.com/niklasvh/base64-arraybuffer
11130                     *
11131                     * Copyright (c) 2012 Niklas von Hertzen
11132                     * Licensed under the MIT license.
11133                     */
11134
11135                    exports.decode64 = function (base64) {
11136                        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
11137                        var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
11138
11139                        var output = "";
11140
11141                        for (i = 0; i < len; i += 4) {
11142                            encoded1 = chars.indexOf(base64[i]);
11143                            encoded2 = chars.indexOf(base64[i + 1]);
11144                            encoded3 = chars.indexOf(base64[i + 2]);
11145                            encoded4 = chars.indexOf(base64[i + 3]);
11146
11147                            byte1 = (encoded1 << 2) | (encoded2 >> 4);
11148                            byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
11149                            byte3 = ((encoded3 & 3) << 6) | encoded4;
11150                            if (encoded3 === 64) {
11151                                output += String.fromCharCode(byte1);
11152                            } else if (encoded4 === 64 || encoded4 === -1) {
11153                                output += String.fromCharCode(byte1, byte2);
11154                            } else {
11155                                output += String.fromCharCode(byte1, byte2, byte3);
11156                            }
11157                        }
11158
11159                        return output;
11160                    };
11161
11162                    exports.getBounds = function (node) {
11163                        if (node.getBoundingClientRect) {
11164                            var clientRect = node.getBoundingClientRect();
11165                            var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
11166                            return {
11167                                top: clientRect.top,
11168                                bottom: clientRect.bottom || (clientRect.top + clientRect.height),
11169                                right: clientRect.left + width,
11170                                left: clientRect.left,
11171                                width: width,
11172                                height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
11173                            };
11174                        }
11175                        return {};
11176                    };
11177
11178                    exports.offsetBounds = function (node) {
11179                        var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : { top: 0, left: 0 };
11180
11181                        return {
11182                            top: node.offsetTop + parent.top,
11183                            bottom: node.offsetTop + node.offsetHeight + parent.top,
11184                            right: node.offsetLeft + parent.left + node.offsetWidth,
11185                            left: node.offsetLeft + parent.left,
11186                            width: node.offsetWidth,
11187                            height: node.offsetHeight
11188                        };
11189                    };
11190
11191                    exports.parseBackgrounds = function (backgroundImage) {
11192                        var whitespace = ' \r\n\t',
11193                            method, definition, prefix, prefix_i, block, results = [],
11194                            mode = 0, numParen = 0, quote, args;
11195                        var appendResult = function () {
11196                            if (method) {
11197                                if (definition.substr(0, 1) === '"') {
11198                                    definition = definition.substr(1, definition.length - 2);
11199                                }
11200                                if (definition) {
11201                                    args.push(definition);
11202                                }
11203                                if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1) + 1) > 0) {
11204                                    prefix = method.substr(0, prefix_i);
11205                                    method = method.substr(prefix_i);
11206                                }
11207                                results.push({
11208                                    prefix: prefix,
11209                                    method: method.toLowerCase(),
11210                                    value: block,
11211                                    args: args,
11212                                    image: null
11213                                });
11214                            }
11215                            args = [];
11216                            method = prefix = definition = block = '';
11217                        };
11218                        args = [];
11219                        method = prefix = definition = block = '';
11220                        backgroundImage.split("").forEach(function (c) {
11221                            if (mode === 0 && whitespace.indexOf(c) > -1) {
11222                                return;
11223                            }
11224                            switch (c) {
11225                                case '"':
11226                                    if (!quote) {
11227                                        quote = c;
11228                                    } else if (quote === c) {
11229                                        quote = null;
11230                                    }
11231                                    break;
11232                                case '(':
11233                                    if (quote) {
11234                                        break;
11235                                    } else if (mode === 0) {
11236                                        mode = 1;
11237                                        block += c;
11238                                        return;
11239                                    } else {
11240                                        numParen++;
11241                                    }
11242                                    break;
11243                                case ')':
11244                                    if (quote) {
11245                                        break;
11246                                    } else if (mode === 1) {
11247                                        if (numParen === 0) {
11248                                            mode = 0;
11249                                            block += c;
11250                                            appendResult();
11251                                            return;
11252                                        } else {
11253                                            numParen--;
11254                                        }
11255                                    }
11256                                    break;
11257
11258                                case ',':
11259                                    if (quote) {
11260                                        break;
11261                                    } else if (mode === 0) {
11262                                        appendResult();
11263                                        return;
11264                                    } else if (mode === 1) {
11265                                        if (numParen === 0 && !method.match(/^url$/i)) {
11266                                            args.push(definition);
11267                                            definition = '';
11268                                            block += c;
11269                                            return;
11270                                        }
11271                                    }
11272                                    break;
11273                            }
11274
11275                            block += c;
11276                            if (mode === 0) {
11277                                method += c;
11278                            } else {
11279                                definition += c;
11280                            }
11281                        });
11282
11283                        appendResult();
11284                        return results;
11285                    };
11286
11287                }, {}
11287], 27: [function (_dereq_, module, exports) {
11288                    var GradientContainer = _dereq_('./gradientcontainer');
11289
11290                    function WebkitGradientContainer(imageData) {
11291                        GradientContainer.apply(this, arguments);
11292                        this.type = imageData.args[0] === "linear" ? GradientContainer.TYPES.LINEAR : GradientContainer.TYPES.RADIAL;
11293                    }
11294
11295                    WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
11296
11297                    module.exports = WebkitGradientContainer;
11298
11299                }, { "./gradientcontainer": 9 }], 28: [function (_dereq_, module, exports) {
11300                    function XHR(url) {
11301                        return new Promise(function (resolve, reject) {
11302                            var xhr = new XMLHttpRequest();
11303                            xhr.open('GET', url);
11304
11305                            xhr.onload = function () {
11306                                if (xhr.status === 200) {
11307                                    resolve(xhr.responseText);
11308                                } else {
11309                                    reject(new Error(xhr.statusText));
11310                                }
11311                            };
11312
11313                            xhr.onerror = function () {
11314                                reject(new Error("Network Error"));
11315                            };
11316
11317                            xhr.send();
11318                        });
11319                    }
11320
11321                    module.exports = XHR;
11322
11323                }, {}]
11324            }, {}, [4])(4)
11325        });
11326    });
11327
11328    var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
11329        return typeof obj;
11330    } : function (obj) {
11331        return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
11332    };
11333
11334    // Import dependencies.
11335    // Get dimensions of a PDF page, as determined by jsPDF.
11336    jspdf_min.getPageSize = function (orientation, unit, format) {
11337        // Decode options object
11338        if ((typeof orientation === 'undefined' ? 'undefined' : _typeof(orientation)) === 'object') {
11339            var options = orientation;
11340            orientation = options.orientation;
11341            unit = options.unit || unit;
11342            format = options.format || format;
11343        }
11344
11345        // Default options
11346        unit = unit || 'mm';
11347        format = format || 'a4';
11348        orientation = ('' + (orientation || 'P')).toLowerCase();
11349        var format_as_string = ('' + format).toLowerCase();
11350
11351        // Size in pt of various paper formats
11352        var pageFormats = {
11353            'a0': [2383.94, 3370.39], 'a1': [1683.78, 2383.94],
11354            'a2': [1190.55, 1683.78], 'a3': [841.89, 1190.55],
11355            'a4': [595.28, 841.89], 'a5': [419.53, 595.28],
11356            'a6': [297.64, 419.53], 'a7': [209.76, 297.64],
11357            'a8': [147.40, 209.76], 'a9': [104.88, 147.40],
11358            'a10': [73.70, 104.88], 'b0': [2834.65, 4008.19],
11359            'b1': [2004.09, 2834.65], 'b2': [1417.32, 2004.09],
11360            'b3': [1000.63, 1417.32], 'b4': [708.66, 1000.63],
11361            'b5': [498.90, 708.66], 'b6': [354.33, 498.90],
11362            'b7': [249.45, 354.33], 'b8': [175.75, 249.45],
11363            'b9': [124.72, 175.75], 'b10': [87.87, 124.72],
11364            'c0': [2599.37, 3676.54], 'c1': [1836.85, 2599.37],
11365            'c2': [1298.27, 1836.85], 'c3': [918.43, 1298.27],
11366            'c4': [649.13, 918.43], 'c5': [459.21, 649.13],
11367            'c6': [323.15, 459.21], 'c7': [229.61, 323.15],
11368            'c8': [161.57, 229.61], 'c9': [113.39, 161.57],
11369            'c10': [79.37, 113.39], 'dl': [311.81, 623.62],
11370            'letter': [612, 792],
11371            'government-letter': [576, 756],
11372            'legal': [612, 1008],
11373            'junior-legal': [576, 360],
11374            'ledger': [1224, 792],
11375            'tabloid': [792, 1224],
11376            'credit-card': [153, 243]
11377        };
11378
11379        // Unit conversion
11380        switch (unit) {
11381            case 'pt':
11382                var k = 1; break;
11383            case 'mm':
11384                var k = 72 / 25.4; break;
11385            case 'cm':
11386                var k = 72 / 2.54; break;
11387            case 'in':
11388                var k = 72; break;
11389            case 'px':
11390                var k = 72 / 96; break;
11391            case 'pc':
11392                var k = 12; break;
11393            case 'em':
11394                var k = 12; break;
11395            case 'ex':
11396                var k = 6; break;
11397            default:
11398                throw 'Invalid unit: ' + unit;
11399        }
11400
11401        // Dimensions are stored as user units and converted to points on output
11402        if (pageFormats.hasOwnProperty(format_as_string)) {
11403            var pageHeight = pageFormats[format_as_string][1] / k;
11404            var pageWidth = pageFormats[format_as_string][0] / k;
11405        } else {
11406            try {
11407                var pageHeight = format[1];
11408                var pageWidth = format[0];
11409            } catch (err) {
11410                throw new Error('Invalid format: ' + format);
11411            }
11412        }
11413
11414        // Handle page orientation
11415        if (orientation === 'p' || orientation === 'portrait') {
11416            orientation = 'p';
11417            if (pageWidth > pageHeight) {
11418                var tmp = pageWidth;
11419                pageWidth = pageHeight;
11420                pageHeight = tmp;
11421            }
11422        } else if (orientation === 'l' || orientation === 'landscape') {
11423            orientation = 'l';
11424            if (pageHeight > pageWidth) {
11425                var tmp = pageWidth;
11426                pageWidth = pageHeight;
11427                pageHeight = tmp;
11428            }
11429        } else {
11430            throw 'Invalid orientation: ' + orientation;
11431        }
11432
11433        // Return information (k is the unit conversion ratio from pts)
11434        var info = { 'width': pageWidth, 'height': pageHeight, 'unit': unit, 'k': k };
11435        return info;
11436    };
11437
11438    // Determine the type of a variable/object.
11439    var objType = function objType(obj) {
11440        if (typeof obj === 'undefined') return 'undefined'; else if (typeof obj === 'string' || obj instanceof String) return 'string'; else if (typeof obj === 'number' || obj instanceof Number) return 'number'; else if (!!obj && obj.constructor === Array) return 'array'; else if (obj && obj.nodeType === 1) return 'element'; else if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object') return 'object'; else return 'unknown';
11441    };
11442
11443    // Create an HTML element with optional className, innerHTML, and style.
11444    var createElement = function createElement(tagName, opt) {
11445        var el = document.createElement(tagName);
11446        if (opt.className) el.className = opt.className;
11447        if (opt.innerHTML) {
11448            el.innerHTML = opt.innerHTML;
11449            var scripts = el.getElementsByTagName('script');
11450            for (var i = scripts.length; i-- > 0; null) {
11451                scripts[i].parentNode.removeChild(scripts[i]);
11452            }
11453        }
11454        for (var key in opt.style) {
11455            el.style[key] = opt.style[key];
11456        }
11457        return el;
11458    };
11459
11460    // Deep-clone a node and preserve contents/properties.
11461    var cloneNode = function cloneNode(node, javascriptEnabled) {
11462        // Recursively clone the node.
11463        var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
11464        for (var child = node.firstChild; child; child = child.nextSibling) {
11465            if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
11466                clone.appendChild(cloneNode(child, javascriptEnabled));
11467            }
11468        }
11469
11470        if (node.nodeType === 1) {
11471            // Preserve contents/properties of special nodes.
11472            if (node.nodeName === 'CANVAS') {
11473                clone.width = node.width;
11474                clone.height = node.height;
11475                clone.getContext('2d').drawImage(node, 0, 0);
11476            } else if (node.nodeName === 'TEXTAREA' || node.nodeName === 'SELECT') {
11477                clone.value = node.value;
11478            }
11479
11480            // Preserve the node's scroll position when it loads.
11481            clone.addEventListener('load', function () {
11482                clone.scrollTop = node.scrollTop;
11483                clone.scrollLeft = node.scrollLeft;
11484            }, true);
11485        }
11486
11487        // Return the cloned node.
11488        return clone;
11489    };
11490
11491    // Convert units using the conversion value 'k' from jsPDF.
11492    var unitConvert = function unitConvert(obj, k) {
11493        var newObj = {};
11494        for (var key in obj) {
11495            newObj[key] = obj[key] * 72 / 96 / k;
11496        }
11497        return newObj;
11498    };
11499
11500    /**
11501     * Generate a PDF from an HTML element or string using html2canvas and jsPDF.
11502     *
11503     * @param {Element|string} source The source element or HTML string.
11504     * @param {Object=} opt An object of optional settings: 'margin', 'filename',
11505     *    'image' ('type' and 'quality'), and 'html2canvas' / 'jspdf', which are
11506     *    sent as settings to their corresponding functions.
11507     */
11508    var html2pdf = function html2pdf(source, opt) {
11509        // Handle input.
11510        opt = objType(opt) === 'object' ? opt : {};
11511        var source = html2pdf.parseInput(source, opt);
11512
11513        // Determine the PDF page size.
11514        var pageSize = jspdf_min.getPageSize(opt.jsPDF);
11515        pageSize.inner = {
11516            width: pageSize.width - opt.margin[1] - opt.margin[3],
11517            height: pageSize.height - opt.margin[0] - opt.margin[2]
11518        };
11519        pageSize.inner.ratio = pageSize.inner.height / pageSize.inner.width;
11520
11521        // Copy the source element into a PDF-styled container div.
11522        var container = html2pdf.makeContainer(source, pageSize);
11523        var overlay = container.parentElement;
11524
11525        // Get the locations of all hyperlinks.
11526        if (opt.enableLinks) {
11527            // Find all anchor tags and get the container's bounds for reference.
11528            opt.links = [];
11529            var links = container.querySelectorAll('a');
11530            var containerRect = unitConvert(container.getBoundingClientRect(), pageSize.k);
11531
11532            // Treat each client rect as a separate link (for text-wrapping).
11533            Array.prototype.forEach.call(links, function (link) {
11534                var clientRects = link.getClientRects();
11535                for (var i = 0; i < clientRects.length; i++) {
11536                    var clientRect = unitConvert(clientRects[i], pageSize.k);
11537                    clientRect.left -= containerRect.left;
11538                    clientRect.top -= containerRect.top;
11539                    opt.links.push({ el: link, clientRect: clientRect });
11540                }
11541            });
11542        }
11543
11544        // Render the canvas and pass the result to makePDF.
11545        var onRendered = opt.html2canvas.onrendered || function () { };
11546        opt.html2canvas.onrendered = function (canvas) {
11547            onRendered(canvas);
11548            document.body.removeChild(overlay);
11549            html2pdf.makePDF(canvas, pageSize, opt);
11550        };
11551        html2canvas$1(container, opt.html2canvas);
11552    };
11553
11554    html2pdf.parseInput = function (source, opt) {
11555        // Parse the opt object.
11556        opt.jsPDF = opt.jsPDF || {};
11557        opt.html2canvas = opt.html2canvas || {};
11558        opt.filename = opt.filename && objType(opt.filename) === 'string' ? opt.filename : 'file.pdf';
11559        opt.enableLinks = opt.hasOwnProperty('enableLinks') ? opt.enableLinks : true;
11560        opt.image = opt.image || {};
11561        opt.image.type = opt.image.type || 'jpeg';
11562        opt.image.quality = opt.image.quality || 0.95;
11563
11564        // Parse the margin property of the opt object.
11565        switch (objType(opt.margin)) {
11566            case 'undefined':
11567                opt.margin = 0;
11568            case 'number':
11569                opt.margin = [opt.margin, opt.margin, opt.margin, opt.margin];
11570                break;
11571            case 'array':
11572                if (opt.margin.length === 2) {
11573                    opt.margin = [opt.margin[0], opt.margin[1], opt.margin[0], opt.margin[1]];
11574                }
11575                if (opt.margin.length === 4) {
11576                    break;
11577                }
11578            default:
11579                throw 'Invalid margin array.';
11580        }
11581
11582        // Parse the source element/string.
11583        if (!source) {
11584            throw 'Missing source element or string.';
11585        } else if (objType(source) === 'string') {
11586            source = createElement('div', { innerHTML: source });
11587        } else if (objType(source) === 'element') {
11588            source = cloneNode(source, opt.html2canvas.javascriptEnabled);
11589        } else {
11590            throw 'Invalid source - please specify an HTML Element or string.';
11591        }
11592
11593        // Return the parsed input (opt is modified in-place, no need to return).
11594        return source;
11595    };
11596
11597    html2pdf.makeContainer = function (source, pageSize) {
11598        // Define the CSS styles for the container and its overlay parent.
11599        var overlayCSS = {
11600            position: 'fixed', overflow: 'hidden', zIndex: 1000,
11601            left: 0, right: 0, bottom: 0, top: 0,
11602            backgroundColor: 'rgba(0,0,0,0.8)'
11603        };
11604        var containerCSS = {
11605            position: 'absolute', width: pageSize.inner.width + pageSize.unit,
11606            left: 0, right: 0, top: 0, height: 'auto', margin: 'auto',
11607            backgroundColor: 'white'
11608        };
11609
11610        // Set the overlay to hidden (could be changed in the future to provide a print preview).
11611        overlayCSS.opacity = 0;
11612
11613        // Create and attach the elements.
11614        var overlay = createElement('div', { className: 'html2pdf__overlay', style: overlayCSS });
11615        var container = createElement('div', { className: 'html2pdf__container', style: containerCSS });
11616        container.appendChild(source);
11617        overlay.appendChild(container);
11618        document.body.appendChild(overlay);
11619
11620        // Enable page-breaks.
11621        var pageBreaks = source.querySelectorAll('.html2pdf__page-break');
11622        var pxPageHeight = pageSize.inner.height * pageSize.k / 72 * 96;
11623        Array.prototype.forEach.call(pageBreaks, function (el) {
11624            el.style.display = 'block';
11625            var clientRect = el.getBoundingClientRect();
11626            el.style.height = pxPageHeight - clientRect.top % pxPageHeight + 'px';
11627        }, this);
11628
11629        // Return the container.
11630        return container;
11631    };
11632
11633    html2pdf.makePDF = function (canvas, pageSize, opt) {
11634        // Calculate the number of pages.
11635        var ctx = canvas.getContext('2d');
11636        var pxFullHeight = canvas.height;
11637        var pxPageHeight = Math.floor(canvas.width * pageSize.inner.ratio);
11638        var nPages = Math.ceil(pxFullHeight / pxPageHeight);
11639
11640        // Create a one-page canvas to split up the full image.
11641        var pageCanvas = document.createElement('canvas');
11642        var pageCtx = pageCanvas.getContext('2d');
11643        var pageHeight = pageSize.inner.height;
11644        pageCanvas.width = canvas.width;
11645        pageCanvas.height = pxPageHeight;
11646
11647        // Initialize the PDF.
11648        var pdf = new jspdf_min(opt.jsPDF);
11649
11650        for (var page = 0; page < nPages; page++) {
11651            // Trim the final page to reduce file size.
11652            if (page === nPages - 1) {
11653                pageCanvas.height = pxFullHeight % pxPageHeight;
11654                pageHeight = pageCanvas.height * pageSize.inner.width / pageCanvas.width;
11655            }
11656
11657            // Display the page.
11658            var w = pageCanvas.width;
11659            var h = pageCanvas.height;
11660            pageCtx.fillStyle = 'white';
11661            pageCtx.fillRect(0, 0, w, h);
11662            pageCtx.drawImage(canvas, 0, page * pxPageHeight, w, h, 0, 0, w, h);
11663
11664            // Add the page to the PDF.
11665            if (page) pdf.addPage();
11666            var imgData = pageCanvas.toDataURL('image/' + opt.image.type, opt.image.quality);
11667            pdf.addImage(imgData, opt.image.type, opt.margin[1], opt.margin[0], pageSize.inner.width, pageHeight);
11668
11669            // Add hyperlinks.
11670            if (opt.enableLinks) {
11671                var pageTop = page * pageSize.inner.height;
11672                opt.links.forEach(function (link) {
11673                    if (link.clientRect.top > pageTop && link.clientRect.top < pageTop + pageSize.inner.height) {
11674                        var left = opt.margin[1] + link.clientRect.left;
11675                        var top = opt.margin[0] + link.clientRect.top - pageTop;
11676                        pdf.link(left, top, link.clientRect.width, link.clientRect.height, { url: link.el.href });
11677                    }
11678                });
11679            }
11680        }
11681
11682        // Finish the PDF.
11683        pdf.save(opt.filename);
11684    };
11685
11686    return html2pdf;
11687
11688})));
11689/**
11690 * 'Login logout Factory'
11691 */
11692
11693
11694var loginLogout = (function() {
11695
11696    'use strict';
11697
11698    /**
11699     * 'Store data in session [private]'
11700     * @params {object} args 'Object containing key and value'
11701     * @return {null}
11702     */
11703
11704    function _storeInSession(args) {
11705        window.localStorage.setItem(args.userId, args.flag);
11706    }
11707
11708    /**
11709     * 'Get data stored in session [private]'
11710     * @param  {string} key 'session's key
11711     * @return {null}
11712     */
11713
11714    function _getFromSession(key) {
11715        if (localStorage.getItem(key)) {
11716            try {
11717                return localStorage.getItem(key);
11718            } catch (e) {
11719                console.log('Error getting the session data', e);
11720            }
11721        } else {
11722            return null;
11723        }
11724    }
11725
11726    /**
11727     * loadAnonymousProfile handles CTA and load anonymous profile in context hub.
11728     * @param  {string} text
11729     */
11730
11731    function loadAnonymousProfile(elem) {
11732
11733        var isValidMode = true;
11734        let userId = elem.data('userid');
11735
11736        if(typeof _satellite !== 'undefined') {
11737            setHeaderCta(elem.text());
11738        }
11739
11740        if (document.querySelector('[data-runMode]').dataset.runmode.indexOf('author') !== -1) {
11741            isValidMode = false;
11742        }
11743
11744        if(isValidMode) {
11745            _storeInSession({
11746                userId: userId,
11747                flag: 'loggedOut'
11748            });
11749        }
11750
11751        var store = ContextHub.getStore('profile');
11752        var anonymousUserPath = store.config.initialValues.path;
11753        var contextHubUserPath = store.getTree().path;
11754        if(!contextHubUserPath || contextHubUserPath !== anonymousUserPath){
11755        store.loadProfile(anonymousUserPath);
11756        }
11757
11758
11759        //logout from AEM
11760        $.ajax({
11761          url : '/system/sling/logout',
11762          type : 'post',
11763          success : function(data) {
11764            //logout from EDIP server
11765            window.location = elem.data('logouturl');
11766          },
11767          error : function(xhr, status, err) {
11768            console.log(err);
11769          }
11770        });
11771
11772    }
11773
11774    /**
11775     * 'Initialize or config function [public]'
11776     * @return {null}
11777     */
11778
11779    function init() {
11780        var $template = $('#welcome-template').html();
11781        var $template_parent = $('.welcome-header .contain-header');
11782        var welcome_string;
11783        let userId = $('#logoutLink').data('userid');
11784
11785        if (homePageVideo.ElementExist($('.welcome-header'))) {
11786            if (userId !== 'anonymous') {
11787                if (_getFromSession(userId)) {
11788                    // Welcome back
11789                    welcome_string = $('.welcome-header').children().get(2).value + ' ' + $('.welcome-header').children().get(3).value;
11790                }
11791                else {
11792                    // First Time Login
11793                    welcome_string = $('.welcome-header').children().get(1).value + ' ' + $('.welcome-header').children().get(3).value;
11794                }
11795
11796                $template_parent.append(Mustache.render($template, {
11797                    value: welcome_string
11798                }));
11799                
11800				var userType = ContextHub.get('profile')['userType'];
11801				var isAdvisorCookie = document.cookie.replace(/(?:(?:^|.*;\s*)isAdvisor\s*\=\s*([^;]*).*$)|^.*$/, "$1");
11802
11803				if (isAdvisorCookie === "") { // Check if the "isAdvisor" cookie is being set for the first time
11804					// Calculate the expiration date (1 year from the current date)
11805					var expirationDate = new Date();
11806					expirationDate.setFullYear(expirationDate.getFullYear() + 1);
11807					// Format the expiration date string in the required format (e.g., "Thu, 16 Apr 2023 00:00:01 GMT")
11808					var expirationDateString = expirationDate.toUTCString();
11809
11810					if (userType === 'BOA_Admin') {
11811						document.cookie = "isAdvisor=false; Path=/; Expires=" + expirationDateString + ";";
11812					} else {
11813						document.cookie = "isAdvisor=true; Path=/; Expires=" + expirationDateString + ";";
11814					}
11815				} else if (userType === 'BOA_Admin') {
11816					if (isAdvisorCookie !== "false") {
11817						document.cookie = "isAdvisor=false; Path=/;";
11818					}
11819				} else if (isAdvisorCookie !== "true") {
11820					document.cookie = "isAdvisor=true; Path=/;";
11821				}
11822                _storeInSession({
11823                    userId: userId,
11824                    flag: 'loggedIn'
11825                });
11826            }
11827        }
11828    }
11829   
11830    return {
11831        init: init,
11832        loadAnonymousProfile:loadAnonymousProfile
11833    };
11834
11835}());
11836
11837var navigationMenu = {
11838
11839    init: function() {
11840        if($('.header-container').length !== 0) {
11841            const isAuthor = (document.querySelector('[data-runMode]').dataset.runmode.indexOf('author') !== -1);
11842            isAuthor ? $('body').addClass('gn author') : $('body').addClass('gn');
11843		}
11844
11845    $('body').css({'visibility':'visible','opacity':'1'});
11846    topNavigation.configureTopNavigation();
11847
11848    },
11849
11850};
11851
11852var onboardUser = {
11853    init: function(){
11854        let userId = $('#logoutLink').data('userid');
11855        let userIdOccurence=userId+"_occ";
11856        let userIdClose=userId+"_close";
11857        occurences=(parseInt(onboardUser.getFromSession(userIdOccurence))||0);
11858        usercloseactivate=onboardUser.getFromSession(userIdClose);
11859        max_occurences=(parseInt($('.occurenceCount').text()));
11860        mode_for_display=$('.edit_mode_onboarding').text();
11861        if (mode_for_display=="false"){
11862
11863             if  (usercloseactivate=="true"){
11864                $('.onboarding-container').hide();
11865            }
11866            else if (occurences>=max_occurences){
11867                $('.onboarding-container').hide();
11868            }
11869            else{
11870                occurences++;
11871                onboardUser.storeInSession({key:userIdOccurence,data:occurences});
11872                occurences=parseInt(onboardUser.getFromSession(userIdOccurence));
11873                  if ($(window).width() > 929) {
11874                  $('.mobile-tablet-only').hide();
11875                  $('.large-device-only').show();  
11876                }
11877                else {
11878                    $('.mobile-tablet-only').show();
11879                    $('.large-device-only').hide();
11880                }
11881            }
11882        }
11883        else{
11884            $('.onboarding-container').show();
11885        }
11886
11887        $(window).on('debouncedresize.onboardUser',function () {
11888                if ($(window).width() > 929) {
11889                  $('.mobile-tablet-only').hide();
11890                  $('.large-device-only').show();
11891                }
11892                else {
11893                    $('.mobile-tablet-only').show();
11894                    $('.large-device-only').hide();
11895                }
11896        });
11897
11898        $('.welcome-close').on('click', function () {
11899            onboardUser.welcomeCloseClick();
11900        });
11901    },
11902    welcomeCloseClick:function()
11903    {
11904        let userId = $('#logoutLink').data('userid');
11905        let userIdClose=userId+"_close";
11906        $('.mobile-tablet-only').hide();
11907        $('.onboarding-container').hide();
11908        onboardUser.storeInSession({key:userIdClose,data:'true'});
11909
11910    },
11911    storeInSession: function(args){
11912        window.localStorage.setItem(args.key, JSON.parse(args.data));
11913    },
11914    getFromSession: function(key){
11915        if(localStorage.getItem(key)) {
11916            try{
11917                return localStorage.getItem(key);
11918            }catch(e){
11919                console.log('Error getting the session data',e);
11920            }
11921        }
11922        else {
11923            return false;
11924        }
11925    }
11926};
11927var accordionModify = {
11928    init : function() {
11929        if (document.querySelector("[data-runMode]") && document.querySelector("[data-runMode]").dataset && document.querySelector("[data-runMode]").dataset.runmode.indexOf("publish") != -1) {
11930            if ($(".accordion-item").hasClass("form-group-accordian-item")==true){
11931            	//solution for removing accoridan in form group link
11932            }
11933            else{
11934                $(".accordion-item").each(
11935                    function(element, i) {
11936                        if ($(this).hasClass("formGroupRemoved") && $(this).find(".accordion-content").children().children().length == 0) {
11937                            $(this).remove();
11938                        }
11939                    });
11940            }
11941        }
11942    }
11943};
11944
11945$(document).ready(function () {
11946
11947    var validForm = false;
11948
11949    $('.clear-checkbox').each(function(){
11950      $(this).prop('checked', false);
11951    });
11952
11953    $('#manage__preference-final').hide();
11954
11955    $('.addPolicy .crossIcon.icon').hide();
11956
11957    $(document).on('keyup change', '.manage__preference-input', function(){
11958      managePreferenceValidation(validForm);
11959    });
11960
11961    $('.hide-first').hide();
11962    $('.manage__preference-checkbox').change(function () {
11963      displayHeading();
11964      if ($('input[name="unsubscribe-phone"]:checked').length) {
11965          $('#manage-input-email').css('float', 'right');
11966      } else {
11967          $('#manage-input-email').css('float', 'left');
11968      }
11969
11970      var toggleElem = $(this).data('id');
11971      if($('#' + toggleElem).length) {
11972        $('#' + toggleElem).toggleClass('manage__preference-hide');
11973      } else {
11974        $('.manage-input-form, .info-sharing-names').toggleClass('manage__preference-hide');
11975        namesDisplay();
11976      }
11977      managePreferenceValidation(validForm);
11978    });
11979
11980    $('.manage__marketing-checkbox').change(function() {
11981      displayHeading();
11982      namesDisplay();
11983      managePreferenceValidation(validForm);
11984    });
11985
11986    if ($('.info-sharing-policy').length) {
11987      var policyTemplate = $('.addPolicy')[0].outerHTML;
11988      $('.addPolicyButton').click(function () {
11989          $(policyTemplate).insertBefore('.addPolicyButton');
11990          $('#manage__preference-submit').addClass('disableButton');
11991          if ($('.addPolicy').length > 1) {
11992            $('.addPolicy .crossIcon.icon').show();
11993          } else {
11994            $('.addPolicy .crossIcon.icon').hide();
11995          }
11996          $('.inputField').on('blur', function() {
11997            bhfFormValidator.textFieldValidator($(this));
11998          });
11999      });
12000    }
12001
12002    $('#manage__preference-submit').click(function (e) {
12003        e.preventDefault();
12004        let data = {};
12005        if($('input[name=unsubscribe-phone]').is(':checked')) {
12006          data.mobileNo = $('#mobileNo').val();
12007        }
12008        if($('input[name=unsubscribe-email]').is(':checked')) {
12009          data.email = $('#email').val();
12010        }
12011        if($('input[name=unsubscribe-mail]').is(':checked')) {
12012          data.firstName = $('#firstName').val();
12013          data.lastName = $('#lastName').val();
12014          data.address1 = $('#address1').val();
12015          data.city = $('#city').val();
12016          data.zip = $('#zip').val();
12017          data.state = $('#state').find(":selected").val();
12018        }
12019        if($('input.manage__marketing-checkbox:checkbox:checked').length){
12020          data.unsubscribePolicy = $('input[name=unsubscribe-policy]').is(':checked');
12021          data.unsubscribeMarketing = $('input[name=unsubscribe-marketing]').is(':checked');
12022          data.firstName = $('#firstName').val();
12023          data.lastName = $('#lastName').val();
12024          let unsubscribePolicyNumber = [];
12025          $('#appendPolicy > .inputWrap.addPolicy').each(function(){
12026            let policyNumber = $(this).find('input').val().trim();
12027            if('' !== policyNumber) {
12028              unsubscribePolicyNumber.push(policyNumber);
12029            }
12030          });
12031          data['policyNumbers'] = unsubscribePolicyNumber;
12032        }
12033        if(document.querySelector('[data-runMode]').dataset.runmode.indexOf('author') === -1) {
12034          $.ajax({
12035            url : '/content.manage.preference',
12036            type : 'POST',
12037            data : data,
12038            success : function(data) {
12039              $('#manage__preference-initial').hide();
12040              $(window).scrollTop(0);
12041              $('#manage__preference-final').show();
12042            },
12043            error : function(xhr, status, err) {
12044              console.log(err);
12045            }
12046          }); 
12047        } else {
12048          $('#manage__preference-initial').hide();
12049          $(window).scrollTop(0);
12050          $('#manage__preference-final').show();
12051        }
12052    });
12053
12054    $('#manage__preference-submit').keypress(function(e) {
12055      if(!$(this).hasClass('disableButton')) {
12056        let charCode = e.which || e.keyCode;
12057        if(charCode === 13) {
12058          $(this).click();
12059        }
12060      }
12061    });
12062
12063    $(document).on('blur', '.manage__preference-input.policy-input', function() {
12064      if($(this).val().trim() !== '') {
12065        $(this).addClass('validated-field');
12066      }
12067    });
12068
12069    //delete policy input
12070    $('#appendPolicy').on('click', 'i.crossIcon.icon', function (e) {
12071        if ($('.addPolicy').length > 1) {
12072          $(this).parent().remove();
12073        } 
12074        if($('.addPolicy').length == 1){
12075          $('i.crossIcon.icon').hide();
12076        }
12077        managePreferenceValidation(validForm);
12078    });
12079});
12080
12081function managePreferenceValidation(validForm) {
12082  var req_elements = $('.required:visible');
12083  for (var i=0; i<req_elements.length; i++){
12084    if(!$(req_elements[i]).hasClass('form-select-search') && $(req_elements[i]).val().trim() === '') {
12085      validForm = false;
12086      break;
12087    }else if ($(req_elements[i]).hasClass('phone')) {
12088      if($(req_elements[i]).val().length !== 10) {
12089        validForm = false;
12090        break;
12091      }else {
12092        validForm = true;
12093      }
12094    }else if($(req_elements[i]).hasClass('email')) {
12095      var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
12096      if(!emailReg.test($(req_elements[i]).val())){
12097        validForm = false;
12098        break;
12099      }else {
12100        validForm = true;
12101      }
12102    }else if ($(req_elements[i]).hasClass('form-select-search')) {
12103      if($(req_elements[i]).val() === null || $(req_elements[i]).val().length === 0) {
12104        validForm = false;
12105        break;
12106      }else {
12107        validForm = true;
12108      }
12109    }else {
12110      validForm = true;         
12111    }
12112  }
12113  if(validForm) {
12114    $('#manage__preference-submit').removeClass('disableButton');
12115  }else {
12116    $('#manage__preference-submit').addClass('disableButton');
12117  }
12118}
12119
12120function namesDisplay() {
12121  if($('.manage__marketing-checkbox:checkbox:checked').length) {
12122    $('.info-sharing-names, .info-sharing-policy').removeClass('manage__preference-hide');
12123  } else {
12124    if($('.manage__mail-checkbox:checkbox:checked').length) {
12125      $('.info-sharing-policy').addClass('manage__preference-hide');
12126    } else{
12127      $('.info-sharing-names, .info-sharing-policy').addClass('manage__preference-hide');
12128    }
12129  }
12130}
12131
12132function displayHeading() {
12133  if ($('.manage__preference-checkbox:checkbox:checked').length || $('.manage__marketing-checkbox:checkbox:checked').length) {
12134    $('.hide-first').show();
12135  } else {
12136    $('.hide-first').hide();
12137  }
12138}
12139var message = (function () {
12140
12141  'use strict';
12142
12143  /**
12144   * 'Ajax call values [private]'
12145   * @type {Object}
12146   */
12147
12148  const _configVars = {
12149    "URL_SRC" : "/content.notification.fetchArchivedMsgs",
12150    "URL_TYPE" : "GET"
12151  };
12152
12153  /**
12154   * 'To enable button only if response from previous call received'
12155   * @type {Boolean}
12156   */
12157
12158  var _enableButton = true;
12159
12160  /**
12161   * 'Offset to pass to the ajax call [private]'
12162   * @type {Number}
12163   */
12164
12165  var _offset = 5;
12166
12167  /**
12168   * 'Total Cound of archived mesaage counts [private]'
12169   * @type {Number}
12170   */
12171
12172  var _archivedTotalCount = 0;
12173
12174  /**
12175   * 'Store data in session [private]'
12176   * @params {object} args 'Object containing key and value'
12177   * @return {null}
12178   */
12179
12180  function _storeInSession(args) {
12181      window.sessionStorage.setItem(args.key, args.data);
12182  }
12183
12184  /**
12185   * 'Get data stored in session [private]'
12186   * @param  {string} key 'session's key
12187   * @return {null}
12188   */
12189
12190  function _getFromSession(key) {
12191      if(sessionStorage.getItem(key)) {
12192          try{
12193            return sessionStorage.getItem(key);
12194          } catch(exception){
12195            throw exception;
12196          }
12197      } else {
12198          return false;
12199      }
12200  }
12201
12202  /**
12203   * 'Invoke the dismiss event [private]'
12204   * @return {null}
12205   */
12206
12207  function _invokeEvent() {
12208
12209      $(document).on('click', '.message-cross', function(event) {
12210          // Stop the event propogation
12211          event.stopPropagation();
12212          window.location.href = $(this).data('href') + '?notification=open';
12213      });
12214
12215      $('.message-cross').on('click','.dismiss_notification',function(event) {
12216        // Stop the event propogation
12217        event.stopPropagation();
12218
12219          $(this).parents(':eq(6)').hide();
12220
12221          if (typeof(Storage) !== 'undefined') {
12222              try {
12223                _storeInSession({
12224                  key:'dismissed',
12225                  data: $(this).data('dismiss')
12226                });
12227              } catch(exception) {
12228                throw exception;
12229              }
12230          } else {
12231            console.log('Storage not available');
12232          }
12233
12234      });
12235
12236      $('.message-cross').on('click','a',function(event) {
12237        // Stop the event propogation
12238        event.stopPropagation();
12239      });
12240
12241  }
12242
12243  /**
12244   * 'Parse Query Params [private]'
12245   * @param  {String} variable 'The Param to find'
12246   * @return {String}          'Value of the params ?param=value'
12247   */
12248
12249  function _getQueryVariable(variable) {
12250      var query = window.location.search.substring(1);
12251      var vars = query.split('&');
12252      for (var i in vars) {
12253          var pair = vars[i].split('=');
12254
12255          if (pair[0] === variable) {
12256              return pair[1];
12257          }
12258      }
12259  }
12260
12261  /**
12262   * 'Load More Button Click callback [private]'
12263   * @return {null}
12264   */
12265
12266  function _loadMoreGist() {
12267    _enableButton = false;
12268    $.ajax({
12269        type: _configVars.URL_TYPE,
12270        url: _configVars.URL_SRC + '?offset=' + _offset,
12271        success: function(data) {
12272            data = JSON.parse(data);
12273            var $msg_ul = $('#archivedMsgUl');
12274            var $load_msg_template = $('#load-more-msg-template').html();
12275            $msg_ul.append(
12276              Mustache.render($load_msg_template, data));
12277              Foundation.reInit('accordion');
12278
12279            _offset = _offset+5;
12280
12281            if(_offset >= _archivedTotalCount) {
12282                $('.loadMoreMsgWrapper').hide();
12283            }
12284            _enableButton = true;
12285        },
12286        error: function(err){
12287            throw err;
12288        }
12289    });
12290  }
12291
12292  /**
12293   * 'Show or hide the section based on session dismissed value [private]'
12294   * @return {null}
12295   */
12296
12297  function _showHide() {
12298    if(_getFromSession('dismissed')) {
12299        let dismissed = _getFromSession('dismissed');
12300
12301        if(!$('.dashboard-msg-section').eq(0).hasClass(dismissed)){
12302            $('.dashboard-msg-section').eq(0).removeClass('hide');
12303        }
12304
12305    } else {
12306      $('.dashboard-msg-section').eq(0).removeClass('hide');
12307    }
12308  }
12309
12310  /**
12311   * 'Initialize or config function [public]'
12312   * @return {null}
12313   */
12314
12315   function init() {
12316
12317      // Run if Section present
12318      if($('.dashboard-msg-section').length !== 0 ) {
12319          _showHide();
12320          _invokeEvent();
12321      }
12322
12323      // Run if Section present
12324      if($('.msg-section').length !== 0) {
12325          if(_getQueryVariable('notification') === 'open') {
12326             $('.msg-section .current-message-section li:first-child a.accordion-title').eq(0).trigger('click');
12327          }
12328      }
12329
12330      // Run if Section present
12331      if($('#loadMoreArchivedMsg').length !== 0) {
12332
12333        _archivedTotalCount = $('#archivedMsgUl').next().val();
12334
12335        $('#loadMoreArchivedMsg').on('click',function(){
12336          _enableButton && _loadMoreGist();
12337        });
12338
12339      }
12340
12341  }
12342
12343  return {
12344    init: init
12345  };
12346
12347}());
12348var formGroup = {
12349    data: {},
12350    arranged: false,
12351    init: function() {
12352        if (document.querySelector('[data-runMode]').dataset.runmode.indexOf('publish') !== -1 && $('.formgroup-container').length >0) {
12353            $.ajax({
12354                url: '/content.user.entitlement',
12355                type: 'get',
12356                success: function(d) {
12357                    $('.formgroup-container').each(function() {
12358                        let isComponentVisible = false;
12359                        $(this).find('.form-group-element').each(function(element, j) {
12360                            if (formGroup.showHideElement($(this), d)) {
12361                                isComponentVisible = true;
12362                            }
12363                        });
12364                        if (!isComponentVisible) {
12365                        	$(this).parent().closest(".accordion-item").addClass("formGroupRemoved");
12366                            $(this).parent().remove();
12367                        }
12368                    });
12369                    accordionModify.init();
12370
12371                }
12372            });
12373        }
12374    },
12375
12376    showHideElement: function(element, entitlementList) {
12377        var isVisible = true;
12378        let mutualEntitlement = formGroup.intersect(element.attr('data-entitlement'), entitlementList);
12379        if (!(mutualEntitlement)) {
12380            element.remove();
12381            isVisible = false;
12382        }
12383        return isVisible;
12384    },
12385
12386
12387
12388    intersect: function(a, b) {
12389
12390        if (typeof(a) === 'undefined' || a.length === 0) {
12391            return true;
12392        }
12393
12394        let aArr = a.split(',');
12395        let bArr = b.split(',');
12396        let ai = 0,
12397            bi = 0;
12398        for (let i = 0; i < aArr.length; i+=1) {
12399            for (let j = 0; j < bArr.length; j+=1) {
12400                if (aArr[i].length !== 0 && bArr[j].length !== 0 && aArr[i].trim().toLowerCase() === bArr[j].trim().toLowerCase()) {
12401                    return true;
12402                }
12403            }
12404        }
12405        return false;
12406    }
12407
12408
12409};
12410var formGroupLink = {
12411    windowWidth : 0,
12412
12413    init: function() {
12414        formGroupLink.windowWidth = $(window).width();
12415
12416        setTimeout(function(){
12417            formGroupLink._allContainers();
12418            formGroupLink._mobileClick();
12419        }, 600);
12420
12421        $(window).on('debouncedresize.formGroupLink',function() {
12422            if ($(window).width() !== formGroupLink.windowWidth) {
12423                formGroupLink.windowWidth = $(window).width();
12424                formGroupLink._allContainers();
12425                formGroupLink._mobileClick();
12426            }
12427        });
12428    },
12429
12430    _tabTitle: function () {
12431        if(homePageVideo.ElementExist($('.tabs-title'))) {
12432            $('.tabs-title','.form-group-tab').on('click', function() {
12433                let textToUpdate = $(this).text().trim();
12434                let $close_dropdown = $(this).parent('#formgroup-tabs').siblings('.relative').find('.custom-dropdown-btn');
12435                $close_dropdown.html(textToUpdate + '<i class="fix-dropdown-icon-location icon caret-medium-dark"></i>');
12436            });
12437        }
12438    },
12439
12440    _allContainers: function() {
12441        formGroupLink._tabTitle();
12442        $('.form-group-container').each(function(eq, el) {
12443            el = $(el);
12444            var panel_element = el.find('.tabs-panel');
12445            var dropdown_element = el.find('.custom-dropdown-option');
12446
12447            if (panel_element.length !== 0) {
12448                var check_width = 0;
12449                var all_titles = el.find('.tabs-title');
12450                var parent_width = el.find('.formgroup-tabs-class').width();
12451
12452                all_titles.each(function(){
12453                    check_width += $(this).width();
12454                });
12455
12456                if ($(window).width() < 640) {
12457                    el.find('.custom-dropdown-btn').show();
12458                    el.find('.dropdown-pane').show();
12459                    el.find('.formgroup-tabs-class').hide();
12460                } else if (($(window).width() >= 640) && (check_width > parent_width)) {
12461                    el.find('.custom-dropdown-btn').show();
12462                    el.find('.dropdown-pane').show();
12463                    el.find('.formgroup-tabs-class').hide();
12464                } else {
12465                    el.find('.custom-dropdown-btn').hide();
12466                    el.find('.dropdown-pane').hide();
12467                    el.find('.formgroup-tabs-class').show();
12468                }
12469            }
12470        });
12471    },
12472
12473    _mobileClick: function() {
12474        if(homePageVideo.ElementExist($('.mobile-tab-option'))) {
12475
12476            // Clear Events Before Invoking New to prevent Stacking
12477            $('.mobile-tab-option').off('click.mobileTabOption');
12478
12479            // Invoke New Event
12480            $('.mobile-tab-option').on('click.mobileTabOption', function(e) {
12481                e.preventDefault();
12482                e.stopPropagation();
12483                $(this).parent().parent().parent().trigger('click');
12484                var toggleText = $(this).text().trim();
12485                var $close_dropdown = $(this).parents('.dropdown-pane').siblings('.custom-dropdown-btn');
12486                $close_dropdown.html(toggleText + '<i class="fix-dropdown-icon-location icon caret-medium-dark"></i>');
12487
12488                var click_div = $(this).attr('id');
12489                var r = $(this).parents('.form-group-container');
12490                $(r).each(function(eq, el) {
12491                    el = $(el);
12492                    var m = el.find('.tabs-panel');
12493                    $(m).removeClass('is-active');
12494                    $(m).attr('aria-hidden', 'true');
12495                    var expanded_tabs = el.find('[aria-hidden="false"]');
12496
12497                    for (var i = 0; i < expanded_tabs.length - 1; i+=1) {
12498                        $(expanded_tabs[i]).attr('aria-hidden', 'true');
12499                    }
12500                    for (var i = 0; i < m.length - 1; i+=1) {
12501                        $(m[i]).attr('aria-hidden', 'true');
12502
12503                        var title = document.getElementById(m[i].id + '-label');
12504                        if (title) {
12505                            $(title).removeClass('is-active');
12506                        }
12507                    }
12508                });
12509                var m = document.getElementById('formlink-' + click_div);
12510                m.setAttribute('aria-hidden', 'false');
12511                m.className += ' is-active';
12512
12513                $(this).parents('.form-group-container').find('.form-group-tab li').removeClass('is-active');
12514                $(this).parents('.form-group-container').find('.form-group-tab li#formlink-'+click_div+'-label').addClass('is-active');
12515            });
12516        }
12517    }
12518};
12519(function($, me) {
12520
12521    // Enable strict mode
12522    "use strict";
12523
12524    me.paginationConstant = 5;
12525    me.objectData = null;
12526    me.allComponentURL = '/content.componentList.fetchJSON';
12527    me.getComponentsDataURL = '/content.pageList.fetchJSON';
12528
12529    me.canBeParsed = function(str) {
12530        try {
12531            JSON.parse(str);
12532        } catch (e) {
12533            return false;
12534        }
12535        return true;
12536    };
12537
12538    me.getAllComponentsList = function () {
12539        $.ajax({
12540            url: me.allComponentURL,
12541            type: 'GET',
12542            success: function(data) {
12543                var $ul = $('#list-dropdown ul');
12544                var $template= $('#render-dropdown-list').html();
12545                $ul.append(Mustache.render($template, (me.canBeParsed(data) ? JSON.parse(data) : data).components));
12546                me.componentListEvents();
12547            },
12548            error: function(xhr, status, err) {
12549                console.log('Error in fetching', JSON.parse(xhr.responseText), err, status);
12550            }
12551        });
12552    };
12553
12554    me.componentListEvents = function() {
12555        $('#pages-container input[type="checkbox"]').on('change', function(e) {
12556            const query = $(this).data('name');
12557            const $queryElem = $('.pages-data').find("[data-name='" + query + "']");
12558            if($queryElem.length) {
12559                $queryElem.remove();
12560            } else {
12561                if($(this).is(':checked')) {
12562                    me.renderTiles($(this).data('name'));
12563                }
12564            }
12565        });
12566        $('#pages-container input[type="text"]').on('keyup', function() {
12567            let val = $(this).val();
12568            if(val.length > 0) {
12569                let matches = $('#pages-container').find('li span:containsCase('+val+')').parent();
12570                $('#pages-container li:not(:first-child)').show().not(matches).hide();
12571            } else {
12572                $('#pages-container li:not(:first-child)').show();
12573            }
12574        });
12575    };
12576
12577    me.init = function() {
12578        me.getAllComponentsList();
12579    	$('.save-data').on('click', me.generateTable);
12580    };
12581
12582    me.renderPagination = function () {
12583    	const data = me.objectData;
12584        var listItems = new Array(Math.ceil(data.length/me.paginationConstant)).fill().map(function(item, index){ return ++index;});
12585        listItems[0] = {id: 1, first: true};
12586        var $container = $('.export-data .pagination-wrapper');
12587        $container.html('');
12588        var $template= $('#table-pagination').html();
12589        $container.append(Mustache.render($template, listItems));
12590        $('.pagination-tray a').on('click', function() {
12591            const index = $(this).data('id') - 1;
12592            const slicedData = data.slice(index*me.paginationConstant, me.paginationConstant*(index+1));
12593            $(this).addClass('active').siblings().removeClass('active');
12594            me.renderTable(slicedData, false);
12595        });
12596    };
12597
12598    me.renderTable = function (data, flag) {
12599        var $container = $('.generated-data .wrapper');
12600        var $template= $('#generated-data-template').html();
12601        $container.html('');
12602        const proData = data.length > me.paginationConstant ? data.slice(0, me.paginationConstant) : data;
12603        $container.append(Mustache.render($template, proData));
12604        if(me.objectData.length > me.paginationConstant && flag) me.renderPagination();
12605        else if (me.objectData.length <= me.paginationConstant) $('.export-data .pagination-wrapper').html('');
12606        $('.generated-data').show();
12607    };
12608
12609    me.renderTiles = function(name, index) {
12610    	var $ul = $('.pages-data');
12611      	var $template= $('#pages-data-template').html();
12612      	$ul.append(Mustache.render($template, {name: name}));
12613    };
12614
12615    me.generateCSV = function (items) {
12616        var str = 'Component Name, Comment, Page Name, Page Path, Total Usage, Last modified, Last published\r\n';
12617        items.map(function(row){
12618            row.data.map(function(rowData) {
12619                var arr = new Array();
12620                arr.push(row.name,row.comment,rowData.titleUpdated, rowData.pagePath,rowData.count,
12621                    rowData.lastModifiedDate.split(',').join(''),rowData.lastPublishedDate.split(',').join(''));
12622                var joinedArray = arr.join(',').concat('\r\n');
12623                str+= joinedArray;
12624            });
12625        });
12626        var blobObject = new Blob([str], { type: 'text/csv' });
12627        var filename = 'Report-'+Math.floor(Date.now() / 1000)+'.csv';
12628        if(window.navigator.msSaveOrOpenBlob) {
12629            //For IE and other browsers which doesn't support createObjectUrl
12630            $('.export-data > a').click(function(e){
12631                e.preventDefault();
12632                window.navigator.msSaveOrOpenBlob(blobObject, filename);
12633            });
12634        } else {
12635            var csvUrl = window.URL.createObjectURL(blobObject);
12636            $('.export-data > a').attr({
12637                'download': filename,
12638                'href': csvUrl
12639            });
12640        }
12641    };
12642
12643    me.generateTable = function() {
12644	    let selectTiles = new Array();
12645        let objectData = new Array();
12646
12647		if(homePageVideo.ElementExist($('.data-tile'))) {
12648			$.map($('.data-tile'), function(elem) {
12649                selectTiles.push('component='+$(elem).data('name'));
12650            });
12651
12652            $.ajax({
12653                url: me.getComponentsDataURL+'?'+ selectTiles.join('&'),
12654                type: 'GET',
12655                success: function(data) {
12656                    var parsedData = JSON.parse(JSON.stringify(data));
12657                    for(let i in parsedData) {
12658                        let pageData = new Array();
12659                        for(let j in parsedData[i]) {
12660                            pageData.push({
12661                                pagePath: window.location.origin+j,
12662                                pageTitle: parsedData[i][j].pageTitle,
12663                                titleUpdated: parsedData[i][j].pageTitle.replace(/\,/g, ';'),
12664                                count: parsedData[i][j].count,
12665                                lastModifiedDate: parsedData[i][j].lastModifiedDate,
12666                                lastPublishedDate: parsedData[i][j].lastPublishedDate,
12667                            });
12668                        }
12669                        objectData.push({
12670                            name: i,
12671                            comment: $('.data-tile[data-name="'+i+'"]').find('input').val(),
12672                            data: pageData
12673                        });
12674                    }
12675                    me.objectData = objectData;
12676                    me.renderTable(objectData, true);
12677                    me.generateCSV(objectData);
12678                },
12679                error: function(xhr, status, err) {
12680                    console.log('Error in fetching', JSON.parse(xhr.responseText), err, status);
12681                }
12682            });
12683		} else {
12684            $('.generated-data .wrapper, .export-data .pagination-wrapper').html('');
12685            $('.generated-data').hide();
12686        }
12687    };
12688
12689
12690
12691    $(function() {
12692    	homePageVideo.ElementExist($('.report-filter')) ? me.init() : null ;
12693    });
12694
12695}($, this));
12696$(document).ready(function() {
12697	if ($('form').is('#loyaltyProgram')) {
12698		loyaltyProgram.getCustomreList();
12699	}
12700	$('#loyaltyProgram').on('submit', function(e) {
12701		e.preventDefault();
12702		if (content.trim() == $('#loyaltyProgramContent').val().trim()) {
12703			$('#errorMsg').html("Nothing to update!");
12704			$('#errorMsg').css("display", "block");
12705			$('#errorMsg').css("color", "red");
12706			$('#errorMsg').hide().fadeIn();
12707			setTimeout(function() {
12708				$('#errorMsg').fadeOut();
12709			}, 2000);
12710
12711		} else {
12712			loyaltyProgram.updateCustomerList();
12713		}
12714	});
12715});
12716var content ="";
12717var loyaltyProgram = {
12718	updateCustomerList : function() {
12719		$.ajax({
12720			url : '/content.loyaltyProgram.customers/',
12721			type : 'POST',
12722			data : {
12723				"content" : $('#loyaltyProgramContent').val()
12724			},
12725			success : function(data) {
12726						$('#errorMsg').html("Customer List Updated Successfully!");
12727						$('#errorMsg').css("display", "block");
12728						$('#errorMsg').css("color", "green");					
12729					$('#errorMsg').hide().fadeIn();
12730						setTimeout(function() {
12731							$('#errorMsg').fadeOut();
12732						}, 2000);
12733					content = $('#loyaltyProgramContent').val();
12734				},
12735				error : function() {
12736				$('#errorMsg').html("Error While Updating Customer List!");
12737				$('#errorMsg').css("display", "block");
12738				$('#errorMsg').css("color", "red");
12739			}
12740		});
12741	},
12742	
12743	getCustomreList : function() {
12744		$.ajax({
12745			url : '/content.loyaltyProgram.customers/',
12746			type : 'GET',
12747			success : function(data) {
12748					$('#errorMsg').html("");
12749					$('#errorMsg').css("display", "none");
12750					$('#loyaltyProgramContent').val(data);
12751					content = data;
12752			},
12753			error : function() {
12754				$('#errorMsg').html("Error While loading Customer List!");
12755				$('#errorMsg').css("display", "block");
12756				$('#errorMsg').css("color", "red");
12757			}
12758		});
12759	}
12760}
12761
12762/**
12763 *
12764 * Array.fill Polyfills for older browsers.
12765 *
12766 */
12767
12768if (!Array.prototype.fill) {
12769  Object.defineProperty(Array.prototype, 'fill', {
12770    value: function(value) {
12771
12772      if (this == null) {
12773        throw new TypeError('this is null or not defined');
12774      }
12775
12776      var O = Object(this);
12777
12778      var len = O.length >>> 0;
12779      console.log('>>', len);
12780      var start = arguments[1];
12781      var relativeStart = start >> 0;
12782
12783      var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len);
12784
12785      var end = arguments[2];
12786      var relativeEnd = (typeof end === 'undefined') ? len : end >> 0;
12787
12788      var finalValue = relativeEnd < 0 ? Math.max(len + relativeEnd, 0):Math.min(relativeEnd, len);
12789
12790      while (k < finalValue) {
12791        O[k] = value;
12792        k++;
12793      }
12794
12795      return O;
12796    }
12797  });
12798}
12799
12800$(document).ready(function(){
12801    if(homePageVideo.ElementExist($('.contactLabel'))) {
12802        var contactPagePath = window.location.pathname;
12803        var buttonColor = $('.contactLabel').attr('buttonColor');
12804        var buttonHoverColor = $('.contactLabel').attr('buttonHoverColor');
12805        var labelColor = $('.contactLabel').attr('labelColor');
12806        var labelHoverColor = $('.contactLabel').attr('labelHoverColor');
12807        var padding = $('.contactLabel').attr('padding');
12808        var labelClicked = false;
12809        var formScroll = $('.questionsDropdown')[0];
12810        var thankYouScroll = $('.questionsDropdown')[1];
12811    
12812        $('.hideFirst').hide();
12813    
12814        $(window).load(function(){
12815            setTimeout(function() {
12816                $('.contactLabel').show();
12817            },3000);
12818        });
12819
12820        $('.contactLabel').click(function(e) {
12821            e.preventDefault();
12822            labelClicked = true;
12823            $(this).hide();
12824            if($(window).width() > 1024) {
12825                $('.fromBottom').animate({top: '25%'});
12826            } else if($(window).width() > 790 && $(window).width() < 1024) {
12827                $('.fromBottom').animate({top: '40%'});
12828            }else {
12829                $('.fromBottom').animate({top: '70'});
12830            }
12831            $('.fromBottom').show();
12832            if(localStorage.getItem('formSubmit_'+contactPagePath) === 'yes') {
12833                $('.questionsDropdown').hide();
12834                $('.questionsThankyou').show();
12835            } else {
12836                $('.questionsDropdown').show();
12837                $('.questionsThankyou').hide();
12838            }
12839            if($(window).width() >= 768) {
12840                if(topNavigation.isTouchDevice()) {
12841                    let obj = $('.fromBottom')[0];
12842                    var questDrop = $('.questionsDropdown')[0];
12843                    var thankDrop = $('.questionsDropdown')[1];
12844                    let body = $('body')[0];
12845                    obj.addEventListener('touchmove', function(e){
12846                        e.stopPropagation();
12847                        bodyScrollLock.disableBodyScroll(questDrop);
12848                    }, true);
12849                    thankDrop.addEventListener('touchmove', function(e){
12850                        e.stopPropagation();
12851                        bodyScrollLock.disableBodyScroll(thankDrop);
12852                    }, true);
12853                    body.addEventListener('touchmove', function(e){
12854                        e.stopPropagation();
12855                        bodyScrollLock.clearAllBodyScrollLocks();
12856                    });           
12857                } else {
12858                    $(".fromBottom").hover(function() {
12859                        let oldScrollPos = $(window).scrollTop();
12860        
12861                        $(document).on('scroll.scrolldisabler', function(event) {
12862                            $(window).scrollTop(oldScrollPos);
12863                            event.preventDefault();
12864                        });
12865                    }, function() {
12866                        $(document).off('scroll.scrolldisabler');
12867                    });
12868                }
12869            } else {
12870                mobileScroll();
12871            }
12872        });
12873    
12874        $('.selectProducts').on('change', (function(){
12875            $('.formDisplay').removeClass('margin-for-scroll');
12876            $('.hideFirst').hide();
12877            var selectedOption = $(this).val();
12878            $('#' + selectedOption).show();
12879            const nonSelectedValues = [];
12880            $('.questionsOption').each(function(){
12881                if(selectedOption != $(this).val()){
12882                    nonSelectedValues.push($(this).val())
12883                }
12884            });
12885            nonSelectedValues.forEach(element => {
12886                if($('#' + element).hasClass('salesForm')){
12887                    $('#' + element).find('.recaptcha').remove();
12888                }
12889            });
12890            const submitElement = $('#' + selectedOption).find('.bhf-form-submit-container');
12891            $(submitElement).before('<div class="cell small-12 medium-12 large-12">
12891<div class="recaptcha" id="recaptcha_html_element_contact_wholesaler" verified="false"></div></div>')
12892            const siteKey = $('#contact-wholesaler-site-key').val() || null;
12893            if(siteKey){
12894                var captcha = grecaptcha.enterprise.render('recaptcha_html_element_contact_wholesaler', { 
12895                    'sitekey' : siteKey, 
12896                    'action'  : 'contact-wholesaler', 
12897                    'callback': function(resp){
12898                        recaptchaContactWholesalerCallback(resp)
12899                    },
12900                    'expired-callback': recaptchaContactWholesalerExpiredCallback
12901                }); 
12902            }else{
12903                console.log("unable to get siteKey");
12904            }
12905        }));
12906    
12907        $('.questionsClose').click(function(e) {
12908            e.preventDefault();
12909            if($('.formDisplay .textLinkSection').is(':visible') && !$('.formDisplay .textLinkSection .connectWholesaler').is(':visible') ){
12910                setToolComplete();
12911            }
12912            $('.formDisplay').addClass('margin-for-scroll');
12913            $('.questionsDropdown').scrollTop(0);
12914            bodyScrollLock.clearAllBodyScrollLocks();
12915            labelClicked = false;
12916            $('.fromBottom').animate({top: '100%'});
12917            $('.contactLabel').show();
12918            $('#selectedTopic').text($('.selectProducts').children('option').eq(0).text());
12919            $('.hideFirst').hide();
12920            $('fromBottom').hide();
12921            $('.error-form').hide();
12922            var forms = $('form.salesSubmit');
12923            for(var i=0; i<forms.length; i++) {
12924                forms[i].reset();
12925            }
12926
12927            $('.questionsOption').each(function(){
12928                if($('#' + $(this).val()).hasClass('salesForm')){
12929                    $('#' + $(this).val()).find('.recaptcha').remove();
12930                }
12931            });
12932        });
12933    
12934        $('.salesSubmit').on('submit', function(e) {
12935            e.preventDefault();
12936            $('.questionsDropdown').hide();
12937            $('.questionsThankyou').show();
12938            if($(window).width() < 768){
12939                mobileScroll();
12940            }
12941            localStorage.setItem('formSubmit_'+contactPagePath,'yes');
12942            var form = $(this);
12943            var url = '/content.salesforceAPI.connect';
12944            var currentPagePath  = $("#currentPagePathContactWholesaler").val();
12945            var formData = form.serializeArray();
12946        	formData.push({name: "currentPagePath", value: currentPagePath});
12947            $.ajax({
12948                type: "POST",
12949                url: url,
12950                data: formData,
12951                success: function()
12952                {
12953                console.log('Form Submitted');
12954                },
12955                error: function() {
12956                    console.log('Error in submitting salesforce form');
12957                }
12958            });
12959        });
12960    
12961        $('.contactLabel').css("background-color", buttonColor);
12962        $('.contactLabel').css("color", labelColor);
12963        if(padding != "")
12964        {
12965        $('.contactLabel').css("padding", padding);
12966        }
12967    
12968    
12969        $('.contactLabel').hover(function() {
12970                $(this).css("background-color", buttonHoverColor);
12971                $(this).css("color", labelHoverColor)
12972            }, function() {
12973                $(this).css("background-color", buttonColor);
12974                $(this).css("color", labelColor);
12975            }
12976        );
12977        
12978        if($('.styledSelect').hasClass('active')) {
12979            $('.icon.arrow-down-icon').addClass('rotated');
12980        } else {
12981            $('.icon.arrow-down-icon').removeClass('rotated');
12982        }
12983    
12984        
12985        $(window).on('orientationchange', function() {
12986            if (labelClicked) {
12987                $('.fromBottom').hide();
12988                setTimeout(function(){$('.contactLabel').trigger('click');}, 500);
12989            }
12990        });
12991
12992        function ishidden(el){
12993            return (el.offsetParent === null);
12994        }
12995    
12996        function mobileScroll(){
12997            if(ishidden(thankYouScroll)){
12998                bodyScrollLock.disableBodyScroll(formScroll);
12999            }else{
13000                bodyScrollLock.disableBodyScroll(thankYouScroll);
13001            }
13002        }
13003    }
13004
13005
13006    function recaptchaContactWholesalerCallback(response) {
13007        let recaptchaThresholdValue = $('#recaptcha-threshold').val();
13008        var url = "/content.enterpriseRecaptcha";
13009        $.ajax({
13010            type: "POST",
13011            url: url,
13012            data : {
13013                token: response,
13014                recaptchaThresholdValue: recaptchaThresholdValue
13015            },
13016            success: function (data) {
13017                let userObj = JSON.parse(data);
13018                let formSubmitContact = $('#recaptcha_html_element_c
13018ontact_wholesaler').closest('form');
13019                if (userObj['isSuccess'] == true) {
13020                    $('#recaptcha_html_element_contact_wholesaler').attr('verified',true);
13021                    bhfFormValidator.submitValidator($($(formSubmitContact).find('.text-field-validation')));
13022                    //return true;
13023                } else {
13024                    $('#recaptcha_html_element_contact_wholesaler').attr('verified',false);
13025                    bhfFormValidator.submitValidator($($(formSubmitContact).find('.text-field-validation')));
13026                    return false
13027                }
13028            },
13029            error: function () {
13030                console.log('Error in getting verify response form');
13031                return false
13032            }
13033        });
13034    }
13035    
13036    function recaptchaContactWholesalerExpiredCallback() {
13037        let formSubmitContact = $('#recaptcha_html_element_contact_wholesaler').closest('form');
13038        $('#recaptcha_html_element_contact_wholesaler').attr('verified',false);
13039        bhfFormValidator.submitValidator($($(formSubmitContact).find('.text-field-validation')));
13040    }
13041});
13042
13043$(function(){
13044    $('.selectProducts').each(function () {
13045
13046        var $this = $(this),
13047            numberOfOptions = $(this).children('option').length;
13048
13049        $this.addClass('s-hidden');
13050
13051        $this.wrap('<div class="select"></div>');
13052
13053        $this.after('<div class="styledSelect"><div id="selectedTopic"></div><div class="selectIcon"><i class="icon arrow-down-icon"></i></div></div>');
13054
13055        var $styledDiv = $this.next('div.styledSelect');
13056        var $styledSelect = $('#selectedTopic');
13057
13058        $styledSelect.text($this.children('option').eq(0).text());
13059
13060        var $list = $('<ul />', {
13061            'class': 'options'
13062        }).insertAfter($styledDiv);
13063
13064
13065        for (var i = 1; i < numberOfOptions; i++) {
13066            $('<li />', {
13067                text: $this.children('option').eq(i).text(),
13068                rel: $this.children('option').eq(i).val()
13069            }).appendTo($list);
13070        }
13071
13072        var $listItems = $list.children('li');
13073
13074        $styledDiv.click(function (e) {
13075            e.stopPropagation();
13076            $(this).toggleClass('active').next('ul.options').toggle();
13077            $('.icon.arrow-down-icon').toggleClass('rotated');
13078        });
13079
13080        $listItems.click(function (e) {
13081            e.stopPropagation();
13082            $listItems.css('background-color', '#ffffff');
13083            $styledSelect.text($(this).text());
13084            $(this).css('background-color', '#f1f1f1');
13085            $styledDiv.removeClass('active');
13086            $('.icon.arrow-down-icon').removeClass('rotated');
13087            $this.val($(this).attr('rel'));
13088            $list.hide();
13089            $this.trigger("change");
13090            setToolTopic($(this).text());
13091        });
13092
13093        $(document).click(function () {
13094            $styledDiv.removeClass('active');
13095            $('.icon.arrow-down-icon').removeClass('rotated');
13096            $list.hide();
13097        });
13098
13099    });
13100});
13101var accountSettings = {
13102    authorMode: document.querySelector("[data-runMode]") && document.querySelector("[data-runMode]").dataset ? document.querySelector("[data-runMode]").dataset.runmode.indexOf("author") != -1 : null,
13103    groupNumbersData:[],
13104    selectedGroupData:[],
13105    boaInfoIds:{'boa-address1':'','boa-address2':'','boa-city':'','boa-state':'','boa-zip':''},
13106    modalFunction: function (elem) {
13107        elem.addClass('disableButton');
13108        if (!accountSettings.authorMode) {
13109            $.ajax({
13110                type: 'POST',
13111                url: (window.location.host.indexOf('pro.com') > -1) ? '/content.advisor.cancelRegLocation' : '/content.consumer.cancelRegLocation',
13112                data: {
13113                    "StateOfResidence": window.localStorage.getItem('StateOfResidence'),
13114                    "StateResidentConsentSignature": window.localStorage.getItem('StateResidentConsentSignature'),
13115                    "StateResidentConsentDate": window.localStorage.getItem('StateResidentConsentDate')
13116                },
13117                success: function (data) {
13118                    let response = JSON.parse(data);
13119                    if (response.isRequestSuccessful === true) {
13120                        loginLogout.loadAnonymousProfile(elem);
13121                    } else {
13122                        accountSettings.showErrorComponent($('#locationEditError'));
13123                    }
13124                },
13125                error: function (error) {
13126                    accountSettings.showErrorComponent($('#locationEditError'));
13127                }
13128            });
13129        } else {
13130            $('.account-setting-modal,.reveal-overlay').css('display', 'none');
13131            $('body').removeClass('is-reveal-open');
13132        }
13133    },
13134
13135    saveBoaDeleteData: function (boaName) {
13136        let boaDetails = {
13137            "boa": boaName
13138        };
13139        let redirectLink = $('.boaDelete .saveBtn > .modalBtn').attr('href');
13140        $.ajax({
13141            type: 'POST',
13142            url: "/bin/deleteboa",
13143            data: boaDetails,
13144            success: function (resultData) {
13145                window.location.replace(redirectLink);
13146            },
13147            error: function () {
13148                console.log('error');
13149            }
13150        });
13151    },
13152
13153    emailTab: function (elem, index, type) {
13154        if(type==='add') {
13155            elem.focus();
13156        }
13157        elem.attr('id', 'email' + parseInt(index + 1));
13158        elem.attr('tabindex', index + 1);
13159    },
13160
13161    buttonTab: function (elem, index) {
13162        elem.attr('tabindex', index + 1);
13163    },
13164
13165    addCCSaveValidator: function (isChanged) {
13166        let maxCCmail = $("#maxCCEmailLimit").val();
13167        if ($('.pref-email-validator:visible').length) {
13168            let enablePrefBtn = false;
13169            $('.pref-email-validator:visible').each(function () {
13170                if ($(this).hasClass('bhf-form-error') || $(this).val().trim() == '') {
13171                    enablePrefBtn = false;
13172                    return false;
13173                } else {
13174                    enablePrefBtn = true;
13175                }
13176            });
13177            if ($('.addCCInput').length > maxCCmail) {
13178                enablePrefBtn = false;
13179            }
13180            if (enablePrefBtn) {
13181                $('.editButtons .saveBtn').removeClass("disableButton");
13182            } else {
13183                $('.editButtons .saveBtn').addClass("disableButton");
13184            }
13185        } else {
13186            if (isChanged) {
13187                $('.editButtons .saveBtn').removeClass("disableButton");
13188            } else {
13189                $('.editButtons .saveBtn').addClass("disableButton");
13190            }
13191        }
13192    },
13193
13194    contentOverflow: function (arg) {
13195        if (arg === 'hide') {
13196            $('#content').css('overflow', 'hidden');
13197            $('#content').parent().css('overflow', 'hidden');
13198        } else {
13199            $('#content').css('overflow', 'visible');
13200            $('#content').parent().css('overflow', 'visible');
13201        }
13202    },
13203
13204    updateData: function (firstTime, key, data, path, redirectLink, errorComponent) {
13205        var $data;
13206        var $path;
13207
13208        if (document.querySelector("[data-runMode]") && document.querySelector("[data-runMode]").dataset && document.querySelector("[data-runMode]").dataset.runmode.indexOf("author") != -1) {
13209            window.location.replace(redirectLink);
13210            return;
13211        }
13212        if (firstTime) {
13213            let keyString = key.toString();
13214            if (keyString.indexOf('EDelivery') == -1) {  // Condition to check if the user is not on the delivery preference screen
13215                for (let i = 0; i < key.length; i++) {
13216                    window.localStorage.setItem(key[i], data[i]);   // maps the key and corresponding data in localStorage
13217                }
13218                window.location.replace(redirectLink);
13219            } else {
13220                if (window.location.host.indexOf('pro.com') > -1) {
13221                    $path = '/content.advisor.firstTimeLogin';
13222                    $data = {
13223                        "StateOfResidence": window.localStorage.getItem('StateOfResidence'),
13224                        "StateResidentConsentSignature": window.localStorage.getItem('StateResidentConsentSignature'),
13225                        "StateResidentConsentDate": window.localStorage.getItem('StateResidentConsentDate'),
13226                        "SuppressAllEmail": data[0],
13227                        "EDeliveryPreferenceAnnuity": data[1],
13228                        "EDeliveryPreferenceLifeInsurance": data[2]
13229                    }
13230                    if (window.localStorage.getItem('EConsentDate') !== null) {
13231                        $data['EConsentDate'] = window.localStorage.getItem('EConsentDate');
13232                    }
13233                    accountSettings.removeLocalStorage();
13234                } else {
13235                    $path = '/content.consumer.firstTimeLogin';
13236                    $data = {
13237                        "StateOfResidence": window.localStorage.getItem('StateOfResidence'),
13238                        "StateResidentConsentSignature": window.localStorage.getItem('StateResidentConsentSignature'),
13239                        "StateResidentConsentDate": window.localStorage.getItem('StateResidentConsentDate'),
13240                        "EDeliveryPreference": data[0]
13241                    }
13242                    if (window.localStorage.getItem('EConsentDate') !== null) {
13243                        $data['EConsentDate'] = window.localStorage.getItem('EConsentDate');
13244                    }
13245                    accountSettings.removeLocalStorage();
13246                }
13247                accountSettings.updateServer($data, $path, redirectLink, errorComponent); // makes the ajax call as this is the last part of first time login
13248            }
13249        } else { // If user is trying to edit his data
13250            $data = {};
13251            for (let i = 0; i < key.length; i++) {
13252                $data[key[i]] = data[i];
13253            }
13254            accountSettings.removeLocalStorage();
13255            accountSettings.updateServer($data, path, redirectLink, errorComponent);
13256        }
13257    },
13258
13259    isEmailMatch: function(inputEmail,email){
13260        if(inputEmail === email){
13261            return true;
13262        }
13263        return false;
13264    },
13265    // Analytics on form submiision bounced
13266    updateAnalytics: function(ele){
13267        $(ele).closest('form').find('input[type="hidden"]').each(function() {
13268            if ($(ele).attr("name") == "formName") {
13269                setFormName($(ele).val());
13270            }
13271            if ($(ele).attr("name") == "formType") {
13272                setFormType($(ele).val());
13273            }
13274        });
13275        formAnalytics.track({event: 'formcomplete'});
13276        if($(ele).data("cwanalytics")){
13277            setToolComplete();
13278        }
13279    },
13280    // API call for CRM to EDS email
13281    updateEmailCommuincationAddress: function(element,email,isCommPrefApiCallPending=false,isEDSCallRequired=true){
13282        const responseJson = {};
13283        accountSettings.updateAnalytics(element);
13284        return new Promise((resolve,reject) =>{
13285            accountSettings.startCommPrefEmailLoader();
13286            try {
13287                $.ajax({
13288                    url : '/content.aemCrmApiUpdateAccountSetting',
13289                    type :'POST',
13290                    data : {
13291                        "emailId" : email
13292                    },
13293                    success: function(response) {
13294                        const {isRequestSuccessful} = JSON.parse(response);
13295                        if(isRequestSuccessful && isEDSCallRequired){
13296                            // call update Bounce back
13297                            $.ajax({
13298                                url : '/content.advisor.updatebouncebackEmail',
13299                                type :'POST',
13300                                data : {
13301                                    "emailId" : email
13302                                },
13303                                success: function(response) {
13304                                    if(!isCommPrefApiCallPending){
13305                                        accountSettings.stopCommPrefEmailLoader();
13306                                    }
13307                                    const {isRequestSuccessful} = JSON.parse(response);
13308                                    if(isRequestSuccessful){
13309                                        responseJson.isApiRequest = true;
13310                                        resolve(responseJson)
13311                                    }else{
13312                                        responseJson.isApiRequest = false;
13313                                        resolve(responseJson);
13314                                    }
13315                                },
13316                                error: function(xhr, status, err) {
13317                                    responseJson.isApiRequest = false;
13318                                    resolve(responseJson);
13319                                }
13320                            });
13321                        }else if(isRequestSuccessful && !isEDSCallRequired){
13322                            responseJson.isApiRequest = true;
13323                            resolve(responseJson);
13324                        }else{
13325                            accountSettings.stopCommPrefEmailLoader();
13326                            responseJson.isApiRequest = false;
13327                            resolve(responseJson);
13328                        }
13329                    },
13330                    error: function(xhr, status, err) {
13331                        accountSettings.stopCommPrefEmailLoader();
13332                        responseJson.isApiRequest = false;
13333                        resolve(responseJson);
13334                    }
13335                });
13336            } catch (error) {
13337                console.log("Unable to call API", error.message);
13338                responseJson.isApiRequest = false;
13339                resolve(responseJson);
13340            }
13341            
13342        });
13343    },
13344    // API call for comm pref only this method get's call for email bounced secnario
13345    updateCommuincationData: function (firstTime, key, data, path, redirectLink, errorComponent,isOnlyCommPrefApiCall=false) {
13346        var $data;
13347        var $path;
13348        if (document.querySelector("[data-runMode]") && document.querySelector("[data-runMode]").dataset && document.querySelector("[data-runMode]").dataset.runmode.indexOf("author") != -1) {
13349            window.location.replace(redirectLink);
13350            return;
13351        }
13352        if(!firstTime){
13353            $data = {};
13354            for (let i = 0; i < key.length; i++) {
13355                $data[key[i]] = data[i];
13356            }
13357            accountSettings.removeLocalStorage();
13358            return accountSettings.updateCommuicationServer($data, path, redirectLink, errorComponent,isOnlyCommPrefApiCall);
13359        }
13360    },
13361    // loader handle for email bounce and comm pref
13362    startCommPrefEmailLoader : function() {
13363        bounceAjaxTimer = setTimeout(function () {
13364            $('.loader__bg').show();
13365            $('.loader__content').css({ 'display': 'flex' });
13366            $('body').addClass('is-reveal-open');
13367        }, 2000);
13368    },
13369    // loader handle for email bounce and comm pref
13370    stopCommPrefEmailLoader: function () {
13371        clearTimeout(bounceAjaxTimer);
13372        $('.loader__bg').hide();
13373        $('.loader__content').hide();
13374        $('body').removeClass('is-reveal-open');
13375    },
13376    // API call for comm pref only this method get's call for email bounced secnario
13377    updateCommuicationServer: function (data, path, redirectLink, errorComponent,isOnlyCommPrefApiCall) {
13378        let responseJson={};
13379        return new Promise((resolve,reject) =>{
13380            if(isOnlyCommPrefApiCall){
13381                accountSettings.startCommPrefEmailLoader();
13382            }
13383            $.ajax({
13384                type: 'POST',
13385                url: path,
13386                data: data,
13387                success: function (data) {
13388                    accountSettings.stopCommPrefEmailLoader();
13389                    let response = JSON.parse(data);
13390                    if (response.isRequestSuccessful == false) {
13391                        responseJson.isApiRequest=false;
13392                        resolve(responseJson)
13393                    } else {
13394                        responseJson.isApiRequest=true;
13395                        resolve(responseJson)
13396                    }
13397                },
13398                error: function () {
13399                    accountSettings.stopCommPrefEmailLoader();
13400                    responseJson.isApiRequest=false;
13401                    resolve(responseJson)
13402                }
13403            });
13404        })
13405        
13406    },
13407    removeLocalStorage: function () {
13408        var keysToRemove = ["StateOfResidence", "StateResidentConsentSignature", "StateResidentConsentDate", "EConsentDate"];
13409        for (var $key in keysToRemove) {
13410            window.localStorage.removeItem(keysToRemove[$key]);
13411        }
13412    },
13413
13414    updateServer: function (data, path, redirectLink, errorComponent) {
13415        $.ajax({
13416            type: 'POST',
13417            url: path,
13418            data: data,
13419            success: function (data) {
13420                let response = JSON.parse(data);
13421                if (response.isRequestSuccessful == false) {
13422                    if (response.redirectionPath) {
13423                        window.location.replace(response.redirectionPath);
13424                    } else {
13425                        accountSettings.showErrorComponent(errorComponent);
13426       					if(window.location.href.indexOf('multiple') > -1){
13427	                        setTimeout(() => {
13428	    					window.location.replace(redirectLink);
13429							}, 4000);
13430						}   
13431                    }
13432                } else {
13433                    window.location.replace(redirectLink);
13434                }
13435            },
13436            error: function () {
13437                accountSettings.showErrorComponent(errorComponent);
13438            }
13439        });
13440    },
13441    
13442    showErrorComponent: function (errorComponent) {
13443        if (errorComponent.length) {
13444            errorComponent.show();
13445        }
13446    },
13447
13448    submitBoa: function (element, userType) {
13449        element.addClass('disable-boa-add');
13450        let _self = element;
13451        let serveletUrl = '/content.boa.addBOA';
13452        let riaFirmName=null;
13453        let riaFirmId=null;
13454        let groupNumberList=[];
13455        let boatype = $("#boa__user__type").val();
13456        if(accountSettings.checkIsRiaUser(boatype)){
13457            riaFirmName = $($("#boa_man").select2('data')[0].element).attr("riafirmname");
13458            riaFirmId = $($("#boa_man").select2('data')[0].element).attr("riafirmId");
13459        }
13460        if(accountSettings.checkIsPlanSponser(boatype) && $("#boa__group__code").select2('data').length){
13461            $($("#boa__group__code").select2('data')).each(function(){
13462                groupNumberList.push($($(this)[0].element).attr("value"));
13463            })
13464            groupNumberList = groupNumberList.join(",");
13465        }
13466        
13467        let data = {
13468            "firstName": $("#boa-firstName").val(),
13469            "lastName": $("#boa-lastName").val(),
13470            "RIAFirmId": riaFirmId,
13471            "RIAFirmName":riaFirmName,
13472            "phoneNumber": $("#boa-phone").data('phone'),
13473            "address1": $("#boa-address1").val(),
13474            "address2": $("#boa-address2").val(),
13475            "city": $("#boa-city").val(),
13476            "state": $("#boa-state").val()[0],
13477            "zip": $("#boa-zip").val(),
13478            "groupNumberList": groupNumberList
13479        };
13480
13481        if ($('#add-boa-pm').length){
13482            data["associatedRelationship"] = $('#firms-boa-pm').val();
13483            data["email"] = $('#boa-email-pm').val().toLowerCase();
13484            data["userType"] = $($('#firms-boa-pm').select2('data')[0].element).attr("data-userType") || null;
13485            data["status"] = $('#boa-status').val();
13486            const regToken = $('#boa-regToken').val();
13487            if(regToken) {
13488                data["registrationToken"] = regToken;
13489                serveletUrl = '/content.boa.editBOA';
13490            }
13491            
13492
13493        }
13494
13495        if ($('#add-boa').length || $('#edit-boa').length){
13496            data['associatedRelationship'] = [];
13497            data["email"] = $("#boa-email-ia").val().toLowerCase();
13498            $('#associated-relationship tbody tr').each(function (ind) {
13499
13500                if ($(this).hasClass('selected')) {
13501                    let associatedData = {};
13502                    $(this).find('td').each(function (index, element) {
13503                        if (index !== 0) {
13504
13505                            switch (index) {
13506                                case 1:
13507                                    associatedData['FirmNipr'] = element.innerText;
13508                                    break;
13509                                case 2:
13510                                    associatedData['channel'] = element.innerText;
13511                                    break;
13512                                case 3:
13513                                    associatedData['ProfileCode'] = element.innerText;
13514                                    break;
13515                                case 4:
13516                                    associatedData['firmName'] = element.innerText;
13517                                    break;
13518                                case 5:
13519                                    associatedData['hierarchyLevel'] = element.innerText;
13520                                    break;
13521                            }
13522
13523                        }
13524                    });
13525                    data.associatedRelationship.push(JSON.stringify(associatedData));
13526                }
13527            });
13528
13529            if (userType === 'internalAdmin') {
13530                data["firmNipr"] = $("#boa__firm__code").val().toString();
13531                data["userType"] = $("#boa__user__type").val();
13532                if ($('.manage__boa__edit').length) {
13533                    serveletUrl = '/content.boa.editBOA';
13534                    data["registrationToken"] = _self.data('regtoken');
13535                }
13536            } else {
13537                data["firmNipr"] = $("firms").val();
13538            }
13539        }
13540
13541        $('#PmEiamId').val() != "" ? data['PmEiamId'] = $('#PmEiamId').val() : null;
13542        $.ajax({
13543            url: serveletUrl,
13544            type: 'post',
13545            data: data,
13546            success: function (data) {
13547                let response = JSON.parse(data);
13548                if (response.isRequestSuccessful == true) {
13549                    if(!response.isAddAssistantEnabled){
13550                        if ($('#add-boa-pm').length){
13551                            $('.doneBoa .cancelBtn').hide();
13552                            $('.doneBoa .saveBtn').addClass('justify-center');
13553                        }
13554                    }
13555                    if (!$('.manage__boa__edit').length) {
13556                        $('.boaEditSection').hide();
13557                        $('.doneBoa').show();
13558                        $(document).scrollTop(0);
13559                        const emailBoa = "<span class='accountEditEmail'>" + response.email + "</span>";
13560                        const boaToken = response.registrationToken;
13561                        let boaMailHtml = $("#boaSentEmail").html().replace("{USER_EMAIL}", emailBoa).replace("{USER_REGISTRATION_TOKEN}", boaToken);
13562                        $("#boaSentEmail").html(boaMailHtml);
13563                    }
13564                    else {
13565                        window.location.href = _self.data('href');
13566                    }
13567                } else {
13568                    if (response.duplicateBGABOAEmail) {
13569                        accountSettings.showErrorComponent($('#boaError-dupEmail'));
13570                        $("#boa-email-pm").addClass('dup-email');
13571                    }else {
13572                        accountSettings.showErrorComponent($('#boaError'));
13573                    }
13574                }
13575            },
13576            error: function (data, status) {
13577                accountSettings.showErrorComponent($('#boaError'));
13578            }
13579        });
13580    },
13581
13582    isJsonEmpty: function (obj) {
13583        for (var key in obj) {
13584            if (obj.hasOwnProperty(key))
13585                return false;
13586        }
13587        return true;
13588    },
13589
13590    boaValidator: function () {
13591        let disabled = true;
13592        $(".boa-input-required").each(function () {
13593            let value = this.value;
13594            if ((value.trim() == '') && !$(this).hasClass('phone')) {
13595                disabled = true;
13596                return false;
13597            } else {
13598                disabled = false;
13599            }
13600
13601            if ($(this).hasClass('boaEmail')) {
13602                if ($(this).hasClass('bhf-form-error')) {
13603                    disabled = true;
13604                    return false;
13605                }
13606            }
13607
13608            if ($(this).hasClass('userType-select')) {
13609                if ($(this).val() === "") {
13610                    disabled = true;
13611                    return false;
13612                }
13613            }
13614
13615            if ($(this).hasClass('multi-validator')) {
13616                if ($(this).val().length === 0 || $(this).val() === null) {
13617                    disabled = true;
13618                    return false;
13619                } else {
13620                    disabled = false;
13621                }
13622            }
13623
13624            if ($(this).hasClass('phone')) {
13625                if ($(this).val().length !== 14 && $(this).val().length !== 10) {
13626                    disabled = true;
13627                    return false;
13628                } else {
13629                    disabled = false;
13630                }
13631            }
13632        });
13633
13634        if (($('#add-boa').length || $('#submit-boa[data-usertype=internalAdmin]').length) && $('#associated-relationship .selected').length === 0) {
13635            disabled = true;
13636        }
13637        if (disabled) {
13638            $('.addChanges .modalBtn:not(".secondaryBtn")').addClass("disable-boa-add");
13639        } else {
13640            $('.addChanges .modalBtn:not(".secondaryBtn")').removeClass("disable-boa-add");
13641        }
13642        
13643        
13644    },
13645
13646    boaValidateEmail: function(element){
13647        if (!(element.hasClass('bhf-form-error') || element.val() == '')) {
13648            if($('#boa-email-pm').val().toLowerCase() != $('#boa-validation-email-pm').val().toLowerCase()){
13649                element.siblings('.bhf-form-error-container').children(".constraint-validate-msg").show();
13650                element.addClass("bhf-form-error");
13651            }else{
13652                element.siblings('.bhf-form-error-container').children(".constraint-validate-msg").hide();
13653                element.removeClass("bhf-form-error");
13654            }
13655        }else{
13656            element.siblings('.bhf-form-error-container').children(".constraint-validate-msg").hide();
13657            element.removeClass("bhf-form-error");
13658        }
13659    },
13660
13661    printForm: function (title, data) {
13662        let isIphone = /iphone/i.test(navigator.userAgent.toLocaleLowerCase());
13663        let printWindow = window.open('', '', 'height=400,width=800');
13664        printWindow.document.write('<html><head><title>' + title + '</title>');
13665        printWindow.document.write('</head><body >');
13666        printWindow.document.write(data);
13667        if (isIphone) printWindow.document.write('<script>window.onload=function(){ setTimeout(window.print,500);}</script>');
13668        printWindow.document.write('</body></html>');
13669        printWindow.document.close();
13670        printWindow.print();
13671    },
13672
13673    printConsentModalOpen: function (queryParamValue, modalElem) {
13674        var queryParam = window.location.search;
13675        if (queryParam.substring(1, queryParam.indexOf('=')) === queryParamValue) {
13676            $(window).on('load', function () {
13677                accountSettings.consentOpenModal(modalElem);
13678            });
13679        }
13680    },
13681
13682    consenttype: function (consentdata, element) {
13683        $.ajax({
13684            url: (window.location.host.indexOf('pro.com') > -1) ? '/content.advisor.revokeConsent' : '/content.consumer.revokeConsent',
13685            type: 'POST',
13686            data: {
13687                'consentType': consentdata
13688            },
13689            success: function (data) {
13690                let response = JSON.parse(data);
13691                if (response.isRequestSuccessful == true) {
13692                    loginLogout.loadAnonymousProfile(element);
13693                }
13694                else {
13695                    accountSettings.showErrorComponent($('#consentError'));
13696                }
13697            },
13698            error: function (data, status) {
13699                $('.closeConsentModal').click();
13700                accountSettings.showErrorComponent($('#consentError'));
13701            }
13702        });
13703    },
13704
13705    consentOpenModal: function (modalElem) {
13706        setTimeout(function () {
13707            new Foundation.Reveal($('#' + modalElem)).open();
13708            revealCenterAlign.revealRePosition();
13709            $('.reveal-overlay').animate({ scrollTop: 0 }, 10);
13710            accountSettings.dynmicMargin();
13711        }, 10);
13712    },
13713
13714    dynmicMargin: function () {
13715        if ($('.revokeConsentSection').length) {
13716            var isIphonePad = /iphone|ipad/i.test(navigator.userAgent.toLocaleLowerCase());
13717            if (isIphonePad && $(window).width() < 991) {
13718                let dynamicMargin = ($(window).width() - $('.revokeConsentSection .customWidth').width()) / 2;
13719                $('.revokeConsentSection .customWidth').css({ 'margin-left': dynamicMargin + 'px', 'margin-right': dynamicMargin + 'px' });
13720            }
13721            else {
13722                $('.revokeConsentSection .customWidth').css({ 'margin-left': '', 'margin-right': '' });
13723            }
13724        }
13725    },
13726
13727    createTable: function (data, type) {
13728        if (type === 'existing') {
13729            $('#existing-relationship tbody').empty();
13730            data.sort(function (a, b) {
13731                var lccomp = a.RegistrationTokenId.toLowerCase().localeCompare(b.RegistrationTokenId.toLowerCase());
13732                return lccomp ? lccomp : a.RegistrationTokenId > b.RegistrationTokenId ? 1 : a.RegistrationTokenId < b.RegistrationTokenId ? -1 : 0;
13733            });
13734            $.each(data, function (i, ind) {
13735                var $tr = $('<tr>').append(
13736                    $('<td>').html('<span class="firm-name">' + ind.RegistrationTokenId + '<span class="detail-name regToken">' + ind.RegistrationTokenId + '</span></span>'),
13737                    $('<td class="set-size-150">').text(ind.FirstName + " " + ind.LastName),
13738                    $('<td class="set-size-150">').text(ind.UserType),
13739                    $('<td class="set-size-150">').text(ind.FirmNipr),
13740                    $('<td class="set-size-100">').text(ind.Channel),
13741                    $('<td class="set-size-100">').text(ind.ProfileCode),
13742                    $('<td class="set-size-100">').text(ind.FirmCode),
13743                    $('<td>').html('<span class="firm-name">' + ind.FirmName + '<span class="detail-name">' + ind.FirmName + '</span></span>'),
13744                    $('<td class="set-size-150">').text(ind.HierarchyLevel)
13745                );
13746                $('#existing-relationship tbody').append($tr);
13747            });
13748        } else {
13749            $.each(data, function (i, elem) {
13750                let selected = elem.isChecked ? 'selected' : '';
13751                let checked = elem.isChecked ? 'checked' : '';
13752                var $tr = $('<tr class="tr-border ' + selected + '">').append(
13753                    $('<td>').html('<span class="check-container"><input type="checkbox" ' + checked + '><span class="check-mark"></span></span>'),
13754                    $('<td class="firm-nipr">').text(elem.FirmNipr),
13755                    $('<td>').text(elem.Channel),
13756                    $('<td>').text(elem.ProfileCode),
13757                    $('<td class="firm-code">').text(elem.FirmCode),
13758                    $('<td>').html('<span class="firm-name">' + elem.FirmName + '<span class="detail-name">' + elem.FirmName + '</span></span>'),
13759                    $('<span class="detail-name">').text(elem.FirmName),
13760                    $('<td>').text(elem.HierarchyLevel)
13761                );
13762                $('#associated-relationship tbody').append($tr);
13763            });
13764        }
13765    },
13766
13767    removeRows: function (data) {
13768        $('#associated-relationship tbody tr').each(function () {
13769            if ($(this).find('.firm-code').text() === data) {
13770                $(this).remove();
13771            }
13772        });
13773    },
13774
13775    advPrefChangeHandler: function () {
13776        var life = $("input[name='lifeInsurance']:checked").val();
13777        var annuities = $("input[name='annuities']:checked").val();
13778        if (life == "3" && annuities == "3") {
13779            $(".suppress-yes")[0].checked = true;
13780            $('#supressNotif input').attr('disabled', true);
13781        } else {
13782            $('#supressNotif input').attr('disabled', false);
13783        }
13784    },
13785
13786    hideComponent: function ($elem) {
13787        $elem.hide();
13788    },
13789
13790    consentModalOpenEvent: function ($elem, modal) {
13791        $elem.on('click', function () {
13792            accountSettings.consentOpenModal(modal);
13793        });
13794    },
13795
13796    removeQueryFromUrl: function () {
13797        let uri = window.location.toString();
13798        if (uri.indexOf("?") > 0) {
13799            let indexOfParam = uri.indexOf("?modalEConsent");
13800            if (indexOfParam === -1) {
13801                indexOfParam = uri.indexOf("?modalStateConsent")
13802            }
13803            let clean_uri = uri.substring(0, indexOfParam);
13804            window.history.replaceState({}, document.title, clean_uri);
13805        }
13806    },
13807
13808    printConsent: function ($consentData, title) {
13809        let data = $consentData.html();
13810        accountSettings.printForm(title, data);
13811    },
13812
13813    revokeConsentClickHandler: function ($elem, dataAttr) {
13814        let consentdata = $elem.data(dataAttr);
13815        $('.closeConsentModal').click();
13816        if (!accountSettings.authorMode) {
13817            accountSettings.consenttype(consentdata, $elem);
13818        }
13819    },
13820
13821    setDateAsInputValue: function ($elem) {
13822        let today = new Date();
13823        let dd = ("0" + today.getDate()).slice(-2);
13824        let mm = ("0" + (today.getMonth() + 1)).slice(-2);
13825        let yyyy = today.getFullYear();
13826        today = mm + '/' + dd + '/' + yyyy;
13827        $elem.val(today);
13828    },
13829
13830    cancelRegistrationClickHandler: function ($modal, $this, firstTimeUser) {
13831        if (firstTimeUser) {
13832            setTimeout(function () {
13833                $('.cancel-registration').removeClass('disableButton');
13834                new Foundation.Reveal($modal).open();
13835                revealCenterAlign.revealRePosition();
13836            }, 10);
13837        } else {
13838            window.location.href = $this.attr('data-href');
13839        }
13840    },
13841
13842    getexistingData: function () {
13843        $.ajax({
13844            url: '/content.boa.existingRelationship',
13845            type: 'POST',
13846            data: {
13847                "EmailAddress": $('#boa-email-ia').val().toLowerCase(),
13848                "registrationToken": $('#submit-boa').data('regtoken') ? $('#submit-boa').data('regtoken') : '',
13849            },
13850            success: function (data) {
13851                $('.loader__content').hide();
13852                let existingRel = JSON.parse(data);
13853                let tableData = JSON.parse(existingRel.data);
13854                if (tableData.length > 0) {
13855                    accountSettings.createTable(tableData, 'existing');
13856                    $('#existing-relationship').show();
13857                } else {
13858                    $('#existing-relationship').hide();
13859                }
13860            },
13861            error: function (error) {
13862                $('#existing-relationship').hide();
13863            }
13864        });
13865    },
13866
13867    checkIsPlanSponser : function(userType){
13868        return $("#planSponsorUser").length && $("#planSponsorUser").val().split(',').includes(userType);
13869    },
13870
13871    checkIsRiaUser : function(userType){
13872        return $("#riaUser").length && $("#riaUser").val().split(',').includes(userType);
13873    },
13874
13875    checkIsCswUser: function(userType){
13876        return $("#cswUser").length && $("#cswUser").val().split(',').includes(userType);
13877    },
13878
13879    generateMasterAccountNumber : function(){
13880        $.ajax({
13881            url: '/content.boa.manField',
13882            type: 'POST',
13883            success: function(data) {
13884                let manListData = JSON.parse(data).data;
13885                $.each(manListData, function (index,value) {
13886                    let riaFirmId=value.RIAFirmId;
13887                    let riaFirmName=value.RIAFirmName;
13888                    let riaFirmDisplayName=value.riaFirmCodeDisplayName;
13889                    let $option = $('<option>').text(riaFirmDisplayName).attr({"riafirmname":`${riaFirmName}`,"riafirmId":`${riaFirmId}`});
13890                    $('#boa_man').append($option);
13891                });
13892                $('#boa_man').select2({
13893                    sorter: function (data) {
13894                        return data.sort(function (a, b) {
13895                            return a.text.localeCompare(b.text);
13896                        });
13897                    },
13898                    dropdownAutoWidth: true,
13899                    dropdownParent: $('#boa-man-drop-parent'),
13900                });
13901            },
13902            error: function(e) {
13903                console.log("eror getting man list");
13904                console.log(e);
13905            }
13906        });
13907        setTimeout(() => {
13908          $('#boa__group__code').select2({width:'100%'});
13909        }, 5);
13910        $('#boa_man').addClass('boa-input-required');
13911        $('#boa_man').addClass('required');
13912        $('.inputMasterAccountNumber').removeClass('hide');
13913        $('#boa__group__code').removeClass('boa-input-required');
13914        $('#boa__group__code').removeClass('required');
13915        $('.inputGroupNumber').addClass('hide');
13916    },
13917
13918    generateGroupNumber: function(selectedGroupNumberList=[]){
13919      $('#boa__group__code').prop('disabled', false);
13920      accountSettings.getGroupInfo().then(groupInfo => {
13921        accountSettings.addCustomGroupPagination(groupInfo,selectedGroupNumberList);
13922        $("#boa-group-drop-parent").find('.select2-search__field').css('width','100%');
13923        $('#boa__group__code').addClass('boa-input-required');
13924        $('#boa__group__code').addClass('required');
13925        $('.inputGroupNumber').removeClass('hide');
13926        $('#boa_man').removeClass('boa-input-required');
13927        $('#boa_man').removeClass('required');
13928        $('.inputMasterAccountNumber').addClass('hide');
13929      });
13930    },
13931    getGroupInfo: function() {
13932      return new Promise((resolve,reject)=>{
13933        $.ajax({
13934          url: '/content.boa.groupNumber',
13935          type: 'POST',
13936          success: function (data) {
13937            resolve(JSON.parse(data));
13938          }, 
13939          error: function (err) {
13940            console.log("Error getting group information");
13941            reject([])
13942          },
13943        });
13944      })
13945    },
13946    addCustomGroupPagination: function(groupNumbers,selectedGroupNumberList){
13947      let items = groupNumbers.data;
13948      const updatedGroupData = items.map(({groupNumber: id,groupDisplayName:text,...rest}) => ({
13949          id,
13950          text,
13951          ...rest
13952      }));
13953      groupPageSize = 300;
13954      jQuery.fn.select2.amd.define('select2/data/customAdapter',[
13955          'select2/data/array',
13956          'select2/utils',
13957      ],function (ArrayAdapter, Utils) {
13958              function CustomDataAdapter ($element, options) {
13959                  CustomDataAdapter.__super__.constructor.call(this, $element, options);
13960              }
13961              Utils.Extend(CustomDataAdapter, ArrayAdapter);
13962              CustomDataAdapter.prototype.query = function (params, callback) {
13963                  var results = [];
13964                  if (params.term && params.term !== '') {
13965                      results = updatedGroupData.filter(resp=> {
13966                          return resp.text.toLowerCase().indexOf(params.term.toLowerCase()) >= 0
13967                      });
13968                  } else {results = updatedGroupData;}
13969      
13970                  if (!("page" in params)) {
13971                      params.page = 1;
13972                  }
13973                  var data = {};
13974                  data.results = results.slice((params.page - 1) * groupPageSize, params.page * groupPageSize);
13975                  data.pagination = {};
13976                  data.pagination.more = params.page * groupPageSize < results.length;
13977                  callback(data);
13978              };
13979              return CustomDataAdapter;
13980          }
13981      );
13982      var customAdapter =jQuery.fn.select2.amd.require('select2/data/customAdapter');
13983      $('#boa__group__code').select2({
13984          ajax: {},
13985          tags: true,
13986          dataAdapter:customAdapter,
13987          dropdownAutoWidth: true,
13988          width:'100%',
13989          placeholder: "Group Number",
13990          dropdownParent: $('#boa-group-drop-parent'),
13991          data: accountSettings.displayGroupNumber(updatedGroupData,selectedGroupNumberList),
13992      });
13993    },
13994    getGroupDetails : function(groupId){
13995       return accountSettings.groupNumbersData.filter(({id})=> id == groupId)[0];
13996    },
13997    displayGroupNumber: function(groupNumbers,selectedGroupNumberList){
13998        $('#boa__group__code').val(selectedGroupNumberList).trigger('change');
13999        let isEditBOA=false;
14000        if(selectedGroupNumberList.length) isEditBOA=true;
14001        if (!accountSettings.isJsonEmpty(JSON.parse(JSON.stringify(groupNumbers)))) {
14002            $('#boa__group__code').prop('disabled', false);
14003            let responseData = JSON.parse(JSON.stringify(groupNumbers));
14004            if(isEditBOA){
14005                let selectedListPosition={};
14006                for(const [index,id] of selectedGroupNumberList.entries()){
14007                    selectedListPosition[id] = index;
14008                }
14009                responseData.sort((a,b)=> selectedListPosition[a.id] - selectedListPosition[b.id]);
14010            }
14011            accountSettings.groupNumbersData = responseData;
14012            if(isEditBOA){
14013                selectedGroupNumberList.map((groupNumber)=>{
14014                    const groupDetails = accountSettings.getGroupDetails(groupNumber);
14015                    $option = $("<option selected='selected'></option>").val(groupDetails.id).text(groupDetails.text)
14016                    $('#boa__group__code').append($option).trigger('change');
14017                    accountSettings.selectedGroupData.push({
14018                        groupNumber:groupDetails.id,
14019                        groupName:groupDetails.text
14020                    });
14021                    $('.addChanges .modalBtn:not(".secondaryBtn")').addClass("disable-boa-add");
14022                })
14023            }
14024            const isDisable = $('#boa-status').val() == 'Active' ? false : true;
14025            if(isEditBOA){
14026                accountSettings.boaInfoIds["boa-address1"] = $("#boa-address1").val(),
14027                accountSettings.boaInfoIds["boa-address2"] = $("#boa-address2").val(),
14028                accountSettings.boaInfoIds["boa-city"] = $("#boa-city").val(),
14029                accountSettings.boaInfoIds["boa-state"] = $("#boa-state").val()[0],
14030                accountSettings.boaInfoIds["boa-zip"] = $("#boa-zip").val(),
14031                $.each(accountSettings.boaInfoIds, function (key,value) {
14032                    value ? $(`#${key}`).val(`${value}`) : $(`#${key}`).val('');
14033                    if(value) $(`#${key}`).prop('disabled', isDisable);
14034                });
14035            }
14036        }
14037    },
14038    updateBOAInfo: function(boaInfo){
14039        accountSettings.boaInfoIds = {'boa-address1':'','boa-address2':'','boa-city':'','boa-state':'','boa-zip':''};
14040        accountSettings.clearBOAInfo(accountSettings.boaInfoIds);
14041        $.each(boaInfo, function (key,value) {
14042            value ? $(`#${key}`).val(`${value}`) : $(`#${key}`).val('');
14043            if(value) $(`#${key}`).prop('disabled', true);
14044            if(key == 'boa-address1' && value){
14045                $(`#boa-address2`).prop('disabled', true);
14046            }
14047            if(key == 'boa-state') {
14048                $(`#${key}`).trigger('change');
14049                if(value) $('.select2-selection').blur();
14050            }else{
14051                if(value) bhfFormValidator.boaFormValidator($(`#${key}`));
14052            }
14053        });
14054        accountSettings.boaValidator();
14055    },
14056    clearBOAInfo: function(boaInfo,isdisableOnly=true){
14057        $.each(boaInfo, function (key,value) {
14058            if(!isdisableOnly) $(`#${key}`).val('');
14059            $(`#${key}`).prop('disabled', false);
14060        });
14061    },
14062    updateEmailCommuicationRadio: function(disableLife,disabledAnnuity,status){
14063        if(status == 'show'){
14064            // show email section and disable all radio buttons
14065            $('.emailBounceBack').find('#emaildesktop').removeAttr('disabled')
14066            $('.emailPreference.advisor').find('.preferencesForm > #emailPreference').find("input[name='annuities']").attr('disabled','disabled');
14067            $('.emailPreference.advisor').find('.preferencesForm > #emailPreference').find("input[name='lifeInsurance']").attr('disabled','disabled');
14068            $('.emailPreference.advisor').find('.preferencesForm > #supressNotif').find("input[name='suppress']").attr('disabled',true);
14069        }else if(status == 'pending'){
14070            // hide email Section and update eDeliver as it is and remove supress disable
14071            $('.emailPreference.advisor').find('.preferencesForm > #emailPreference').find("input[name='annuities']").removeAttr('disabled','disabled');
14072            $('.emailPreference.advisor').find('.preferencesForm > #emailPreference').find("input[name='lifeInsurance']").removeAttr('disabled','disabled');
14073            $('.emailPreference.advisor').find('.preferencesForm > #supressNotif').find("input[name='suppress']").removeAttr('disabled');
14074            $('.emailBounceBack').find('#emaildesktop').removeAttr('disabled')
14075            accountSettings.advPrefChangeHandler();
14076        }else{
14077            $('.emailBounceBack').find('#emaildesktop').removeAttr('disabled')
14078            // show email section and update eDeliver as it is and remove supress disable
14079            if(disableLife == 'true'){
14080                $('.emailPreference.advisor').find('.preferencesForm > #emailPreference').find("input[name='lifeInsurance']").attr('disabled','disabled');
14081            }else{
14082                $('.emailPreference.advisor').find('.preferencesForm > #emailPreference').find("input[name='lifeInsurance']").removeAttr('disabled');
14083            }
14084            if(disabledAnnuity == 'true'){
14085                $('.emailPreference.advisor').find('.preferencesForm > #emailPreference').find("input[name='annuities']").attr('disabled','disabled');
14086            }else{
14087                $('.emailPreference.advisor').find('.preferencesForm > #emailPreference').find("input[name='annuities']").removeAttr('disabled');
14088            }
14089            accountSettings.advPrefChangeHandler();
14090        }
14091    },
14092    showDuplicateErrorMessage: function(element){
14093        $(element).find('.search-input').addClass('bhf-form-error');
14094        $(element).find('.bhf-form-error-container .duplicate-msg').show();
14095    },
14096    handleCommuincationEmailAndPref: function(element,
14097        emailAddress,
14098        currentEmail,
14099        status,
14100        redirectLink,
14101        firstTimeUser,
14102        key,
14103        data,
14104        path,
14105        errorComp,
14106        isSameCommPrefData){
14107            // condition where email bounced in this case won't able to update comm preference due bounced email
14108            if(status == 'show'){
14109                $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
14110                $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
14111                accountSettings.updateEmailCommuincationAddress(element,emailAddress)
14112                .then((apiResp) =>{
14113                    const {cookieKey,isApiRequest} = apiResp;
14114                    isApiRequest ? setTimeout(() => {window.location.replace(redirectLink)}, 100) : accountSettings.showErrorComponent(errorComp);
14115                })
14116                .catch((resp) =>{
14117                    accountSettings.showErrorComponent(errorComp);
14118                })
14119            // condition where email submitted and pending for 48 hrs 
14120            }else if(status == 'resolved' || status == 'pending'){
14121                // won't call crm if email id is same
14122                const isSameEmail = accountSettings.isEmailMatch(emailAddress,currentEmail);
14123                if(isSameEmail){
14124                    $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
14125                    $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
14126                    // call when comm pref changes
14127                    if(!isSameCommPrefData){
14128                        const MailPreferenceResponse = accountSettings.updateCommuincationData(firstTimeUser, key, data, path, redirectLink, errorComp,true);
14129                        MailPreferenceResponse.then((MailPrefApiResp) =>{
14130                            const {isApiRequest} = MailPrefApiResp;
14131                            if(isApiRequest){
14132                                $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
14133                                $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
14134                                setTimeout(() => {window.location.replace(redirectLink)}, 100)
14135                            }else{
14136                                $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
14137                                $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
14138                                accountSettings.showErrorComponent(errorComp);
14139                            }
14140                        })
14141                        .catch((resp) =>{
14142                            accountSettings.stopCommPrefEmailLoader();
14143                            $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
14144                            $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
14145                            accountSettings.showErrorComponent(errorComp);
14146                        })
14147                    }else{
14148                        document.cookie = "delay-success-message=true; path=/;";
14149                        setTimeout(() => {window.location.replace(redirectLink)}, 100)
14150                    }
14151                }else{
14152                    // call when bounced email and comm pref changes 
14153                    var isEDSCallRequired=true;
14154                    if(status == 'resolved') isEDSCallRequired = false;
14155                    const EDSResponse = accountSettings.updateEmailCommuincationAddress(element,emailAddress,true,isEDSCallRequired);
14156                    EDSResponse.then((EdsApiResp) =>{
14157                        const {isApiRequest} = EdsApiResp;
14158                        if(isApiRequest){
14159                            if(!isSameCommPrefData){
14160                                const MailPreferenceResponse = accountSettings.updateCommuincationData(firstTimeUser, key, data, path, redirectLink, errorComp,false);
14161                                MailPreferenceResponse.then((MailPrefApiResp) =>{
14162                                    const {isApiRequest} = MailPrefApiResp;
14163                                    if(isApiRequest){
14164                                        $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
14165                                        $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
14166                                        if(status == 'resolved') {
14167                                            document.cookie = "delay-success-message=true; path=/;";
14168                                            document.cookie = "success-message=; path=/;";
14169                                        }
14170                                        setTimeout(() => {window.location.replace(redirectLink)}, 100)
14171                                    }else{
14172                                        $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
14173                                        $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
14174                                        accountSettings.showErrorComponent(errorComp);
14175                                    }
14176                                })
14177                                .catch((resp) =>{
14178                                    $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
14179                                    $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
14180                                    accountSettings.showErrorComponent(errorComp);
14181                                })
14182                            }else{
14183                                accountSettings.stopCommPrefEmailLoader();
14184                                $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
14185                                $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
14186                                if(status == 'resolved') document.cookie = "delay-success-message=true; path=/;";
14187                                setTimeout(() => {window.location.replace(redirectLink)}, 100)
14188                            }
14189                            
14190                        }else{
14191                            if(!isSameCommPrefData){
14192                                accountSettings.stopCommPrefEmailLoader();
14193                                accountSettings.updateCommuincationData(firstTimeUser, key, data, path, redirectLink, errorComp,true)
14194                            }else{
14195                                accountSettings.stopCommPrefEmailLoader();
14196                            }
14197                            $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
14198                            $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
14199                            accountSettings.showErrorComponent(errorComp);
14200                        }
14201                    }).catch((resp) =>{
14202                        $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
14203                        $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
14204                        accountSettings.showErrorComponent(errorComp);
14205                    });
14206                }
14207            }
14208    }
14209};
14210
14211
14212
14213$(document).ready(function () {
14214
14215    let firstTimeUser = $('.first-time').data('firsttime');
14216    let isCommPrefChanged = false;
14217    let maxCCEmailLimit = 0;
14218    let userType = $('#boa__user__type').val();
14219
14220    if (!accountSettings.authorMode) {
14221        accountSettings.hideComponent($('.error-fragment'));
14222        accountSettings.hideComponent($('.loader__bg'));
14223        accountSettings.hideComponent($('.loader__content'));
14224    }
14225
14226    if (homePageVideo.ElementExist($('#revokeEConsentLink'))) {
14227        accountSettings.consentModalOpenEvent($('#revokeEConsentLink'), 'revokeEConsent');
14228    }
14229
14230    if (homePageVideo.ElementExist($('#revokeStateConsentLink'))) {
14231        accountSettings.consentModalOpenEvent($('#revokeStateConsentLink'), 'revokeStateConsent');
14232    }
14233
14234    if (homePageVideo.ElementExist($('.revokeLinkUserEConsent'))) {
14235        accountSettings.consentModalOpenEvent($('.revokeLinkUserEConsent'), 'userEConsent');
14236    }
14237
14238    if (homePageVideo.ElementExist($('.revokeLinkUserStateConsent'))) {
14239        accountSettings.consentModalOpenEvent($('.revokeLinkUserStateConsent'), 'userStateConsent');
14240    }
14241
14242    if (homePageVideo.ElementExist('#userEConsent')) {
14243        accountSettings.printConsentModalOpen('modalEConsent', 'userEConsent');
14244    }
14245
14246    if (homePageVideo.ElementExist('#userStateConsent')) {
14247        accountSettings.printConsentModalOpen('modalStateConsent', 'userStateConsent');
14248    }
14249
14250    if (homePageVideo.ElementExist($('.revokeConsentSection'))) {
14251        var uri = window.location.toString();
14252        if (uri.indexOf("?") > 0) {
14253
14254            var indexOfParam = uri.indexOf("?modalEConsent");
14255            if (indexOfParam === -1) {
14256                indexOfParam = uri.indexOf("?modalStateConsent")
14257            }
14258            var clean_uri = uri.substring(0, indexOfParam);
14259            window.history.replaceState({}, document.title, clean_uri);
14260        }
14261    }
14262
14263    if (homePageVideo.ElementExist($('.pmBoa'))) {
14264        $(document).on('click', '.delete-pm-boa', function(e){
14265            e.preventDefault();
14266            const redirectLink = $(this).data('href');
14267            const regToken = $(this).data('regtoken');
14268            const createdBy = $(this).data('assigner');
14269            const emailId = $(this).data('email');
14270            let toDelete = [{
14271                "email": emailId,
14272                "registrationToken": regToken,
14273                "CreatedByUser": createdBy
14274            }];
14275            localStorage.setItem('boaDelete', JSON.stringify(toDelete));
14276            window.location.replace(redirectLink);
14277        });
14278    }
14279
14280    if (homePageVideo.ElementExist($('#eCosentPrintLabel'))) {
14281        $('#eCosentPrintLabel').on('click', function () {
14282            accountSettings.printConsent($("#eConsentData"), "EConsent Form");
14283        });
14284    }
14285    if (homePageVideo.ElementExist($('#emailPreference'))) {
14286        accountSettings.advPrefChangeHandler();
14287        $(document).on('change', '#emailPreference input', accountSettings.advPrefChangeHandler);
14288    }
14289
14290    if (homePageVideo.ElementExist($('#stateCosentPrintLabel'))) {
14291        $('#stateCosentPrintLabel').on('click', function () {
14292            accountSettings.printConsent($("#stateConsentData"), "State Consent Form");
14293        });
14294    }
14295
14296    if (homePageVideo.ElementExist($('.modalBtn.eConsentModal'))) {
14297        $('.modalBtn.eConsentModal').click(function () {
14298            accountSettings.revokeConsentClickHandler($(this), 'econsent');
14299        });
14300    }
14301
14302    if (homePageVideo.ElementExist($('.modalBtn.sConsentModal'))) {
14303        $('.modalBtn.sConsentModal').click(function () {
14304            accountSettings.revokeConsentClickHandler($(this), 'sconsent');
14305        });
14306    }
14307
14308    if (homePageVideo.ElementExist($("#consentDate"))) {
14309        accountSettings.setDateAsInputValue($("#consentDate"));
14310
14311        $('.inputConsentName').keyup(function () {
14312            if ($(this).val().trim() != "" && $('.consentInfo').html().trim().length !== 0) {
14313                $("#consentForm").removeClass('disableButton');
14314            } else {
14315                $("#consentForm").addClass('disableButton');
14316            }
14317        });
14318    }
14319
14320    if (homePageVideo.ElementExist($("#declineConsentButton"))) {
14321        $('#declineConsentButton').click(function () {
14322            setTimeout(function () {
14323                $('.modalBtn').removeClass('disableButton');
14324                new Foundation.Reveal($('#declineConsent')).open();
14325                revealCenterAlign.revealRePosition();
14326            }, 10);
14327        });
14328    }
14329
14330    if (homePageVideo.ElementExist($('#cancelReg'))) {
14331        $('#cancelReg').click(function () {
14332            accountSettings.cancelRegistrationClickHandler($('#cancelRegistration'), $(this), firstTimeUser);
14333        });
14334    }
14335
14336    if (homePageVideo.ElementExist($('#cancelRegistration'))) {
14337        $(document).on('click', '#cancelRegistration .secondaryBtn', function () {
14338            $('.editStateSection .cancelBtn').hide();
14339        });
14340    }
14341
14342    if (homePageVideo.ElementExist($('.boaEditSection'))) {
14343
14344        let associatedData;
14345        let associatedTimer;
14346        if ($('#boaform').length != 0) {
14347            $('#boaform')[0].reset();
14348        }
14349        // hide the confirmation screen on load
14350        accountSettings.hideComponent($('.doneBoa'));
14351
14352        $('.addBOABtn .modalBtn:not(".secondaryBtn")').click(function (e) {
14353            if (!accountSettings.authorMode) {
14354                accountSettings.submitBoa($(this), $(this).data('usertype'));
14355            }
14356        });
14357
14358        $('.addBOABtn .modalBtn:not(".secondaryBtn")').keypress(function (e) {
14359            if (!accountSettings.authorMode) {
14360                if ((e.which || e.keyCode) == 13) {
14361                    accountSettings.submitBoa($(this), $(this).data('usertype'));
14362                }
14363            }
14364        });
14365
14366        $(document).on('blur', '.boaEditSection .boa-input-required', function () {
14367            bhfFormValidator.boaFormValidator($(this));
14368            accountSettings.boaValidator();
14369        });
14370
14371        $(document).on('keyup', '.boaEditSection .boa-input-required', function () {
14372            accountSettings.boaValidator();
14373        });
14374
14375        $(document).on('change', '.boaEditSection .bhf-form-select', function () {
14376            accountSettings.boaValidator();
14377        });
14378
14379        $('#firms-boa-pm').select2({
14380            placeholder: "Select Firm",
14381            dropdownAutoWidth: true,
14382            dropdownParent: $('#firms-boa-pm-container'),
14383        });
14384
14385        if($('.boa-channel-radio-btn').length){
14386            if(!$('.manage__boa__edit').length){
14387                let selectedBoaChannel = $('input[name="boaChannel"]:checked').val();
14388                if(selectedBoaChannel){
14389                    let selectedChannel = $('input[name="boaChannel"]:checked').val();
14390                    let $select2 = $('#firms-boa-pm');
14391                    let $options = $select2.find('option');
14392                    $options.each(function(){
14393                        if(selectedChannel != $(this).attr('data-channel')){
14394                            $(this).prop('disabled',true);
14395                        }else{
14396                            $(this).prop('disabled',false);
14397                        }
14398                    })
14399                    $('#firms-boa-pm').select2();
14400                }
14401            }
14402            $('input[name="boaChannel"]').on('change',function(e){
14403                $('#firms-boa-pm').removeAttr('disabled');
14404                $('#firms-boa-pm').val('').trigger('change');
14405                let selectedChannel = $('input[name="boaChannel"]:checked').val();
14406                let $select2 = $('#firms-boa-pm');
14407                let $options = $select2.find('option');
14408                $options.each(function(){
14409                    if(selectedChannel != $(this).attr('data-channel')){
14410                        $(this).prop('disabled',true);
14411                    }else{
14412                        $(this).prop('disabled',false);
14413                    }
14414                })
14415                $('#firms-boa-pm').select2();
14416            })
14417        }
14418
14419
14420        $('#boa__user__type').select2({
14421            placeholder: "Select a User Type",
14422        });
14423
14424        if(accountSettings.checkIsRiaUser(userType)){
14425            $('#boa_man').addClass('boa-input-required');
14426            $('#boa_man').addClass('required');
14427            $('.inputMasterAccountNumber').removeClass('hide');
14428            // plan sponsor userType
14429            $('#boa__group__code').removeClass('boa-input-required');
14430            $('#boa__group__code').removeClass('required');
14431            $('.inputGroupNumber').addClass('hide');
14432        }else if(accountSettings.checkIsPlanSponser(userType)){
14433            $('#boa__group__code').addClass('boa-input-required');
14434            $('#boa__group__code').addClass('required');
14435            $('.inputGroupNumber').removeClass('hide');
14436            //RIA user
14437            $('#boa_man').removeClass('boa-input-required');
14438            $('#boa_man').removeClass('required');
14439            $('.inputMasterAccountNumber').addClass('hide');
14440        }else{
14441            $('#boa_man').removeClass('boa-input-required');
14442            $('#boa_man').removeClass('required');
14443            $('.inputMasterAccountNumber').addClass('hide');
14444            // plan sponsor userType
14445            $('#boa__group__code').removeClass('boa-input-required');
14446            $('#boa__group__code').removeClass('required');
14447            $('.inputGroupNumber').addClass('hide');
14448        }
14449
14450        if ($(".manage__boa__edit").length) {
14451            if ($("#boa-email-ia").length && $("#boa-email-ia").val().length) {
14452                bhfFormValidator.boaFormValidator($("#boa-email-ia"));
14453            }
14454            $('#boa-address2').on('keyup change', function () {
14455                accountSettings.boaValidator();
14456            });
14457            accountSettings.boaValidator();
14458        }
14459        $('table').hide();
14460
14461        $('#boa-email-ia').on('keyup', function () {
14462            clearTimeout(associatedTimer);
14463            bhfFormValidator.boaFormValidator($(this));
14464            if ($(this).hasClass('bhf-form-error') || $(this).val() == '' || $(this).val().length < 3) {
14465                $('#existing-relationship').hide();
14466                return;
14467            }
14468            associatedTimer = setTimeout(function () {
14469                accountSettings.getexistingData();
14470            }, 2000);
14471        });
14472
14473        $('#boa-email-pm').on('blur', function () {
14474            bhfFormValidator.boaFormValidator($(this));
14475            if($('#fPUser').val() == 'true'){
14476                accountSettings.boaValidateEmail($('#boa-validation-email-pm'));
14477                accountSettings.boaValidator();
14478            }
14479        });
14480        $('#boa-validation-email-pm').on('blur', function () {
14481            const element = $(this);
14482            bhfFormValidator.boaFormValidator(element);
14483            accountSettings.boaValidateEmail(element);
14484            accountSettings.boaValidator();
14485        });
14486
14487        $('#boa-validation-email-pm').on("cut copy paste",function(e) {
14488            e.preventDefault();
14489         });
14490
14491        $('#boa-email-ia').on('blur', function () {
14492            if ($(this).hasClass('bhf-form-error') || $(this).val() == '') {
14493                $('#existing-relationship').hide();
14494                return;
14495            }
14496            accountSettings.getexistingData();
14497        });
14498
14499        $('#boa-email-ia').on('keydown', function () {
14500            clearTimeout(associatedTimer);
14501        });
14502
14503        $('#boa__user__type').change(function () {
14504            $('#associated-relationship tbody').empty();
14505            $('#associated-relationship').hide();
14506            $('#boa__firm__code').find('option').remove();
14507            $('#boa__group__code').find('option').remove();
14508            $('#boa_man').find('option').remove();
14509            userType = $('#boa__user__type').val();
14510            if(accountSettings.checkIsRiaUser(userType)){
14511                accountSettings.generateMasterAccountNumber();
14512                accountSettings.clearBOAInfo(accountSettings.boaInfoIds);
14513            }else if(accountSettings.checkIsPlanSponser(userType)){
14514                accountSettings.generateGroupNumber();
14515            }else{
14516                accountSettings.clearBOAInfo(accountSettings.boaInfoIds);
14517                $('#boa_man').removeClass('boa-input-required');
14518                $('#boa_man').removeClass('required');
14519                $('.inputMasterAccountNumber').addClass('hide');
14520                $('#boa__group__code').removeClass('boa-input-required');
14521                $('#boa__group__code').removeClass('required');
14522                $('.inputGroupNumber').addClass('hide');
14523            }
14524            $.ajax({
14525                url: '/content.boa.associatedRelationship',
14526                type: 'POST',
14527                data: {
14528                    'userType': userType
14529                },
14530                success: function (data) {
14531                    if (!accountSettings.isJsonEmpty(JSON.parse(data))) {
14532                        $('#boa__firm__code').prop('disabled', false);
14533                        let firmsData = JSON.parse(data);
14534                        associatedData = JSON.parse(firmsData.data);
14535                        let isCswUser = accountSettings.checkIsCswUser(userType);
14536                        let isPlanSponsor = accountSettings.checkIsPlanSponser(userType);
14537                        if(isCswUser || isPlanSponsor){
14538                            $.each(associatedData, function (key) {
14539                                let $option = $('<option selected>').text(key);
14540                                let tableData = associatedData[key];
14541                                $('#boa__firm__code').append($option);
14542                                accountSettings.createTable(tableData, 'associated');
14543                            });
14544                            $('#associated-relationship').show();
14545                            $('#boa-drop-parent').find('.bhf-form-error-container .error-form').css('display','none');
14546                            $('#boa__firm__code').prop('disabled', true);
14547                            accountSettings.boaValidator();
14548                        }else{
14549                            $.each(associatedData, function (key) {
14550                                let $option = $('<option>').text(key);
14551                                $('#boa__firm__code').append($option);
14552                            });
14553                        }
14554                    }
14555
14556                    $('#boa__firm__code').select2({
14557                        sorter: function (data) {
14558                            return data.sort(function (a, b) {
14559                                return a.text.localeCompare(b.text);
14560                            });
14561                        },
14562                        dropdownAutoWidth: true,
14563                        dropdownParent: $('#boa-drop-parent'),
14564                        placeholder: "Firm Code",
14565                    });
14566
14567                },
14568                error: function (e) {
14569                    $('#boa__firm__code').prop('disabled', false);
14570                    console.log(e);
14571                }
14572            });
14573        });
14574
14575        $('#boa_man').on('select2:select', function (e) {
14576            var element = e.params.data.element;
14577            var $element = $(element);
14578            $element.detach();
14579            $(this).append($element);
14580            $(this).trigger("change");
14581        });
14582
14583        $('#boa__firm__code').on('select2:select', function (e) {
14584            var element = e.params.data.element;
14585            var $element = $(element);
14586            $element.detach();
14587            $(this).append($element);
14588            $(this).trigger("change");
14589            if (associatedData.hasOwnProperty(e.params.data.text)) {
14590                let tableData = associatedData[e.params.data.text];
14591                accountSettings.createTable(tableData, 'associated');
14592            }
14593            $('#associated-relationship').show();
14594        });
14595
14596        $('#boa__group__code').on('select2:selecting', function (event) {
14597           const {id,text} = event.params.args.data
14598           accountSettings.selectedGroupData.push({
14599              groupNumber:id,
14600              groupName:text
14601           });
14602        });
14603
14604        $('#boa__group__code').on('select2:select', function (e) {
14605            $("#boa__group__code").val('').trigger('change');
14606            accountSettings.selectedGroupData.map(resp =>{
14607              let $option = $("<option selected='selected'></option>").val(resp.groupNumber).text(resp.groupName)
14608              $('#boa__group__code').append($option).trigger('change');
14609            })
14610            const groupId = $($("#boa__group__code").select2('data')[0].element).attr("value");
14611            if(accountSettings.groupNumbersData.length){
14612                let groupDetails = accountSettings.groupNumbersData.filter((group) => group.id == groupId);
14613                if($('#edit-boa').length){
14614                    if(groupDetails.length){
14615                        accountSettings.boaInfoIds["boa-address1"] = groupDetails[0].address1;
14616                        accountSettings.boaInfoIds["boa-address2"] = groupDetails[0].address2;
14617                        accountSettings.boaInfoIds["boa-city"] = groupDetails[0].city;
14618                        accountSettings.boaInfoIds["boa-state"] = groupDetails[0].state;
14619                        accountSettings.boaInfoIds["boa-zip"] = groupDetails[0].zip;
14620                        $.each(accountSettings.boaInfoIds, function (key,value) {
14621                            if(value) {
14622                                $(`#${key}`).val(`${value}`)
14623                                $(`#${key}`).prop('disabled', true);
14624                            }else{
14625                                $(`#${key}`).val('');
14626                                $(`#${key}`).prop('disabled', false);
14627                            }
14628                            if(accountSettings.boaInfoIds["boa-address1"]){
14629                                $(`#boa-address2`).prop('disabled', true);
14630                            }
14631                            if(key == 'boa-address1' && value){
14632                                $(`#boa-address2`).prop('disabled', true);
14633                            }
14634                            if(key == 'boa-state') {
14635                                $(`#${key}`).trigger('change');
14636                                if(value) $('.select2-selection').blur();
14637                            }else{
14638                                if(value) bhfFormValidator.boaFormValidator($(`#${key}`));
14639                             }
14640                        });
14641                    }
14642                    accountSettings.boaValidator();
14643                }else{
14644                    if(groupDetails.length){
14645                        accountSettings.boaInfoIds["boa-address1"] = groupDetails[0].address1;
14646                        accountSettings.boaInfoIds["boa-address2"] = groupDetails[0].address2;
14647                        accountSettings.boaInfoIds["boa-city"] = groupDetails[0].city;
14648                        accountSettings.boaInfoIds["boa-state"] = groupDetails[0].state;
14649                        accountSettings.boaInfoIds["boa-zip"] = groupDetails[0].zip;
14650                        accountSettings.updateBOAInfo(accountSettings.boaInfoIds);
14651                    }
14652                }
14653            }
14654        });
14655
14656        $('#boa__group__code').on('select2:unselect', function (e) {
14657            const {id} = e.params.data;
14658            accountSettings.selectedGroupData = accountSettings.selectedGroupData.filter(resp => resp.groupNumber !== id);
14659            if($("#boa__group__code").select2('data').length){
14660                const groupId = $($("#boa__group__code").select2('data')[0].element).attr("value");
14661                if(accountSettings.groupNumbersData.length){
14662                    let groupDetails = accountSettings.groupNumbersData.filter((group) => group.id == groupId);
14663                    if($('#edit-boa').length){
14664                        if(groupDetails.length){
14665                            accountSettings.boaInfoIds["boa-address1"] = groupDetails[0].address1;
14666                            accountSettings.boaInfoIds["boa-address2"] = groupDetails[0].address2;
14667                            accountSettings.boaInfoIds["boa-city"] = groupDetails[0].city;
14668                            accountSettings.boaInfoIds["boa-state"] = groupDetails[0].state;
14669                            accountSettings.boaInfoIds["boa-zip"] = groupDetails[0].zip;
14670                            $.each(accountSettings.boaInfoIds, function (key,value) {
14671                                if(value) {
14672                                    $(`#${key}`).val(`${value}`)
14673                                    $(`#${key}`).prop('disabled', true);
14674                                }else{
14675                                    $(`#${key}`).val('');
14676                                    $(`#${key}`).prop('disabled', false);
14677                                }
14678                                if(accountSettings.boaInfoIds["boa-address1"]){
14679                                    $(`#boa-address2`).prop('disabled', true);
14680                                }
14681                                if(key == 'boa-state') {
14682                                    $(`#${key}`).trigger('change');
14683                                    if(value) $('.select2-selection').blur();
14684                                }else{
14685                                    if(value) bhfFormValidator.boaFormValidator($(`#${key}`));
14686                                 }
14687                            });
14688                        }
14689                        accountSettings.boaValidator();
14690                    }else{
14691                        if(groupDetails.length){
14692                            accountSettings.boaInfoIds["boa-address1"] = groupDetails[0].address1;
14693                            accountSettings.boaInfoIds["boa-address2"] = groupDetails[0].address2;
14694                            accountSettings.boaInfoIds["boa-city"] = groupDetails[0].city;
14695                            accountSettings.boaInfoIds["boa-state"] = groupDetails[0].state;
14696                            accountSettings.boaInfoIds["boa-zip"] = groupDetails[0].zip;
14697                            accountSettings.updateBOAInfo(accountSettings.boaInfoIds);
14698                        }
14699                    }
14700                }
14701            }else{
14702                if(!$('#edit-boa').length){
14703                    accountSettings.boaInfoIds = {'boa-address1':'','boa-address2':'','boa-city':'','boa-state':'','boa-zip':''}
14704                    accountSettings.clearBOAInfo(accountSettings.boaInfoIds,false);
14705                }
14706            }
14707        });
14708
14709        $(document).on('mouseenter focus click', '.firm-name', function () {
14710            $(this).find('span.detail-name').show();
14711        }).on('mouseleave', '.firm-name', function () {
14712            $(this).find('span.detail-name').hide();
14713        });
14714
14715        $('#boa__firm__code').on('select2:unselect', function (e) {
14716            accountSettings.removeRows(e.params.data.text.slice(0, 3));
14717            if (!$('#boa__firm__code').val()) {
14718                $('#associated-relationship').hide();
14719            }
14720        });
14721
14722        $('#boa__firm__code').on('select2:open', function (e) {
14723            setTimeout(function () {
14724                $('#boa-drop-parent .select2-results ul').scrollTop(0);
14725            }, 5);
14726        });
14727
14728        $('#boa_man').on('select2:open', function (e) {
14729            setTimeout(function () {
14730                $('#boa-man-drop-parent .select2-results ul').scrollTop(0);
14731            }, 5);
14732        });
14733
14734        $(document).on('click', 'table tr .check-container .check-mark', function () {
14735            if(accountSettings.checkIsCswUser(userType) || accountSettings.checkIsPlanSponser(userType))  return;
14736            $(this).siblings('input').prop('checked', !$(this).siblings('input').prop('checked'));
14737            $(this).parents('tr').toggleClass('selected');
14738            accountSettings.boaValidator()
14739        });
14740
14741        if ($('#edit-boa').length && !accountSettings.authorMode) {
14742            if(accountSettings.checkIsRiaUser(userType)){
14743	 			let selectedRiaFirmCodeDisplayName = $('#RIADisplayName').val();
14744                $.ajax({
14745                    url: '/content.boa.manField',
14746                    type: 'POST',
14747                    success: function(data) {
14748                        let manListData = JSON.parse(data).data;
14749                        $.each(manListData, function (index,value) {
14750                            let riaFirmId = value.RIAFirmId;
14751                            let riaFirmName = value.RIAFirmName;
14752 							let riaFirmDisplayName=value.riaFirmCodeDisplayName;
14753                            let optionText  = riaFirmId;
14754                            let optionValue = riaFirmId;
14755                            let $option = null;
14756                            if(selectedRiaFirmCodeDisplayName == riaFirmDisplayName){
14757                                $option = `<option riafirmname="${riaFirmName}" riafirmId="${riaFirmId}" value="${optionValue}" selected>${riaFirmDisplayName}</option>`
14758                            }else{
14759                                $option = `<option riafirmname="${riaFirmName}" riafirmId="${riaFirmId}" value="${optionValue}">${riaFirmDisplayName}</option>`
14760                            }
14761                            $('#boa_man').append($option);
14762                        });
14763                        $('#boa_man').select2({
14764                            sorter: function (data) {
14765                                return data.sort(function (a, b) {
14766                                    return a.text.localeCompare(b.text);
14767                                });
14768                            },
14769                            dropdownAutoWidth: true,
14770                            dropdownParent: $('#boa-man-drop-parent'),
14771                        });
14772                    },
14773                    error: function(e) {
14774                        console.log("eror getting man list");
14775                        console.log(e);
14776                    }
14777                });
14778            }
14779
14780            if(accountSettings.checkIsPlanSponser(userType)){
14781                let selectedGroupNumberList = $('#selectedGroups').val().split('|');
14782                selectedGroupNumberList = selectedGroupNumberList.filter(function (el) {
14783                    return el != "";
14784                  });
14785                accountSettings.generateGroupNumber(selectedGroupNumberList);
14786            }
14787            
14788            $.ajax({
14789                url: '/content.boa.associatedRelationship',
14790                type: 'POST',
14791                data: {
14792                    'userType': $('#boa__user__type').val()
14793                },
14794                success: function (data) {
14795                    let firmsData = JSON.parse(data);
14796                    associatedData = JSON.parse(firmsData.data);
14797                }
14798            });
14799            $('#boa__firm__code').select2({
14800                sorter: function (data) {
14801                    return data.sort(function (a, b) {
14802                        return a.text.localeCompare(b.text);
14803                    });
14804                },
14805                dropdownAutoWidth: true,
14806                dropdownParent: $('#boa-drop-parent'),
14807                placeholder: "Firm Code",
14808            });
14809
14810            if(accountSettings.checkIsCswUser(userType) || accountSettings.checkIsPlanSponser(userType)) $('#boa__firm__code').prop('disabled','true');
14811            $('#boa__user__type:disabled').siblings('.select2-container').find('.select2-selection').css({
14812                "background-color": "#e6e6e6",
14813                "cursor": "not-allowed"
14814            });
14815            $('#boa-email-ia').trigger('keyup');
14816            let selectedString = $('#boa__firm__code').data('value').toString();
14817            selectedString = selectedString.replace(/[{}]/g, '');
14818            let selectedFirm = [];
14819            if (selectedString.indexOf('|') > 0) {
14820                selectedFirm = selectedString.split('|');
14821                selectedFirm.pop();
14822            } else {
14823                selectedFirm.push(selectedString);
14824            }
14825            for (let i = 0; i < selectedFirm.length; i++) {
14826                selectedFirm[i] = selectedFirm[i].replace(/\s+/g, " ").trim();
14827            }
14828            $('#boa__firm__code').val(selectedFirm).trigger('change');
14829            $('#associated-relationship').show();
14830        }
14831
14832
14833        if ($('#add-boa-pm').length && $('.manage__boa__edit').length) {
14834            const regToken = $('#boa-regToken').val();
14835            const boaSubHeading = $(".boaSubHeading").html().replace("{REG_TOKEN}", regToken);
14836            $(".boaSubHeading").html(boaSubHeading);
14837            const firmValues = $('#firms-boa-pm').data('firmvalues').toString();
14838            let selectedFirm = [];
14839            if (firmValues.indexOf('|') > 0) {
14840                selectedFirm = firmValues.split('|');
14841            }else {
14842                selectedFirm.push(firmValues);
14843            }
14844            $('#firms-boa-pm').val(selectedFirm).trigger('change');
14845        }
14846
14847    }
14848
14849    if (homePageVideo.ElementExist($('.boaAssign'))) {
14850        $('.cancelBtn .boaAssign').on('click', function () {
14851            window.location.reload(true);
14852        });
14853    }
14854
14855    if (homePageVideo.ElementExist($('.consumerEditPreference'))) {
14856        $('#preferenceEmailSelect').append('<option value="other">Other</option>');
14857        $('#preferenceEmailSelect').select2({});
14858
14859        $('#preferenceEmailSelect').on('change', function () {
14860            $(this).siblings('.control-display').addClass('hide');
14861            isCommPrefChanged = true;
14862            if ($(this).val() === 'other') {
14863                $(this).siblings('.control-display').removeClass('hide');
14864                $(this).removeClass('get-pref-value');
14865                $(this).siblings('.control-display').find('.prefEmailField').addClass('get-pref-value');
14866            }else {
14867                $(this).addClass('get-pref-value');
14868                $(this).siblings('.control-display').find('.prefEmailField').removeClass('get-pref-value');
14869            }
14870            accountSettings.addCCSaveValidator(isCommPrefChanged);
14871        });
14872        $('.consumerEditPreference input[type="radio"]').on('change', function (e) {
14873            isCommPrefChanged = true;
14874            $('.editButtons .modalBtn').removeClass("disableButton");
14875            accountSettings.addCCSaveValidator(isCommPrefChanged);
14876        });
14877
14878        $('.consumerEditPreference .prefEmailField').on('change', function () {
14879            bhfFormValidator.textFieldValidator($(this));
14880            accountSettings.addCCSaveValidator(isCommPrefChanged);
14881        });
14882    }
14883
14884    if (homePageVideo.ElementExist($('.editCommunication'))) {
14885        $('.preferencesForm input[type="radio"]').on('change', function (e) {
14886            $('.editButtons .modalBtn').removeClass("disableButton");
14887        });
14888    }
14889
14890    if (homePageVideo.ElementExist($('#maxCCEmailLimit'))) {
14891        maxCCEmailLimit = $("#maxCCEmailLimit").val();
14892
14893        if ($('.addCCInput').length > maxCCEmailLimit) {
14894            $('.editButtons .saveBtn').addClass("disableButton");
14895        }
14896
14897        $(".addCC").click(function (e) {
14898            let template = $('#addEmail-templ').html();
14899            $('.emailAdd').append(template);
14900            if ($('.addCCInput').length >= maxCCEmailLimit) {
14901                $('.addCC').hide();
14902            }
14903            $('.addCCInput').each(function (index) {
14904                accountSettings.emailTab($(this), index, 'add');
14905            });
14906            accountSettings.addCCSaveValidator(isCommPrefChanged);
14907        });
14908
14909        if ($('.addCCInput').length != 0) {
14910            $('.addCCInput').each(function (index) {
14911                accountSettings.emailTab($(this), index, 'load');
14912            });
14913
14914        }
14915
14916        $(document).on('blur', ".addCCInput", function (e) {
14917            bhfFormValidator.textFieldValidator($(this));
14918            accountSettings.addCCSaveValidator(isCommPrefChanged);
14919        });
14920
14921        if ($(".inputEmail").length < maxCCEmailLimit) {
14922            $('.addCC').removeClass("hide");
14923        }
14924
14925        $('.emailAdd').on('click', '.deleteField', function (e) {
14926            $(this).parent().remove();
14927            if ($(".addCCInput").length < maxCCEmailLimit) {
14928                $(".addCC").css('display', 'block');
14929                $(".addCC").removeClass('hide');
14930            }
14931            if (!firstTimeUser) {
14932                isCommPrefChanged = true;
14933            }
14934            accountSettings.addCCSaveValidator(isCommPrefChanged);
14935        });
14936    }
14937
14938    if (homePageVideo.ElementExist($('.ccButton'))) {
14939        $('.ccButton').each(function (index) {
14940            accountSettings.buttonTab($(this), maxCCEmailLimit + index);
14941        });
14942    }
14943
14944    if (homePageVideo.ElementExist($('.editStateSection'))) {
14945        $('.editStateSection .hideStateSection').click(function (e) {
14946            if ($(".defaultCheckBox").prop("checked")) {
14947                $('.editStateSection').hide();
14948                $('.editConsentSection').show();
14949                $('.successMessage').show();
14950            } else {
14951                $(".checkTick").css({
14952                    "border": "2px solid red"
14953                });
14954                e.preventDefault();
14955            }
14956        });
14957    }
14958
14959    if (homePageVideo.ElementExist($('#accountSettingState'))) {
14960        $('#accountSettingState').change(function () {
14961            if ($(this).val() === null || $(this).val().length === 0) {
14962                $('.hideStateSection').addClass('disableButton');
14963            } else {
14964                $('.hideStateSection').removeClass('disableButton');
14965            }
14966            if ($('#stateValue').data('states') != undefined) {
14967                var statesString = $('#stateValue').data('states').toLowerCase();
14968                var statesArray = statesString.split(',');
14969                if ($(this).val() !== null) {
14970                    var selectedState = $('#accountSettingState').val()[0];
14971                    var label;
14972                    if (statesArray.indexOf(selectedState.toLowerCase()) > -1) {
14973                        label = $('#saveStateConsent').data('consent');
14974                    } else {
14975                        label = $('#saveStateConsent').data('next');
14976                    }
14977                    $('#saveStateConsent').text(label);
14978                }
14979            }
14980        });
14981    }
14982
14983    if (homePageVideo.ElementExist($('#saveStateConsent'))) {
14984        $('#saveStateConsent').click(function (e) {
14985            e.preventDefault();
14986            $(this).addClass('disableButton');
14987            let path;
14988            let redirectLink;
14989            let boaFirst = firstTimeUser;
14990            let errorComp = $('#locationEditError');
14991            let selectedState = $('#accountSettingState').val()[0];
14992            let data = [$('.select2-selection__choice').attr('title')];
14993            let userType = $(this).data('usertype');
14994            let key = ['StateOfResidence'];
14995            firstTimeUser = userType === 'BOA' ? false : firstTimeUser;
14996            if ($('#stateValue').data('states') != undefined) {
14997                let statesString = $('#stateValue').data('states').toLowerCase();
14998                let statesArray = statesString.split(',');
14999                if (statesArray.indexOf(selectedState.toLowerCase()) > -1) {
15000                    redirectLink = $(this).data('true') + '?userStateCode=' + $('.select2-selection__choice').attr('title');
15001                    if (!firstTimeUser) {
15002                        window.localStorage.setItem(key[0], data[0]);
15003                        window.location.replace(redirectLink);
15004                        return;
15005                    }
15006                } else {
15007                    redirectLink = $(this).data('false');
15008                }
15009            } else {
15010                redirectLink = $(this).data('false');
15011            }
15012            if (window.location.host.indexOf('pro.com') > -1) {
15013                if (userType === 'BOA' && boaFirst) {
15014                    path = '/content.advisor.firstTimeLogin';
15015                    if (window.localStorage.getItem('EConsentDate') !== null) {
15016                        key.push('EConsentDate');
15017                        data.push(window.localStorage.getItem('EConsentDate'));
15018                    }
15019                } else {
15020                    path = '/content.advisor.location';
15021                }
15022            } else {
15023                path = '/content.consumer.location';
15024            }
15025            accountSettings.updateData(firstTimeUser, key, data, path, redirectLink, errorComp);
15026        });
15027    }
15028
15029    if (homePageVideo.ElementExist($('#consentForm'))) {
15030        $('#consentForm').click(function (e) {
15031            e.preventDefault();
15032            $(this).addClass('disableButton');
15033            let boaFirst = firstTimeUser;
15034            let today = new Date();
15035            today = ("0" + (today.getMonth() + 1)).slice(-2) + '/' + ("0" + today.getDate()).slice(-2) + '/' + today.getFullYear();
15036            let path;
15037            let errorComp = $('#stateConsentError');
15038            let signature = $('.inputConsentName').val();
15039            let date = $('.inputConsentDate').val() || today;
15040            let redirectLink = $(this).data('href');
15041            let userType = $(this).data('usertype');
15042            let key;
15043            if ($(this).data('type') === 'stateConsent') {
15044                firstTimeUser = userType === 'BOA' ? false : firstTimeUser;
15045                key = ['StateResidentConsentDate', 'StateResidentConsentSignature'];
15046            }
15047            else {
15048                key = ['EConsentDate'];
15049            }
15050            let data = [date, signature];
15051            if (!firstTimeUser) {
15052                key.push('StateOfResidence');
15053                data.push(window.localStorage.getItem('StateOfResidence'));
15054            }
15055            if (window.location.host.indexOf('pro.com') > -1) {
15056                if (userType === 'BOA' && boaFirst) {
15057                    path = '/content.advisor.firstTimeLogin';
15058                    if (window.localStorage.getItem('EConsentDate') !== null) {
15059                        key.push('EConsentDate');
15060                        data.push(window.localStorage.getItem('EConsentDate'));
15061                    }
15062                } else {
15063                    path = '/content.advisor.location';
15064                }
15065            } else {
15066                path = '/content.consumer.location';
15067            }
15068            accountSettings.updateData(firstTimeUser, key, data, path, redirectLink, errorComp);
15069        });
15070    }
15071
15072    if (homePageVideo.ElementExist($('#saveConsumerPreference'))) {
15073        $('#saveConsumerPreference').click(function (e) {
15074            e.preventDefault();
15075            $(this).addClass('disableButton');
15076            let path = '/content.consumer.mailPreference';
15077            let errorComp = $('#consumerComPreffError');
15078            let eDeliveryPreference = $("input[name='consumerPreference']:checked").val();
15079            let ccEmailsVisible = $("#ccEmailsVisible").length;
15080            let key = ['EDeliveryPreference', 'ccEmailsVisible'];
15081            let data = [eDeliveryPreference, ccEmailsVisible];
15082            let redirectLink = $(this).data('href');
15083            if ($(".addCCInput").length) {
15084                for (let i = 1; i <= $(".addCCInput").length; i++) {
15085                    key.push('CcEmail' + i);
15086                }
15087                $(".addCCInput").each(function () {
15088                    if ($(this).val() != undefined && $(this).val().trim() != "") {
15089                        data.push($(this).val());
15090                    }
15091                });
15092            }
15093
15094            if ($('.consumerPrefEmail').length) {
15095                key.push('communicationEmail');
15096                data.push($('.consumerPrefEmail').find('.get-pref-value').val())
15097            }
15098            accountSettings.updateData(firstTimeUser, key, data, path, redirectLink, errorComp);
15099        });
15100    }
15101
15102    if (homePageVideo.ElementExist($('#saveAdvisorPreference'))) {
15103        let suppress = $("input[name='suppress']:checked").val();
15104        let eDeliveryPreferenceAnnuity = $("input[name='annuities']:checked").val();
15105        let eDeliveryPreferenceLifeInsurance = $("input[name='lifeInsurance']:checked").val();
15106        let PrevCommPrefdata = [suppress, eDeliveryPreferenceAnnuity, eDeliveryPreferenceLifeInsurance];
15107        $('#saveAdvisorPreference').click(function (e) {
15108            e.preventDefault();
15109            $(this).addClass('disableButton');
15110            let path = '/content.advisor.mailPreference';
15111            let errorComp = $('#advisorComPreffError');
15112            let suppress = $("input[name='suppress']:checked").val();
15113            let eDeliveryPreferenceAnnuity = $("input[name='annuities']:checked").val();
15114            let eDeliveryPreferenceLifeInsurance = $("input[name='lifeInsurance']:checked").val();
15115            let key = ['SuppressAllEmail', 'EDeliveryPreferenceAnnuity', 'EDeliveryPreferenceLifeInsurance'];
15116            let data = [suppress, eDeliveryPreferenceAnnuity, eDeliveryPreferenceLifeInsurance];
15117            const isSameCommPrefData = PrevCommPrefdata.length === data.length && PrevCommPrefdata.every((el, index) => el === data[index]);
15118            let redirectLink = $(this).data('href');
15119            let emailAddress = $('.emailBounceBack').find('#emaildesktop').val();
15120            let currentEmail = $('#currentEmailAddress').val();
15121            let status = $('#bounceBackEmailIndStatus').val();
15122            if(status){
15123                    // method used to update bounce back email and comm preferences
15124                    accountSettings.handleCommuincationEmailAndPref(
15125                    this,
15126                    emailAddress,
15127                    currentEmail,
15128                    status,
15129                    redirectLink,
15130                    firstTimeUser,
15131                    key,
15132                    data,
15133                    path,
15134                    errorComp,
15135                    isSameCommPrefData
15136                );
15137            }else{
15138                if(firstTimeUser){
15139                    accountSettings.updateData(firstTimeUser, key, data, path, redirectLink, errorComp);
15140                }else{
15141                    const MailPreferenceResponse = accountSettings.updateCommuincationData(firstTimeUser, key, data, path, redirectLink, errorComp,true);
15142                    MailPreferenceResponse.then((MailPrefApiResp) =>{
15143                        const {isApiRequest} = MailPrefApiResp;
15144                        if(isApiRequest){
15145                            $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
15146                            $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
15147                            setTimeout(() => {window.location.replace(redirectLink)}, 100)
15148                        }else{
15149                            $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
15150                            $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
15151                            accountSettings.showErrorComponent(errorComp);
15152                        }
15153                    })
15154                    .catch((resp) =>{
15155                        $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
15156                        $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
15157                        accountSettings.showErrorComponent(errorComp);
15158                    })
15159                }
15160            }
15161        });
15162    }
15163
15164    if (homePageVideo.ElementExist($('.cancel-registration'))) {
15165        $(document).on('click', '.cancel-registration', function (e) {
15166            let redirect = $(this).data('href');
15167            $(this).addClass('disableButton');
15168            if (firstTimeUser && document.querySelector("[data-runMode]") && document.querySelector("[data-runMode]").dataset && document.querySelector("[data-runMode]").dataset.runmode.indexOf("author") == -1) {
15169                accountSettings.modalFunction($(this));
15170            } else {
15171                window.location.replace(redirect);
15172            }
15173        });
15174    }
15175
15176    if (homePageVideo.ElementExist($('.consent-decline'))) {
15177        $(document).on('click', '.consent-decline', function (e) {
15178            if (!accountSettings.authorMode) {
15179                $.ajax({
15180                    type: 'POST',
15181                    url: (window.location.host.indexOf('pro.com') > -1) ? '/content.advisor.cancelRegConsent' : '/content.consumer.cancelRegConsent',
15182                    data: {
15183                        "StateOfResidence": window.localStorage.getItem('StateOfResidence')
15184                    },
15185                    success: function (data) {
15186                        let response = JSON.parse(data);
15187                        if (response.isRequestSuccessful === true) {
15188                            loginLogout.loadAnonymousProfile($(this));
15189                        } else {
15190                            accountSettings.showErrorComponent($('#stateConsentError'));
15191                        }
15192                    },
15193                    error: function (error) {
15194                        accountSettings.showErrorComponent($('#stateConsentError'));
15195                    }
15196                });
15197            } else {
15198                $('.account-setting-modal,.reveal-overlay').css('display', 'none');
15199                $('body').removeClass('is-reveal-open');
15200            }
15201        });
15202    }
15203
15204    if (homePageVideo.ElementExist($('.loader__bg'))) {
15205        const bounceBackStatus = $('#bounceBackEmailIndStatus').val() || null;
15206        if(!bounceBackStatus){
15207            var ajaxTimer;
15208            $(document).ajaxStart(function () {
15209                ajaxTimer = setTimeout(function () {
15210                    $('.loader__bg').show();
15211                    $('.loader__content').css({ 'display': 'flex' });
15212                    $('body').addClass('is-reveal-open');
15213                }, 2000);
15214            }).ajaxStop(function () {
15215                clearTimeout(ajaxTimer);
15216                $('.loader__bg').hide();
15217                $('.loader__content').hide();
15218                $('body').removeClass('is-reveal-open');
15219            });
15220        }
15221    }
15222
15223
15224    if (homePageVideo.ElementExist($('.emailInfoIcon'))) {
15225        if (topNavigation.isTouchDevice()) {
15226            $(document).on('click touchmove', function () {
15227                if ($('.toolTip').is(':visible')) {
15228                    accountSettings.contentOverflow('unhide');
15229                } else {
15230                    accountSettings.contentOverflow('hide');
15231                }
15232            });
15233        } else {
15234            $('.emailInfoIcon, .toolTip').hover(function () {
15235                accountSettings.contentOverflow('unhide');
15236            },
15237                function () {
15238                    accountSettings.contentOverflow('hide');
15239                });
15240        }
15241    }
15242
15243    if (homePageVideo.ElementExist($('#redirect-component')) && !accountSettings.authorMode) {
15244        let redirectTime = $('#redirect-component').data('timer') * 1000;
15245        setTimeout(function () {
15246            loginLogout.loadAnonymousProfile($('#redirect-component'))
15247        }, redirectTime);
15248    }
15249
15250    if (homePageVideo.ElementExist($('.inputField'))) {
15251        $(document).on('paste', '.name-field, .city', function (event) {
15252            let allowedChars = /^[a-zA-Z0-9\s.&\/_,'()-]+$/;
15253            if (window.clipboardData && window.clipboardData.getData) {
15254                if ($(this).hasClass('name-field')) { // For IE 
15255                    if (!window.clipboardData.getData('Text').match(allowedChars)) {
15256                        event.preventDefault();
15257                    }
15258                } else if ($(this).hasClass('city')) {
15259                    if (!window.clipboardData.getData('Text').match(/^[A-Za-z\s]+$/)) {
15260                        event.preventDefault();
15261                    }
15262                }
15263
15264            }
15265            else if (event.originalEvent.clipboardData && event.originalEvent.clipboardData.getData) { // All other browsers
15266                if ($(this).hasClass('name-field')) {
15267                    if (!event.originalEvent.clipboardData.getData('Text').match(allowedChars)) {
15268                        event.preventDefault();
15269                    }
15270                } else if ($(this).hasClass('city')) {
15271                    if (!event.originalEvent.clipboardData.getData('Text').match(/^[A-Za-z\s]+$/)) {
15272                        event.preventDefault();
15273                    }
15274                }
15275            }
15276        });
15277
15278        $(document).on('paste', '.inputField.zipTextField', function (event) {
15279            if (window.clipboardData && window.clipboardData.getData) {
15280                if (!window.clipboardData.getData('Text').match(/^\d+$/)) {
15281                    event.preventDefault();
15282                }
15283            } else if (event.originalEvent.clipboardData && event.originalEvent.clipboardData.getData) {
15284                if (!event.originalEvent.clipboardData.getData('Text').match(/^\d+$/)) {
15285                    event.preventDefault();
15286                }
15287            }
15288        });
15289
15290        $(document).on('keypress', '.boaEditSection .inputField.zipTextField', function (event) {
15291            var navU = navigator.userAgent;
15292            var isAndroidMobile = navU.indexOf('Android') > -1 && navU.indexOf('Mozilla/5.0') > -1 && navU.indexOf('AppleWebKit') > -1;
15293            var isNumber = /^\d+$/.test($(this).val());
15294            if (isAndroidMobile) {
15295                my_val = my_val.replace(/\D/g, '');
15296                if (!isNumber) {
15297                    current_element.val($.trim($(this).val()));
15298                }
15299            } else {
15300                var my_key = event.keyCode || event.which;
15301                if ((my_key > 57 || my_key < 48)) {
15302                    event.preventDefault();
15303                    return false;
15304                }
15305            }
15306            return true;
15307        });
15308
15309        $('.boaEditSection .name-field').on('keypress', function (evt) {
15310            var charCode = (evt.which) ? evt.which : evt.keyCode;
15311            let allowedChars = /[a-zA-Z0-9.&'\/_,()-\s]/;
15312            if (!allowedChars.test(String.fromCharCode(charCode))) {
15313                return false;
15314            }
15315            return true;
15316        });
15317
15318        $('.boaEditSection .city').on('keypress', function (e) {
15319            var keyCode = (e.which) ? e.which : e.keyCode;
15320            let allowedChars = /[a-zA-Z\s]/;
15321            if (!allowedChars.test(String.fromCharCode(keyCode))) {
15322                return false;
15323            }
15324            return true;
15325        });
15326        $('.boaEditSection .phone').on('keypress', function (e) {
15327            var keyCode = (e.which) ? e.which : e.keyCode;
15328            if ((keyCode < 48 || keyCode > 57)) {
15329                return false;
15330            }
15331            return true;
15332        });
15333        $('.boaEditSection .man').on('keypress', function (e) {
15334            var keyCode = (e.which) ? e.which : e.keyCode;
15335            if ((keyCode < 48 || keyCode > 57)) {
15336                return false;
15337            }
15338            return true;
15339        });
15340        $(document).on('keypress',".boaEditSection #boa-email-pm", function (e) {
15341            $(this).removeClass("dup-email");
15342        });
15343    }
15344
15345    $(document).click('[data-close]', function () {
15346        $(this).parents('.reveal-overlay').css('display', 'none');
15347    });
15348
15349
15350    //bounce back handle for account setting
15351    if (homePageVideo.ElementExist($('.emailBounceBack'))) {
15352        const disableLife = $('#disablelife').val();
15353        const disableAnnuity = $('#disableannuity').val();
15354        const status = $('#bounceBackEmailIndStatus').val();
15355        const email = $('.emailBounceBack').data()['email'] ? $('.emailBounceBack').data()['email'] : null;
15356        $('.bounce-back-email-container').find('.general_alert.thankyou_msg').hide();
15357        $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
15358        $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .successMessage').hide();
15359        accountSettings.updateEmailCommuicationRadio(disableLife,disableAnnuity,status);
15360        if(status == 'pending'){
15361            $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').show();
15362            $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .comm-preff-success-message').hide();
15363            $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .comm-email-success-message').show();
15364        }else{
15365            $('.advisorCommunicationPreferenceEdit').find('comm-success-msg').hide();
15366            $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .comm-preff-success-message').hide();
15367            $('.advisorCommunicationPreferenceEdit').find('.comm-success-msg .comm-email-success-message').hide();
15368        }
15369        $('.emailBounceBack').find('#emaildesktop').on('blur',function(){
15370            var inputEmail = $(this).val();
15371            var element = $(this);
15372            const isMatched = accountSettings.isEmailMatch(inputEmail,email);
15373            if(isMatched && status == 'show'){
15374                element.addClass('bhf-form-error');
15375                element.siblings('.bhf-form-error-container').children(".duplicate-msg").show();
15376                element.find('#submit').addClass('disabled');
15377            }
15378            if(!$(this).hasClass('bhf-form-error')){
15379                $('.editButtons .modalBtn#saveAdvisorPreference').removeClass("disableButton");
15380            }else{
15381                $('.editButtons .modalBtn#saveAdvisorPreference').addClass("disableButton");
15382            }
15383            
15384        });
15385        $('.emailBounceBack').find('#emaildesktop').on('input',function(){
15386            $(this).css('color','#333');
15387        });
15388    }
15389});
15390var CookieAccountSetting = (function(){
15391	
15392	//status:
15393	//	success = success message is to be shown
15394	//	fail = failure message is to be shown
15395	var createCookie = function(status){
15396		let date = new Date();
15397		date.setTime(date.getTime() + (Number.MAX_SAFE_INTEGER * 24 * 60 * 60 * 1000));
15398		let expires = "expires="+date.toUTCString();
15399		document.cookie = "accountSettingMessageStatus" + "=" + status + ";" + expires + ";path=/";
15400	}
15401	
15402	
15403	//returns the value for 'accountSettingMessageStatus' cookie
15404	var getCookieStatus = function(){
15405		let value = "; " + document.cookie;
15406		let cookieName = "accountSettingMessageStatus";
15407		let parts = value.split(";
15407 " + cookieName + "=");
15408		if (parts.length == 2){
15409			return parts.pop().split(";").shift();
15410		} 
15411	}
15412	
15413	// deletes 'accountSettingMessageStatus' cookie
15414	var deleteCookie  = function(){
15415		let cookieName = "accountSettingMessageStatus";
15416		document.cookie = cookieName + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
15417	}
15418	
15419	
15420	return {
15421		createCookie : createCookie,
15422		getCookieStatus : getCookieStatus,
15423		deleteCookie : deleteCookie
15424	}
15425	
15426})();
15427String.prototype.count = function (c) {
15428    var result = 0,
15429        i = 0;
15430    for (i; i < this.length; i++)
15431        if (this[i] == c) result++;
15432    return result;
15433};
15434
15435var pleFirmSelector = {
15436
15437    showingFirmSelection: true,
15438
15439    getFinalURL: function (url, queryParam, firmCode, relationshipDetail) {
15440        if (url.indexOf("?") > -1) {
15441            queryParam = "&" + queryParam;
15442        } else {
15443            queryParam = "?" + queryParam;
15444        }
15445        url = url + queryParam;
15446        if (relationshipDetail) {
15447            url = url.replace("__param1__", relationshipDetail.AgentNipr);
15448            url = url.replace("__param2__", relationshipDetail.AgentProfileCode);
15449            url = url.replace("__param3__", relationshipDetail.FirmCode);
15450            url = url.replace("__param4__", relationshipDetail.FirmNipr);
15451            url = url.replace("__param5__", relationshipDetail.ProfileCode);
15452        } else {
15453            url = url.replace("__param1__", firmCode);
15454            url = url.replace("__param2__", firmCode);
15455            url = url.replace("__param3__", firmCode);
15456            url = url.replace("__param4__", firmCode);
15457            url = url.replace("__param5__", firmCode);
15458        }
15459        return url;
15460    },
15461
15462    openPleFirmSelector: function (element, dataPleApp, pleModalOpenId, selectorType) {
15463        // Check the type of modal and assign respective IDs
15464        let optionListId = selectorType === 'lob' ? '#optionList-lob' : '#optionList';
15465        let dropDownId = selectorType === 'lob' ? '#customSelect-lob' : '#customSelect';
15466        let confirmBtnId = selectorType === 'lob' ? '#loginCTABtn-lob' : '#loginCTABtn';
15467        let attribute = selectorType === 'lob' ? 'data-title' : 'href';
15468        let selectContainerId = selectorType === 'lob' ? '#select2-customSelect-lob-container' : '#select2-customSelect-container';
15469        let isPleApp = element.data(dataPleApp);
15470        let $this = element.attr('href');
15471
15472        if (isPleApp != undefined) {
15473            optionList = element.data(dataPleApp).toUpperCase();
15474            let optionData = $(optionListId + ' li[data-pleapp~=' + optionList + ']');
15475            $(optionData).each(function () {
15476                let obj = $(this).data();
15477                $(dropDownId).append("<option title='" + obj.pleapp + '~' + obj.url + "'>" + obj.firmname + "</option>");
15478            });
15479            $(dropDownId + ' option').eq(0).attr('selected', 'selected');
15480            if (selectorType === 'lob') {
15481                $("#firmSelectorModal").show();
15482                $("#lobSelectorModal").hide();
15483            } else {
15484                $('.pleConfirmBtn > a#loginCTABtn').attr('target', "_blank");
15485            }
15486            setTimeout(function () {
15487                new Foundation.Reveal($('#' + pleModalOpenId)).open();
15488                revealCenterAlign.revealRePosition();
15489                $('body').css({
15490                    "width": "100%"
15491                });
15492                $('.pleConfirmBtn > a' + confirmBtnId).attr(attribute, $(selectContainerId).attr('title').split('~')[1]);
15493                if (selectorType === 'lob') {
15494                    if ($('#customSelect-lob option').length === 1) {
15495                        $('#loginCTABtn-lob').click();
15496                    }
15497                }
15498            }, 10);
15499        } else {
15500            let url = $this;
15501
15502            let questionCount = url.count("?");
15503
15504            if (questionCount > 1) {
15505                url = url.split("?cid")[0];
15506            }
15507            window.open(url, "_blank");
15508        }
15509    },
15510
15511    removePleFirmList: function (elementToRemove) {
15512        $(elementToRemove).remove();
15513    },
15514
15515    initDropdowns: function () {
15516        if ($('#customSelect').length) {
15517            $('#customSelect').select2({
15518                dropdownParent: $('#dropdownParent'), //select2 dropdown down parent
15519                sorter: function (data) {
15520                    return data.sort();
15521                }
15522            });
15523        }
15524
15525        if ($('#customSelect-lob').length) {
15526            $('#customSelect-lob').select2({
15527                dropdownParent: $('#dropdownParent-lob'),
15528                sorter: function (data) {
15529                    return data.sort();
15530                }
15531            });
15532        }
15533    },
15534
15535    closePleModalEvents: function () {
15536
15537        $('.plecancelBtn > a.revealCloseWrapper').click(function () { //remove last append firm list in dropdown on close
15538            pleFirmSelector.removePleFirmList('select#customSelect option'); //remove ple firm list function call
15539            $('body').css({
15540                "width": ""
15541            });
15542        });
15543
15544        $('#pleModal').on('closed.zf.reveal', function () {
15545            pleFirmSelector.removePleFirmList('select#customSelect option');
15546        });
15547
15548        $('.plecancelBtn > a.revealCloseWrapper').click(function () {
15549            pleFirmSelector.removePleFirmList('select#customSelect-lob option');
15550            pleFirmSelector.showingFirmSelection = true;
15551        });
15552
15553        $('#pleOptionModal').on('closed.zf.reveal', function () {
15554            pleFirmSelector.removePleFirmList('select#customSelect-lob option');
15555        });
15556
15557        $('.plecancelBtn > .revealCloseWrapper').click(function () {
15558            $('body').css({
15559                "width": ""
15560            });
15561            pleFirmSelector.showingFirmSelection = true;
15562        });
15563
15564        $("[data-close]").on("click", function () {
15565            if ($('body').hasClass('videoNoScroll')) {
15566                $('body').removeClass('videoNoScroll');
15567            }
15568            pleFirmSelector.showingFirmSelection = true;
15569        });
15570    },
15571
15572    iterateUserProfile: function (obj) {
15573        $.each(obj.userProfile, function (i, elem) {
15574            let appDetail = JSON.parse(elem);
15575            if (obj.appName.toLowerCase() === appDetail.appName.toLowerCase()) {
15576                pleFirmSelector.assignClassAndUrl(obj, appDetail);
15577            }
15578        });
15579    },
15580
15581    assignClassAndUrl: function (obj, appDetail) {
15582        if (obj.modalOpen) {
15583            if (appDetail.associatedFirms.length > 1 || obj.userTypeValue === "IE") {
15584                this.setClassAndTarget(obj.element, obj.setDataAttr, appDetail);
15585            } else {
15586                let firmCode = appDetail.associatedFirms[0];
15587                if (obj.firmCodeMap && obj.firmCodeMap[firmCode]) {
15588                    let relationship = JSON.parse(obj.firmCodeMap[firmCode]);
15589                    if (relationship.isMulti) {
15590                        this.setClassAndTarget(obj.element, obj.setDataAttr, appDetail);
15591                    } else {
15592                        let url = pleFirmSelector.getFinalURL(appDetail.appUrl, obj.queryParam, firmCode, relationship.firmRelationships[0]);
15593                        this.setUrl(obj.element, url);
15594                    }
15595                } else {
15596                    let url = pleFirmSelector.getFinalURL(appDetail.appUrl, obj.queryParam, firmCode);
15597                    this.setUrl(obj.element, url);
15598                }
15599            }
15600        } else {
15601            this.setUrl(obj.element, appDetail.appUrl);
15602        }
15603    },
15604
15605    setClassAndTarget: function (elem, setDataAttr, appDetail) {
15606        elem.addClass('pleopenModal');
15607        elem.attr('target', '_blank');
15608        if (setDataAttr) {
15609            elem.attr('data-pleapp', appDetail.appName);
15610        }
15611    },
15612
15613    setUrl: function (elem, url) {
15614        elem.attr('href', url);
15615        elem.attr('target', '_blank');
15616    },
15617};
15618
15619$(document).ready(function () {
15620
15621    let publishMode = document.querySelector("[data-runMode]") && document.querySelector("[data-runMode]").dataset ? document.querySelector("[data-runMode]").dataset.runmode.indexOf("publish") > -1 : null;
15622
15623    //Add condition to check for the PLE-APP link
15624    if (publishMode) {
15625        let queryParam = $('#pleAppURLQueryParam').val();
15626        let userTypeValue = $('#userTypeValue').val();
15627        let userProfile = ContextHub.get('profile').PLE_APPS;
15628        let advisorFirmMap = ContextHub.get('profile').AdvisorFirmMap;
15629        let isLoggedIn = ContextHub.get('profile').displayName !== 'anonymous';
15630        let firmCodeMap;
15631        let userProfileAppsMap = new Map();
15632        let validMode = publishMode && isLoggedIn && $('.ple-app-rte').length > 0 && userProfile;
15633
15634        if (advisorFirmMap) {
15635            firmCodeMap = JSON.parse(ContextHub.get('profile').AdvisorFirmMap);
15636        }
15637
15638        pleFirmSelector.initDropdowns();
15639        pleFirmSelector.closePleModalEvents();
15640
15641        $(document).on('click', '.pleopenModal', function (e) { // open ple app modal on click
15642            e.preventDefault();
15643            e.stopPropagation();
15644            pleFirmSelector.openPleFirmSelector($(this), 'pleapp', 'pleModal', 'firm'); // call pleFirmSelector Function
15645        });
15646
15647        $(document).on('click', '.ple-lob-modal', function (e) {
15648            e.preventDefault();
15649            e.stopPropagation();
15650            pleFirmSelector.openPleFirmSelector($(this), 'pleapp', 'pleOptionModal', 'lob');
15651        });
15652
15653        $(document).on('change', '#customSelect', function () { // change url of confirm button
15654            let confirmUrl = $('#select2-customSelect-container').attr('title').split('~')[1];
15655            $('.pleConfirmBtn > a#loginCTABtn').attr('href', confirmUrl);
15656        });
15657
15658        $('#loginCTABtn-lob').click(function (e) {
15659            e.preventDefault();
15660            e.stopPropagation();
15661            if (pleFirmSelector.showingFirmSelection) {
15662                pleFirmSelector.showingFirmSelection = !pleFirmSelector.showingFirmSelection;
15663                $("#firmSelectorModal").hide();
15664                $("#lobSelectorModal").show();
15665                let lobUrl = $(this).attr('data-title');
15666                let redUrl = lobUrl.replace("__param6__", $("input[name='lob']:checked").val());
15667                $(this).attr('href', redUrl);
15668                $(this).css({
15669                    'background-color': '#00465a',
15670                    'color': '#fff',
15671                });
15672                $(this).removeAttr('style');
15673            } else {
15674                pleFirmSelector.showingFirmSelection = !pleFirmSelector.showingFirmSelection;
15675                let redUrl = $(this).attr('href');
15676                window.open(redUrl, "_blank");
15677                $(".plecancelBtn > .revealCloseWrapper").click();
15678            }
15679        });
15680
15681        $(document).on('change', '#customSelect-lob', function () {
15682            let confirmUrl = $('#select2-customSelect-lob-container').attr('title').split('~')[1];
15683            $('#loginCTABtn-lob').attr('data-title', confirmUrl);
15684
15685        });
15686
15687        $(document).on('change', '#lob-selection', function () {
15688            let lobUrl = $('#loginCTABtn-lob').attr('data-title');
15689            let redUrl = lobUrl.replace("__param6__", $("input[name='lob']:checked").val());
15690            $('#loginCTABtn-lob').attr('href', redUrl);
15691        });
15692
15693        if ($('#pleOptionModal').length) {
15694            $(document).on('mouseenter', ".select2-selection__rendered, .select2-results__option", function () {
15695                let title = $(this).attr("title");
15696                $(this).attr("tmp_title", title);
15697                $(this).attr("title", "");
15698            });
15699            $(document).on('mouseleave', ".select2-selection__rendered, .select2-results__option", function () {
15700                let title = $(this).attr("tmp_title");
15701                $(this).attr("title", title);
15702            });
15703        }
15704
15705        if ($('.ipadModalFix').length) {
15706            let isIphone = /iphone/i.test(navigator.userAgent.toLocaleLowerCase());
15707            let iPad = /iPad/i.test(navigator.userAgent.toLocaleLowerCase());
15708            $(window).on('orientationchange', function (e) {
15709                if ($('body').hasClass('is-reveal-open')) {
15710                    if (iPad) {
15711                        $(window).scrollTop(0);
15712                    }
15713                    if (isIphone) {
15714                        $('body').removeClass('videoNoScroll');
15715                        $('body').addClass('videoNoScroll');
15716                    }
15717                }
15718            });
15719        }
15720
15721        // Approach 2
15722        (function () {
15723            if (validMode) {
15724                $('.ple-app-rte').each(function () {
15725                    let _self = $(this);
15726                    let appName = $(this).data('pleapp');
15727                    let modalOpen = $(this).data('modalopen');
15728                    let dataObj = {
15729                        element: _self,
15730                        appName: appName,
15731                        modalOpen: modalOpen,
15732                        userProfile: userProfile,
15733                        userTypeValue: userTypeValue,
15734                        firmCodeMap: firmCodeMap,
15735                        queryParam: queryParam,
15736                        setDataAttr: false,
15737                    }
15738
15739                    if (appName) {
15740                        pleFirmSelector.iterateUserProfile(dataObj);
15741                    }
15742                });
15743            }
15744        })();
15745
15746
15747
15748        //Approach 3
15749        (function () {
15750            if (publishMode && isLoggedIn && userProfile) {
15751                $.each(userProfile, function (i, elem) {
15752                    let temp = JSON.parse(elem);
15753                    userProfileAppsMap.set(temp.appName.toLowerCase(), temp);
15754                });
15755
15756                $.ajax({
15757                    url: '/content.ple_app_list_response.fetchJson',
15758                    type: 'GET',
15759                    success: function (data) {
15760                        if(typeof(data) == 'object'){
15761                            $.each(data, function (i, elem) {
15762                                let appUrl = elem.appURL;
15763                                $('a[href*="' + appUrl + '"]').each(function () {
15764                                    let _self = $(this);
15765                                    let modalOpen = elem.showModal;
15766                                    let validCondition = (!(_self.hasClass('pleopenModal') || _self.data("pleapp")) && !_self.hasClass('metlife-link'));
15767                                    let dataObj = {
15768                                        element: _self,
15769                                        modalOpen: modalOpen,
15770                                        userProfile: userProfile,
15771                                        userTypeValue: userTypeValue,
15772                                        firmCodeMap: firmCodeMap,
15773                                        queryParam: queryParam,
15774                                        setDataAttr: true,
15775                                    }
15776                                    if (validCondition) {
15777                                        let appDetail = userProfileAppsMap.get(elem.appName.toLowerCase());
15778                                        if (appDetail) {
15779                                            pleFirmSelector.assignClassAndUrl(dataObj, appDetail);
15780                                        }
15781                                    }
15782                                });
15783                            });
15784                        }
15785                    },
15786                    error: function () {
15787                        console.log('Error getting PLE APPs');
15788                    }
15789                });
15790            }
15791        })();
15792    }
15793});
15794
15795String.prototype.count = function (c) {
15796    var result = 0,
15797        i = 0;
15798    for (i; i < this.length; i++)
15799        if (this[i] == c) result++;
15800    return result;
15801};
15802
15803var pleFirmSuritySelector = {
15804
15805    showingFirmSelection: true,
15806    openPleFirmSelector: function (element, dataPleApp, pleModalOpenId) {
15807
15808        let optionListId =  '#optionListSureify';
15809        let dropDownId = '#customSelectSureify';
15810        let confirmBtnId = '#loginCTABtn';
15811        let attribute =  'href';
15812        let selectContainerId = '#select2-customSelectSureify-container';
15813        let isPleApp = element.data(dataPleApp);
15814        let $this = element.attr('href');
15815
15816        if (isPleApp != undefined) {
15817            optionList = element.data(dataPleApp).toUpperCase();
15818            let optionData = $(optionListId + ' li[data-pleapp~=' + optionList + ']');
15819            $(optionData).each(function () {
15820                let obj = $(this).data();
15821                $(dropDownId).append("<option title='" + obj.pleapp + '~' + obj.url + "'>" + obj.firmname + "</option>");
15822            });
15823            $(dropDownId + ' option').eq(0).attr('selected', 'selected');
15824            $('.pleConfirmBtn > a#loginCTABtn').attr('target', "_blank");
15825            setTimeout(function () {
15826                            new Foundation.Reveal($('#' + pleModalOpenId)).open();
15827                            revealCenterAlign.revealRePosition();
15828                            $('body').css({
15829                                "width": "100%"
15830                            });
15831                            $('.pleConfirmBtn > a' + confirmBtnId).attr(attribute, $(selectContainerId).attr('title').split('~')[1]);
15832                        }, 10);
15833        } else {
15834            let url = $this;
15835
15836            let questionCount = url.count("?");
15837
15838            if (questionCount > 1) {
15839                url = url.split("?cid")[0];
15840            }
15841            window.open(url, "_blank");
15842        }
15843    },
15844
15845    removePleFirmList: function (elementToRemove) {
15846        $(elementToRemove).remove();
15847    },
15848
15849    initDropdowns: function () {
15850        if ($('#customSelectSureify').length) {
15851            $('#customSelectSureify').select2({
15852                dropdownParent: $('#dropdownParent-sureify'), //select2 dropdown down parent
15853                sorter: function (data) {
15854                    return data.sort();
15855                }
15856            });
15857        }
15858    },
15859
15860    closePleModalEvents: function () {
15861
15862        $('.plecancelBtn > a.revealCloseWrapper').click(function () { //remove last append firm list in dropdown on close
15863            pleFirmSuritySelector.removePleFirmList('select#customSelectSureify option'); //remove ple firm list function call
15864            $('body').css({
15865                "width": ""
15866            });
15867        });
15868
15869        $('#pleSureifyModal').on('closed.zf.reveal', function () {
15870            pleFirmSuritySelector.removePleFirmList('select#customSelectSureify option');
15871        });
15872
15873        $("[data-close]").on("click", function () {
15874            if ($('body').hasClass('videoNoScroll')) {
15875                $('body').removeClass('videoNoScroll');
15876            }
15877            pleFirmSuritySelector.showingFirmSelection = true;
15878        });
15879    },
15880
15881    setUrl: function (elem, url) {
15882        elem.attr('href', url);
15883        elem.attr('target', '_blank');
15884    }
15885};
15886
15887$(document).ready(function () {
15888
15889    let publishMode = document.querySelector("[data-runMode]") && document.querySelector("[data-runMode]").dataset ? document.querySelector("[data-runMode]").dataset.runmode.indexOf("publish") > -1 : null;
15890
15891    //Add condition to check for the PLE-APP link
15892    if (publishMode) {
15893        pleFirmSuritySelector.initDropdowns();
15894        pleFirmSuritySelector.closePleModalEvents();
15895
15896        $(document).on('click', '.ple-sureify-modal', function (e) { // open ple app modal on click
15897            e.preventDefault();
15898            e.stopPropagation();
15899            pleFirmSuritySelector.openPleFirmSelector($(this), 'pleapp', 'pleSureifyModal'); // call pleFirmSelector Function
15900        });
15901
15902
15903        $(document).on('change', '#customSelectSureify', function () { // change url of confirm button
15904            let confirmUrl = $('#select2-customSelectSureify-container').attr('title').split('~')[1];
15905            $('.pleConfirmBtn > a#loginCTABtn').attr('href', confirmUrl);
15906        });
15907
15908        if ($('.ipadModalFix').length) {
15909            let isIphone = /iphone/i.test(navigator.userAgent.toLocaleLowerCase());
15910            let iPad = /iPad/i.test(navigator.userAgent.toLocaleLowerCase());
15911            $(window).on('orientationchange', function (e) {
15912                if ($('body').hasClass('is-reveal-open')) {
15913                    if (iPad) {
15914                        $(window).scrollTop(0);
15915                    }
15916                    if (isIphone) {
15917                        $('body').removeClass('videoNoScroll');
15918                        $('body').addClass('videoNoScroll');
15919                    }
15920                }
15921            });
15922        }
15923    }
15924});
15925
15926var table = null;
15927$(document).ready(function () {
15928    var data = {
15929        width: '0px',
15930        targets: [0, 21],
15931    }
15932    var screenSize = $(window).width();
15933    $(window).resize(function () {
15934        screenSize = $(window).width();
15935    });
15936    var deleteRedirectLink = $('#deleteOption').data('href');
15937    if (navigator.userAgent.indexOf('Chrome') > -1) {
15938        data.width = '1px';
15939    } else {
15940        data.width = '0px';
15941        data.targets = [0, 21];
15942    }
15943    $.fn.dataTable.ext.errMode = 'throw';
15944    table = $('#manage-boa-table').DataTable({
15945        "ajax": {
15946            "url": "/content.boa.manageBOA",
15947            "type": 'POST',
15948            "dataSrc": function (json) {
15949                let finalData = json.data;
15950                if (!finalData) {
15951                    $('.bottom , #manage-boa-table_paginate').hide();
15952                    return [];
15953                } else {
15954                    for (var i = 0; i < finalData.length; i++) {
15955                        finalData[i]["FullName"] = {"firstname":finalData[i].FirstName,"lastname":finalData[i].LastName}
15956                        finalData[i]["DotsBtn"] = "<span class='manage-boa-table-dots-button'><div></div><div></div><div></div><div class='options hide-manage-boa'><div class='edit'>Edit</div><div class='delete'>Remove</div></span>";
15957                        if(finalData[i].UserType === "DELBOA"){
15958                            finalData[i]["DotsBtn"] = "<span class='manage-boa-table-dots-button'><div></div><div></div><div></div><div class='options hide-manage-boa'><div class='delete'>Remove</div></span>";
15959                        }
15960                        if(finalData[i].RIAFirmId === null) {
15961                            finalData[i]['RIAFirmId'] = "Not Added";
15962                        }else{
15963                            finalData[i]["RIAFirmId"] = finalData[i].RIAFirmId;
15964                        }
15965                        if(finalData[i].PMName === null) {
15966                            finalData[i]['PMName'] = "Not Added";
15967                        }
15968                        if (finalData[i].AEMAccessStatus === null) {
15969                            finalData[i]['AEMAccessStatus'] = "Null";
15970                        }
15971                        if(!finalData[i].hasOwnProperty('Group')){
15972                            finalData[i]['Group'] = "Not Added"
15973                        }
15974                    }
15975                    return finalData;
15976                }
15977            }
15978        },
15979        "columns": [{
15980            className: 'select-checkbox',
15981            orderable: false,
15982            data: null,
15983            defaultContent: '',
15984            targets: 0,
15985            'checkboxes': {
15986                'selectRow': true
15987            },
15988        },
15989        {
15990            "data": "FullName",
15991            "render": function (data, type, row, meta) {
15992                if (!data) {
15993                    return '';
15994                }
15995                if (type === 'export') {
15996                    return data;
15997                }
15998                if (type === 'display' && data.length > 15) {
15999                    return '<div class="fullname"><span>' + data.firstname + '</span><br/><span>' + data.lastname + '</span></div>';
16000                } else {
16001                    return '<div class="fullname"><span>'+data.firstname+' '+data.lastname+'</span></div>'
16002                }
16003            }
16004        },
16005        {
16006            "data": "DotsBtn",
16007            targets: -1,
16008            className: "dots",
16009            sortable: false
16010        },
16011        {
16012            "data": "EmailAddress",
16013            className: "tdEmail",
16014            targets: 5,
16015            "render": function (data, type, row, meta) {
16016                if (!data) {
16017                    return '';
16018                }
16019                if (type === 'export') {
16020                    return data;
16021                }
16022                if (type === 'display' && data.length > 25) {
16023                    var index = data.indexOf('@') + 1;
16024                    var em1 = data.substring(0,index);
16025                    var em2 = data.substring(index);
16026                    return '<span class="firm__details__copy_email">' + em1 +'<br />'+em2+'</span>';
16027                } else {
16028                    return '<span class="firm__details__copy_email title="' + data + '">' + data + '</span>';
16029                }
16030            }
16031        },
16032        {
16033            "data": "AEMAccessStatus",
16034            targets: 6,
16035            "render": function (data, type) {
16036                let className;
16037                let title;
16038                if (!data) {
16039                    return '';
16040                }
16041                if (type === 'export') {
16042                    return data;
16043                }
16044
16045                if(data  === 'Active') {
16046                    className  = 'registered-icon';
16047                    title = 'Registered';
16048                }else if(data === 'Inactive') {
16049                    className = 'inactive-icon';
16050                    title = 'Pending State Consent';
16051                }else if(data === 'Pending') {
16052                    className = 'pending-icon';
16053                    title = 'Registration Incomplete';
16054                }else {
16055                    className = 'null-icon';
16056                    title = 'Not Registered';
16057                }
16058                return '<span hidden>' + data + '</span><div title="' + title + '"class="firm__details__tooltip ' + className + '"><div class="reg-info ' + title + '"></div></div>';
16059            }
16060        },
16061        {
16062            "data": "UserType"
16063        },
16064        {
16065            "data": "FirmDetails",
16066            className: "firm__details",
16067            targets: 2,
16068            "render": function (data, type, row, meta) {
16069
16070                if (!data) {
16071                    return '';
16072                }
16073                let firmNames = [];
16074                let firmCodeName = [];
16075                $.each(data, function (i, elem) {
16076                    if (firmCodeName.indexOf(elem.FirmCode + elem.FirmName) == -1) {
16077                        firmNames.push(elem.FirmName);
16078                        firmCodeName.push(elem.FirmCode + elem.FirmName);
16079                    }
16080                });
16081
16082                if (type === 'export') {
16083                    let firmDetails = [];
16084                    $.each(data, function (i, elem) {
16085                        firmDetails.push(elem.FirmNipr + ', ' + elem.ProfileCode);
16086                    });
16087
16088                    let finalString = firmDetails.join('; ');
16089                    return finalString;
16090                }
16091
16092                let remainingNames = firmNames.length - 1;
16093                if (firmNames.length > 1) {
16094                    return '<span title="' + firmNames + '" class="firm__details__copy">' + firmNames[0].substring(0, 6) + '...' + '</span>' + ' <span title="' + firmNames + '" class="firm__details__tooltip"><span class="firm__details__length">' + '+' + remainingNames + '</span>' + '<div>' + '</div></span>';
16095                } else {
16096                    if (firmNames[0].length > 10) {
16097                        return '<span class="firm__details__copy" title="' + firmNames + '">' + firmNames[0].substring(0, 10) + '...' + '</span>';
16098                    } else {
16099                        return '<span class="firm__details__copy" title="' + firmNames + '">' + firmNames[0] + '</span>';
16100                    }
16101                }
16102            },
16103        },
16104        {
16105            "data": "FirmDetails",
16106            className: "firm__details",
16107            targets: 3,
16108            "render": function (data, type, row, meta) {
16109
16110                if (!data) {
16111                    return '';
16112                }
16113                let firmCodes = [];
16114                $.each(data, function (i, elem) {
16115                    if (firmCodes.indexOf(elem.FirmCode) == -1) {
16116                        firmCodes.push(elem.FirmCode);
16117                    }
16118                });
16119
16120                if (type === 'export') {
16121                    let firmName = '';
16122                    let highLevel = 0;
16123                    $.each(data, function (i, elem) {
16124                        if (+elem.HierarchyLevel > highLevel) {
16125                            highLevel = +elem.HierarchyLevel;
16126                            firmName = elem.FirmName;
16127                        }
16128                    });
16129                    return firmName;
16130                }
16131                let remainingCodes = firmCodes.length - 1;
16132                if (firmCodes.length > 1) {
16133                    return '<span title="' + firmCodes + '" class="firm__details__copy">' + firmCodes[0] + '</span>' + ',' + '<span title="' + firmCodes + '" class="firm__details__tooltip"><span class="firm__details__length">' + '+' + remainingCodes + '</span>' + '<div class="remaining-codes">' + '</div></span>';
16134                } else {
16135                    return '<span title="' + firmCodes + '" class="firm__details__copy">' + firmCodes + '</span>';
16136                }
16137            }
16138        },
16139        {
16140            "data": "RegistrationTokenId",
16141            className: "regToken",
16142            targets: 4,
16143            "render": function (data, type, row, meta) {
16144                if (!data) {
16145                    return '';
16146                }
16147                if (type === 'export') {
16148                    return data;
16149                }
16150                if(type === 'display' && data.length) {
16151                    if($(window).width() > 1550) {
16152                      return  '<span class="reg__token__data" title="' + data + '">' + data + '</span>'
16153                    }else {
16154                        return '<span class="reg__token__data" title="' + data + '">
16154' + data.substring(0, 15) + '...</span>';
16155                    }
16156                } else {
16157                    return data;
16158                }
16159
16160            }
16161        },
16162        {
16163            "data": "Address1",
16164            className: "add__1",
16165            targets: 6,
16166            visible: false,
16167            "render": function (data, type, row, meta) {
16168                if (!data) {
16169                    return '';
16170                }
16171                if (type === 'export') {
16172                    return data;
16173                }
16174                if (data.length >= 1) {
16175                    return '<span class="phone__data" title="' + data + '">' + data + '</span>';
16176                }
16177            }
16178        },
16179        {
16180            "data": "Address2",
16181            className: "add__2",
16182            targets: 7,
16183            visible: false,
16184            "render": function (data, type, row, meta) {
16185                if (!data) {
16186                    return '';
16187                }
16188                if (type === 'export') {
16189                    return data;
16190                }
16191                if (data.length >= 1) {
16192                    return '<span class="phone__data" title="' + data + '">' + data + '</span>';
16193                }
16194            }
16195        },
16196        {
16197            "data": "City",
16198            className: "city",
16199            targets: 8,
16200            visible: false,
16201            "render": function (data, type, row, meta) {
16202                if (!data) {
16203                    return '';
16204                }
16205                if (type === 'export') {
16206                    return data;
16207                }
16208                if (data.length >= 1) {
16209                    return '<span class="phone__data" title="' + data + '">' + data + '</span>';
16210                }
16211            }
16212        },
16213        {
16214            "data": "State",
16215            className: "state",
16216            targets: 9,
16217            visible: false,
16218            "render": function (data, type, row, meta) {
16219                if (!data) {
16220                    return '';
16221                }
16222                if (type === 'export') {
16223                    return data;
16224                }
16225                if (data.length >= 1) {
16226                    return '<span class="phone__data" title="' + data + '">' + data + '</span>';
16227                }
16228            }
16229        },
16230        {
16231            "data": "ZipCode",
16232            className: "zip__code",
16233            targets: 10,
16234            visible: false,
16235            "render": function (data, type, row, meta) {
16236                if (!data) {
16237                    return '';
16238                }
16239                if (type === 'export') {
16240                    return data;
16241                }
16242                if (data.length >= 1) {
16243                    return '<span class="phone__data" title="' + data + '">' + data + '</span>';
16244                }
16245            }
16246        },
16247        {
16248            "data": "ContactPhone",
16249            className: "phone",
16250            targets: 11,
16251            type: 'phoneNumber',
16252            visible: false,
16253            "render": function (data, type, row, meta) {
16254                if (!data) {
16255                    return '';
16256                }
16257                if (type === 'export') {
16258                    return data;
16259                }
16260                if (data.length >= 1) {
16261                    return '<span class="phone__data" title="' + data + '">' + data.substring(0, 3) + '-' + data.substring(3, 6) + '-' + data.substring(6, 10) + '</span>';
16262                }
16263            },
16264        },
16265        {
16266            "data": "CreatedByUser",
16267            className: "created__by",
16268            targets: 12,
16269            visible: false,
16270            "render": function (data, type, row, meta) {
16271                if (!data) {
16272                    return '';
16273                }
16274                if (type === 'export') {
16275                    return data;
16276                }
16277                if (data.length >= 1) {
16278                    return '<span class="phone__data" title="' + data + '">' + data + '</span>';
16279                }
16280            }
16281        },
16282        {
16283            "data": "PMName",
16284            "render": function(data) {
16285                if(data === 'Not Added') {
16286                    return '<span class="not-added">' + data + '</span>';
16287                }else {
16288                    return data;
16289                }
16290            }
16291        },
16292        {
16293            "data": "RIAFirmId",
16294            "render": function (data, type, row, meta) {
16295                if (!data) {
16296                    return '';
16297                }
16298                if (type === 'export') {
16299                    return data;
16300                }
16301                if(data === 'Not Added') {
16302                    return '<span class="not-added">' + data + '</span>';
16303                }else {
16304                    return '<span class="man-number" title="' + data + '">' + data + '</span>';
16305                }
16306            }
16307        },
16308        {
16309            "data": "LastModifiedDate",
16310        },
16311        {
16312            "data": "Group",
16313            className: "firm__details",
16314            targets: 13,
16315            "render": function (data, type, row, meta) {
16316
16317                if (!data) {
16318                    return '';
16319                }
16320                if(data === 'Not Added') {
16321                    return '<span class="not-added">' + data + '</span>';
16322                }
16323                let groupNames = [];
16324                $.each(data, function (i, elem) {
16325                    if (groupNames.indexOf(elem.PlanSponsorName) == -1) {
16326                        groupNames.push(elem.PlanSponsorName);
16327                    }
16328                });
16329
16330                if (type === 'export') {
16331                    let groupName = [];
16332                    $.each(data, function (i, elem) {
16333                        groupName.push(elem.PlanSponsorName);
16334                    });
16335
16336                    let finalString = groupName.join(', ');
16337                    return finalString;
16338                }
16339                let remainingNames = groupNames.length - 1;
16340                if (groupNames.length > 1) {
16341                    return '<span title="' + groupNames + '" class="firm__details__copy">' + groupNames[0].substring(0, 6) + '...' + '</span>' + ' <span title="' + groupNames + '" class="firm__details__tooltip"><span class="firm__details__length">' + '+' + remainingNames + '</span>' + '<div>' + '</div></span>';
16342                } else {
16343                    if (groupNames[0].length > 10) {
16344                        return '<span class="firm__details__copy" title="' + groupNames + '">' + groupNames[0].substring(0, 10) + '...' + '</span>';
16345                    } else {
16346                        return '<span class="firm__details__copy" title="' + groupNames + '">' + groupNames[0] + '</span>';
16347                    }
16348                }
16349            }
16350        },
16351        {
16352            "data": "Group",
16353            className: "firm__details",
16354            targets: 15,
16355            "render": function (data, type, row, meta) {
16356
16357                if (!data) {
16358                    return '';
16359                }
16360                if(data === 'Not Added') {
16361                    return '<span class="not-added">' + data + '</span>';
16362                }
16363                let groupNumbers = [];
16364                $.each(data, function (i, elem) {
16365                    if (groupNumbers.indexOf(elem.GroupNumber) == -1) {
16366                        groupNumbers.push(elem.GroupNumber);
16367                    }
16368                });
16369
16370                if (type === 'export') {
16371                    let groupCode = [];
16372                    $.each(data, function (i, elem) {
16373                        groupCode.push(elem.GroupNumber);
16374                    });
16375
16376                    let finalString = groupCode.join(', ');
16377                    return finalString;
16378                }
16379                let remainingNumbers = groupNumbers.length - 1;
16380                if (groupNumbers.length > 1) {
16381                    return '<span title="' + groupNumbers + '" class="firm__details__copy">' + groupNumbers[0].substring(0, 6) + '...' + '</span>' + ' <span title="' + groupNumbers + '" class="firm__details__tooltip"><span class="firm__details__length">' + '+' + remainingNumbers + '</span>' + '<div class="remaining-codes">' + '</div></span>';
16382                } else {
16383                    if (groupNumbers[0].length > 10) {
16384                        return '<span class="firm__details__copy" title="' + groupNumbers + '">' + groupNumbers[0].substring(0, 10) + '...' + '</span>';
16385                    } else {
16386                        return '<span class="firm__details__copy" title="' + groupNumbers + '">' + groupNumbers[0] + '</span>';
16387                    }
16388                }
16389            }
16390        },
16391        {
16392            "data": "FirstName",
16393            visible: false
16394        },
16395        {
16396            "data": "LastName",
16397            visible: false
16398        },
16399        {
16400            "data": "FirmDetails",
16401            visible: false,
16402            target: 18,
16403            "render": function (data, type) {
16404                if (!data) {
16405                    return '';
16406                }
16407                if (type === 'export') {
16408                    let firmDetails = [];
16409                    $.each(data, function (i, elem) {
16410                        if (firmDetails.indexOf(elem.FirmCode) == -1) {
16411                            firmDetails.push(elem.FirmCode);
16412                        }
16413                    });
16414
16415                    let finalString = firmDetails.join(',');
16416                    return finalString;
16417                }
16418                return '';
16419            }
16420        }
16421
16422        ],
16423        oLanguage: {
16424            sProcessing: "<img height='150px' width='150px' src='/etc/designs/bhf/images/icons/loaderPL.gif'>",
16425            "sEmptyTable": $('table').data('empty-msg')
16426        },
16427        "language": {
16428            "loadingRecords": "<p class='dataTables_processing'>Loading...</p>",
16429            "paginate": {
16430                "previous": screenSize > 480 ? "Previous" : "",
16431                "next": screenSize > 480 ? "Next" : ""
16432            }
16433        },
16434        processing: true,
16435        "info": false,
16436        responsive: {
16437            details: {
16438                display: $.fn.dataTable.Responsive.display.childRowImmediate,
16439                type: 'none',
16440                target: ''
16441            },
16442            breakpoints: [{ name: 'desktop', width: Infinity },
16443            { name: 'tablet-l', width: 1024 },
16444            { name: 'tablet-p', width: 768 },
16445            { name: 'mobile-l', width: 576 },
16446            { name: 'mobile-p', width: 320 }]
16447
16448        },
16449        "dom": '<"top">rt<"bottom"p><"clear">B',
16450        buttons: [{
16451            extend: 'csvHtml5',
16452            title: 'BOA List',
16453            extension: '.csv',
16454            exportOptions: {
16455                orthogonal: 'export',
16456                columns: [8,3,21,22,17,9,10,11,12,13,14,6,7,8,23,5,6,15,18,16,17,19,20],
16457            },
16458            customize: function (csv) {
16459                let csvRows = csv.split('\n');
16460                csvRows[0] = csvRows[0].replace("MANMaster Account Number","MAN");
16461                csvRows[0] = csvRows[0].replace('"Sort by:Name"', '"Name"');
16462                csvRows[0] = csvRows[0].replace('"Firm Name"', '"Firm Relationships"');
16463                csvRows[0] = csvRows[0].replace('"Firm Code"', '"Firm Name"');
16464                return csvRows.join('\n');
16465            }
16466        }],
16467        columnDefs: [
16468            {
16469                width: data.width,
16470                targets: data.targets,
16471                orderable: false,
16472            },
16473        ],
16474        select: {
16475            style: 'multi',
16476            selector: 'td:first-child',
16477            info: false
16478        },
16479        "createdRow": function (row, data) {
16480            if (!data.FirmDetails) {
16481                $(row).addClass('disabled-row');
16482            }
16483            if(data.Status !== "Active") {
16484                $(row).addClass('registered-row');
16485            }
16486            if(data.FullName.length > 50){
16487                $(row).css('height','180px')
16488            }
16489        },
16490        "initComplete": function (settings, json) {
16491            $('.total-records').show();
16492            $('#total-count').text(table.data().count());
16493            $('#total-registered').text(table.rows('.registered-row').count());
16494        },
16495        scrollX: screenSize > 768 ? true : false,
16496        fixedColumns: {
16497            leftColumns: screenSize > 768 ? 3 : 0,
16498            scrollX:false
16499        }
16500    });
16501    table.on('page.dt', function () {
16502        $(document).scrollTop($(".manage-boa-heading").offset().top);
16503    });
16504
16505    $(document).on('click', '#checkBox', function () {
16506        if ($(this).is(':checked')) {
16507            table.rows({ filter: 'applied' }).select();
16508            const isPmAddedBOAExist = checkIsPMAddedBOAExist();
16509            isPmAddedBOAExist ? $('#deleteOption').addClass('disabled__action') : $('#deleteOption').removeClass('disabled__action');
16510            $('.bulk__data').text("(" + table.rows('.selected').count() + ")");
16511        } else {
16512            table.rows().deselect();
16513            $('#deleteOption').addClass('disabled__action');
16514            $('.bulk__data').text("");
16515        }
16516    });
16517    $('.manage-boa td').on('click', function () {
16518        $('tr').each(function () {
16519            if (!$(this).hasClass('selected')) {
16520                $('th input').prop('checked', false);
16521            }
16522        });
16523    });
16524
16525    $(document).on('click', '.select-checkbox:not(th)', function () {
16526        deleteCounter(table.rows({ selected: true }).count());
16527    });
16528
16529    $('#searchBOA').click(function () {
16530        table.search($('#inputBOA').val()).draw();
16531        deleteCounter(table.rows({ selected: true }).count());
16532    });
16533
16534    table.on('search.dt', function (e) {
16535        if (!table.page.info().recordsDisplay) {
16536            $('#exportto__csv').addClass('disabled__action');
16537            $('#checkBox').prop('disabled', true);
16538            $('.manage-boa .bottom').hide();
16539            $('.manage-boa thead').hide();
16540            $('.matching-records').hide();
16541        } else {
16542            $('#exportto__csv').removeClass('disabled__action');
16543            $('#checkBox').prop('disabled', false);
16544            $('.manage-boa .bottom').show();
16545            $('.manage-boa thead').show();
16546            $('.matching-records').show();
16547            $('#matching-count').text(table.rows({ filter: 'applied' }).count());
16548        }
16549        if ($('#checkBox').is(':checked')) {
16550            $('#checkBox').prop('checked', false);
16551            table.rows().deselect();
16552        }
16553         if($('#inputBOA').val().trim() === ""){
16554             $('.matching-records').hide();
16555         }
16556    });
16557
16558    $('#inputBOA').focus(function () {
16559        $('.search_icon').css('opacity', 0);
16560        $(this).attr('placeholder', '');
16561    })
16562        .blur(function () {
16563            if ($(this).val() === '') {
16564                $('.search_icon').css('opacity', 1);
16565                $(this).attr('placeholder', '       Search Records');
16566            }
16567        })
16568        .keypress(function (e) {
16569            let key = e.which || e.charCode;
16570            if (key === 13) {
16571                table.search($(this).val()).draw();
16572                deleteCounter(table.rows({ selected: true }).count());
16573            }
16574        })
16575        .keydown(function (e) {
16576            let keyBackspace = e.which || e.charCode;
16577            if (keyBackspace === 8 && $(this).val().length < 2) {
16578                table.search($(this).val()).draw();
16579                deleteCounter(table.rows({ selected: true }).count());
16580            }
16581        });
16582    $('#openOption').click(function (e) {
16583        e.stopPropagation();
16584        toggleClasses($(this));
16585    });
16586
16587    $(document).click(function () {
16588        if ($('#deleteOption').is(':visible')) {
16589            toggleClasses($('#openOption'));
16590        }
16591    });
16592    $('#deleteOption').click(function () {
16593        let rowsToDelete = [];
16594        $(table.rows({ selected: true })[0]).each(function (ind, val) {
16595            let fullData = table.rows(val).data()[0];
16596            if(fullData.PMName == 'Not Added' && (fullData.PmEiamId != undefined || fullData.PmEiamId == undefined)){
16597                let reqData;
16598                reqData = {
16599                            "email": fullData.EmailAddress,
16600                            "registrationToken": fullData.RegistrationTokenId,
16601                            "UserType":fullData.UserType,
16602                            "CreatedByUser": full
16602Data.CreatedByUser,
16603                        };
16604                let FpEiamIds=null;
16605                if (fullData.FirmDetails && fullData.FirmDetails.some((val) => val.FpEiamId)) {
16606                    FpEiamIds = fullData.FirmDetails.filter(ele => ele.FpEiamId.length).map(ele => ele.FpEiamId) || null;
16607                }
16608                reqData.FpEiamId = FpEiamIds ? FpEiamIds:null;
16609                rowsToDelete.push(reqData);
16610            }
16611        });
16612        localStorage.setItem('boaDelete', JSON.stringify(rowsToDelete));
16613        window.location.replace($(this).data('href'));
16614    })
16615
16616    $(document).on('click', '.manage-boa-table-dots-button', function (e) {
16617        $('.options').each(function () { $(this).addClass('hide-manage-boa'); });
16618        $(this).find('.options').toggleClass('hide-manage-boa');
16619        e.stopPropagation();
16620    });
16621    $(document).click(function (e) {
16622        $('.manage-boa-table-dots-button').find('.options').not('.hide-manage-boa').addClass('hide-manage-boa');
16623    });
16624
16625    $('#manage-boa-table').on('click', 'tbody .edit', function () {
16626        let editLink = $('table').data('editlink');
16627        let rowData = table.row($(this).closest('tr')).data();
16628        if (editLink) {
16629            let updatedURL = editLink.substring(0, editLink.lastIndexOf('.'));
16630            updatedURL += '.' + rowData.MaskedRegistrationTokenId + ".html";
16631            window.location.href = updatedURL;
16632        }
16633    });
16634    $('#manage-boa-table').on('click', 'tbody .delete', function () {
16635        let fullData = table.row($(this).closest('tr')).data();
16636        let rowToDelete;
16637        rowToDelete = [{
16638                    "email": fullData.EmailAddress,
16639                    "registrationToken": fullData.RegistrationTokenId,
16640                    "UserType":fullData.UserType,
16641                    "CreatedByUser": fullData.CreatedByUser
16642                }];
16643        let FpEiamIds = null; 
16644        if (fullData.FirmDetails && fullData.FirmDetails.some((val) => val.FpEiamId)) {
16645          FpEiamIds = fullData.FirmDetails ? fullData.FirmDetails.filter(ele => ele.FpEiamId.length).map(ele => ele.FpEiamId) : null;
16646        }
16647        rowToDelete.map(ele=>{
16648            ele.FpEiamId = FpEiamIds ? FpEiamIds:null;
16649        })
16650        localStorage.setItem('boaDelete', JSON.stringify(rowToDelete));
16651        window.location.replace(deleteRedirectLink);
16652    });
16653
16654    // Same logic for both PM and IA delete BOA.
16655
16656    if ($('.boaDelete').length) {
16657        if (localStorage.getItem('boaDelete')) {
16658            let rowsToDelete = JSON.parse(localStorage.getItem('boaDelete'));
16659            let dataToPost = [];
16660            let namesToDisplay = '';
16661            $.each(rowsToDelete, function (i, elem) {
16662                dataToPost.push({
16663                            "RegistrationToken": elem.registrationToken,
16664                            "CreatedBy": elem.CreatedByUser.substring(0,20),
16665                            "FpEiamId":elem.FpEiamId
16666                        });
16667                if (i === rowsToDelete.length - 1) {
16668                    namesToDisplay += '<span class="accountEditEmail">' + elem.email + ' [' + elem.registrationToken + ']</span><br/>';
16669                } else {
16670                    namesToDisplay += '<span class="accountEditEmail">' + elem.email + ' [' + elem.registrationToken + '],</span></br>';
16671                }
16672            });
16673            let subHeading = $('.boaDeleteSubHeading').html();
16674            let changedSub = subHeading.replace('{USER_EMAIL}', "<span id='boaUnassignedName'>" + namesToDisplay + "</span>");
16675            $('.boaDeleteSubHeading').html(changedSub);
16676            $('.boaDelete .btnParent .saveBtn a').on('click', function (e) {
16677                e.preventDefault();
16678                $(this).addClass('disable-boa-add');
16679                let redirectLink = $(this).attr('href');
16680                $.ajax({
16681                    url: '/content.boa.removeBOA',
16682                    type: 'POST',
16683                    data: { "removeBOA": JSON.stringify(dataToPost) },
16684                    success: function (data) {
16685                        let receivedData = JSON.parse(data);
16686                        if (receivedData.isRequestSuccessful) {
16687                            localStorage.removeItem('boaDelete');
16688                            window.location.replace(redirectLink);
16689                        } else {
16690                            let jsonData = JSON.parse(data);
16691                            let failedEmails = '';
16692                            $.each(jsonData.data, function (i, elem) {
16693                                let regToken = Object.keys(elem)[0];
16694                                let emailAdd = elem[regToken];
16695                                if (i === jsonData.data.length - 1) {
16696                                    failedEmails += '<span class="accountEditEmail">' + emailAdd + ' [' + regToken + ']</span>';
16697                                } else {
16698                                    failedEmails += '<span class="accountEditEmail">' + emailAdd + ' [' + regToken + ']</span>, ';
16699                                }
16700                            });
16701                            let errorMsg = $('#boaDeleteError .error-title').html();
16702                            let changedMsg = errorMsg.replace('{USER_EMAIL}', failedEmails);
16703                            $('#boaDeleteError .error-title').html(changedMsg);
16704                            $('#boaDeleteError').show();
16705                            $('.boaDelete .saveBtn a').addClass('disable-boa-add');
16706                            $('.boaDeleteSubHeading').hide();
16707                        }
16708                    },
16709                    error: function (error) {
16710                        let errorMsg = $('#boaDeleteError .error-title').html();
16711                        let changedMsg = errorMsg.replace('{USER_EMAIL}', namesToDisplay);
16712                        $('#boaDeleteError .error-title').html(changedMsg);
16713                        $('#boaDeleteError').show();
16714                        $('.boaDelete .saveBtn a').addClass('disable-boa-add');
16715                        $('.boaDeleteSubHeading').hide();
16716                    }
16717                });
16718            });
16719        }
16720    }
16721
16722    $(document).on('mouseenter focus click', '.firm__details__tooltip', function () {
16723        $(this).children('div').text($(this).closest('.firm__details__tooltip').attr("title").split(','));
16724        $(this).children('div').scrollTop(0);
16725        $(this).children('div').show();
16726    }).on('mouseleave', '.firm__details__tooltip', function () {
16727        $(this).children('div').hide();
16728    });
16729    $(document).on('mouseenter focus click', '.email-show', function () {
16730        $(this).children('div').text($(this).attr("title"));
16731        $(this).children('div').show();
16732    }).on('mouseleave', '.email-show', function () {
16733        $(this).children('div').hide();
16734    });
16735    $(document).on('click', '.firm__details__copy:not(".firm__details__tooltip"), .email__data, .reg__token__data', function () {
16736        copyToclipBoard($(this));
16737        $('.copied__content').css({
16738            'opacity': '1',
16739            'z-index': '1',
16740        });
16741        setTimeout(function () {
16742            $('.copied__content').css({
16743                'opacity': '',
16744                'z-index': '',
16745            });
16746        }, 1000);
16747    });
16748    $('#exportto__csv').on('click', function () {
16749        $('.buttons-csv').click();
16750    });
16751
16752    table.on('order.dt', function () {
16753        if (table.rows('.selected').count()) {
16754            $('.bulk__data').text("(" + table.rows('.selected').count() + ")");
16755            $('#deleteOption').removeClass('disabled__action');
16756        } else {
16757            $('.bulk__data').text("");
16758            $('#deleteOption').addClass('disabled__action');
16759        }
16760
16761    });
16762});
16763
16764function toggleClasses(elem) {
16765    elem.toggleClass('green-border');
16766    elem.find('.icon').toggleClass('rotated');
16767    elem.siblings('.bulk-action__options').toggleClass('hide-option');
16768}
16769
16770function copyToclipBoard(element) {
16771    let _self = element;
16772    let copyLongText = _self.attr("title");
16773    let text = element.text();
16774    let elem = document.createElement("textarea");
16775    elem.style.position = "fixed";
16776    if (copyLongText) {
16777        text = copyLongText;
16778    }
16779    document.body.appendChild(elem);
16780    elem.value = text;
16781    elem.select();
16782    document.execCommand("copy");
16783    document.body.removeChild(elem);
16784}
16785function deleteCounter(rowsSelected) {
16786    if ($('tr.selected').length) {
16787        const isPmAddedBOAExist = checkIsPMAddedBOAExist();
16788        isPmAddedBOAExist ? $('#deleteOption').addClass('disabled__action') : $('#deleteOption').removeClass('disabled__action');
16789        $('.bulk__data').text("(" + rowsSelected + ")");
16790    } else {
16791        $('#deleteOption').addClass('disabled__action');
16792        $('.bulk__data').text("");
16793    }
16794}
16795
16796function checkIsPMAddedBOAExist(){
16797    let isPmAddedExist=true;
16798    $(table.rows({ selected: true })[0]).each(function (ind, val) {
16799        let fullData = table.rows(val).data()[0];
16800        if (fullData.PMName == 'Not Added' && (fullData.PmEiamId != undefined || fullData.PmEiamId == undefined)) isPmAddedExist =  false;
16801    });
16802    return isPmAddedExist;
16803}
16804
16805$.fn.DataTable.ext.type.search.phoneNumber = function (data) {
16806    return !data ?
16807        '' :
16808        typeof data === 'string' ?
16809            data + data.replace(/[ \-]/g, '') :
16810            data;
16811};
16812
16813(function(){
16814
16815    var returnMethodSelected;
16816    var ageTooltipText = '';
16817    var durTooltipText = '';
16818    var returnMethod = '';
16819    var faxLabel = $('#inforce-fax').data('label');
16820    var mailLabel = $('#inforce-returnAddress').data('label');
16821    var emailLabel = $('#inforce-email').data('label');
16822    var isAndroidMobile = navigator.userAgent.indexOf('Android') > -1;
16823
16824    var inforceFormMethods = {
16825
16826        scenariosAdded: 1,
16827
16828        prePopulateUserData: function (currentUserProfileData) {
16829            if(currentUserProfileData) {
16830                if(currentUserProfileData.givenName) {
16831                    $('#inforce-firstName').val(currentUserProfileData.givenName);
16832                }
16833                if(currentUserProfileData.familyName) {
16834                    $('#inforce-lastName').val(currentUserProfileData.familyName);
16835                }
16836                if(currentUserProfileData.NiprId) {
16837                    $('#inforce-nipr').val(currentUserProfileData.NiprId);
16838                }
16839            }
16840        },
16841
16842        getInforceFormData: function (form) {
16843            var inforceData = {
16844                "policyInfo": {
16845                    "policyNumber": form.find('#inforce-policyNumber').val().trim(),
16846                    "policySuffix": form.find('#inforce-policySuffix').val(),
16847                    "productType": form.find('#inforce-productType').val(),
16848                    "insuredFirstName": form.find('#inforce-insuredFirstName').val(),
16849                    "insuredLastName": form.find('#inforce-insuredLastName').val(),
16850                },
16851                "requestor": {
16852                    "firstName": form.find('#inforce-firstName').val(),
16853                    "lastName": form.find('#inforce-lastName').val(),
16854                    "phoneNumber": form.find('#inforce-phone').val(),
16855                    "agencyName": form.find('#inforce-agencyName').val(),
16856                    "niprID": form.find('#inforce-nipr').val(),
16857                    "returnCompletedTo": form.find('#inforce-completedIllustration').val(),
16858                    "returnMethod": form.find('#inforce-returnMethod').val(),
16859                    "comments": form.find('#inforce-comments').val(),
16860                    "illustrationScenarios": [],
16861                }
16862            }
16863
16864            if (form.find('#inforce-email').val().trim().length) {
16865                inforceData['requestor']['email'] = form.find('#inforce-email').val();
16866            }
16867            if (form.find('#inforce-fax').val().trim().length) {
16868                inforceData['requestor']['faxNumber'] = form.find('#inforce-fax').val();
16869            }
16870            if (form.find('#inforce-returnAddress').val().trim().length) {
16871                inforceData['requestor']['address'] = form.find('#inforce-returnAddress').val();
16872            }
16873
16874            form.find('.completed-scenario').each(function(){
16875                var scenarioData = {};
16876
16877                if ($(this).find('.temp-requestScenario').val()) {
16878                    scenarioData['scenarioRequested'] = $(this).find('.temp-requestScenario').val();
16879                }
16880
16881                if ($(this).find('.temp-specialInstructions').val()) {
16882                    scenarioData['specialInstructions'] = $(this).find('.temp-specialInstructions').val();
16883                }
16884                
16885                if ($(this).find('.temp-durationSelection').val()) {
16886                    scenarioData['duration'] = $(this).find('.temp-durationSelection').val();
16887                    if ($(this).find('.temp-durationSelection').val() === 'MATURITY') {
16888                        scenarioData['MATURITY'] = "";
16889                    }
16890                }
16891
16892                if ($(this).find('.temp-startAtText').val()) {
16893                    if ($(this).find('.temp-durationSelection').val() && $(this).find('.temp-durationSelection').val() === 'ENDOW_AT_AGE') {
16894                        scenarioData['ENDOW_AT'] = $(this).find('.temp-startAtText').val();
16895                    } else if ($(this).find('.temp-requestScenario').val() === 'REDUCE_BASE_FACE_COVERAGE' || $(this).find('.temp-requestScenario').val() === 'CAL_MIN_PREMIUM') {
16896                        if ($(this).find('.temp-durationSelection').val() === 'YEAR') {
16897                            scenarioData['year'] = $(this).find('.temp-startAtText').val();
16898                        } else if ($(this).find('.temp-durationSelection').val() === 'AGE') {
16899                            scenarioData['age'] = $(this).find('.temp-startAtText').val();
16900                        }
16901                    } else {
16902                        scenarioData['age'] = $(this).find('.temp-startAtText').val();
16903                    }
16904                }
16905
16906                if ($(this).find('.temp-durationText').val()) {
16907                    scenarioData['year'] = $(this).find('.temp-durationText').val();
16908                }
16909
16910                if ($(this).find('.temp-amountText').val()) {
16911                    scenarioData['amount'] = $(this).find('.temp-amountText').val().replace(/,/g, '');
16912                }
16913                
16914                
16915                
16916                inforceData['requestor']['illustrationScenarios'].push(scenarioData);
16917            });
16918
16919            return inforceData;
16920        },
16921
16922        formValidator: function() {
16923            var isFormValid = true;
16924            $('#inforce-form .required').each(function(){
16925                if ($(this).val().trim() == "" 
16926                || $(this).hasClass('bhf-form-error') 
16927                || $(this).val() === null 
16928                ) {
16929                    isFormValid = false;
16930                    return;
16931                }
16932
16933            });
16934
16935            if($('input#inforce-nipr').val().length < 4){
16936                $(this).addClass('bhf-form-error');
16937                $(this).siblings('.bhf-form-error-container').find('.required-msg').hide();
16938                $(this).siblings('.bhf-form-error-container').find('.contstrain-msg').show();
16939                isFormValid = false;
16940                return;
16941            }
16942
16943            if (isFormValid) {
16944                $('#inforce-form .inforce-submit').removeClass('disableButton');
16945            } else {
16946                $('#inforce-form .inforce-submit').addClass('disableButton');
16947            }
16948        },
16949
16950        initiateFormSelect2: function (elem) {
16951            var placeholder = elem.attr('placeholder');
16952            elem.select2({
16953                tags: "true",
16954                placeholder: placeholder,
16955                dropdownParent: elem.parent(),
16956            });
16957        },
16958
16959        scenarioDurationHandler: function (elem) {
16960            var selectedIllustration = elem.find(':selected').data('category');
16961            var info = elem.find(':selected').data('info');
16962            var durationContainer = elem.parents('.scenarios-container').find('.durationContainer');
16963            durationContainer.empty();
16964            var specialInstruction = $('#special-inst-template').html();
16965            if(info){
16966                elem.parents('.dropDown').find('.requestScenario__info').text(info);
16967             }
16968             else{
16969               elem.parents('.dropDown').find('.requestScenario__info').text('');
16970             }
16971            if (elem.find(':selected').data('agetip') && elem.find(':selected').data('agetip') !== "") {
16972                ageTooltipText = elem.find(':selected').data('agetip');
16973            }else {
16974                ageTooltipText = '';
16975            }
16976            if (elem.find(':selected').data('durtip') && elem.find(':selected').data('durtip') !== "") {
16977                durTooltipText = elem.find(':selected').data('durtip');
16978            } else {
16979                durTooltipText = '';
16980            }
16981
16982            if (selectedIllustration === "") {
16983                durationContainer.append(specialInstruction);
16984                elem.parents('.inforce-form').find('.add-scenario-btn').removeClass('disableButton');
16985            } else {
16986                var durationSelect = $('#duration-select-template').clone().html();
16987                durationContainer.append(durationSelect);
16988                $(durationContainer).find('select option').each(function(){
16989                    if (!$(this).hasClass(selectedIllustration) && !$(this).hasClass('dummy_inforce_option')) {
16990                        $(this).remove();
16991                    }
16992                });
16993                if (ageTooltipText !== '') {
16994                    $(durationContainer).find('.inforce_tooltip').removeClass('hide');
16995                    $(durationContainer).find('.inforce_tooltip__text-age').html(ageTooltipText);
16996                }
16997            }
16998            
16999            inforceFormMethods.initiateFormSelect2($(durationContainer.find('.durationSelection')));
17000            $('#inforce-form .inforce-submit').addClass('disableButton');
17001            inforceFormMethods.enableAddScenarioBtn(elem.parents('.scenarios-container'));
17002            inforceFormMethods.formValidator();
17003
17004            durationContainer.addClass('fade-in');
17005        },
17006
17007        returnMethodchangeHandler: function(val) {
17008            $('.return-method-option').hide();
17009            $('.return-method-option input').removeClass('required');
17010            if(val === 'fax') {
17011                $('.return-method-option.if-fax').show();
17012                $('.inforce-form .faxNumber').addClass('required');
17013                returnMethodSelected = faxLabel;
17014            } else if(val === 'email') {
17015                $('.return-method-option.if-email').show();
17016                $('.inforce-form .email').addClass('required');
17017                returnMethodSelected = emailLabel;
17018            } else if(val === 'mail') {
17019                $('.return-method-option.if-mail').show();
17020                $('.inforce-form .mail').addClass('required');
17021                returnMethodSelected = mailLabel;
17022            }
17023        },
17024
17025        durationSelectChangeHandler: function(elem) {
17026            var durationSection = $('#duration-text-template').clone().html();
17027            elem.parents('.row.set-width').find('.durationInputContainer').empty();
17028            elem.parents('.row.set-width').find('.durationInputContainer').append(durationSection);
17029            var startLabel = elem.find(':selected').data('startlabel');
17030            var durLabel = elem.find(':selected').data('durlabel');
17031            var amountLabel = elem.find(':selected').data('amountlabel');
17032            var isReduceSelected = elem.find(':selected').data('isreduce');
17033
17034            if(startLabel !== "") {
17035                elem.parents('.row.set-width').find('.start-at-input-row label').text(startLabel);
17036            }else {
17037                elem.parents('.row.set-width').find('.start-at-input-row').remove();
17038            }
17039
17040            if(durLabel !== "") {
17041                elem.parents('.row.set-width').find('.duration-input-row label').text(durLabel);
17042            } else {
17043                elem.parents('.row.set-width').find('.duration-input-row').remove();
17044            }
17045
17046            if(amountLabel !== "") {
17047                elem.parents('.row.set-width').find('.loan-amount-input-row label').text(amountLabel);
17048            } else {
17049                elem.parents('.row.set-width').find('.loan-amount-input-row').remove();
17050            }
17051
17052            if(isReduceSelected) {
17053                elem.parents('.row.set-width').find('.start-at-input-row .start-loan-at').removeClass('required');
17054                elem.parents('.row.set-width').find('.loan-amount-input-row .loan-amount').removeClass('required');
17055            }
17056
17057            if(durTooltipText !== '') {
17058                elem.parents('.row.set-width').find('.durationInputContainer .with_toolTip .inforce_tooltip').removeClass('hide');
17059                elem.parents('.row.set-width').find('.with_toolTip .inforce_tooltip .inforce_tooltip__text-dur').html(durTooltipText);
17060            }
17061
17062            elem.parents('.row.set-width').find('.durationInputContainer').addClass('fade-in');
17063        },
17064
17065        scenarioNumberDisplay: function() {
17066            $('#scenarios-section .scenario-number').each(function (i) {
17067                var count = i + 1;
17068                $(this).text('Scenario ' + count + ':');
17069            });
17070        },
17071
17072        handleCancelScenario: function(btn) {
17073            btn.parents('.scenarios-container').remove();
17074            inforceFormMethods.scenarioNumberDisplay();
17075            inforceFormMethods.scenariosAdded--;
17076            inforceFormMethods.formValidator();
17077        },
17078
17079        handleAddScenario: function(btn) {
17080            var cancelScenarioBtn = $('#cancel-scenario-template').html();
17081            btn.addClass('disableButton');
17082            inforceFormMethods.handleCompletedScenario();
17083            if (inforceFormMethods.scenariosAdded === 4) {
17084                btn.parents('.inforce-form').find('.add-scenario-btn').addClass('disableButton');
17085                return;
17086            }else if(inforceFormMethods.scenariosAdded < 4) {
17087                var scenarioTemplate = $('#scenarios-template').html();
17088                $('#scenarios-section').append(scenarioTemplate);
17089                $('#scenarios-section').find('.scenarios-container:last-child').addClass('fade-in');
17090                inforceFormMethods.scenarioNumberDisplay();
17091                inforceFormMethods.initiateFormSelect2($('#scenarios-section .requestScenario'));
17092                inforceFormMethods.scenariosAdded++;
17093                $('#scenarios-section').find('.scenarios-container .being-filled').append(cancelScenarioBtn);
17094            }
17095
17096            if (inforceFormMethods.scenariosAdded === 4) {
17097                btn.parents('.inforce-form').find('.max-scenario-message').removeClass('hide');
17098            }
17099            if (btn.parents('.inforce-form').find('.being-filled').length){
17100                $([document.documentElement, document.body]).animate({
17101                    scrollTop: btn.parents('.inforce-form').find('.being-filled').offset().top
17102                }, 500);
17103            }
17104            
17105        },
17106
17107        enableAddScenarioBtn: function(elem) {
17108            var isScenarioComplete = false;
17109            elem.find('.required').each(function(){
17110                if($(this).val() === null 
17111                || $(this).val() === ''
17112                || $(this).hasClass('bhf-form-error')) {
17113                    isScenarioComplete = false;
17114                    return false;
17115                }else {
17116                    isScenarioComplete = true;
17117                }
17118            });
17119            if(isScenarioComplete) {
17120                elem.parents('.inforce-form').find('.add-scenario-btn').removeClass('disableButton');
17121            }else {
17122                elem.parents('.inforce-form').find('.add-scenario-btn').addClass('disableButton');
17123            }
17124        },
17125
17126        handleCompletedScenario: function() {
17127            var completedScenario = $('#scenarios-section').find('.scenarios-container .being-filled');
17128            var completedScenarioInfo = '';
17129            var completedScenarioTemplate = $($('#completed-scenario').html());
17130            completedScenario.parents('.scenarios-container').removeClass('fade-in').addClass('fade-out');
17131            completedScenarioTemplate.find('.temp-requestScenario').val(completedScenario.find('select.requestScenario').val());
17132            completedScenarioTemplate.find('.temp-specialInstructions').val(completedScenario.find('.specialInstructions').val());
17133            completedScenarioInfo = completedScenario.find('select.requestScenario').val();
17134
17135            if (completedScenario.find('.inforce-select_duration').length) {
17136                if (completedScenario.find('.inforce-select_duration').val()) {
17137                    completedScenarioInfo += ' / ' + completedScenario.find('.inforce-select_duration').val();
17138                    completedScenarioTemplate.find('.temp-durationSelection').val(completedScenario.find('.inforce-select_duration').val());
17139                }
17140
17141                if (completedScenario.find('.start-loan-at').length && completedScenario.find('.start-loan-at').val().trim() !== "") {
17142                    completedScenarioInfo += ' / ' + completedScenario.find('.start-loan-at').val();
17143                    completedScenarioTemplate.find('.temp-startAtText').val(completedScenario.find('.start-loan-at').val());
17144                }
17145
17146                if (completedScenario.find('.durationText').length && completedScenario.find('.durationText').val().trim() !== "") {
17147                    completedScenarioInfo += ' / ' + completedScenario.find('.durationText').val();
17148                    completedScenarioTemplate.find('.temp-durationText').val(completedScenario.find('.durationText').val());
17149                }
17150
17151                if (completedScenario.find('.loan-amount').length && completedScenario.find('.loan-amount').val().trim() !== "") {
17152                    completedScenarioInfo += ' / $' + completedScenario.find('.loan-amount').val();
17153                    completedScenarioTemplate.find('.temp-amountText').val(completedScenario.find('.loan-amount').val());
17154                }
17155            }
17156
17157            if (completedScenario.find('.specialInstructions').val() && completedScenario.find('.specialInstructions').val().trim() !== "") {
17158                completedScenarioInfo += ' / ' + completedScenario.find('.specialInstructions').val();
17159            }
17160            
17161            completedScenarioTemplate.find('.completed-scenario-info').text(completedScenarioInfo);
17162            completedScenario.empty();
17163            completedScenario.removeClass('being-filled').addClass('scenario-filled');
17164            completedScenario.append(completedScenarioTemplate);
17165            completedScenario.parents('.scenarios-container').addClass('completed');
17166            completedScenario.parents('.scenarios-container').addClass('fade-in');
17167        },
17168
17169        initiateIllustrations: function() {
17170            inforceFormMethods.scenariosAdded = 1;
17171            $('.not-to-print').show();
17172            $('.being-filled').parents('.scenarios-container').show();
17173            $('.dropDown').css('margin-bottom', '-40px');
17174            var scenarioTemplate = $('#scenarios-template').html();
17175            $('#scenarios-section').find('.scenarios-container').remove();
17176            $('#scenarios-section').append(scenarioTemplate);
17177            $('.scenarios-container').addClass('fade-in');
17178            inforceFormMethods.scenarioNumberDisplay();
17179            inforceFormMethods.initiateFormSelect2($('#scenarios-section .requestScenario'));
17180            $('.download-inforce-checkbox').prop('checked', true);
17181        },
17182
17183        resetInforceForm: function(form) {
17184            form.find('.to-reset').each(function(){
17185                if($(this).is('select')){
17186                    $(this).val('').trigger('change');
17187                }else {
17188                    $(this).val('');
17189                }
17190            });
17191            form.find('.masked-phone-div').text('');
17192            form.find('.max-scenario-message').addClass('hide');
17193            $('.download-inforce-checkbox').prop('checked', false);
17194            $('.bhf-form-error').removeClass('bhf-form-error');
17195            $('.error-form').hide();
17196            form.find('.add-scenario-btn').addClass('disableButton');
17197            inforceFormMethods.initiateIllustrations();
17198        },
17199
17200        removeScenarioHandler: function(elem) {
17201            if (inforceFormMethods.scenariosAdded === 4) {
17202                elem.parents('.inforce-form').find('.add-scenario-btn').removeClass('disableButton');
17203                elem.parents('.inforce-form').find('.max-scenario-message').addClass('hide');
17204            }
17205            elem.parents('.scenarios-container').remove();
17206            inforceFormMethods.scenariosAdded--;
17207            if(inforceFormMethods.scenariosAdded === 0) {
17208                inforceFormMethods.initiateIllustrations();
17209            }else {
17210                inforceFormMethods.scenarioNumberDisplay();
17211            }
17212            inforceFormMethods.formValidator();
17213        },
17214
17215        formatAmount: function(val) {
17216            if(val.trim() === '') {
17217                return;
17218            }
17219            if(val.indexOf('.') > -1) {
17220                let valArr = val.split('.');
17221                let decValue = valArr[1].substring(0,2);
17222                const formatNum = valArr[0].replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
17223                return formatNum+'.'+decValue;
17224            }else {
17225                return val.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
17226            }
17227        },
17228
17229        attachEvents: function() {
17230
17231            $(document).on('change', '.requestScenario', function () {
17232                inforceFormMethods.scenarioDurationHandler($(this));
17233            });
17234
17235            $('#inforce-form .inforce-submit').on('click', function () {
17236                $('#inforce-form').trigger('submit');
17237            });
17238
17239            $(document).on('blur', '#inforce-form input', function () {
17240                bhfFormValidator.textFieldValidator($(this));
17241            });
17242
17243            $(document).on('keydown blur', '#inforce-form input:not(#inforce-nipr)', '#inforce-form textarea', function () {
17244                inforceFormMethods.formValidator();
17245            });
17246
17247
17248            $(document).on('keyup blur', 'input#inforce-nipr', function () {
17249                if($(this).val().length == 0){
17250                    $(this).addClass('bhf-form-error');
17251                    $(this).siblings('.bhf-form-error-container').find('.contstrain-msg').hide();
17252                    $(this).siblings('.bhf-form-error-container').find('.required-msg').show();
17253                    $('#inforce-form .inforce-submit').addClass('disableButton');
17254                }else if($(this).val().length < 4){
17255                    $(this).addClass('bhf-form-error');
17256                    $(this).siblings('.bhf-form-error-container').find('.required-msg').hide();
17257                    $(this).siblings('.bhf-form-error-container').find('.contstrain-msg').show();
17258                    $('#inforce-form .inforce-submit').addClass('disableButton');
17259                }else{
17260                    $(this).removeClass('bhf-form-error');
17261                    $(this).siblings('.bhf-form-error-container').find('.contstrain-msg').hide();
17262                    $(this).siblings('.bhf-form-error-container').find('.required-msg').hide();
17263                    inforceFormMethods.formValidator();
17264                }
17265            });
17266
17267            $(document).on('change', '#inforce-form select', function () {
17268                inforceFormMethods.formValidator();
17269            });
17270
17271            $(document).on('blur', '.select2-selection--single', function () {
17272                $(this).parents('.select2-container').siblings('.inforce-select').trigger('blur');
17273            });
17274
17275            $(document).on('change', '.inforce-select_duration', function(){
17276                inforceFormMethods.durationSelectChangeHandler($(this));
17277                inforceFormMethods.formValidator();
17278            });
17279
17280            $(document).on('blur', '#inforce-form select', function () {
17281                bhfFormValidator.selectValidator($(this));
17282            });
17283            $(document).on('change', '#inforce-form select', function () {
17284                bhfFormValidator.selectValidator($(this));
17285            });
17286
17287            $(document).on('click', '.cancel-scenario-btn', function(e){
17288                e.preventDefault();
17289                inforceFormMethods.handleCancelScenario($(this));
17290                $('.inforce-form').find('.add-scenario-btn').removeClass('disableButton');
17291            });
17292
17293            $(document).on('click', '.add-scenario-btn', function(e){
17294                e.preventDefault();
17295                inforceFormMethods.handleAddScenario($(this));
17296                inforceFormMethods.formValidator();
17297            });
17298
17299            $(document).on('change', '.scenarios-container', function(){
17300                inforceFormMethods.enableAddScenarioBtn($(this));
17301            });
17302
17303            $(document).on('keyup', '.loan-amount', function () {
17304
17305                inforceFormMethods.enableAddScenarioBtn($(this).parents('.scenarios-container'));
17306            });
17307
17308            $(document).on('click', '.cancel-completed-scenario span', function(e) {
17309                e.preventDefault();
17310                inforceFormMethods.removeScenarioHandler($(this));
17311            });
17312
17313            $(document).on('blur', 'input.loan-amount', function (event) {
17314                var val = $(this).val();
17315                $(this).val(inforceFormMethods.formatAmount(val));
17316                if($(this).val().trim() !== ''){
17317                    var floatVal = parseFloat($(this).val().replace(/\,/g, ""));
17318                    if(floatVal > 9999999.99) {
17319                        $(this).addClass('bhf-form-error');
17320                        $(this).siblings('.bhf-form-error-container').find('.contstrain-msg').show();
17321                    }else {
17322                        $(this).removeClass('bhf-form-error');
17323                        $(this).siblings('.bhf-form-error-container').find('.contstrain-msg').hide();
17324                    }
17325                }else {
17326                    $(this).removeClass('bhf-form-error');
17327                    $(this).siblings('.bhf-form-error-container').find('.contstrain-msg').hide();
17328                }
17329                inforceFormMethods.formValidator();
17330                inforceFormMethods.enableAddScenarioBtn($(this).parents('.scenarios-container'));
17331                
17332            });
17333
17334            $(document).on('focus', 'input.loan-amount', function (event) {
17335                var val = $(this).val();
17336                $(this).val(val.replace(/\,/g, ""));
17337            });
17338
17339            if(isAndroidMobile) {
17340                $(document).on('input', 'input.phone', function (event) {
17341                    var isNumber = /^\d+$/.test($(this).val());
17342                    var my_val = $(this).val().replace(/\D/g, '');
17343                    if (!isNumber) {
17344                        $(this).val($.trim(my_val));
17345                    }
17346                });
17347
17348                $(document).on('input', 'input.numberField', function (event) {
17349                    var isNumber = /^\d+\.+$/.test($(this).val());
17350                    var my_val = $(this).val().replace(/\D/g, '');
17351                    if (!isNumber) {
17352                        $(this).val($.trim(my_val));
17353                    }
17354                });
17355
17356                $(document).on('input', '.alphaNumericOnly', function (e) {
17357                    if($(this).val().length > 15){
17358                        $(this).val($(this).val().slice(0,15))
17359                    }else{
17360                        var alphaNumericValues = $(this).val().replace(/[^A-Za-z0-9 ]/gi,'')
17361                        $(this).val(alphaNumericValues)
17362                    }
17363                });
17364            }else {
17365                $(document).on('keydown', 'input.phone', function (event) {
17366                    var condition = !(/^[0-9]$/i.test(event.key)) && event.key !== 'Backspace' && event.key !== 'Tab';
17367                    if (condition) return false;
17368                });
17369
17370                $(document).on('keydown', 'input.numberField', function (event) {
17371                    var condition = !(/^[0-9.]$/i.test(event.key)) && event.key !== 'Backspace' && event.key !== 'Tab';
17372                    if (condition) return false;
17373                });
17374
17375                $(document).on('keydown', '.alphaNumericOnly', function (e) {
17376                    var alphaNumeric = new RegExp('^[A-Za-z0-9 ]*$');
17377                    if (!alphaNumeric.test(e.key)) {
17378                        return false;
17379                    } else {
17380                        return true;
17381                    }
17382                });
17383            }
17384
17385            $('#inforce-returnMethod').on('change', function(){
17386                $('.return-method-option input').val('');
17387                $('#inforce-form .inforce-submit').addClass('disableButton');
17388                inforceFormMethods.returnMethodchangeHandler($(this).val());
17389                inforceFormMethods.formValidator();
17390            });
17391
17392        },
17393    }
17394
17395    $(document).ready(function(){
17396        if ($('.inforce-form').length) {
17397
17398            var currentUserProfileData = ContextHub.get('profile');
17399            inforceFormMethods.prePopulateUserData(currentUserProfileData);
17400            $('.form-select-custom').each(function(){
17401                inforceFormMethods.initiateFormSelect2($(this));
17402            });
17403            var authorMode = document.querySelector("[data-runMode]") && document.querySelector("[data-runMode]").dataset ? document.querySelector("[data-runMode]").dataset.runmode.indexOf("author") != -1 : null;
17404            inforceFormMethods.initiateFormSelect2($('#scenarios-section .requestScenario'));
17405            inforceFormMethods.attachEvents();
17406            inforceFormMethods.initiateIllustrations();
17407            if(!authorMode){
17408                $('.error-fragment').hide();
17409            }
17410            $('.loader__bg').hide();
17411            $('.loader__content').hide();
17412            $('#inforce-form').on('submit', function(e){
17413                e.preventDefault();
17414                var thisForm = $(this);
17415                $(this).find('.inforce-submit').addClass('disableButton');
17416                if ($(this).find('.being-filled').length) {
17417                    inforceFormMethods.handleCompletedScenario();
17418                }
17419                $('.being-filled').parents('.scenarios-container').hide();
17420                $('.dropDown').css('margin-bottom', '0');
17421                var inforceData = inforceFormMethods.getInforceFormData(thisForm);
17422                
17423                $.ajax({
17424                    url: '/content.inforce_illustration.fetchRequest',
17425                    type: 'POST',
17426                    data: {
17427                        data: JSON.stringify(inforceData),
17428                    },
17429                    success: function(data){
17430                        if (JSON.parse(data).isRequestSuccessful) {
17431                            if ($('.download-check').find('.download-inforce-checkbox').is(':checked')) {
17432                                var printObj = JSON.parse(JSON.stringify(inforceData));
17433                                printObj['timeStamp'] = new Date();
17434                                if (printObj.requestor.phoneNumber) {
17435                                    printObj['requestor']['phoneNumber'] = bhfFormValidator.formatPhoneNumber(printObj.requestor.phoneNumber);
17436                                }
17437                                if (printObj.requestor.faxNumber && printObj.requestor.faxNumber !== "") {
17438                                    printObj['requestor']['faxNumber'] = bhfFormValidator.formatPhoneNumber(printObj.requestor.faxNumber);
17439                                }
17440                                printObj['returnLabel'] = returnMethodSelected;
17441                                var temp = $('#inforce-print-section').html();
17442                                var printDom = Mustache.render(temp, printObj);
17443                                $('#inforce-print-dom').append(printDom);
17444
17445                                $('.scenarios-container.completed').each(function () {
17446                                    $('#inforce-print-dom').find('.infoce-illustration-print__scenario').append($(this).clone());
17447                                });
17448
17449                                var opt = {
17450                                    margin: 0.5,
17451                                    filename: 'inforceRequest.pdf',
17452                                    image: { type: 'jpeg', quality: 1 },
17453                                    html2canvas: { scale: 2 },
17454                                    jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' },
17455                                    pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
17456                                };
17457                                var elem = document.getElementById('inforce-print-dom');
17458                                html2pdf(elem, opt);
17459                                $('#inforce-print-dom').empty();
17460                            }
17461                            $('.inforce-thank-section').show();
17462                            inforceFormMethods.resetInforceForm(thisForm);
17463                            $([document.documentElement, document.body]).animate({ scrollTop: 0 }, 1200);
17464                            $('#inforceFormError').hide();
17465                        }else {
17466                            $('.inforce-thank-section').hide();
17467                            $('#inforceFormError').show();
17468                            $('.dropDown').css('margin-bottom', '-40px');
17469                        }
17470
17471                    },
17472                    error: function(){
17473                        $('.inforce-thank-section').hide();
17474                        $('#inforceFormError').show();
17475                        $('.dropDown').css('margin-bottom', '-40px');
17476                    }
17477                });
17478            });
17479        }
17480    });
17481})();
17482function recaptchaFormContainerCallback() {
17483    var response = grecaptcha.enterprise.getResponse();
17484    let recaptchaThresholdValue = $('#recaptcha-threshold').val();
17485    var url = "/content.enterpriseRecaptcha";
17486    $.ajax({
17487        type: "POST",
17488        url: url,
17489        data : {
17490            token: response,
17491            recaptchaThresholdValue: recaptchaThresholdValue
17492        },
17493        success: function (data) {
17494            let userObj = JSON.parse(data);
17495            if (userObj['isSuccess'] == true) {
17496                $('.saleForceFormSubmit #recaptcha_html_element_form_container').attr('verified',true);
17497                bhfFormValidator.submitValidator($('.saleForceFormSubmit .text-field-validation'));
17498                //return true;
17499            } else {
17500                $('.saleForceFormSubmit #recaptcha_html_element_form_container').attr('verified',false);
17501                bhfFormValidator.submitValidator($('.saleForceFormSubmit .text-field-validation'));
17502                return false
17503            }
17504        },
17505        error: function () {
17506            console.log('Error in getting verify response form');
17507            return false
17508        }
17509    });
17510}
17511
17512function recaptchaFormContainerExpiredCallback() {
17513    $('.saleForceFormSubmit #recaptcha_html_element_form_container').attr('verified',false);
17514    bhfFormValidator.submitValidator($('.saleForceFormSubmit .text-field-validation'));
17515}
17516$(document).ready(function(){
17517    if($('.bounce-back-email-wrapper').length && !(window.localStorage.getItem('ContextHubPersistence') === 'null')){
17518        const BouncedEmailInd = $('.bounce-back-email-wrapper').data()['bounced'] ? $('.bounce-back-email-wrapper').data()['bounced'].toString() : null;
17519        const email = $('.bounce-back-email-wrapper').data()['email'] ? $('.bounce-back-email-wrapper').data()['email'] : null;
17520        $('.bounce-back-email-wrapper').find('.bounce-back-email-error').hide();
17521        $('.bounce-back-email-container').find('.general_alert.thankyou_msg').hide();
17522        if(BouncedEmailInd){
17523            if(BouncedEmailInd == 'resolved' || BouncedEmailInd == 'pending'){
17524                $('.bounce-back-email-container').find('.general_alert.thankyou_msg').hide();
17525                $('.bounce-back-email-container').find('.general_alert.bounce_back').hide();
17526                $('.bounce-back-email-wrapper').hide();
17527            }else if(BouncedEmailInd == 'show'){
17528                $('.bounce-back-email-container').find('.general_alert.thankyou_msg').hide();
17529                $('.bounce-back-email-container').find('.general_alert.bounce_back').show();
17530                $('.bounce-back-email-wrapper').show();
17531            }
17532    
17533            $('.general_alert.thankyou_msg').find('.thankypu_msg_close').on('click',function(){
17534                $('.bounce-back-email-container').find('.general_alert.thankyou_msg').hide();
17535                $('.bounce-back-email-container').find('.general_alert.bounce_back').hide();
17536                $('.bounce-back-email-wrapper').hide();
17537            });
17538            $('.bounce-back-email__wrapper').find('#emaildesktop').on('blur',function(){
17539                var inputEmail = $(this).val();
17540                var element = $(this);
17541                const isMatched = bounceBackMethods.isEmailMatch(inputEmail,email);
17542                if(isMatched){
17543                    element.addClass('bhf-form-error');
17544                    element.siblings('.bhf-form-error-container').children(".duplicate-msg").show();
17545                    element.parents('form').find('#submit').addClass('disabled');
17546                    return;
17547                }
17548                if(!$(this).hasClass('bhf-form-error')){
17549                    $('.bounceBackEmailButton').find('a').removeClass('disabled');
17550                    $('.bounceBackEmailButton').find('a').removeAttr('tabindex');
17551                }else{
17552                    $('.bounceBackEmailButton').find('a').addClass('disabled');
17553                    $('.bounceBackEmailButton').find('a').attr('tabindex','-1');
17554                }
17555            });
17556            $('.bounce-back-email__wrapper').find('#emailmobile').on('blur',function(){
17557                var inputEmail = $(this).val();
17558                var element = $(this);
17559                const isMatched = bounceBackMethods.isEmailMatch(inputEmail,email);
17560                if(isMatched){
17561                    element.addClass('bhf-form-error');
17562                    element.siblings('.bhf-form-error-container').children(".duplicate-msg").show();
17563                    element.parents('form').find('#submit').addClass('disabled');
17564                    return;
17565                }
17566                if(!$(this).hasClass('bhf-form-error')){
17567                    $('.bounceBackEmailButton').find('a').removeClass('disabled');
17568                    $('.bounceBackEmailButton').find('a').removeAttr('tabindex');
17569                }else{
17570                    $('.bounceBackEmailButton').find('a').addClass('disabled');
17571                    $('.bounceBackEmailButton').find('a').attr('tabindex','-1');
17572                }
17573            });
17574    
17575            $('.bounceBackEmailButton').find('a').on('click',function(){
17576                if(window.innerWidth >= 1024){
17577                    let inputEmail = $('.bounce-back-email__wrapper').find('#emaildesktop').val();
17578                    const isMatched = bounceBackMethods.isEmailMatch(inputEmail,email);
17579                    if(isMatched){
17580                        bounceBackMethods.showErrorMessage($('.bounce-back-email__wrapper').find('.search-input-container.desktop'))
17581                    }else{
17582                        bounceBackMethods.removeErrorMessage($('.bounce-back-email__wrapper').find('.search-input-container.desktop'));
17583                        bounceBackMethods.submitEmail(inputEmail);
17584                    }
17585                }else{
17586                    let inputEmail = $('.bounce-back-email__wrapper').find('#emailmobile').val();
17587                    bounceBackMethods.removeErrorMessage($('.bounce-back-email__wrapper').find('.search-input-container.mobile'))
17588                    bounceBackMethods.submitEmail(inputEmail);
17589                }
17590                bounceBackMethods.updateAnalytics(this);
17591            })
17592            $('.bounceBackEmailButton').find('a').on('keydown',function(e){
17593                if(e.keyCode == 13){
17594                    if(window.innerWidth >= 1024){
17595                        let inputEmail = $('.bounce-back-email__wrapper').find('#emaildesktop').val();
17596                        bounceBackMethods.removeErrorMessage($('.bounce-back-email__wrapper').find('.search-input-container.desktop'))
17597                        bounceBackMethods.submitEmail(inputEmail);
17598                    }else{
17599                        let inputEmail = $('.bounce-back-email__wrapper').find('#emailmobile').val();
17600                        bounceBackMethods.removeErrorMessage($('.bounce-back-email__wrapper').find('.search-input-container.mobile'));
17601                        bounceBackMethods.submitEmail(inputEmail);
17602                    }
17603                    bounceBackMethods.updateAnalytics(this);
17604                }
17605            })
17606        }
17607    }
17608});
17609const bounceBackMethods = {
17610    emailChanged:0,
17611    isEmailMatch: function(inputEmail,email){
17612        if(inputEmail === email){
17613            return true;
17614        }
17615        return false;
17616    },
17617    showErrorMessage: function(element){
17618        $(element).find('.search-input').addClass('bhf-form-error');
17619        $(element).find('.bhf-form-error-container .constraint-msg').show();
17620    },
17621    removeErrorMessage: function(element){
17622        $(element).find('.search-input').removeClass('bhf-form-error');
17623        $(element).find('.bhf-form-error-container .constraint-msg').hide();
17624        $(element).find('.bhf-form-error-container .duplicate-msg').hide();
17625    },
17626    submitEmail: function(email){
17627        try {
17628            $.ajax({
17629                url : '/content.aemCrmApiUpdate',
17630                type :'POST',
17631                data : {
17632                    "emailId" : email
17633                },
17634                success: function(response) {
17635                    const {isRequestSuccessful} = JSON.parse(response);
17636                    if(isRequestSuccessful){
17637                        $.ajax({
17638                            url : '/content.updatebouncebackEmail',
17639                            type :'POST',
17640                            data : {
17641                                "emailId" : email
17642                            },
17643                            success: function(response) {
17644                                const {isRequestSuccessful} = JSON.parse(response);
17645                                if(isRequestSuccessful){
17646                                    // show thank you message
17647                                    $('.bounce-back-email-container').find('.general_alert.bounce_back').hide();
17648                                    $('.bounce-back-email-container').find('.general_alert.thankyou_msg').show();
17649                                    $('.bounce-back-email__wrapper').find('#emaildesktop').val('');
17650                                    $('.bounce-back-email__wrapper').find('#emailmobile').val('');
17651                                    $('.bounce-back-email-wrapper').find('.bounce-back-email-error').hide();
17652                                }else{
17653                                    $('.bounce-back-email-wrapper').find('.bounce-back-email-error').show();
17654                                }
17655                            },
17656                            error: function(xhr, status, err) {
17657                                console.error("API Failed");
17658                            }
17659                        });
17660                    }else{
17661                        $('.bounce-back-email-wrapper').find('.bounce-back-email-error').show();
17662                    }
17663                },
17664                error: function(xhr, status, err) {
17665                    console.error("API Failed");
17666                }
17667            });
17668        }catch(error){
17669            $('.bounce-back-email-wrapper').find('.bounce-back-email-error').show();
17670        }
17671        
17672    },
17673    updateAnalytics: function(ele){
17674        $(ele).closest('form').find('input[type="hidden"]').each(function() {
17675            if ($(ele).attr("name") == "formName") {
17676                setFormName($(ele).val());
17677            }
17678            if ($(ele).attr("name") == "formType") {
17679                setFormType($(ele).val());
17680            }
17681        });
17682        formAnalytics.track({event: 'formcomplete'});
17683        if($(ele).data("cwanalytics")){
17684            setToolComplete();
17685        }
17686    },
17687}
17688$(window).on('load', function () {
17689    $.ajax({
17690        url: '/content.rtr',
17691        type: 'POST',
17692        success: function (response) {
17693            addCustomAttributes(response);
17694        },
17695        error: function (xhr, status, error) {
17696            console.error("RTR servlet call failed:", status, error);
17697        }
17698    });
17699});
17700
17701
17702$(window).on('load', function () {
17703    $.ajax({
17704        url: '/content.headernav', // selector-based servlet URL
17705        type: 'GET',
17706        success: function (response) {
17707            try {
17708                // let username = null;
17709                // let isLoggedIn = false;
17710                // if (response === null || response === undefined) {
17711                //     return;
17712                // }
17713                // if (typeof response === 'string') {
17714                //     var trimmed = response.trim();
17715                //     trimmed = trimmed.replace(/^\"|\"$/g, '').replace(/^\'|\'$/g, '');
17716                //     const parts = trimmed.split(',');
17717
17718                //     if (parts.length >= 2) {
17719                //         username = parts[0].trim();
17720                //         isLoggedIn = parts[1].trim().toLowerCase() === 'true';
17721                //     }
17722                // } else if (typeof response === 'object' && response !== null) {
17723                //    username = response.username || response.userName || response.name;
17724                //     isLoggedIn = response.islogin === true || response.isLogin === true;
17725                // }
17726                
17727                // if (!username || !isLoggedIn) {
17728                //     return;
17729                // }
17730
17731                // var loginEls = document.querySelectorAll('.login-gn');
17732                // loginEls.forEach(function (el) {
17733                //     var icon = el.querySelector('i');
17734                //     var helloLabel = el.getAttribute('data-hello-label');
17735                //     if (!helloLabel) {
17736                //         helloLabel = 'Welcome';
17737                //     }
17738                //     var newHtml = (icon ? icon.outerHTML + ' ' : '') + helloLabel + ' ' + username;
17739                //     el.innerHTML = newHtml;
17740                // });
17741            } catch (err) {
17742                console.error('Error updating header login username from /content.headernav response', err);
17743            }
17744        },
17745        error: function (xhr, status, error) {
17746            console.error("TestCache servlet call failed:", status, error);
17747        }
17748    });
17749});
17750
17751$(document).ready(function () {
17752    var OSName="Unknown OS";
17753    if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
17754    if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
17755    if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
17756    if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
17757    if(OSName == 'Windows'){
17758        $('.author-tag-icon').addClass('windows');
17759    }
17760    $('.advisor2').closest('.masterRowContainer').addClass('advisor2__row_container');
17761    $('.systemBreadcrumb').next().each(function(){
17762        $(this).find('.advisor2').first().addClass('mt-0');
17763    })
17764    $('.pro-logo').on('click',function(e){
17765        e.stopPropagation();
17766    })
17767    $('.systemBreadcrumb').next().find('.cell').addClass('removeMarginTop');
17768    $('.advisor2-video').parent().addClass('reveal-overlay-advisor2');
17769    $('.columnctrl').each(function () {
17770        if($(this).children('.large-6').length){
17771            let firstElement = $(this).children('.large-6').eq(0);
17772            let secondElement = $(this).children('.large-6').eq(1);
17773            if(firstElement.children('.generalAccordion').length){
17774                firstElement.children('.generalAccordion').addClass("alignMarginLeft");
17775            }
17776            if(secondElement.children('.generalAccordion').length){
17777                secondElement.children('.generalAccordion').addClass("alignMarginRight");
17778            }
17779        }
17780    });
17781    $('.module-alert-content #email').each(function () {
17782        let body_line = escape('\n\n');
17783        $(this).attr('href', $(this).attr('href') + window.location.href);
17784    });
17785
17786    let phoneNumber = $('#mobile-phone').text();
17787    phoneNumber = bhfFormValidator.formatPhoneNumber(phoneNumber);
17788    $('#mobile-phone').text(phoneNumber);
17789    appController.adjustGenericVideo();
17790    appController.handleToolSection();
17791    appController.handleLocalStorage();
17792    appController.updateBreadCrumb();
17793    //check is Tablet
17794    let userAgent = navigator.userAgent.toLowerCase();
17795    let isTablet = /(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/.test(userAgent);
17796    let landscape = window.matchMedia("(orientation: landscape)");
17797    if(isTablet || landscape.matches){
17798        let loggedUserWidth = $('.login-content').find('.align-right').width() || null;
17799        if(loggedUserWidth){
17800            loggedUserWidth = loggedUserWidth + 75;
17801            $('.pro-logo').css('right',`${loggedUserWidth}px`)
17802        }
17803    }
17804    $(window).resize(function(){
17805        userAgent = navigator.userAgent.toLowerCase();
17806        isTablet = /(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/.test(userAgent);
17807        landscape = window.matchMedia("(orientation: landscape)");
17808        if(isTablet || landscape){
17809            loggedUserWidth = $('.login-content').find('.align-right').width() || null;
17810            if(loggedUserWidth){
17811                loggedUserWidth = loggedUserWidth + 75;
17812                $('.pro-logo').css('right',`${loggedUserWidth}px`)
17813            }
17814        }
17815    });
17816})
17817
17818
17819let appController = {
17820    adjustGenericVideo : function(){
17821        $('.rowContainer section .row > .genericAEMVideo').each(function () {
17822            $(this).find('.genericeVideoAdvisor2').addClass('generic_video_align_row');
17823        });
17824
17825        $('.rowContainer section .row > .genericYoutubeVideo').each(function () {
17826            $(this).find('.genericeVideoAdvisor2').addClass('generic_video_align_row');
17827        });
17828
17829        $('.columnctrl > .fromColumns .genericAEMVideo').each(function () {
17830            $(this).find('.genericeVideoAdvisor2').addClass('generic_video_align_columnctrl');
17831        });
17832
17833        $('.columnctrl > .fromColumns .genericYoutubeVideo').each(function () {
17834            $(this).find('.genericeVideoAdvisor2').addClass('generic_video_align_columnctrl');
17835        });
17836    },
17837    handleToolSection : function(){
17838        let pathName = window.location.pathname;
17839        const lastString = pathName.split('/')[pathName.split('/').length-2];
17840        let selector=null;
17841        let sectionId=null;
17842        let coreToggleDropdownId=null;
17843        let coreToggletabId=null;
17844        if(lastString != "") {
17845            if(lastString.includes(".")){
17846                if(lastString.split('.')[1].includes('_')){
17847                    selector = lastString.split('.')[1].split('_')[0] || null;
17848                    sectionId = lastString.split('.')[1].split('_')[1] || null;
17849                    if(selector == 'productToggle'){
17850                        coreToggleDropdownId = lastString.split('.')[1].split('_')[2] || null;
17851                        coreToggletabId  = lastString.split('.')[1].split('_')[3] || null;
17852                    }
17853                }
17854            }
17855        }
17856        if(selector == 'productToggle' && $(`#${sectionId}`).length && sectionId != null){
17857            window.onload = function () {
17858                if(coreToggleDropdownId){
17859                    $(`#${sectionId}`).next().find('#shield-value').val(`${coreToggleDropdownId}`).trigger('change');
17860                    setProductToggleTopic($(`#${sectionId}`).next().find('#shield-value option:selected').text());
17861                }
17862                if(coreToggleDropdownId && coreToggletabId){
17863                    $(`#${sectionId}-${coreToggleDropdownId}-${coreToggletabId}-label`).click();
17864                    setProductToggleTab($(`#${sectionId}-${coreToggleDropdownId}`).find('li.is-active span').text());
17865                } 
17866                document.getElementById(`${sectionId}`).scrollIntoView({
17867                    behavior: 'smooth',
17868                    block: 'center',
17869                });
17870                $('html, body').animate({
17871                    scrollTop: $(`#${sectionId}`).offset().top - 120
17872                });
17873            }
17874        }
17875    },
17876    handleLocalStorage : function(){
17877        const currentPageType = $('#pageType').val() || 'other';
17878        if(document.referrer != ''){
17879            const entries = performance.getEntriesByType("navigation");
17880            entries.forEach((entry) => {
17881                    if (entry.type !== "reload") {
17882                        appController.updateLocalStorage(currentPageType);
17883                    }
17884            });
17885        }else{
17886            appController.addLocalStorage(currentPageType);
17887        }
17888    },
17889    updateLocalStorage : function(currentPageType){
17890        let pageType = localStorage.getItem('pageType');
17891        let pageUrl =  localStorage.getItem('pageUrl');
17892        localStorage.setItem('lastPageType',pageType);
17893        localStorage.setItem('lastPageUrl',pageUrl);
17894        localStorage.setItem('pageType',currentPageType);
17895        localStorage.setItem('pageUrl',window.location.pathname);
17896    },
17897    addLocalStorage : function(currentPageType){
17898        localStorage.setItem('pageType',currentPageType);
17899        localStorage.setItem('pageUrl',window.location.pathname);
17900        localStorage.setItem('lastPageType',currentPageType);
17901        localStorage.setItem('lastPageUrl',window.location.pathname);
17902    },
17903    updateBreadCrumb : function(){
17904        const currentPageType = localStorage.getItem('pageType');
17905        const lastPageType = localStorage.getItem('lastPageType');
17906        const lastPageUrl =  localStorage.getItem('lastPageUrl');
17907        if($('.system_bread_crumb_wrapper').length && $('#hiddenSystemBreadCrumb').val() != 'true'){
17908            if(currentPageType == 'tool' && lastPageType == 'product' && lastPageUrl){
17909                $('.system_bread_crumb_wrapper').find('.breadcrumb-links').addClass('hide');
17910                $('.system_bread_crumb_wrapper').find('.tool-breadcrumb-links a').attr('href',lastPageUrl);
17911                $('.system_bread_crumb_wrapper').find('.tool-breadcrumb-links').removeClass('hide');
17912            }
17913        };
17914    },
17915    handleLogout: function(){
17916        $('#logoutLink span').on("click", function(event){
17917            if($('.module-alert-tool-wrapper').length){
17918               let moduleAlertPostLoginInfo = moduleAlert.getIsLoginSession('moduleAlertPostLogin') || null;
17919               if(moduleAlertPostLoginInfo){
17920                let updatemoduleAlertPostLoginInfo = moduleAlertPostLoginInfo.map((item) =>{
17921                    item.isLoggedModuleClose = false;
17922                    return item;
17923                });
17924                localStorage.setItem('moduleAlertPostLogin',JSON.stringify(updatemoduleAlertPostLoginInfo));
17925               }
17926            }
17927            if($('.module-encouragment-wrapper').length){
17928               localStorage.setItem('moduleEncouragementLoggedModuleClose',false);
17929            }
17930       })
17931    }
17932}
17933$(document).ready(function () {
17934    if($('.product-nav-wrapper').length){
17935        updateArrowDirections('.product-nav-wrapper .nav-links li a');
17936        updateStickyArrowDirections('.product-sticky-nav-wrapper .nav-links li a');
17937        $('.product-nav-wrapper .nav-links li a').on('click', function() {
17938            event.preventDefault();
17939            var target = $(this.getAttribute('href')); // Get the target section
17940            const headerHeight = $('.header-container').height();
17941            const navLinkHeight = $('.product-nav-wrapper .nav-links').height();
17942            const windowOuterWidth = $(window).width();
17943            let offsetHeight=null;
17944            if(windowOuterWidth >= 1024){
17945                offsetHeight = 140;
17946            }else if(windowOuterWidth >= 712){
17947                offsetHeight = navLinkHeight == 76 ? 190 : 150;
17948            }else{
17949                offsetHeight = navLinkHeight == 176 ? 300 : 250;
17950            }
17951            if (target.length) {
17952                const scrollPosition = target.offset().top-offsetHeight;
17953                $('html, body').animate({
17954                    scrollTop: scrollPosition // Animate scroll to the target section with offset
17955                }, 1000); // Duration of the scroll in milliseconds
17956            }
17957        });
17958    }
17959    if($('.product-nav-wrapper').length){
17960        productNav.productNavOnScroll();
17961    }
17962});
17963
17964
17965var productNav ={
17966    productNavOnScroll : function(){
17967        let oldScrollPos = $('.product-nav-wrapper > .row').offset().top > 1200 ? $('.product-nav-wrapper > .row').offset().top+240 : $('.product-nav-wrapper > .row').offset().top-65;
17968        $(window).on('scroll', function() {
17969			var scrollPos = window.pageYOffset;
17970            if(scrollPos >= oldScrollPos){
17971                updateStickyArrowDirections('.product-sticky-nav-wrapper .nav-links li a');
17972                $('.product-nav-wrapper').hide();
17973                $('.product-sticky-nav-wrapper').show();
17974                $('.ribbon-bar').hide();
17975            }else{
17976                updateStickyArrowDirections('.product-sticky-nav-wrapper .nav-links li a');
17977                $('.product-sticky-nav-wrapper').hide();
17978                $('.product-nav-wrapper').show();
17979                $('.ribbon-bar').show();
17980            }
17981		});
17982    }
17983}
17984
17985
17986function updateArrowDirections(element){
17987    let productNavTarget = $(element);
17988    let productNavPosition = productNavTarget.offset().top;
17989    $(element).each(function(index){
17990        let productCoreTarget = $(`.product-core-wrapper ${$(this).attr('href')}`);
17991        let productCorePosition = productCoreTarget.offset().top;
17992        let updateIconDirection = $(this).find("span .icon-new")
17993        updateIconDirection.removeClass('up-arrow-direction');
17994        updateIconDirection.addClass('down-arrow-direction');
17995        if(productCorePosition > productNavPosition){
17996            updateIconDirection.removeClass('up-arrow-direction');
17997            updateIconDirection.addClass('down-arrow-direction');
17998        }else{
17999            updateIconDirection.removeClass('down-arrow-direction');
18000            updateIconDirection.addClass('up-arrow-direction');
18001        }
18002    })
18003}
18004
18005function updateStickyArrowDirections(element){
18006    let productNavTarget = $(element);
18007    let productNavPosition = productNavTarget.offset().top;
18008    $(element).each(function(index){
18009        let productCoreTarget = $(`.product-core-wrapper ${$(this).attr('href')}`);
18010        let productCorePosition = productCoreTarget.offset().top;
18011        let updateIconDirection = $(this).find("span .icon-new")
18012        updateIconDirection.removeClass('up-arrow-direction-white');
18013        updateIconDirection.addClass('down-arrow-direction-white');
18014        if(productCorePosition > productNavPosition){
18015            updateIconDirection.removeClass('up-arrow-direction-white');
18016            updateIconDirection.addClass('down-arrow-direction-white');
18017        }else{
18018            updateIconDirection.removeClass('down-arrow-direction-white');
18019            updateIconDirection.addClass('up-arrow-direction-white');
18020        }
18021
18022        if(productCorePosition > productNavPosition){
18023            updateIconDirection.removeClass('up-arrow-direction-white');
18024            updateIconDirection.addClass('down-arrow-direction-white');
18025        }else{
18026            updateIconDirection.removeClass('down-arrow-direction-white');
18027            updateIconDirection.addClass('up-arrow-direction-white');
18028        }
18029        if(productCorePosition < productNavPosition+70){
18030            $(this).find('span').addClass('active');
18031            productNavTarget.not(this).each(function(){
18032                $(this).find('span').removeClass('active');
18033            });
18034        }
18035    })
18036}
18037
18038$(document).ready(function () {
18039    var colWidth = $(".categories").width();
18040    window.onresize = function(){
18041    var colWidth = $(".categories").width();
18042    }
18043
18044    var $grid = $(".productList").masonry({
18045        itemSelector: ".categories",
18046        columnWidth: ".categories",
18047        horizontalOrder:true,
18048        gutter: 40,
18049        fitWidth: true,
18050        transitionDuration: 0
18051    });
18052});
18053$(document).ready(function () {
18054    $('.product-feature-wrapper').each(function(e){
18055        let isCardClickable = Boolean($(this).find('#cardClickable').val());
18056        if(isCardClickable){
18057            $(this).css('cursor','pointer');
18058        }
18059        $(this).on('click', function (e) {
18060            let isCardClickable = Boolean($(this).find('#cardClickable').val());
18061            if(isCardClickable) window.location.href=$(this).find('.buttonTertiary').attr('href');
18062        });
18063    })
18064    
18065});
18066$(document).ready(function () {
18067    let userId = $('#logoutLink').data('userid');
18068    if($('.module-encouragment-wrapper').length){
18069        $('.module-encouragment-wrapper').each(function(){
18070            const uniqueId = $(this).attr('id');
18071            const compEle = $(this);
18072            $(compEle).find('.moduleText a').each(function(e){
18073                $(compEle).attr("onclick",`setCta("${$(this).text()}")`);
18074            });
18075            $(compEle).find('.module-welcome-close').on('click', function (e) {
18076                moduleEncouragment.welcomeCloseClick(e,uniqueId);
18077                e.stopPropagation();
18078            });
18079            $(compEle).find('.module-welcome-close').on('keypress', function (e) {
18080                if (e.type === 'keypress' && e.keyCode == 13) {
18081                    moduleEncouragment.welcomeCloseClick(e,uniqueId);
18082                    e.stopPropagation();
18083                }
18084            });
18085        })
18086
18087        if(userId){
18088            let moduleEncouragementPostLoginInfo = moduleAlert.getIsLoginSession('moduleEncouragementLoggedModuleClose');
18089            if(!moduleEncouragementPostLoginInfo) moduleEncouragementPostLoginInfo=[];
18090            moduleEncouragementPostLoginInfo.map(item =>{
18091                if(item.isLoggedModuleClose){
18092                    $(`#${item.uniqueId}`).hide();
18093                }else{
18094                    $(`#${item.uniqueId}`).show();
18095                }
18096            });
18097        }else{
18098            let preLoginEncouragementComponent = moduleAlert.getIsLoginSession('moduleEncouragementPrelogin');
18099            if(preLoginEncouragementComponent &&  preLoginEncouragementComponent.length){
18100                preLoginEncouragementComponent.map((item)=>{
18101                    let hours = 8;
18102                    let now = new Date().getTime();
18103                    if(item.NotLoggedModuleClose){
18104                        if((now - item.expiry) > hours * 60 * 60 * 1000){
18105                            $(`#${item.uniqueId}`).show();
18106                            var updatedPreLoginEncouragementComponent = preLoginEncouragementComponent.filter(x => {
18107                                return x.uniqueId != item.uniqueId;
18108                            })
18109                            localStorage.setItem('moduleEncouragementPrelogin',updatedPreLoginEncouragementComponent)
18110                        }else{
18111                            $(`#${item.uniqueId}`).hide();
18112                        }
18113                    }else{
18114                        $(`#${uniqueId}`).show();
18115                    }    
18116                })
18117            }
18118        }
18119        appController.handleLogout();
18120    }
18121});
18122
18123const moduleEncouragment = {
18124    getIsLoginSession : function(key){
18125        if(localStorage.getItem(key)) {
18126            try{
18127                return JSON.parse(localStorage.getItem(key));
18128            }catch(e){
18129                console.log('Error getting the session data',e);
18130            }
18131        }
18132        else {
18133            return false;
18134        }
18135    },
18136    welcomeCloseClick:function(e,uniqueId){
18137        let userId = $('#logoutLink').data('userid');
18138        if(userId){
18139            let item ={
18140                'uniqueId':uniqueId,
18141                'isLoggedModuleClose' : true
18142            }
18143            let moduleEncouragmentPostLoginInfo = moduleEncouragment.getIsLoginSession('moduleEncouragementLoggedModuleClose') || [];
18144            moduleEncouragmentPostLoginInfo = [...moduleEncouragmentPostLoginInfo,{...item}]
18145            localStorage.setItem('moduleEncouragementLoggedModuleClose',JSON.stringify(moduleEncouragmentPostLoginInfo));
18146            $(`#${uniqueId}`).hide();
18147        }else{
18148            const now = new Date();
18149            let current_time = now.getTime();
18150            let preLoginInfo = moduleEncouragment.getIsLoginSession('moduleEncouragementPrelogin');
18151            if(!preLoginInfo) preLoginInfo=[];
18152            let item ={
18153                'uniqueId':uniqueId,
18154                'NotLoggedModuleClose' : true,
18155                'expiry': current_time
18156            }
18157            preLoginInfo.push(item)
18158            localStorage.setItem('moduleEncouragementPrelogin',JSON.stringify(preLoginInfo));
18159            $(`#${uniqueId}`).hide();
18160        }
18161    }
18162}
18163$(document).ready(function () {
18164    const windowInnerHeight = window.innerHeight;
18165    $(window).on('mousewheel', function(event) {
18166        $('.product-sticky-nav-wrapper .nav-links li a').each(function(){
18167            $(this).blur(); 
18168        })
18169    });
18170    $('.product-sticky-nav-wrapper .nav-links li a').on('click', function() {
18171        var target = $(this.hash);
18172        var offsetPoint = 120;
18173        let isIpad = /iPad|iPod/i.test(navigator.userAgent);
18174        if (isIpad) {
18175            if(window.innerWidth == '1024'){
18176                var offsetPoint = (windowInnerHeight !== window.innerHeight) ? 40 : 120;
18177            }
18178        } else {
18179            var offsetPoint = 120;
18180        }
18181
18182        // align to center of screen
18183        var el = $($.attr(this, 'href'));
18184        var elOffset = el.offset().top;
18185        var elHeight = el.height();
18186        var windowHeight = $(window).height();
18187        var offset;
18188        if (elHeight < windowHeight) {
18189            offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
18190        }
18191        else {
18192            offset = elOffset;
18193        }
18194
18195        if (target.length) {
18196            // var offsettop  = offset + 120;
18197            var offsettop  = $($.attr(this, 'href')).offset().top - offsetPoint;
18198            $('html, body').animate({ scrollTop: offsettop }, 500);
18199            return false;
18200        }
18201    });
18202    $('.product-sticky-nav-wrapper .nav-backtop .backlink').on('click', function() {
18203        $('html,body').animate({
18204            scrollTop: 0
18205        }, 1000);
18206        return false;
18207    });
18208}); 
18209var productCoreToggle = {
18210    generateTabs: function(productCoreId,selectedValue,dropDownList,count,prodCoreWrapper){
18211        let hideTabsData = dropDownList.filter((val)=> val.dropdownId != selectedValue);
18212        hideTabsData.map((result)=>{
18213            $(`#${productCoreId}-${result.dropdownId} li`).each(function(index,val){
18214                $(this).find('a').attr('aria-selected','false');
18215                $(this).removeClass('is-active');
18216                $(`#${productCoreId}-${result.dropdownId}`).hide();
18217            })
18218
18219            $(`.advisor2-tabs-content.tab-${productCoreId}-${result.dropdownId}`).each(function(index,val){
18220                $(this).find('.tabs-panel').attr('aria-hidden','true');
18221                $(this).find('.tabs-panel').removeClass('is-active');
18222                $(`.advisor2-tabs-content.tab-${productCoreId}-${result.dropdownId}`).hide();
18223            })
18224        });
18225        $(`#${productCoreId}-${selectedValue} li`).each(function(index,val){
18226            $(this).find('a').attr('aria-selected','true');
18227            $(this).addClass(`${!index ? 'is-active' :''}`);
18228            if(!index){
18229                setProductToggleTab($(this).find('a span').text());
18230                productCoreToggle.updateArrayTab(productCoreId,$(this).find('a span').text());
18231                productCoreToggle.updateJsonTab(count,$(this).find('a span').text());
18232            }
18233            $(`#${productCoreId}-${selectedValue}`).show();
18234        })
18235        $(`#${productCoreId}-${selectedValue}`).on('change.zf.tabs', function(event){
18236            $(prodCoreWrapper).find('.advisor2-tabs-content .tabs-panel').removeClass('is-active');
18237        	$(prodCoreWrapper).find('.advisor2-tabs-content .tabs-panel').attr('aria-hidden',true);
18238            let panelId = $(this).find('li.is-active a').attr('data-parent-id');
18239            $(`${panelId}`).addClass('is-active');
18240            $(`${panelId}`).attr('aria-hidden',false);
18241            setProductToggleTab($(this).find('li.is-active span').text());
18242            productCoreToggle.updateJsonTab(count,$(this).find('li.is-active span').text());
18243            productCoreToggle.updateArrayTab(productCoreId,$(this).find('li.is-active span').text());
18244            let tabId = $(this).find('li.is-active').attr('tab-id');
18245            productCoreToggle.updateSessionObject(productCoreId,selectedValue,tabId);
18246        });
18247        $(`.advisor2-tabs-content.tab-${productCoreId}-${selectedValue}`).each(function(index,val){
18248            $(this).find('.tabs-panel').first().attr('aria-hidden','false');
18249            $(this).find('.tabs-panel').first().addClass('is-active');
18250            $(`.advisor2-tabs-content.tab-${productCoreId}-${selectedValue}`).show();
18251        })
18252        $(`#${productCoreId}-${selectedValue} li`).first().addClass('is-active');
18253        $(`.advisor2-tabs-content.tab-${productCoreId}-${selectedValue} > .tabs-panel`).first().attr('aria-hidden','false');
18254        $(`#${productCoreId}-${selectedValue}`).show();
18255        $(`.advisor2-tabscontent.tab-${productCoreId}-${selectedValue}`).show();
18256    },
18257    updatedArrayproductCoreToggleAnyltics: function(productCoreId,productCoreName,selectDrodownName,selectedTabName){
18258        const productCoreToggleAnyltics={
18259            productCoreId:'',
18260            productCoreTitle:'',
18261            selectedTopic: '',
18262            selectedTab: ''
18263        }
18264        productCoreToggleAnyltics.productCoreId=productCoreId;
18265        productCoreToggleAnyltics.productCoreTitle=productCoreName;
18266        productCoreToggleAnyltics.selectedTopic=selectDrodownName;
18267        productCoreToggleAnyltics.selectedTab=selectedTabName;
18268        setProductToggleAnalytics(productCoreToggleAnyltics);
18269    },
18270    updateArrayTopic:function(productCoreId,selectDrodownName){
18271        digitalData.productCoreToggleArray[digitalData.productCoreToggleArray.findIndex(el => el.productCoreId === productCoreId)].selectedTopic = selectDrodownName;
18272    },
18273    updateArrayTab:function(productCoreId,tabName){
18274        digitalData.productCoreToggleArray[digitalData.productCoreToggleArray.findIndex(el => el.productCoreId === productCoreId)].selectedTab = tabName;
18275    },
18276    //json key
18277    updateJsonProductToggleAnlytics:function(count,productCoreId,productCoreName,selectDrodownName,selectedTabName){
18278        const productCoreToggleAnyltics={
18279            [`productCoreToggle-${count}`]:{
18280                productCoreId:'',
18281                productCoreTitle:'',
18282                selectedTopic: '',
18283                selectedTab: ''
18284            }
18285        }
18286        productCoreToggleAnyltics[`productCoreToggle-${count}`].productCoreId=productCoreId;
18287        productCoreToggleAnyltics[`productCoreToggle-${count}`].productCoreTitle=productCoreName;
18288        productCoreToggleAnyltics[`productCoreToggle-${count}`].selectedTopic=selectDrodownName;
18289        productCoreToggleAnyltics[`productCoreToggle-${count}`].selectedTab=selectedTabName;
18290        setJsonProductToggleAnalytics(productCoreToggleAnyltics)
18291    },
18292    updateJsonTopic: function(count,selectDrodownName){
18293        digitalData[`productCoreToggle-${count}`]['selectedTopic']=selectDrodownName;
18294    },
18295    updateJsonTab: function(count,tabName){
18296        digitalData[`productCoreToggle-${count}`]['selectedTab']= tabName;
18297    },
18298    setSessionObject: function(productCoreId,selectDrodownValue,tabId){
18299        let sessionStoredObjects = JSON.parse(sessionStorage.getItem("storedSessionObjects"));
18300        if(!sessionStoredObjects){
18301            let sessionStorageArray = [{
18302                productCoreId:productCoreId,
18303                selectDrodownValue:selectDrodownValue,
18304                tabId:tabId
18305            }]
18306            sessionStorage.setItem("storedSessionObjects",JSON.stringify(sessionStorageArray));
18307        }else{
18308	        let sessionStorageArray = [...sessionStoredObjects, {
18309                productCoreId:productCoreId,
18310                selectDrodownValue:selectDrodownValue,
18311                tabId:tabId
18312            }]
18313            sessionStorage.setItem("storedSessionObjects",JSON.stringify(sessionStorageArray));
18314        }
18315    },
18316    updateSessionObject : function(productCoreId,theSelection,tabId){
18317        let sessionStoredObjects = JSON.parse(sessionStorage.getItem("storedSessionObjects"));
18318        sessionStoredObjects.forEach(sessionObject=>{
18319            if(sessionObject.productCoreId === productCoreId){
18320                sessionObject.selectDrodownValue = theSelection;
18321                sessionObject.tabId = tabId;
18322            }
18323        })
18324        sessionStorage.setItem("storedSessionObjects",JSON.stringify(sessionStoredObjects));
18325    },
18326    getSessionObject:function(productCoreId){
18327        let sessionStoredObjects = JSON.parse(sessionStorage.getItem("storedSessionObjects"));
18328        let sessionStorageArray = sessionStoredObjects.filter(element=>{
18329            return element.productCoreId === productCoreId;
18330        })
18331        let toUpdateValueObject = sessionStorageArray[0];
18332        $('.product-core-wrapper').find("#shield-value").each(function(index, element) {
18333            if ($(element).attr("data-parent-id") === productCoreId) {
18334                $(element).select2();
18335                $(element).val(toUpdateValueObject.selectDrodownValue).trigger("change");
18336            }
18337        });
18338        $('.product-core-wrapper').each((parentIndex,parentElement)=>{
18339            if($(parentElement).find(".headline").attr("id") === productCoreId){
18340             $(parentElement).find('.advisor2-tabs-list li').each((index,element)=>{
18341               if($(element).attr("tab-id") === toUpdateValueObject.tabId){
18342                 $(element).addClass('is-active');
18343                 let panelId = $(element).find('a').attr('data-parent-id');
18344                 $(`${panelId}`).addClass('is-active');
18345                 $(`${panelId}`).attr('aria-hidden',false);
18346                 $(`#${productCoreId}-${toUpdateValueObject.selectDrodownValue}`).show();
18347                 $(`.advisor2-tabs-content.tab-${productCoreId}-${toUpdateValueObject.selectDrodownValue}`).show();
18348               }
18349             })
18350            }
18351        })
18352    }
18353}
18354
18355$(document).ready(function () {
18356    if($('.product-core-toggle-wrapper').length){
18357        $('.product-core-wrapper').each(function(index,val){
18358            const count = ++index;
18359            $(this).find('#shield-value').select2({
18360                escapeMarkup: function(markup) {
18361                    return markup;
18362                },
18363            });
18364            let prodCoreWrapper = $(this);
18365            let productCoreId = $(this).find('.headline').attr('id');
18366            let productCoreName = $(this).find('.headline').text().trim();
18367            let selectDrodownValue =  $(this).find('#shield-value').val();
18368            const selectDrodownName = $(this).find( "#shield-value option:selected" ).text();
18369            const selectedTabName = $(this).find('.advisor2-tabs-list li:first').find('a span').text();
18370            setProductToggleTopic(selectDrodownName);
18371            setProductToggleTab(selectedTabName);
18372            productCoreToggle.updatedArrayproductCoreToggleAnyltics(productCoreId,productCoreName,selectDrodownName,selectedTabName);
18373            productCoreToggle.updateJsonProductToggleAnlytics(count,productCoreId,productCoreName,selectDrodownName,selectedTabName);
18374            let sessionStorageObject = JSON.parse(sessionStorage.getItem("storedSessionObjects"));
18375            let isProdCoreIdExist;
18376            if(sessionStorageObject){
18377                isProdCoreIdExist = $(sessionStorageObject).get().some((sessionData)=>{
18378                    return productCoreId == sessionData.productCoreId;
18379                })
18380            }
18381            let isEdit = $("#isEdit").val().trim() === "true";
18382            let isPreview = $("#isPreview").val().trim() === "true";
18383            if(selectDrodownValue){
18384                if(!sessionStorageObject|| !isProdCoreIdExist || (!isEdit && !isPreview)){
18385                    $(this).find('.advisor2-tabs-list li:first').addClass('is-active');
18386                    $(this).find('.advisor2-tabs-content .tabs-panel:first').addClass('is-active');
18387                    $(this).find('.advisor2-tabs-content .tabs-panel:first').attr('aria-hidden',false);
18388                    $(this).find(`#${productCoreId}-${selectDrodownValue}`).show();
18389                    $(this).find(`.advisor2-tabs-content.tab-${productCoreId}-${selectDrodownValue}`).show();
18390                    let tabId =  $(this).find('.advisor2-tabs-list li:first').attr("tab-id")
18391                    productCoreToggle.setSessionObject(productCoreId,selectDrodownValue,tabId);
18392                }else if(isProdCoreIdExist){
18393                    productCoreToggle.getSessionObject(productCoreId);
18394                }
18395            }
18396            let dropdownValue = $(this).find('#shield-value').val();
18397            $(this).find('#shield-value').on("change", function(e) {
18398                var theSelection = $(this).val();
18399                const selectDrodownName = $(this).find('option:selected').text();
18400                let selectedvalue = theSelection;
18401                let dropDownList = [];
18402                $(this).find('option').each(function(){
18403                    dropDownList.push({
18404                      "dropdownId":$(this).val()
18405                    })
18406                });
18407                let tabId = $(prodCoreWrapper).find(`#${productCoreId}-${theSelection}`).find('li:first').attr('tab-id')
18408                productCoreToggle.updateSessionObject(productCoreId,theSelection,tabId)
18409                setProductToggleTopic(selectDrodownName);
18410                productCoreToggle.updateArrayTopic(productCoreId,selectDrodownName);
18411                productCoreToggle.updateJsonTopic(count,selectDrodownName);
18412                productCoreToggle.generateTabs(productCoreId,selectedvalue,dropDownList,count,prodCoreWrapper);
18413                dropdownValue = theSelection;
18414            });
18415            $(this).find(`#${productCoreId}-${dropdownValue}`).on('change.zf.tabs', function(event){
18416                //removing all
18417                $(prodCoreWrapper).find('.advisor2-tabs-content .tabs-panel').removeClass('is-active');
18418        		$(prodCoreWrapper).find('.advisor2-tabs-content .tabs-panel').attr('aria-hidden',true);
18419            	//showing the particular
18420				let panelId = $(this).find('li.is-active a').attr('data-parent-id');
18421                $(`${panelId}`).addClass('is-active');
18422                $(`${panelId}`).attr('aria-hidden',false);
18423            	///
18424                let tabId = $(this).find('li.is-active').attr('tab-id');
18425                productCoreToggle.updateSessionObject(productCoreId,dropdownValue,tabId)
18426                setProductToggleTab($(this).find('li.is-active span').text());
18427                productCoreToggle.updateArrayTab(productCoreId,$(this).find('li.is-active span').text());
18428                productCoreToggle.updateJsonTab(count,$(this).find('li.is-active span').text());
18429            });
18430        })
18431    }
18432});
18433$(document).ready(function () {
18434    if($('.advisor2.card-video-mini-wrapper').length){
18435        $('.advisor2.card-video-mini-wrapper').each(function(){
18436            let parentelement = $(this);
18437            let isCardClickable = $(this).attr('data-card-clickable');
18438            if(isCardClickable){
18439                $(this).css('cursor','pointer');
18440                $(this).on('click', function(event) {
18441                    event.preventDefault();
18442                    $(this).find('.genericVideo_advisor').trigger("click");
18443                })
18444            }
18445            $(this).find('.description a').each(function(e){
18446                $(this).on('click',function(event){
18447                    setCta(this.text,this);
18448                })
18449            });
18450            if(homePageVideo.ElementExist($(this).find('#cardVideoMiniPromote'))){
18451                $(this).find('#cardVideoMiniPromote').on("click",function(event){
18452                    $(parentelement).find('.genericVideo_advisor').trigger("click");
18453                })
18454            }
18455        });
18456    }
18457});
18458$(document).ready(function () {
18459    $('.card-featured-primary-wrapper').each(function(e){
18460        let isCardClickable = Boolean($(this).find('#cardClickable').val());
18461        if(isCardClickable){
18462            $(this).css('cursor','pointer');
18463        }
18464        $(this).on('click', function (e) {
18465            let isCardClickable = Boolean($(this).find('#cardClickable').val());
18466            if(isCardClickable) {
18467                let target = $(this).attr('data-buttonTarget');
18468                if(target){
18469                    window.open($(this).find('.buttonTertiary').attr('href'),'_blank');
18470                }else{
18471                    window.open($(this).find('.buttonTertiary').attr('href'),'_self');
18472                }
18473            }
18474        });
18475    })
18476    
18477});
18478$(document).ready(function () {
18479    if($('.advisor2.card-video-primary-wrapper').length){
18480        $('.advisor2.card-video-primary-wrapper').each(function(){
18481            let isCardClickable = $(this).attr('data-card-clickable');
18482            if(isCardClickable){
18483                $(this).css('cursor','pointer');
18484                $(this).off('click');
18485                $(this).on('click', function(event) {
18486                    $(this).find('.buttonPrimary.genericVideo_advisor').trigger("click");
18487                })
18488            }
18489            let VideoDuration = $(this).find('.youtube.content-label').attr('data-metaVideoDuration');
18490            try{
18491                let videoMinute = VideoDuration.split('M')[0];
18492                let videoSecond = VideoDuration.split('M')[1].split('S')[0];
18493                if(videoSecond >= 30){
18494                    videoMinute = parseInt(videoMinute) + 1
18495                }else{
18496                    videoMinute = parseInt(videoMinute);
18497                }
18498                $(this).find('.youtube.content-label').text(`${videoMinute}-Minute Video`);
18499            }catch{
18500                return;
18501            }
18502        })
18503       
18504    }
18505});
18506$(document).ready(function () {
18507    $('.sidebar-cardfeature-wrapper').each(function(e){
18508        let isCardClickable = Boolean($(this).find('#cardClickable').val());
18509        let target = $(this).attr('data-buttonTarget');
18510        $(this).find('.card-sidebar').on('click', function (e) {
18511            if(isCardClickable) {
18512                if(target){
18513                    window.open($(this).find('.card-title-link').attr('href'),'_blank');
18514                }else{
18515                    window.open($(this).find('.card-title-link').attr('href'),'_self');
18516                }
18517            }
18518        });
18519        if(isCardClickable){
18520            $(this).find('.card-sidebar').css('cursor','pointer');
18521        }
18522    })
18523});
18524$(document).ready(function () {
18525    if($('.advisor2.card-tool-primary-wrapper').length){
18526        $('.advisor2.card-tool-primary-wrapper').each(function(){
18527            let isCardClickable = Boolean($(this).attr('data-card-cl
18527ickable'));
18528            if(isCardClickable){
18529                $(this).css('cursor','pointer');
18530            }
18531            $(this).on('click', function (e) {
18532                let isCardClickable = Boolean($(this).attr('data-card-clickable'));
18533                if(isCardClickable) {
18534                    let target = $(this).attr('data-buttonTarget');
18535                    if(target){
18536                        window.open($(this).find('.buttonPrimary').attr('href'),'_blank');
18537                    }else{
18538                        window.open($(this).find('.buttonPrimary').attr('href'),'_self');
18539                    }
18540                }
18541            });
18542        });
18543    }
18544});
18545var sidebarCardToolPrimary = {
18546    consentModalOpenEvent: function ($elem, modal) {
18547        $elem.on("click", function(){
18548            sidebarCardToolPrimary.consentOpenModal(modal);
18549        })
18550    },
18551    consentOpenModal: function (modalElem) {
18552        setTimeout(function () {
18553            new Foundation.Reveal($('#' + modalElem)).open();
18554            revealCenterAlign.revealRePosition();
18555            $('.reveal-overlay').addClass('reveal-overlay-advisor2-modal');
18556            $('.reveal-overlay').animate({ scrollTop: 0 }, 10);
18557            sidebarCardToolPrimary.dynmicMargin();
18558        }, 10);
18559    },
18560    dynmicMargin: function () {
18561        if ($('.revokeConsentSection').length) {
18562            var isIphonePad = /iphone|ipad/i.test(navigator.userAgent.toLocaleLowerCase());
18563            if (isIphonePad && $(window).width() < 991) {
18564                let dynamicMargin = ($(window).width() - $('.revokeConsentSection .customWidth').width()) / 2;
18565                $('.revokeConsentSection .customWidth').css({ 'margin-left': dynamicMargin + 'px', 'margin-right': dynamicMargin + 'px' });
18566            }
18567            else {
18568                $('.revokeConsentSection .customWidth').css({ 'margin-left': '', 'margin-right': '' });
18569            }
18570        }
18571    },
18572}
18573
18574$(document).ready(function () {
18575    if($('.advisor2.sidebar-cardtool-wrapper').length){
18576        $('.advisor2.sidebar-cardtool-wrapper').each(function(){
18577            let isCardClickable = Boolean($(this).attr('data-card-clickable'));
18578            if(isCardClickable){
18579                $(this).css('cursor','pointer');
18580            }
18581            $(this).on('click', function (e) {
18582                let isCardClickable = Boolean($(this).attr('data-card-clickable'));
18583                if(isCardClickable) {
18584                    let target = $(this).attr('data-buttonTarget');
18585                    if(target){
18586                        window.open($(this).find('.card-title-link').attr('href'),'_blank');
18587                    }else{
18588                        window.open($(this).find('.card-title-link').attr('href'),'_self');
18589                    }
18590                }
18591            });
18592        });
18593    }
18594});
18595const utilityAccordion = {
18596    enableParsys : function(parentElement,selectedValue){
18597        let utilityAccordionParsys = 'utility-accordion-'+selectedValue+'-parsys';
18598        $(parentElement).find(`.head-title.${utilityAccordionParsys}`).removeClass("hide");
18599        $(parentElement).find(`#${utilityAccordionParsys}`).removeClass("hide");
18600        $(parentElement).find(`#${utilityAccordionParsys}`).removeClass("marginBottom");
18601    },
18602
18603    enableAllParsys: function(parentElement,dropDownElement,selectedValue){
18604        $(dropDownElement).find('option').each(function(){
18605            if($(this).val() != selectedValue){
18606                let utilityAccordionParsys = 'utility-accordion-'+$(this).val()+'-parsys';
18607                $(parentElement).find(`.head-title.${utilityAccordionParsys}`).removeClass("hide");
18608                $(parentElement).find(`#${utilityAccordionParsys}`).removeClass("hide");
18609                $(parentElement).find(`#${utilityAccordionParsys}`).addClass("marginBottom");
18610            }
18611        });
18612    },
18613    parsysReset : function(parentElement,selectedValue,topicList){
18614        let hideUtilityAccordionParsys = topicList.filter((val)=> val.topicValue != selectedValue);
18615        hideUtilityAccordionParsys.map((result)=>{
18616            $(parentElement).find(`.head-title.utility-accordion-${result.topicValue}-parsys`).each(function(index,val){
18617                $(this).addClass('hide');
18618            })
18619            $(parentElement).find(`#utility-accordion-${result.topicValue}-parsys`).each(function(index,val){
18620                $(this).addClass('hide');
18621                $(this).removeClass("marginBottom");
18622            })
18623        });
18624    }
18625}
18626
18627
18628
18629$(document).ready(function () {
18630    $('.utility-accordion-wrapper').each(function(index){
18631        let parentElement = $(this);
18632        let dropDownelement = $(this).find('#utility-accordion-topic-value');
18633        let selectedTopicValue=null;
18634        $(this).find('#utility-accordion-topic-value').select2({
18635            escapeMarkup: function(markup) {
18636                return markup;
18637            },
18638        });
18639        $(dropDownelement).each(function(index){
18640            selectedTopicValue = $(this).val();
18641            if(selectedTopicValue == "All"){
18642                utilityAccordion.enableAllParsys(parentElement,dropDownelement,selectedTopicValue);
18643            }else{
18644                utilityAccordion.enableParsys(parentElement,selectedTopicValue);
18645            }
18646        });
18647        $(dropDownelement).on("change", function(e) {
18648            selectedTopicValue = $(this).val();
18649            let topicList =[];
18650            if(selectedTopicValue == "All"){
18651                utilityAccordion.enableAllParsys(parentElement,dropDownelement,selectedTopicValue);
18652            }else{
18653                $(this).find('option').each(function(){
18654                    topicList.push({
18655                      "topicValue":$(this).val()
18656                    })
18657                });
18658                utilityAccordion.parsysReset(parentElement,selectedTopicValue,topicList);
18659                utilityAccordion.enableParsys(parentElement,selectedTopicValue)
18660            }
18661        });
18662    });
18663});
18664$(document).ready(function () {
18665    if($('.advisor2.sidebar-cardvideo-wrapper').length){
18666        $('.advisor2.sidebar-cardvideo-wrapper').each(function(){
18667            let sidebarCardParentWrapper = $(this);
18668            let isCardClickable = $(this).attr('data-card-clickable');
18669            let cardTitleLinkElement = $(this).find('.card-title-link');
18670            if(isCardClickable){
18671                $(this).find('.cardvideo').css('cursor','pointer');
18672                $(this).find('.cardvideo').off('click');
18673                $(this).find('.cardvideo').on('click', function(event) {
18674                    $(this).find('.genericVideo_advisor').trigger("click");
18675                })
18676            }
18677
18678            $(cardTitleLinkElement).on("click", function(e){
18679                $(sidebarCardParentWrapper).find('.genericVideo_advisor').trigger("click");
18680            })
18681        })
18682       
18683    }
18684});
18685$(document).ready(function () {
18686    if($('.advisor2.card-tool-mini-wrapper').length){
18687        $('.advisor2.card-tool-mini-wrapper').each(function(){
18688            let isCardClickable = Boolean($(this).attr('data-card-clickable'));
18689            if(isCardClickable){
18690                $(this).css('cursor','pointer');
18691            }
18692            $(this).on('click', function (e) {
18693                let isCardClickable = Boolean($(this).attr('data-card-clickable'));
18694                if(isCardClickable) {
18695                    let target = $(this).find('.card-tool-mini-description a').attr('target');
18696                    if(target == '_blank'){
18697                        window.open($(this).find('.card-tool-mini-description a').attr('href'),'_blank');
18698                    }else{
18699                        window.open($(this).find('.card-tool-mini-description a').attr('href'),'_self');
18700                    }
18701                }
18702            });
18703        });
18704    }
18705});
18706$(document).ready(function () {
18707    if($('.utiity-table-wrapper').length){
18708        $('.utiity-table-wrapper').each(function(){
18709            let info = {
18710                "nodeUrl" : $(this).attr('data-url')
18711            };
18712            utilityTableMethods.loadMoreText = $(this).find('#utility_loadtext').val();
18713            if($(this).find('.advisor2-tabs-list #utlity-tabs').length){
18714                let tabelElement = $(this);
18715                //tabs exist
18716                let utilityTableData =null;
18717                $.ajax({
18718                    url: '/content.utilityTable.csv',
18719                    type: 'POST',
18720                    data:info,
18721                    async: false,
18722                    success: successHandler,
18723                    error: function (error) {
18724                        console.log("error--->",error);
18725                    }
18726                });
18727                function successHandler(data){
18728                    utilityTableMethods.tableData = {...utilityTableMethods.tableData,...data};
18729                    utilityTableData = data;
18730                    if(utilityTableData){
18731                        $(tabelElement).find('.advisor2-tabs-list #utlity-tabs li').each(function(index){
18732                            let tableRowsAndColumns = null;
18733                            let tableFiltersData = null;
18734                            let utilityTableLoadMore = null;
18735                            let tabId = $(this).find('a').attr('tabId');
18736                            let tabReferenceId = $(this).find('a').attr('href');
18737                            let tab_parentlement = $(`#${tabId}`);
18738                            let tabEachTableData = null;
18739                            let tabIdIndex = index+1;
18740                            let tableKey = `utilityTab${++index}`;
18741                            tabEachTableData = utilityTableData[tableKey];
18742                            tableRowsAndColumns = utilityTableMethods.getTableData(tab_parentlement,tabEachTableData);
18743                            tableFiltersData = utilityTableMethods.getFilterData(tabEachTableData);
18744        
18745                            utilityTableLoadMore ={
18746                                startIndex:0,
18747                                showCount :0,
18748                                hiddenResults:'',
18749                                utilityTableLoadMoreDataElements:'',
18750                                utilityTableLoadMoreDataLength:0,
18751                            }
18752                            utilityTableMethods.generateColumns($(tab_parentlement).find('#utilityTable'),tableRowsAndColumns[0]);
18753                            utilityTableMethods.generateRows($(tab_parentlement).find('#utilityTable'),tableRowsAndColumns);
18754                            utilityTableMethods.generateFilterData(utilityTableLoadMore,tab_parentlement,$(tab_parentlement).find('.utility-table-filters'),tableFiltersData,tabEachTableData,tabIdIndex);
18755                            utilityTableMethods.generateSearch(utilityTableLoadMore,tab_parentlement,$(tab_parentlement).find('.utility-table-filters'),tableFiltersData,tabEachTableData);
18756                            utilityTableMethods.generatePagination(utilityTableLoadMore,tab_parentlement);
18757                            utilityTableMethods.loadMoreTableResults(utilityTableLoadMore,tab_parentlement,utilityTableMethods.loadMoreText);
18758                            utilityTableMethods.adjustTooltipHeight();
18759                            $(tabelElement).find("#utlity-tabs").on('change.zf.tabs', function(event){
18760                                utilityTableMethods.adjustTooltipHeight();
18761                                $(this).find('li').each(function(){
18762                                    $(`#${$(this).attr('tabId')}`).attr('aria-hidden',true);
18763                                    if($(this).hasClass('is-active')){
18764                                        $(`#${$(this).attr('tabId')}`).attr('aria-hidden',false);
18765                                    }
18766                                })
18767                            });
18768                            utilityTableMethods.handleTooltipClick();
18769                            setTimeout(() => {
18770                                utilityTableMethods.handleAnchorSection(utilityTableLoadMore,tabId,tab_parentlement,$(tab_parentlement).find('.utility-table-filters'),tableFiltersData,tabEachTableData);
18771                            }, 300);
18772                            if(index==1){
18773                                $(`#${tabId}`).attr('aria-hidden',false);
18774                            }
18775                        })
18776                    }else{
18777                        console.log("no data found");
18778                    }
18779                }
18780                
18781            }
18782            else{
18783                let parentElement = $(this).find('#singleTable');
18784                let utilityTableData =null;
18785                $.ajax({
18786                    url: '/content.utilityTable.csv',
18787                    type: 'POST',
18788                    data:info,
18789                    async: false,
18790                    success: function (data) {
18791                        utilityTableData = data.utilityTab1;
18792                        if(utilityTableData){
18793                            let tableRowsAndColumns = null;
18794                            let tableFiltersData = null;
18795                            let utilityTableLoadMore = null;
18796                            tableRowsAndColumns = utilityTableMethods.getTableData(parentElement,utilityTableData);
18797                            tableFiltersData = utilityTableMethods.getFilterData(utilityTableData);
18798                            utilityTableLoadMore ={
18799                                startIndex:0,
18800                                showCount :0,
18801                                hiddenResults:'',
18802                                utilityTableLoadMoreDataElements:'',
18803                                utilityTableLoadMoreDataLength:0,
18804                            }
18805                            utilityTableMethods.generateColumns($(parentElement).find('#utilityTable'),tableRowsAndColumns[0]);
18806                            utilityTableMethods.generateRows($(parentElement).find('#utilityTable'),tableRowsAndColumns);
18807                            utilityTableMethods.generateFilterData(utilityTableLoadMore,parentElement,$(parentElement).find('.utility-table-filters'),tableFiltersData,utilityTableData);
18808                            utilityTableMethods.generateSearch(utilityTableLoadMore,parentElement,$(parentElement).find('.utility-table-filters'),tableFiltersData,utilityTableData);
18809                            utilityTableMethods.generatePagination(utilityTableLoadMore,parentElement);
18810                            utilityTableMethods.loadMoreTableResults(utilityTableLoadMore,parentElement);
18811                            utilityTableMethods.adjustTooltipHeight();
18812                            utilityTableMethods.handleTooltipClick();
18813                            setTimeout(() => {
18814                                utilityTableMethods.handleAnchorSection(utilityTableLoadMore,null,parentElement,$(parentElement).find('.utility-table-filters'),tableFiltersData,utilityTableData);
18815                            }, 300);
18816                        }else{
18817                            console.log("no data found")
18818                        }
18819                    },
18820                    error: function (error) {
18821                        console.log("error--->",error);
18822                    }
18823                });
18824            }
18825        });
18826    }
18827});
18828
18829
18830
18831let utilityTableMethods = {
18832    loadMoreText: null,
18833    tableData:[],
18834    handleAnchorSection: function(utilityTableLoadMore,tabId,parentElement,element,filterData,utilityTableData){
18835        let pathName = window.location.pathname;
18836        // qa build change id
18837        const lastString = pathName.split('/')[pathName.split('/').length-2];
18838        
18839        let selector=null;
18840        let sectionId=null;
18841        if(lastString != "") {
18842            if(lastString.includes(".")){
18843                if(lastString.split('.')[1].includes('_')){
18844                    selector = lastString.split('.')[1].split('_')[0] || null;
18845                    sectionId = lastString.split('.')[1].split('_')[1] || null;
18846                    if(selector == 'utilityTable'){
18847                        // get neccsarry data here
18848                        const anchorTabId = lastString.split('.')[1].split('_')[2] || null;
18849                        if(anchorTabId != null && tabId){
18850                            if(anchorTabId == tabId){
18851                                utilityTableMethods.getTableIds(utilityTableLoadMore,parentElement,element,filterData,utilityTableData,selector,sectionId,tabId,lastString);
18852                            }
18853                        }else{
18854                            utilityTableMethods.getTableIds(utilityTableLoadMore,parentElement,element,filterData,utilityTableData,selector,sectionId,tabId,lastString);
18855                            window.onload = function () {
18856                                utilityTableMethods.performUtilityTableSection(sectionId);
18857                            }
18858                        }
18859                    }
18860                }
18861            }
18862        }
18863    },
18864    getTableIds : function(utilityTableLoadMore,parentElement,element,filterValues,utilityTableData,selector,sectionId,tabId,lastString){
18865        let filterInfo = null;
18866        let filterData=[];
18867        let searchValue = null;
18868        // and qa build change value
18869        if(lastString.split('.').length > 2){
18870            // filter information
18871            filterInfo = lastString.split('.')[lastString.split('.').length-1];
18872            const isSearchKey = filterInfo.split('=')[0] == 'searchKey' ? true : false;
18873            if(filterInfo.split('__').length && !isSearchKey){
18874                filterInfo.split('__').map((val,index) =>{
18875                    const filterId = val.split('=')[0]
18876                    const filterValue = decodeURI(val.split('=')[1]);
18877                    filterData.push({
18878                        "filterId":filterId,
18879                        "filterValue":filterValue
18880                    })
18881                })
18882            }else if(isSearchKey){
18883                searchValue = decodeURI(filterInfo.split('=')[1]) || null;
18884            }
18885            else{
18886                window.onload = function () {
18887                    utilityTableMethods.performUtilityTableSection(sectionId);
18888                }
18889            }
18890        }
18891        utilityTableMethods.performUtilityTable(utilityTableLoadMore,parentElement,element,filterValues,utilityTableData,selector,sectionId,tabId,filterData,searchValue)
18892    },
18893    performUtilityTable: function(utilityTableLoadMore,parentElement,element,filterValues,utilityTableData,selector,sectionId,tabId,filterData,searchValue){
18894        if(Object.keys(filterValues).length) utilityTableMethods.performUtilityTableFilter(utilityTableLoadMore,parentElement,element,filterValues,utilityTableData,sectionId,tabId,filterData);
18895        if(searchValue){
18896            if(sectionId && tabId) $(`#${sectionId}`).find(`#${tabId}`).find('.searchKeyword').val(searchValue.toLowerCase());
18897            utilityTableMethods.tableSearchHandler(parentElement,utilityTableLoadMore,element,searchValue.toLowerCase(),filterValues,utilityTableData)
18898        };
18899        window.onload = function () {
18900            if(sectionId && tabId) $(`#${sectionId}`).find(`#${tabId}-label`).click();
18901            utilityTableMethods.performUtilityTableSection(sectionId);
18902        }
18903    },
18904    performUtilityTableSection: function(sectionId){
18905        document.getElementById(`${sectionId}`).scrollIntoView({
18906            behavior: 'smooth',
18907            block: 'center',
18908        });
18909        $('html, body').animate({
18910            scrollTop: $(`#${sectionId}`).offset().top - 120
18911        });
18912    },
18913    performUtilityTableFilter : function(utilityTableLoadMore,parentElement,element,filterValues,utilityTableData,sectionId,tabId,filterData){
18914        filterData.map((val,index)=>{
18915            const tabIdentifier = tabId ? tabId : '';
18916            $(`#${sectionId} #${tabIdentifier}`).find(`#${val.filterId}`).val(`${val.filterValue}`).trigger('change');
18917            const filterId =  val.filterId;
18918            const filterTypeKey =  val.filterId;
18919            const filterText = val.filterValue;
18920            const filterValue = val.filterValue;
18921            const tabIdIndex = '';
18922            utilityTableMethods.updateDropdownValues(element,tabId,filterId,filterText,filterValue,tabIdIndex,filterData);
18923            utilityTableMethods.tableFilterHandler(parentElement,utilityTableLoadMore,element,filterTypeKey,filterValue,filterText,filterValues,utilityTableData);
18924        })
18925    },
18926    handleTooltipClick:function(){
18927        let screenSize = $(window).width();
18928        if(screenSize > 1024){
18929            $('.utlity-table .tool-tip-table').addClass('hoverTooltip');
18930        }
18931        $('.utlity-table .tool-tip-table').unbind().bind("click",function(e){
18932            e.stopPropagation();
18933            const element = $(this);
18934            $('.utlity-table .tool-tip-table').find('.tooltip-text').each(function(){
18935                if($(this).not($(element).find('.tooltip-text')).is('.active')){
18936                    $(this).removeClass('active');
18937                    $(this).removeClass('inactive');
18938                }
18939            });
18940            if(screenSize < 1024){
18941                if($(element).find('.tooltip-text').is('.active')){
18942                    $(element).find('.tooltip-text').removeClass('active');
18943                    $(element).find('.tooltip-text').addClass('inactive');
18944                    $(element).find('.tooltip-text').removeClass('inactive');
18945                }else{
18946                    $(element).find('.tooltip-text').removeClass('inactive');
18947                    $(element).find('.tooltip-text').addClass('active');
18948                }
18949            }
18950        });
18951        if(screenSize < 1024){
18952            $(document).on("click",function(e){
18953                if($('.utiity-table-wrapper').length){
18954                    $('.utlity-table .tool-tip-table').find('.tooltip-text').removeClass('active');
18955                    $('.utlity-table .tool-tip-table').find('.tooltip-text').removeClass('inactive');
18956                }
18957            });
18958        }
18959    },
18960    adjustTooltipHeight : function(){
18961        let screenSize = $(window).width();
18962        $('.filter-field-label').each(function(index,val){
18963            if($(this).find('.advisor2.tool-tip-table').length && $(this).find('.tooltip-text.top.align-center').length){
18964                const reactTabletTooltip = $(this).find('.tooltip-text.top.align-center')[0].getBoundingClientRect();
18965                $(this).find('.tooltip-text.top.align-center').css('top',-(reactTabletTooltip.height+13)+'px');
18966            }
18967            if($(this).find('.advisor2.tool-tip-table').length && $(this).find('.tooltip-text.top.align-right').length){
18968                const reactTabletTooltip = $(this).find('.tooltip-text.top.align-right')[0].getBoundingClientRect();
18969                $(this).find('.tooltip-text.top.align-right').css('top',-(reactTabletTooltip.height+13)+'px');
18970            }
18971        })
18972        $('.report-head').each(function(index,val){
18973            if($(this).find('.advisor2.tool-tip-table').length && $(this).find('.tooltip-text.top.align-center').length){
18974                const reactTabletTooltip = $(this).find('.tooltip-text.top.align-center')[0].getBoundingClientRect();
18975                $(this).find('.tooltip-text.top.align-center').css('top',-(reactTabletTooltip.height+13)+'px');
18976            }
18977            if($(this).find('.advisor2.tool-tip-table').length && $(this).find('.tooltip-text.top.align-left').length){
18978                const reactTabletTooltip = $(this).find('.tooltip-text.top.align-left')[0].getBoundingClientRect();
18979                $(this).find('.tooltip-text.top.align-left').css('top',-(reactTabletTooltip.height+13)+'px');
18980            }
18981        })
18982
18983        $('#utilityTable span').each(function(index,val){
18984            if($(this).find('.advisor2.tool-tip-table').length && $(this).find('.tooltip-text.top.align-right').length){
18985                const reactTabletTooltip = $(this).find('.tooltip-text.top.align-right')[0].getBoundingClientRect();
18986                $(this).find('.tooltip-text.top.align-right').css('top',-(reactTabletTooltip.height+4)+'px');
18987            }
18988        });
18989    },
18990    getTableData : function(elem,tableData){
18991        let tableInfo=[];
18992        tableData.jsonData.map((array,index)=>{
18993            let keys = Object.keys(array);
18994            let count=1;
18995            let rowData ={};
18996            for (var i = 0; i < keys.length; i++) {
18997                let columnName = "column_"+count;
18998                let columnData = utilityTableMethods.getColumnDetails(tableData,keys[i]);
18999                if(columnData.length){
19000                    let columnWidth ="";
19001                    let toolTipTableTitle = "";
19002                    if(columnData[0].columnType == "both"){
19003                        columnWidth = columnData[0].columnWidth1;
19004                        toolTipTableTitle = index == 0 ? columnData[0].tableTooltip1 : null;
19005                    }else{
19006                        columnWidth =  columnData[0].columnWidth;
19007                        toolTipTableTitle = index == 0 ? columnData[0].tableTooltip : null;
19008                    }
19009                    rowData[columnName] = {columnName:columnData[0].columnLabel,toolTipTableTitle:toolTipTableTitle,csvColumnNameKey:keys[i],value:array[keys[i]],isVisible:columnData[0].columnType,isLink:columnData[0].fieldType,width:columnWidth};
19010                    count++;
19011                }
19012            }
19013            tableInfo.push(rowData);
19014        });
19015        return tableInfo;
19016    },
19017    getColumnDetails : function(tableData,key){
19018        return tableData.utilityItems.filter((val) => (val.columnCSVName == key && (val.columnType == 'tableVisible' || val.columnType == 'both')));
19019    },
19020    getFilterColumnDetails : function(tableData,key){
19021        return tableData.utilityItems.filter((val) => (val.columnCSVName == key && (val.columnType == 'filtervisible' || val.columnType == 'both')));
19022    },
19023    getFilterData : function(tableData){
19024        let filterData ={};
19025        tableData.jsonData.map((array)=>{
19026            let keys = Object.keys(array);
19027            let count=1;
19028            for (var i = 0; i < keys.length; i++) {
19029                let filterName = "filter_"+count;
19030                let columnData = utilityTableMethods.getFilterColumnDetails(tableData,keys[i]);
19031                if(columnData.length){
19032                    let filterLabel ="";
19033                    let toolTipFilter = "";
19034                    let filterId = "";
19035                    if(columnData[0].columnType == "both"){
19036                        filterLabel = columnData[0].filterLabel1;
19037                        toolTipFilter = columnData[0].filterTooltip1;
19038                        filterId = columnData[0].filterID1;
19039                    }else if(columnData[0].columnType == "filtervisible"){
19040                        filterLabel = columnData[0].filterLabel;
19041                        toolTipFilter = columnData[0].filterTooltip;
19042                        filterId = columnData[0].filterID;
19043                    }else{
19044                        filterLabel =  columnData[0].filterLabel;
19045                        toolTipFilter = columnData[0].filterTooltip;
19046                        filterId = columnData[0].filterID;
19047                    }
19048                    if(filterData.hasOwnProperty(filterName)){
19049                        if(!filterData[filterName].some(el => el.value === array[keys[i]])){
19050                            filterData[filterName].push({filterlabel:filterLabel,toolTipFilterTitle:toolTipFilter,filterId:filterId,csvColumnNameKey:keys[i].replace(/\s+/g, '_'),value:array[keys[i]]})
19051                        }
19052                    }else{
19053                        filterData[filterName] = [{filterlabel:filterLabel,toolTipFilterTitle:toolTipFilter,filterId:filterId,csvColumnNameKey:keys[i].replace(/\s+/g, '_'),value:array[keys[i]]}];
19054                    }
19055                    count++;
19056                }
19057            }
19058
19059        });
19060        return filterData;
19061    },
19062    generateFilterData : function(utilityTableLoadMore,parentElement,element,filterData,utilityTableData,tabIdIndex){
19063        Object.keys(filterData).map((filterKey,index)=>{
19064            let filterLabels = filterData[filterKey][0];
19065            let screenSize = $(window).width();
19066            let positionClass;
19067            if(screenSize > 1024){
19068                positionClass = index > 3 ? 'top align-right' : 'right';
19069            }else if(screenSize <= 1024 && screenSize >= 640){
19070                positionClass = index == 1 ? 'top align-right' : 'right';
19071            }else if(screenSize < 640){
19072                positionClass = 'top align-center';
19073            }
19074            let tooltipElement = filterLabels.toolTipFilterTitle ? `<div class="advisor2 tool-tip-table" tabindex="0"><i class="icon-new question-icon-blue"></i><div class="tooltip-text ${positionClass}">${filterLabels.toolTipFilterTitle}</div></div>` : '';
19075            let filterLabelElement =  `<div class="filter-field-label">${filterLabels.filterlabel}${tooltipElement}`
19076            let filterParent =$('<div class="utility-filter-dropdown">').append(filterLabelElement);
19077            filterParent.append($(`<select id="${filterLabels.filterId}" class="form-select-custom bhf-form-select advisor2.0-select">`));
19078            $(element).append(filterParent);
19079            let $option = `<option value="All" data-key="${filterLabels.filterId}">All</option>`;
19080            $(element).find(`#${filterLabels.filterId}`).append($option);
19081            filterData[filterKey].map((resp)=>{
19082                $option = `<option value="${resp.value}" data-key="${resp.filterId}">${resp.value}</option>`;
19083                $(element).find(`#${filterLabels.filterId}`).append($option);
19084            })
19085             $(element).find(`#${filterLabels.filterId}`).select2({
19086                tags:true
19087            })
19088            $(element).find(`#${filterLabels.filterId}`).on('select2:select', function (e) {
19089                const filterId = filterLabels.filterId;
19090                filterTypeKey =  $(element).find(`#${filterLabels.filterId} option:selected`).attr('data-key');
19091                filterText = $(element).find(`#${filterLabels.filterId} option:selected`).val();
19092                filterValue = $(element).find(`#${filterLabels.filterId} option:selected`).text();
19093                const activeTabId = $(element).closest('.tabs-panel').attr('id');
19094                utilityTableMethods.updateDropdownValues(element,activeTabId,filterId,filterText,filterValue,tabIdIndex,filterData,filterKey);
19095                utilityTableMethods.tableFilterHandler(parentElement,utilityTableLoadMore,element,filterTypeKey,filterValue,filterText,filterData,utilityTableData);
19096            });
19097        })
19098    },
19099    updateDropdownValues: function(filterElement,activeTabId,filterId,filterText,filterValue,tabIdIndex,filterData,selectedFilterKey=''){
19100        // update other tab current dropdown filter value 
19101        $('.utiity-table-wrapper')
19102        .find('.advisor2-tabs-content')
19103        .find('.tabs-panel')
19104        .each(function(index){
19105            if($(this).attr('id') !== activeTabId){
19106                const Tabid = $(this).attr('id');
19107                const OptionExist = $(this).find(`#${filterId} option[value="${filterValue}"]`).length > 0;
19108                const parentElement = $(`#${Tabid}`);
19109                const tabFilterElement = $(`#${Tabid}`).find('.utility-table-filters');
19110                const tabKey = `utilityTab${++index}`;
19111                const filterData = utilityTableMethods.getFilterData(utilityTableMethods.tableData[tabKey]);
19112                const tableData = utilityTableMethods.tableData[tabKey];
19113                let utilityTableLoadMore ={
19114                    startIndex:0,
19115                    showCount :0,
19116                    hiddenResults:'',
19117                    utilityTableLoadMoreDataElements:'',
19118                    utilityTableLoadMoreDataLength:0,
19119                }
19120                if(OptionExist){
19121                    $(this).find(`#${filterId}`).val(filterValue).trigger('change');
19122                    utilityTableMethods.tableFilterHandler(parentElement,utilityTableLoadMore,tabFilterElement,filterId,filterValue,filterText,filterData,tableData);
19123                }else{
19124                    $(this).find(`#${filterId}`).val('All').trigger('change');
19125                    let filterValue = 'All';
19126                    let filterText = 'All';
19127                    utilityTableMethods.tableFilterHandler(parentElement,utilityTableLoadMore,tabFilterElement,filterId,filterValue,filterText,filterData,tableData);
19128                }
19129            }
19130        });
19131
19132        // check other filter values and make the changes as in current tab
19133        if(selectedFilterKey){
19134            let remainFilterData=[];
19135            Object.keys(filterData).map((item) =>{
19136                if(item != selectedFilterKey){
19137                    const filterId = filterData[item][0].filterId;
19138                    const currentSelectedValue = $(`#${activeTabId}`).find(`#${filterId}`).find('option:selected').val();
19139                    const currentSelectedText = $(`#${activeTabId}`).find(`#${filterId}`).find('option:selected').text();
19140                    remainFilterData.push({
19141                        filterId:filterId,
19142                        currentValue:currentSelectedValue,
19143                        currentText:currentSelectedText
19144                    })
19145                }
19146            });
19147            utilityTableMethods.updateRemainFilterDataOtherTabs(remainFilterData,activeTabId,filterId);
19148        }
19149    },
19150    updateRemainFilterDataOtherTabs:function(remainFilterData,activeTabId){
19151        $('.utiity-table-wrapper')
19152        .find('.advisor2-tabs-content')
19153        .find('.tabs-panel')
19154        .each(function(index){
19155            if($(this).attr('id') !== activeTabId){
19156                const Tabid = $(this).attr('id');
19157                const tabKey = `utilityTab${++index}`;
19158                remainFilterData.map((item) => {
19159                    const {filterId,currentValue,currentSelectedText} = item;
19160                    const OptionExist = $(this).find(`#${filterId} option[value="${currentValue}"]`).length > 0;
19161                    const parentElement = $(`#${Tabid}`);
19162                    const tabFilterElement = $(`#${Tabid}`).find('.utility-table-filters');
19163                    const filterData = utilityTableMethods.getFilterData(utilityTableMethods.tableData[tabKey]);
19164                    const tableData = utilityTableMethods.tableData[tabKey];
19165                    let utilityTableLoadMore ={
19166                        startIndex:0,
19167                        showCount :0,
19168                        hiddenResults:'',
19169                        utilityTableLoadMoreDataElements:'',
19170                        utilityTableLoadMoreDataLength:0,
19171                    }
19172                    if(OptionExist){
19173                        $(this).find(`#${filterId}`).val(currentValue).trigger('change');
19174                        utilityTableMethods.tableFilterHandler(parentElement,utilityTableLoadMore,tabFilterElement,filterId,currentValue,currentSelectedText,filterData,tableData);
19175                    }else{
19176                        $(this).find(`#${filterId}`).val('All').trigger('change');
19177                        let filterValue = 'All';
19178                        let filterText = 'All';
19179                        utilityTableMethods.tableFilterHandler(parentElement,utilityTableLoadMore,tabFilterElement,filterId,filterValue,filterText,filterData,tableData);
19180                    }
19181                })
19182            }
19183        });
19184    },
19185    generateSearch : function(utilityTableLoadMore,parentElement,element,filterData,utilityTableData){
19186        let searchLabelText = $(element).attr('data-searchtext-label');
19187        let searchLabelElement =  `<div class="filter-field-label">${searchLabelText}:</div>`
19188        let searchInputElement = `<input type="text" placeholder="Search..." class="search-input searchKeyword"  name="search" />`
19189        let searchInputParentElement = $(`<div class="advisor2-input advisor2-search-input-div">`).append(searchInputElement);
19190        let searchParentElement = $('<div class="utility-filter-search">').append(searchLabelElement);
19191        $(searchParentElement).append(searchInputParentElement);
19192        if(searchLabelText) $(element).append(searchParentElement);
19193        $(element).find('.advisor2-search-input-div input').focus(function(){
19194            $(this).data('placeholder',$(this).attr('placeholder'))
19195                    .attr('placeholder','');
19196        }).blur(function(){
19197            $(this).attr('placeholder',$(this).data('placeholder'));
19198        });
19199
19200        $(element).find('.advisor2-search-input-div input').on("keyup",function(){
19201            let value = $(this).val().toLowerCase();
19202            utilityTableMethods.tableSearchHandler(parentElement,utilityTableLoadMore,element,value,filterData,utilityTableData);
19203            utilityTableMethods.adjustTooltipHeight();
19204        })
19205
19206    },
19207
19208    generateColumns: function(tableArea,columnDetails){
19209        let tabelheaderRows = $(tableArea).find('thead tr');
19210        let screenSize = $(window).width();
19211        Object.keys(columnDetails).map((key,index)=>{
19212            let positionClass;
19213            if(screenSize > 1024){
19214                positionClass = index == Object.keys(columnDetails).length-1 ? 'top align-right' : 'right';
19215            }else if(screenSize <= 1024 && screenSize >= 640){
19216                positionClass = index > 0 ? 'top align-right' : 'right';
19217            }else if(screenSize < 640){
19218                positionClass = 'top align-right';
19219            }
19220            let tooltipElement = columnDetails[key].toolTipTableTitle  ? `<div class="advisor2 tool-tip-table" tabindex="0"><i class="icon-new question-icon"></i><div class="tooltip-text ${positionClass}">${columnDetails[key].toolTipTableTitle}</div></div><div class=sorting-icons></div>` : '';
19221            let tableColumns = `<th width=${columnDetails[key].width}% class=${columnDetails[key].isLink != 'textField' ? 'text-center' : ''}>
19221<span>${columnDetails[key].columnName}${tooltipElement}</span></th>`;
19222            tabelheaderRows.append(tableColumns);
19223        })
19224    },
19225
19226    generateRows : function(tableArea,rowData){
19227        let tabelDataRows = $(tableArea).find('tbody');
19228        if($(tableArea).find('tbody tr').length) $(tableArea).find('tbody').empty();
19229        let entryRow=null;
19230        let screenSize = $(window).width();
19231        if(rowData.length){
19232            $(tableArea).find('tbody').empty()
19233            rowData.map((rowsVal) =>{
19234                let tableTextData = "";
19235                let tableIconData = "";
19236                if(screenSize >= 1024){
19237                    entryRow = $('<tr>').append(
19238                        Object.keys(rowsVal).map((rowKeys)=>{
19239                            if(screenSize >= 1024){
19240                                if(rowsVal[rowKeys].isLink == 'textField'){
19241                                    return `<td><div class='report-name'>${rowsVal[rowKeys].value}</div></td>`;
19242                                }else if(rowsVal[rowKeys].isLink == 'document'){
19243                                    if(rowsVal[rowKeys].value.trim()){
19244                                        return `<td><div class="text-center"><a target="_blank" href="${rowsVal[rowKeys].value.trim()}" onclick="setCta(this.text,this)"><i class="icon-new document-icon"></i></a></div></td>`;
19245                                    }else{
19246                                        return `<td></td>`;
19247                                    }
19248                                }else{
19249                                    if(rowsVal[rowKeys].value.trim()){
19250                                        return `<td><div class="text-center"><a target="_blank" href="${rowsVal[rowKeys].value.trim()}" onclick="setCta(this.text,this)"><i class="icon pdf-icon"></i></a></div></td>`;
19251                                    }else{
19252                                        return `<td></td>`;
19253                                    }
19254                                }
19255                            }
19256                        })
19257                    );
19258                    tabelDataRows.append(entryRow);
19259                } else if(screenSize < 1024 && screenSize >= 640){
19260                    $(tableArea).find('thead').css('display','none');
19261                    //tablet view
19262                    Object.keys(rowsVal).map((rowKeys)=>{
19263                        if(rowsVal[rowKeys].isLink == 'textField'){
19264                            //left align
19265                            let positionClass = 'top align-left';
19266                            let tooltipElement = rowsVal[rowKeys].toolTipTableTitle  ? `<div class="advisor2 tool-tip-table" tabindex="0"><i class="icon-new question-icon-blue"></i><div class="tooltip-text ${positionClass}">${rowsVal[rowKeys].toolTipTableTitle}</div></div>` : '';
19267                            tableTextData += `<div class="reports"><div class="report-head">${rowsVal[rowKeys].columnName}${tooltipElement}</div><div class="report-name">${rowsVal[rowKeys].value}</div></div>`;
19268                        }else{
19269                            //right right align
19270                            if(rowsVal[rowKeys].isLink == 'document'){
19271                                if(rowsVal[rowKeys].value.trim()){
19272                                    tableIconData += `<div class="reports_links"><div><a target="_blank" href="${rowsVal[rowKeys].value.trim()}" onclick="setCta(this.text,this)"><i class="icon-new document-icon"></i></a></div><div class="tooltip-icon"><a class="link_text" target="_blank" href="${rowsVal[rowKeys].value.trim()}" onclick="setCta(this.text,this)">${rowsVal[rowKeys].columnName}</a></div></div>`;
19273                                }
19274                            }else{
19275                                if(rowsVal[rowKeys].value.trim()){
19276                                    tableIconData += `<div class="reports_links"><div><a target="_blank" href="${rowsVal[rowKeys].value.trim()}" onclick="setCta(this.text,this)"><i class="icon pdf-icon"></i></a></div><div class="tooltip-icon"><a class="link_text" target="_blank" href="${rowsVal[rowKeys].value.trim()}" onclick="setCta(this.text,this)">${rowsVal[rowKeys].columnName}</a></div></div>`;
19277                                }
19278                            }
19279                        }
19280                    });
19281                    firsttableData = $('<td>').append(tableTextData);
19282                    tableIconWrapper = `<div class="reports_icons">${tableIconData}</div>`
19283                    secondtableData = $('<td>').append(tableIconWrapper);
19284                    entryRow = $('<tr>').append(firsttableData).append(secondtableData);
19285                    tabelDataRows.append(entryRow);
19286                }else if(screenSize < 640){
19287                    // mobile view
19288                    $(tableArea).find('thead').css('display','none');
19289                    Object.keys(rowsVal).map((rowKeys)=>{
19290                        if(rowsVal[rowKeys].isLink == 'textField'){
19291                            //left align
19292                            let positionClass = 'top align-center';
19293                            let tooltipElement = rowsVal[rowKeys].toolTipTableTitle  ? `<div class="advisor2 tool-tip-table" tabindex="0"><i class="icon-new question-icon-blue"></i><div class="tooltip-text ${positionClass}">${rowsVal[rowKeys].toolTipTableTitle}</div></div>` : '';
19294                            tableTextData += `<div class="reports"><div class="report-head">${rowsVal[rowKeys].columnName}${tooltipElement}</div><div class="report-name">${rowsVal[rowKeys].value}</div></div>`;
19295                        }else{
19296                            //right right align
19297                            if(rowsVal[rowKeys].isLink == 'document'){
19298                                if(rowsVal[rowKeys].value.trim()){
19299                                    tableTextData += `<div class="reports_links"><div><a target="_blank" href="${rowsVal[rowKeys].value.trim()}" onclick="setCta(this.text,this)"><i class="icon-new document-icon"></i></a></div><a class="link_text" target="_blank" href="${rowsVal[rowKeys].value.trim()}" onclick="setCta(this.text,this)">${rowsVal[rowKeys].columnName}</a></div>`;
19300                                }
19301                            }else{
19302                                if(rowsVal[rowKeys].value.trim()){
19303                                    tableTextData += `<div class="reports_links"><div><a target="_blank" href="${rowsVal[rowKeys].value.trim()}" onclick="setCta(this.text,this)"><i class="icon pdf-icon"></i></a></div><a class="link_text" target="_blank" href="${rowsVal[rowKeys].value.trim()}" onclick="setCta(this.text,this)">${rowsVal[rowKeys].columnName}</a></div>`;
19304                                }
19305                            }
19306                        }
19307                    });
19308                    firsttableData = $('<td>').append(tableTextData);
19309                    entryRow = $('<tr>').append(firsttableData);
19310                    tabelDataRows.append(entryRow);
19311                }
19312            })
19313        }else{
19314            $(tableArea).find('tbody').empty()
19315            $(tableArea).find('table').css('border-collapse','collapse');
19316            $(tableArea).find('tbody').css('border','1px solid #c9c9c9');
19317            entryRow = $('<div style="padding:20px;width:300px">').append(`<div class='report-name text-center'>No Matching Records Found</div>`);
19318            tabelDataRows.append(entryRow);
19319        }
19320    },
19321
19322    generatePagination : function(loadMoreIntializer,elem){
19323        loadMoreIntializer.startIndex=0;
19324        loadMoreIntializer.showCount=10;
19325        loadMoreIntializer.utilityTableLoadMoreDataElements=$(elem).find('tbody tr');
19326        loadMoreIntializer.utilityTableLoadMoreDataLength=loadMoreIntializer.utilityTableLoadMoreDataElements.length;
19327        if(loadMoreIntializer.utilityTableLoadMoreDataLength>0){
19328            if(loadMoreIntializer.showCount < loadMoreIntializer.utilityTableLoadMoreDataLength){
19329                $(elem).find('#utilityTableLoadMore').removeClass('hide');
19330            }
19331            else if (loadMoreIntializer.utilityTableLoadMoreDataLength == 1){
19332                $(elem).find('#utilityTableLoadMore').addClass('hide');
19333            }
19334            else{
19335                $(elem).find('#utilityTableLoadMore').addClass('hide');
19336            }
19337        }
19338        loadMoreIntializer.startIndex+=loadMoreIntializer.showCount;
19339        loadMoreIntializer.hiddenResults = Array.from(loadMoreIntializer.utilityTableLoadMoreDataElements).slice(loadMoreIntializer.startIndex,loadMoreIntializer.utilityTableLoadMoreDataLength);
19340        utilityTableMethods.hiddenTableResults(loadMoreIntializer.hiddenResults);
19341        if(loadMoreIntializer.hiddenResults.length > 0){
19342            if(loadMoreIntializer.hiddenResults.length < loadMoreIntializer.showCount){
19343                $(elem).find('.utility-table-load-more-btn span').text(`${utilityTableMethods.loadMoreText} ${loadMoreIntializer.hiddenResults.length}+`)
19344            }else{
19345                $(elem).find('.utility-table-load-more-btn span').text(`${utilityTableMethods.loadMoreText} 10+`)
19346            }
19347        }else{
19348            $(elem).find('#utilityTableLoadMore').addClass('hide');
19349        }
19350    },
19351
19352    hiddenTableResults:function(arr){
19353        arr.forEach(el =>{
19354          el.classList.add('hide');
19355        });
19356    },
19357
19358    loadMoreTableResults:function(loadMoreIntializer,elem,loadText){
19359        if($(elem).find('.utility-table-load-more-btn').length>0){
19360            $(elem).find('.utility-table-load-more-btn').off('click').on('click',function(){
19361                loadMoreIntializer.hiddenResults.forEach((element,index) => {
19362                    if(index<loadMoreIntializer.startIndex){
19363                      element.classList.remove('hide');
19364                    }
19365                });
19366                loadMoreIntializer.startIndex+=loadMoreIntializer.showCount;
19367                hideResultsCount = loadMoreIntializer.utilityTableLoadMoreDataLength - loadMoreIntializer.startIndex;
19368                if(loadMoreIntializer.startIndex >= loadMoreIntializer.utilityTableLoadMoreDataLength){
19369                    $(elem).find('#utilityTableLoadMore').addClass('hide');
19370                }
19371                if(hideResultsCount < loadMoreIntializer.showCount){
19372                    $(elem).find('.utility-table-load-more-btn span').text(`${loadText} ${hideResultsCount}+`)
19373                }
19374            })
19375        }
19376    },
19377
19378    tableFilterHandler : function(parentElement,utilityTableLoadMore,element,elementId,value,text,tableFiltersData,utilityTableData){
19379        // utilityTableMethods.resetOtherFilters(element,elementId,tableFiltersData);
19380        utilityTableMethods.regenerateRows(parentElement,utilityTableLoadMore,element,elementId,value,utilityTableData,tableFiltersData);
19381    },
19382
19383    tableSearchHandler : function(parentElement,utilityTableLoadMore,element,value,tableFiltersData,utilityTableData){
19384        utilityTableMethods.resetAllFilters(element,tableFiltersData);
19385        let tableData = {...utilityTableData};
19386        let filteredData = utilityTableMethods.getSearchDataTableData(parentElement,value,tableData);
19387        utilityTableMethods.generateRows(parentElement,filteredData);
19388        utilityTableMethods.generatePagination(utilityTableLoadMore,parentElement);
19389        utilityTableMethods.handleTooltipClick();
19390
19391        const activeTabId = $(parentElement).attr('id');
19392        //reset other tab to all
19393        $('.utiity-table-wrapper')
19394        .find('.advisor2-tabs-content')
19395        .find('.tabs-panel')
19396        .each(function(index){
19397            if($(this).attr('id') !== activeTabId){
19398                let remainFilterData=[];
19399                const Tabid = $(this).attr('id');
19400                const tabKey = `utilityTab${++index}`;
19401                const parentElement = $(`#${Tabid}`);
19402                const tabFilterElement = $(`#${Tabid}`).find('.utility-table-filters');
19403                const filteredData = utilityTableMethods.getFilterData(utilityTableMethods.tableData[tabKey]);
19404                const tableData = utilityTableMethods.tableData[tabKey];
19405                let tableRowsAndColumns = utilityTableMethods.getTableData(parentElement,tableData);
19406                Object.keys(filteredData).map((item) =>{
19407                    const filterId = filteredData[item][0].filterId;
19408                    remainFilterData.push({
19409                        filterId:filterId
19410                    })
19411                });
19412                const filterValue ='All'
19413                const filterText = 'All'
19414                const utilityTableLoadMore ={
19415                    startIndex:0,
19416                    showCount :0,
19417                    hiddenResults:'',
19418                    utilityTableLoadMoreDataElements:'',
19419                    utilityTableLoadMoreDataLength:0,
19420                }
19421                $(this).find('.utility-filter-dropdown').find('select').val('All').trigger('change');
19422                remainFilterData.map((item) => {
19423                    const {filterId} = item;
19424                    utilityTableMethods.tableFilterHandler(parentElement,utilityTableLoadMore,tabFilterElement,filterId,filterValue,filterText,filteredData,tableData);
19425                });
19426            }
19427        });
19428    },
19429
19430    getSearchDataTableData : function(elem,value,tableData){
19431        let searchableData=[];
19432        let columnWidth="";
19433        let toolTipTableTitle="";
19434        tableData.jsonData.map((array,index)=>{
19435            let keys = Object.keys(array);
19436            let count=1;
19437            let rowData ={};
19438            let isSearchKeyExists = false;
19439            for (var i = 0; i < keys.length; i++) {
19440                let columnName = "column_"+count;
19441                let columnData = utilityTableMethods.getColumnDetails(tableData,keys[i]);
19442                if(columnData.length){
19443                    if(columnData[0].columnType == "both"){
19444                        columnWidth = columnData[0].columnWidth1;
19445                        toolTipTableTitle = columnData[0].tableTooltip1;
19446                    }else{
19447                        columnWidth =  columnData[0].columnWidth;
19448                        toolTipTableTitle = columnData[0].tableTooltip;
19449                    }
19450                    if(columnData[0].fieldType == 'textField'){
19451                        if(isSearchKeyExists){
19452                            rowData[columnName] = {columnName:columnData[0].columnLabel,toolTipTableTitle:toolTipTableTitle,csvColumnNameKey:keys[i],value:array[keys[i]],isVisible:columnData[0].columnType,isLink:columnData[0].fieldType,width:columnWidth};
19453                        }else if(array[keys[i]].toLowerCase().indexOf(value) > -1){
19454                            isSearchKeyExists = true;
19455                            rowData[columnName] = {columnName:columnData[0].columnLabel,toolTipTableTitle:toolTipTableTitle,csvColumnNameKey:keys[i],value:array[keys[i]],isVisible:columnData[0].columnType,isLink:columnData[0].fieldType,width:columnWidth};
19456                        }else{
19457                            rowData[columnName] = {columnName:columnData[0].columnLabel,toolTipTableTitle:toolTipTableTitle,csvColumnNameKey:keys[i],value:array[keys[i]],isVisible:columnData[0].columnType,isLink:columnData[0].fieldType,width:columnWidth};
19458                        }
19459                    }else{
19460                        rowData[columnName] = {columnName:columnData[0].columnLabel,toolTipTableTitle:toolTipTableTitle,csvColumnNameKey:keys[i],value:array[keys[i]],isVisible:columnData[0].columnType,isLink:columnData[0].fieldType,width:columnWidth};
19461                    }
19462                }
19463                count++;
19464            }
19465            if(isSearchKeyExists) searchableData.push(rowData);
19466        });
19467        let latestSearchableData=[];
19468        searchableData.map((resp,index)=>{
19469            if(index != 0){
19470                Object.keys(resp).map(column => {
19471                    resp[column] = {...resp[column],toolTipTableTitle:null}
19472                })
19473            }
19474            latestSearchableData.push(resp);
19475        })
19476        return searchableData;
19477    },
19478
19479    resetAllFilters : function(element,tableFiltersData){
19480        Object.keys(tableFiltersData).map((filtersKey)=>{
19481            let resetfilterId = tableFiltersData[filtersKey][0].filterId;
19482            $(element).find(`#${resetfilterId}`).val('All').trigger("change");
19483        })
19484    },
19485
19486    resetOtherFilters : function(element,filterId,tableFiltersData){
19487        $(element).find('.advisor2-search-input-div input').val('');
19488        Object.keys(tableFiltersData).map((filtersKey)=>{
19489            let resetfilterId = tableFiltersData[filtersKey][0].csvColumnNameKey;
19490           if(resetfilterId != filterId){
19491                $(element).find(`#${resetfilterId}`).val('All').trigger("change");
19492           }
19493        })
19494    },
19495
19496    regenerateRows : function(parentElement,utilityTableLoadMore,element,elementId,value,utilityTableData,tableFiltersData){
19497        let filters = {};
19498        if(value != 'All'){
19499            Object.keys(tableFiltersData).map((filtersKey)=>{
19500                tableFiltersData[filtersKey].filter((colName)=>{
19501                    if(colName.filterId == elementId){
19502                        filters[colName.csvColumnNameKey] = value;
19503                    }
19504                })
19505            });
19506        }
19507        Object.keys(tableFiltersData).map((filtersKey)=>{
19508            let resetfilterId = tableFiltersData[filtersKey][0].filterId;
19509            let columnName = tableFiltersData[filtersKey][0].csvColumnNameKey;
19510            if(resetfilterId != elementId && $(element).find(`#${resetfilterId}`).val() != 'All'){
19511                    filters[columnName] = $(element).find(`#${resetfilterId}`).val();
19512            }
19513        })
19514        let csvData = {...utilityTableData};
19515        let filterTableData = csvData.jsonData.filter((el) => {
19516            for(var key in filters){
19517                if(el[key.replace(/_/g,' ')].replace( /(<([^>]+)>)/ig, '') != filters[key].replace(/(<([^>]+)>)/ig, '')){
19518                    return false;
19519                }
19520            }
19521            return true;
19522        });
19523        csvData.jsonData = filterTableData;
19524        let filteredData = utilityTableMethods.getTableData(parentElement,csvData);
19525        utilityTableMethods.generateRows(parentElement,filteredData);
19526        utilityTableMethods.generatePagination(utilityTableLoadMore,parentElement);
19527        utilityTableMethods.loadMoreTableResults(utilityTableLoadMore,parentElement,utilityTableMethods.loadMoreText);
19528        utilityTableMethods.adjustTooltipHeight();
19529        utilityTableMethods.handleTooltipClick();
19530    }
19531}
19532$(document).ready(function () {
19533    if($('.advisor2.card-insightpro-wrapper').length){
19534        $('.advisor2.card-insightpro-wrapper').each(function(){
19535            let isCardClickable = $(this).attr('data-card-clickable');
19536            if(isCardClickable){
19537                $(this).css('cursor','pointer');
19538                $(this).off('click');
19539                $(this).on('click', function(event) {
19540                    let target = $(this).attr('data-buttonTarget');
19541                    if(target){
19542                        window.open($(this).find('.card-title-link').attr('href'),'_blank');
19543                    }else{
19544                        window.open($(this).find('.card-title-link').attr('href'),'_self');
19545                    }
19546                })
19547            }
19548            $('.article-tag-name').each(function(){
19549                $(this).on('click',function(e){
19550                   e.stopPropagation();
19551                })  
19552            })
19553    
19554            $('.article-user-name').each(function(){
19555                $(this).on('click',function(e){
19556                   e.stopPropagation();
19557                })  
19558            })
19559        })
19560    }
19561});
19562$(document).ready(function () {
19563    $(document).on("click", function(e) { 
19564        if(!($(e.target).closest('.module-help-wrapper').length || $(e.target).closest('.get__help').length)){
19565            $('.module-help-wrapper .module-help-wrapper-level1').removeClass('__display');
19566            $('.module-help-wrapper .module-help-wrapper-level2').removeClass('__display');
19567        }
19568    });
19569
19570    $('.get__help').on("click",function(){
19571        $('.module-help-wrapper .module-help-wrapper-level1').addClass('__display');
19572    })
19573
19574    $('.close__side__menu').on("click",function(){
19575        $('.module-help-wrapper .module-help-wrapper-level1').removeClass('__display');
19576        $('.module-help-wrapper .module-help-wrapper-level2').removeClass('__display');
19577    });
19578
19579    $('.content__link.hasChild').on("click",function(){
19580        $('.module-help-wrapper-level2 .level2.content__info').children().remove();
19581        $('.module-help-wrapper-level2 .level2.content__info').append($(this).next().html());
19582        $('.module-help-wrapper-level2 .level2.content__info').find('form').addClass('formSubmit')
19583        if($('.module-help-wrapper-level2 .level2.content__info').find('.content_level2_form').length){
19584            const submitElement = $('.module-help-wrapper-level2 .level2.content__info .cell.large-12').last();
19585            $(submitElement).before('<div class="cell small-12 medium-12 large-12"><div class="recaptcha" id="recaptcha_html_element_module_form" verified="false"></div></div>')
19586			const siteKey = $('#module-form-site-key').val() || null;
19587            if(siteKey){
19588                var captcha = grecaptcha.enterprise.render('recaptcha_html_element_module_form', { 
19589                    'sitekey' : siteKey, 
19590                    'action'  : 'module-help', 
19591                    'callback': function(resp){
19592                        recaptchaModuleFormCallback(resp)
19593                    },
19594                    'expired-callback': recaptchaModuleFormExpiredCallback
19595                }); 
19596            }else{
19597                console.log("unable to get siteKey");
19598            }
19599            
19600        }
19601        $('.module-help-wrapper .module-help-wrapper-level2').addClass('__display');
19602        $(".text-field-validation").on('blur input',function(e){
19603            bhfFormValidator.textFieldValidator($(this));
19604        });
19605
19606        $("#newPhone.phone").on('blur input',function(){
19607            if($(this).val().length===10){
19608                bhfFormValidator.maskPhoneElement($(this));
19609                }else {
19610                bhfFormValidator.validationErrorAdd($(this),"constraint");
19611			}
19612        });
19613        moduleFormHandler();
19614    });
19615
19616    $('.return__link').on("click",function(){
19617        $('.module-help-wrapper .module-help-wrapper-level2').removeClass('__display');
19618    });
19619
19620    //form submit
19621    function moduleFormHandler(){
19622        if(homePageVideo.ElementExist($('.moduleForm'))) {
19623            $('.content_level2_form').show();
19624            $('.content_level2_form_success').hide();
19625            var moduleHelpPagePath = window.location.pathname;
19626            $('.moduleForm').on('submit', function(e) {
19627                e.preventDefault();
19628                $('.content_level2_form').hide();
19629                $('.content_level2_form_success').show();
19630                $('.content_level2_form_success').addClass('active');
19631                localStorage.setItem('moduleFormSubmit_'+moduleHelpPagePath,'yes');
19632                var form = $(this);
19633                var url = '/content.salesforceAPI.connect';
19634        		var currentPagePath  = $("#currentPagePath").val();
19635            	var formData = form.serializeArray();
19636        		formData.push({name: "currentPagePath", value: currentPagePath});
19637                $.ajax({
19638                    type: "POST",
19639                    url: url,
19640                    data: formData,
19641                    success: function()
19642                    {
19643                        console.log('Form Submitted');
19644                    },
19645                    error: function() {
19646                        console.log('Error in submitting module form');
19647                    }
19648                });
19649            });
19650        }
19651    }
19652});
19653
19654function recaptchaModuleFormCallback(response) {
19655    let recaptchaThresholdValue = $('#recaptcha-threshold').val();
19656    var url = "/content.enterpriseRecaptcha";
19657    $.ajax({
19658        type: "POST",
19659        url: url,
19660        data : {
19661            token: response,
19662            recaptchaThresholdValue: recaptchaThresholdValue
19663        },
19664        success: function (data) {
19665            let userObj = JSON.parse(data);
19666            if (userObj['isSuccess'] == true) {
19667                $('#recaptcha_html_element_module_form').attr('verified',true);
19668                bhfFormValidator.submitValidator($('.formSubmit .text-field-validation'));
19669                //return true;
19670            } else {
19671                $('#recaptcha_html_element_module_form').attr('verified',false);
19672                bhfFormValidator.submitValidator($('.formSubmit .text-field-validation'));
19673                return false
19674            }
19675        },
19676        error: function () {
19677            console.log('Error in getting verify response form');
19678            return false
19679        }
19680    });
19681}
19682
19683function recaptchaModuleFormExpiredCallback() {
19684    $('#recaptcha_html_element_module_form').attr('verified',false);
19685    bhfFormValidator.submitValidator($('.formSubmit .text-field-validation'));
19686}
19687
19688$(document).ready(function () {
19689    $('.sidebar-cardinsight-wrapper').each(function(e){
19690        let isCardClickable = $(this).attr('data-card-clickable');
19691        let target = $(this).attr('data-buttonTarget');
19692        $(this).find('.card-sidebar').on('click', function (e) {
19693            if(isCardClickable) {
19694                if(target){
19695                    window.open($(this).find('.card-title-link').attr('href'),'_blank');
19696                }else{
19697                    window.open($(this).find('.card-title-link').attr('href'),'_self');
19698                }
19699            }
19700        });
19701        if(isCardClickable){
19702            $(this).find('.card-sidebar').css('cursor','pointer');
19703        }
19704    })
19705});
19706$(document).ready(function () {
19707    if($('.advisor2.card-bio-grid-wrapper').length){
19708        $('.advisor2.card-bio-grid-wrapper').each(function(){
19709            let isCardClickable = $(this).attr('data-card-clickable');
19710            let uniqueId = $(this).attr('data-uniqueId');
19711            if(isCardClickable){
19712                $(this).css('cursor','pointer');
19713                $(this).off('click');
19714                $(this).on('click', function(e) {
19715                    e.preventDefault();
19716                    cardBioGrid.consentOpenModal(`cardBioModal_${uniqueId}`);
19717                })
19718            }
19719            if(homePageVideo.ElementExist($(this).find('#cardBioModal'))){
19720                cardBioGrid.consentModalOpenEvent($(this).find('#cardBioModal'), `cardBioModal_${uniqueId}`);
19721            }
19722            if($(`#cardBioModal_${uniqueId}`).length && $(`#cardBioModal_${uniqueId}`).attr('aria-hidden','false')){
19723                $(document).on('click', '.modalScreenClose', function (e) {
19724                    $('.reveal-overlay-advisor2-modal').hide();
19725                    $('html').removeClass('is-reveal-open');
19726                    $('body').removeClass('is-reveal-open');
19727                });
19728                $(document).on('click', '.modalCloseBtn', function (e) {
19729                    $('.reveal-overlay-advisor2-modal').hide();
19730                    $('html').removeClass('is-reveal-open');
19731                    $('body').removeClass('is-reveal-open');
19732                });
19733            }
19734        })
19735    }
19736});
19737
19738var cardBioGrid = {
19739    consentModalOpenEvent: function ($elem, modal) {
19740        $elem.on("click", function(){
19741            cardBioGrid.consentOpenModal(modal);
19742        })
19743    },
19744    consentOpenModal: function (modalElem) {
19745        setTimeout(function () {
19746            new Foundation.Reveal($('#' + modalElem)).open();
19747            revealCenterAlign.revealRePosition();
19748            $('.reveal-overlay').addClass('reveal-overlay-advisor2-modal');
19749            $('.reveal-overlay').animate({ scrollTop: 0 }, 10);
19750            cardBioGrid.dynmicMargin();
19751        }, 10);
19752    },
19753    dynmicMargin: function () {
19754        if ($('.revokeConsentSection').length) {
19755            var isIphonePad = /iphone|ipad/i.test(navigator.userAgent.toLocaleLowerCase());
19756            if (isIphonePad && $(window).width() < 991) {
19757                let dynamicMargin = ($(window).width() - $('.revokeConsentSection .customWidth').width()) / 2;
19758                $('.revokeConsentSection .customWidth').css({ 'margin-left': dynamicMargin + 'px', 'margin-right': dynamicMargin + 'px' });
19759            }
19760            else {
19761                $('.revokeConsentSection .customWidth').css({ 'margin-left': '', 'margin-right': '' });
19762            }
19763        }
19764    },
19765}
19766$(document).ready(function () {
19767    $('.card-tool-grid-wrapper').each(function(index,e){
19768        let isCardClickable = $(this).attr('data-card-clickable');
19769        if(isCardClickable){
19770            $(this).css('cursor','pointer');
19771        }
19772        $(this).on('click', function (e) {
19773            let isCardClickable = $(this).attr('data-card-clickable');
19774            if(isCardClickable) {
19775                let target = $(this).attr('data-buttonTarget');
19776                if(target){
19777                    window.open($(this).find('.card-title-link').attr('href'),'_blank');
19778                }else{
19779                    window.open($(this).find('.card-title-link').attr('href'),'_self');
19780                }
19781            }
19782        });
19783        cardToolGrid.updateMasterRowContainer(this);
19784        cardToolGrid.checkisValidEntitlement(this);
19785    })
19786    $('.card-tool-grid-wrapper').closest('.product-core-wrapper').each(function(){
19787        let isToolHidden=true;
19788        $(this).find('.cell').each(function(){
19789            if(!$(this).hasClass('hide')){
19790                isToolHidden=false;
19791            }
19792        });
19793        if(isToolHidden) $(this).addClass('hide');
19794    })  
19795});
19796
19797
19798const cardToolGrid = {
19799    updateMasterRowContainer: function(element){
19800        const masterRowContainer = $(element).closest('.grid-x');
19801        $(masterRowContainer).addClass('no-padding');
19802    },
19803    checkisValidEntitlement: function(element){
19804        const isValid = $(element).attr('data-isValidEntilement');
19805        if(isValid !== 'true'){
19806            $(element).closest('.cell').addClass('hide');
19807        }
19808    }
19809}
19810let parsedProcessArticles = [];
19811let requestedPageArticle = 0;
19812let ajaxUrl = '/content.LatestGrid.cardInsightGrid';
19813$(document).ready(function(){
19814    if($('.card-insight-grid-wrapper').length || $('#cardInsightGridTopic').length){
19815        let path = $('#path').val();
19816        let parentLink = $('#parentLink').val();
19817        let featureCardLink = $('#featureCardLink').val();
19818        let articlePagePath = $('#articlePagePath').val();
19819        let topicList = $('#topicList').val();
19820        let pageTitle = $('#pageTitle').val();
19821        $.ajax({
19822            url: ajaxUrl,
19823            type: 'post',
19824            data: {"path":path,"parentPath":parentLink,"featuredCardPath":featureCardLink,"articleParentPath":articlePagePath,"topicList":topicList,"pageTitle":pageTitle},
19825            success: function(data) {
19826                let totalArticles = data.listSize;
19827                if(data.featuredCard){
19828
19829                    if (data.featuredCard.articleType === 'article') {
19830                        data.featuredCard.article = true;
19831                    } else if (data.featuredCard.articleType === 'video') {
19832                        data.featuredCard.video = true;
19833                    } else if (data.featuredCard.articleType === 'graph') {
19834                        data.featuredCard.graph = true;
19835                    } else if (data.featuredCard.articleType === 'quiz') {
19836                        data.featuredCard.quiz = true;
19837                    } else if (data.featuredCard.articleType === 'house') {
19838                        data.featuredCard.house = true;
19839                    } else if (data.featuredCard.articleType === 'panel') {
19840                        data.featuredCard.panel = true;
19841                    } else if (data.featuredCard.articleType === 'podcast') {
19842                        data.featuredCard.podcast = true;
19843                    }
19844                    var tag_list = data.featuredCard.topicList;
19845                    if (tag_list.length > 0) {
19846                        var first_tag = tag_list[0];
19847                        var last_tag = tag_list[tag_list.length - 1];
19848                        last_tag.last = true;
19849                        first_tag.first = true;
19850                        tag_list[0] = first_tag;
19851                        tag_list[tag_list.length - 1] = last_tag;
19852                    }
19853                    data.featuredCard.topicList = tag_list;
19854                    var contributors_list = data.featuredCard.contributors;
19855                    if (contributors_list.length > 0) {
19856                        var first_contributor = contributors_list[0];
19857                        var last_contributor = contributors_list[contributors_list.length - 1];
19858                        last_contributor.last = true;
19859                        first_contributor.first = true;
19860                        contributors_list[0] = first_contributor;
19861                        contributors_list[contributors_list.length - 1] = last_contributor;
19862                    }
19863                    data.featuredCard.contributors = contributors_list;
19864                    var template = $('#mustache-templ-featuredCard-insight-grid').html();
19865                    var html = Mustache.to_html(template, data.featuredCard);
19866                    $('#insightFeaturedCard').append(html);
19867                    if(totalArticles >= 4){
19868                        $('#cardInsightGridLoadMore').removeClass('hide');
19869                    }
19870                    $('.card-insight-grid-wrapper').find('.loader').addClass('hide');
19871                    let articleLists = data;
19872                    let featuredPathLink = data.featuredCard.path;
19873                    articleLists = articleLists.secondaryList.filter(resp => resp.path != featuredPathLink);
19874                    if(articleLists.length && totalArticles){
19875                        cardInsightGrid.getArticleList(articleLists)
19876                    }
19877                    cardInsightGrid.updateCardClickable();
19878                }
19879            }
19880        });
19881    }
19882})
19883
19884
19885let cardInsightGrid = {
19886    getArticleList: function(articleLists){
19887        for(var i in articleLists){
19888            let parsed_array = articleLists[i];
19889
19890            if (parsed_array.articleType === 'article') {
19891                parsed_array.article = true;
19892            } else if (parsed_array.articleType === 'video') {
19893                parsed_array.video = true;
19894            } else if (parsed_array.articleType === 'graph') {
19895                parsed_array.graph = true;
19896            } else if (parsed_array.articleType === 'quiz') {
19897                parsed_array.quiz = true;
19898            } else if (parsed_array.articleType === 'house') {
19899                parsed_array.house = true;
19900            } else if (parsed_array.articleType === 'panel') {
19901                parsed_array.panel = true;
19902            } else if (parsed_array.articleType === 'podcast') {
19903                parsed_array.podcast = true;
19904            }
19905
19906            var tag_list = parsed_array.topicList;
19907            if (tag_list.length > 0) {
19908                var first_tag = tag_list[0];
19909                var last_tag = tag_list[tag_list.length - 1];
19910                last_tag.last = true;
19911                first_tag.first = true;
19912                tag_list[0] = first_tag;
19913                tag_list[tag_list.length - 1] = last_tag;
19914            }
19915    
19916            parsed_array.topicList = tag_list;
19917    
19918            var contributors_list = parsed_array.contributors;
19919            if (contributors_list.length > 0) {
19920                var first_contributor = contributors_list[0];
19921                var last_contributor = contributors_list[contributors_list.length - 1];
19922                last_contributor.last = true;
19923                first_contributor.first = true;
19924                contributors_list[0] = first_contributor;
19925                contributors_list[contributors_list.length - 1] = last_contributor;
19926            }
19927            parsed_array.contributors = contributors_list;
19928            parsedProcessArticles.push(parsed_array);
19929        }
19930        cardInsightGrid.generateArticleTemplate();
19931    },
19932
19933    generateArticleTemplate: function(){
19934        var current_process = parsedProcessArticles.slice((requestedPageArticle * 4), (requestedPageArticle * 4) + 4);
19935        var template = $('#mustache-templ-secondaryCard-insight-grid').html();
19936        var html = Mustache.to_html(template, current_process);
19937        $('#insightSecondaryCards').append(html);
19938        imageRendition.showRendition();
19939        if ((requestedPageArticle + 1) * 4 >= parsedProcessArticles.length) {
19940            $('#cardInsightGridLoadMore').addClass('hide');
19941        }
19942        requestedPageArticle = requestedPageArticle + 1;
19943        cardInsightGrid.updateCardClickable();
19944    },
19945
19946    customEqualiser: function(){
19947        $('.equalizeInsightCard').each(function () {
19948            for (var i = 0; i < $('[class^="equalizeInsight-"]').length + 5; i++) {
19949                if ($(window).width() >= 640) {
19950                    var maxHeight = 0;
19951                    var presentEqualize = $(this).find('.equalizeInsight-' + i);
19952                    if (presentEqualize.length) {
19953                        presentEqualize.each(function () {
19954                            if ($(this).height() > maxHeight) {
19955                                maxHeight = $(this).height();
19956                            }
19957                        });
19958                        presentEqualize.height(maxHeight);
19959                    }
19960                } else {
19961                    var smallEqualize = $(this).find('.equalizeInsight-' + i);
19962                    if (smallEqualize.length) {
19963                        smallEqualize.each(function () {
19964                            $(this).css('height', '');
19965                        });
19966                    }
19967                }
19968            }
19969        });
19970    },
19971
19972    updateCardClickable: function(){
19973        let isInsightGridCardClickable = $('#cardInsightGrid').attr('data-card-cl
19973ickable');
19974        let isInsightGridTopicCardClickable = $('#cardInsightGridTopic').attr('data-card-clickable');
19975        if(isInsightGridCardClickable){
19976            $('#cardInsightGrid').find('.card-insight-grid').css('cursor','pointer');
19977            $('#cardInsightGrid').find('.card-insight-secondary-grid').css('cursor','pointer');
19978        }
19979        $('#cardInsightGrid').find('.card-insight-grid').on('click', function (e) {
19980            isInsightGridCardClickable = $('#cardInsightGrid').attr('data-card-clickable');
19981            let target = $('#cardInsightGrid').attr('data-buttonTarget');
19982            isInsightGridCardClickable && cardInsightGrid.handleCardClickableAction($(this),target)
19983        });
19984
19985        $('#cardInsightGrid').find('.card-insight-secondary-grid').on('click', function (e) {
19986            isInsightGridCardClickable = $('#cardInsightGrid').attr('data-card-clickable');
19987            let target = $('#cardInsightGrid').attr('data-buttonTarget');
19988            isInsightGridCardClickable && cardInsightGrid.handleCardClickableAction($(this),target)
19989        });
19990
19991        if(isInsightGridTopicCardClickable){
19992            $('#cardInsightGridTopic').find('.card-insight-grid').css('cursor','pointer');
19993            $('#cardInsightGridTopic').find('.card-insight-secondary-grid').css('cursor','pointer');
19994        }
19995        $('#cardInsightGridTopic').find('.card-insight-grid').on('click', function (e) {
19996            let isInsightGridTopicCardClickable = $('#cardInsightGridTopic').attr('data-card-clickable');
19997            let target = $('#cardInsightGridTopic').attr('data-buttonTarget');
19998            isInsightGridTopicCardClickable && cardInsightGrid.handleCardClickableAction($(this),target)
19999            
20000        });
20001
20002        $('#cardInsightGridTopic').find('.card-insight-secondary-grid').on('click', function (e) {
20003            let isInsightGridTopicCardClickable = $('#cardInsightGridTopic').attr('data-card-clickable');
20004            let target = $('#cardInsightGridTopic').attr('data-buttonTarget');
20005            isInsightGridTopicCardClickable && cardInsightGrid.handleCardClickableAction($(this),target)
20006        });
20007
20008        $('.article-tag-name').each(function(){
20009            $(this).on('click',function(e){
20010               e.stopPropagation();
20011            })  
20012        })
20013
20014        $('.article-user-name').each(function(){
20015            $(this).on('click',function(e){
20016               e.stopPropagation();
20017            })  
20018        })
20019    },
20020    handleCardClickableAction :function(elem,target){
20021        if(target){
20022            window.open(elem.find('.card-title-link').attr('href'),'_blank');
20023        }else{
20024            window.open(elem.find('.card-title-link').attr('href'),'_self');
20025        }
20026    }
20027}
20028
20029
20030function getLatestArticles() {
20031    cardInsightGrid.generateArticleTemplate();
20032    setTimeout(() => {
20033        cardInsightGrid.customEqualiser();
20034    }, 300);
20035}
20036
20037$(window).load(function() {
20038    if($('.equalizeInsightCard').children().length >0)  cardInsightGrid.customEqualiser();
20039});
20040
20041
20042
20043
20044$(document).ready(function () {
20045    $('.card-insight-callout-wrapper').each(function(e){
20046        let isCardClickable = $(this).attr('data-card-clickable');
20047        if(isCardClickable){
20048            $(this).css('cursor','pointer');
20049        }
20050        $(this).on('click', function (e) {
20051            let isCardClickable = $(this).attr('data-card-clickable');
20052            if(isCardClickable) {
20053                let target = $(this).attr('data-buttonTarget');
20054                if(target){
20055                    window.open($(this).find('.card-title-link').attr('href'),'_blank');
20056                }else{
20057                    window.open($(this).find('.card-title-link').attr('href'),'_self');
20058                }
20059            }
20060        });
20061    })
20062    
20063});
20064$(document).ready(function () {
20065    $('.utility-form-wrapper .advisor2-dropdown-list').find("#state").each(function(){
20066        $(this).val(' ').trigger("change");
20067    });
20068
20069    $(document).on('keyup', '.utility-form-wrapper .advisor2-dropdown-list .select2-container--default', function (e) {
20070        console.log("key poress");
20071        e.stopPropagation() 
20072        e.stopImmediatePropagation();
20073        var code = e.keyCode || e.which;
20074        if(code == '9'){
20075            const ele = $(this).prev();
20076            $(ele).select2('open');
20077        }
20078        return false;
20079    });
20080
20081    $(".utility-form-wrapper .advisor2-dropdown-list").find('#state').on('select2:closing', function (e) {
20082        $(e.target).data("select2").$selection.one('keyup', function (e) {
20083          e.stopPropagation();
20084          return;
20085        });
20086      });
20087  
20088    $(window).load(function() {
20089        $('.utility-form-wrapper .advisor2-dropdown-list').find("#state").each(function(){
20090            $(this).val(' ').trigger("change");
20091        });
20092    });
20093    if($('.utilityForm').parent().hasClass('row')){
20094        $('.rowContainer .row > .utilityForm').css('margin','0px 15px');
20095    }
20096    function getQueryString() {
20097        var key = false, res = {}, itm = null;
20098        var qs = location.search.substring(1);
20099
20100        if (arguments.length > 0 && arguments[0].length > 1)
20101            key = arguments[0];
20102
20103        var pattern = /([^&=]+)=([^&]*)/g;
20104
20105        while (itm = pattern.exec(qs)) {
20106            if (key !== false && decodeURIComponent(itm[1]) === key)
20107                return decodeURIComponent(itm[2]);
20108            else if (key === false)
20109                res[decodeURIComponent(itm[1])] = decodeURIComponent(itm[2]);
20110        }
20111
20112        return key === false ? res : null;
20113    }
20114
20115    var dropCID = getQueryString('cid');
20116    if(dropCID){
20117        $('.utility-form-wrapper .campaign_id').each(function(e){
20118            $(this).val(`${dropCID}`);
20119        });
20120    }
20121
20122    if(homePageVideo.ElementExist($('.utilityFormSubmit'))){
20123        $('.utilityFormSubmit').on('submit', function(e) {
20124            e.preventDefault();
20125            var form = $(this);
20126            var url = '/content.salesforceAPI.connect';
20127            var currentPagePath  = $("#currentPagePath").val();
20128            var formData = form.serializeArray();
20129        	formData.push({name: "currentPagePath", value: currentPagePath});
20130            $.ajax({
20131                type: "POST",
20132                url: url,
20133                data: formData,
20134                success: function()
20135                {
20136                    console.log('Form Submitted');
20137                },
20138                error: function() {
20139                    console.log('Error in submitting module form');
20140                }
20141            });
20142            var redirectPage = $(this).find("input[name=retURL]").val();
20143    		setTimeout(function() {
20144    			window.location.href =  isEmpty(redirectPage)?window.location.pathname:redirectPage;
20145    		}, 2000);
20146        });
20147        function isEmpty(val){
20148            return (val === undefined || val == null || val.length <= 0) ? true : false;
20149        }
20150    }
20151});
20152
20153function recaptchaUtilityFormCallback(resp) {
20154    var response = resp;
20155    let recaptchaThresholdValue = $('#recaptcha-threshold').val();
20156    var url = "/content.enterpriseRecaptcha";
20157    $.ajax({
20158        type: "POST",
20159        url: url,
20160        data : {
20161            token: response,
20162            recaptchaThresholdValue: recaptchaThresholdValue
20163        },
20164        success: function (data) {
20165            let userObj = JSON.parse(data);
20166            if (userObj['isSuccess'] == true) {
20167                $('.utilityFormSubmit #recaptcha_html_element_utiltiy_form').attr('verified',true);
20168                bhfFormValidator.submitValidator($('.utilityFormSubmit .text-field-validation'));
20169                //return true;
20170            } else {
20171                $('.utilityFormSubmit #recaptcha_html_element_utiltiy_form').attr('verified',false);
20172                bhfFormValidator.submitValidator($('.utilityFormSubmit .text-field-validation'));
20173                return false
20174            }
20175        },
20176        error: function () {
20177            console.log('Error in getting verify response form');
20178            return false
20179        }
20180    });
20181}
20182
20183function recaptchaUtilityFormExpiredCallback() {
20184    $('.utilityFormSubmit #recaptcha_html_element_utiltiy_form').attr('verified',false);
20185    bhfFormValidator.submitValidator($('.utilityFormSubmit .text-field-validation'));
20186}
20187
20188$(document).ready(function() {
20189     if($('.advisor360.wholesaler-wrapper').length){
20190              const wholesaleInfoData = $('#wholeSaleData').val() || [];
20191              if (!wholeSalerAdvisor360.isJsonEmpty(JSON.parse(wholesaleInfoData))) {
20192                  let wholesalerDetails = JSON.parse(wholesaleInfoData);
20193                  if(wholesalerDetails.advisorDetailMap != null && Object.keys(wholesalerDetails.advisorDetailMap).length){
20194                      let wholeSalerDetails={};
20195                          //multiple relationship wholesalers
20196                      var template = $('#mustache-templ-multi-relationship-wholesaler').html();
20197                      wholeSalerDetails["generateWholeSalerDetails"]=[];
20198                      let formWholeSalerData = {"isTabExist":false,"isAnnuity":false,"isLife":false,"isNoWholeSaler":false};
20199                      firmsValues = Object.keys(wholesalerDetails.advisorDetailMap);
20200                      for(var i in firmsValues){
20201                          let resetData = wholeSalerAdvisor360.resetEmptyObject(wholesalerDetails.advisorDetailMap[firmsValues[i]]);
20202                          let firmValue = firmsValues[i].split('|')[0].trim();
20203                          wholeSalerDetails["generateWholeSalerDetails"].push({
20204                              id:i,
20205                              firmname:firmValue,
20206                              ...resetData,
20207                              ...formWholeSalerData
20208                          });
20209                      }
20210                      wholeSalerDetails["isDropdownExist"] = false;
20211                      if(firmsValues.length > 1) wholeSalerDetails["isDropdownExist"] = true;
20212                      let regenerateWholeSalerData = wholeSalerAdvisor360.updateIsWholeSalerExist(wholeSalerDetails);
20213                      var html = Mustache.to_html(template, regenerateWholeSalerData);
20214                      $('#wholesaler_info_content').append(html);
20215                      if(firmsValues.length > 1) wholeSalerAdvisor360.loadDropdown();
20216                      wholeSalerAdvisor360.loadTabs(regenerateWholeSalerData);
20217                      if(firmsValues.length > 1) wholeSalerAdvisor360.handleMultiRelationship(firmsValues);
20218                      wholeSalerAdvisor360.formatPhoneNumber();
20219                  }else{
20220                      $('#wholesaler_info_content').find('.no_wholesaler').removeClass('hide');
20221                      wholeSalerAdvisor360.formatPhoneNumber();
20222                  }
20223              }else{
20224                  $('#wholesaler_info_content').find('.no_wholesaler').removeClass('hide');
20225                  wholeSalerAdvisor360.formatPhoneNumber();
20226              }
20227           }
20228});
20229
20230
20231let wholeSalerAdvisor360 = {
20232    isJsonEmpty: function (obj) {
20233        for (var key in obj) {
20234            if (obj.hasOwnProperty(key))
20235                return false;
20236        }
20237        return true;
20238    },
20239    loadDropdown:function(){
20240        $('#wholesaler_multifirms').addClass("form-select-custom")
20241        $('#wholesaler_multifirms').select2();
20242    },
20243    formatPhoneNumber:function(){
20244        $('.wholesaler-phone').each(function(){
20245            let phoneNumber = $(this).find('.phone').text();
20246            phoneNumber = bhfFormValidator.formatPhoneNumber(phoneNumber);
20247            if(phoneNumber){
20248                $(this).find('.phone').text(phoneNumber);
20249            }else{
20250                $(this).addClass('hide');
20251            }
20252        })
20253    },
20254    handleMultiRelationship: function(firmsValues){
20255        $('.multi__tab__list').hide();
20256        if(firmsValues.length > 1) $('#firm_0').show();
20257        $('#wholesaler_multifirms').change(function () {
20258          $('.multi__tab__list').hide();
20259          $('#'+$(this).val()).show();
20260          $('#'+$(this).val()).find('.tabs-panel.is-active').attr('aria-hidden','false');
20261        })
20262    },
20263    loadTabs: function(wholeSalerDetails){
20264        wholeSalerDetails.generateWholeSalerDetails.map((resp,index)=>{
20265            if(resp.isTabExist) new Foundation.Tabs($(`#wholesaler_tabs_${resp.id}`));
20266            if(resp.isTabExist && resp.id==0){
20267                $(`#annuity_wholesaler_${resp.id}`).attr('aria-hidden',false);
20268            }
20269
20270        });
20271        $('.advisor360.wholesaler-wrapper').find(".tabs").on('change.zf.tabs', function(event){
20272            $(this).find('li').each(function(){
20273                $(`#${$(this).attr('tabId')}`).attr('aria-hidden',true);
20274                $(`#${$(this).attr('tabId')}`).removeClass('is-active');
20275                if($(this).hasClass('is-active')){
20276                    $(`#${$(this).attr('tabId')}`).attr('aria-hidden',false);
20277                    $(`#${$(this).attr('tabId')}`).addClass('is-active');
20278                }
20279            })
20280        });
20281    },
20282    updateIsWholeSalerExist:function(wholeSalerInfo){
20283        wholeSalerInfo.generateWholeSalerDetails.map((resp,index)=>{
20284            if((resp.annuityExternalDetail != null || resp.annuityInternalDetail != null) && (resp.lifeExternalDetail != null || resp.lifeInternalDetail != null)){
20285                resp.isTabExist = true;
20286                resp.annuityTabId=`annuity_wholesaler_${index}`
20287                resp.annuityTabRef=`#annuity_wholesaler_${index}`
20288                resp.lifeTabId=`life_wholesaler_${index}`
20289                resp.lifeTabRef=`#life_wholesaler_${index}`
20290            }else if(resp.annuityExternalDetail != null || resp.annuityInternalDetail != null){
20291                resp.isAnnuity = true;
20292            }else if(resp.lifeExternalDetail != null || resp.lifeInternalDetail != null){
20293                resp.isLife = true;
20294            }else{
20295                resp.isNoWholeSaler = true;
20296            }
20297        })
20298        return wholeSalerInfo;
20299    },
20300    resetEmptyObject: function(wholeSalerDetails){
20301        Object.keys(wholeSalerDetails).filter((val,key)=>{
20302            if(!Object.keys(wholeSalerDetails[val]).length) {
20303                wholeSalerDetails[val] = null;
20304            }
20305        });
20306        return wholeSalerDetails;
20307    }
20308}
20309
20310$(document).ready(function () {
20311    let userId = $('#logoutLink').data('userid');
20312    if($('.module-alert-tool-wrapper').length){
20313        $('.module-alert-tool-wrapper').each(function(){
20314            const uniqueId = $(this).attr('id');
20315            const compEle = $(this);
20316            $(compEle).find('.moduleText a').each(function(e){
20317                $(compEle).attr("onclick",`setCta("${$(this).text()}")`);
20318            });
20319            $(compEle).find('.module-welcome-close').on('click', function (e) {
20320                moduleAlert.welcomeCloseClick(e,uniqueId);
20321                e.stopPropagation();
20322            });
20323            $(compEle).find('.module-welcome-close').on('keypress', function (e) {
20324                if (e.type === 'keypress' && e.keyCode == 13) {
20325                    moduleAlert.welcomeCloseClick(e,uniqueId);
20326                    e.stopPropagation();
20327                }
20328            });
20329        })
20330        if(userId){
20331            let moduleAlertPostLoginInfo = moduleAlert.getIsLoginSession('moduleAlertPostLogin');
20332            if(!moduleAlertPostLoginInfo) moduleAlertPostLoginInfo=[];
20333            moduleAlertPostLoginInfo.map(item =>{
20334                if(item.isLoggedModuleClose){
20335                    $(`#${item.uniqueId}`).hide();
20336                }else{
20337                    $(`#${item.uniqueId}`).show();
20338                }
20339            });
20340        }else{
20341            let preLoginAlertComponent = moduleAlert.getIsLoginSession('moduleAlertprelogin');
20342            if(preLoginAlertComponent &&  preLoginAlertComponent.length){
20343                preLoginAlertComponent.map((item)=>{
20344                    let hours = 8;
20345                    let now = new Date().getTime();
20346                    if(item.NotLoggedModuleClose){
20347                        if((now - item.expiry) > hours * 60 * 60 * 1000){
20348                            $(`#${item.uniqueId}`).show();
20349                            var updatedPreLoginAlertComponent = preLoginAlertComponent.filter(x => {
20350                                return x.uniqueId != item.uniqueId;
20351                            })
20352                            localStorage.setItem('moduleAlertprelogin',updatedPreLoginAlertComponent)
20353                        }else{
20354                            $(`#${item.uniqueId}`).hide();
20355                        }
20356                    }else{
20357                        $(`#${uniqueId}`).show();
20358                    }    
20359                })
20360            }
20361        }
20362        appController.handleLogout();
20363    }
20364});
20365
20366const moduleAlert = {
20367    getIsLoginSession : function(key){
20368        if(localStorage.getItem(key)) {
20369            try{
20370                return JSON.parse(localStorage.getItem(key));
20371            }catch(e){
20372                console.log('Error getting the session data',e);
20373            }
20374        }
20375        else {
20376            return false;
20377        }
20378    },
20379    welcomeCloseClick: function(e,uniqueId){
20380        let userId = $('#logoutLink').data('userid');
20381        if(userId){
20382            let item ={
20383                'uniqueId':uniqueId,
20384                'isLoggedModuleClose' : true
20385            }
20386            let moduleAlertPostLoginInfo = moduleAlert.getIsLoginSession('moduleAlertPostLogin') || [];
20387            moduleAlertPostLoginInfo = [...moduleAlertPostLoginInfo,{...item}]
20388            localStorage.setItem('moduleAlertPostLogin',JSON.stringify(moduleAlertPostLoginInfo));
20389            $(`#${uniqueId}`).hide();
20390        }else{
20391            const now = new Date();
20392            let current_time = now.getTime();
20393            let preLoginInfo = moduleAlert.getIsLoginSession('moduleAlertprelogin');
20394            if(!preLoginInfo) preLoginInfo=[];
20395            let item ={
20396                'uniqueId':uniqueId,
20397                'NotLoggedModuleClose' : true,
20398                'expiry': current_time
20399            }
20400            preLoginInfo.push(item)
20401            localStorage.setItem('moduleAlertprelogin',JSON.stringify(preLoginInfo));
20402            $(`#${uniqueId}`).hide();
20403        }
20404    }
20405}
20406$(document).ready(function () {
20407    if($('.sidebar-cardinsight-wrapper').length && $('.sidebar-cardinsight-wrapper').data('isautopopulate')){
20408        $('.sidebar-cardinsight-wrapper').each(function(){
20409            const isAutoPopulate = $(this).data('isautopopulate');
20410            const pagePath = $(this).data('pagepath');
20411            const parentEle = $(this);
20412            if(isAutoPopulate){
20413                let payLoad={"articlePagePath":[]};
20414                let articlePagePath = pagePath || null;
20415                const templateId = $(this).find('#mustache-templ-sidebar-card-insight');
20416                const elementId= $(this).find('#sidebarInsight');
20417                const ajaxUrl = '/content.automaticPopulate.fetchProperties';
20418                payLoad.articlePagePath.push({"articlePagePath":articlePagePath});
20419                $.ajax({
20420                    url: ajaxUrl,
20421                    type: 'post',
20422                    data:{
20423                        "jsonData":JSON.stringify(payLoad)
20424                    },
20425                    success: function(data) {
20426                        if(data.length){
20427                            insightArticle.updateArticleInsights(data,parentEle,templateId,elementId);
20428                            $(parentEle).show();
20429                        }else{
20430                            $(parentEle).hide();
20431                        }
20432                    },
20433                    error: function(err){
20434                      console.log("Error getting article info")
20435                    }
20436                });
20437            }
20438        })
20439    }
20440    if($('.card-insight-primary-wrapper').length && $('.card-insight-primary-wrapper').data('isautopopulate')){
20441        $('.card-insight-primary-wrapper').each(function(){
20442            const isAutoPopulate = $(this).data('isautopopulate');
20443            const pagePath = $(this).data('pagepath');
20444            const parentEle = $(this);
20445            if(isAutoPopulate){
20446                let payLoad={"articlePagePath":[]};
20447                let articlePagePath = pagePath || null;
20448                const templateId = $(this).find('#mustache-templ-card-insight-primary');
20449                const elementId= $(this).find('#cardInsightPrimary');
20450                const ajaxUrl = '/content.automaticPopulate.fetchProperties';
20451                payLoad.articlePagePath.push({"articlePagePath":articlePagePath});
20452                $.ajax({
20453                    url: ajaxUrl,
20454                    type: 'post',
20455                    data:{
20456                        "jsonData":JSON.stringify(payLoad)
20457                    },
20458                    success: function(data) {
20459                        if(data.length){
20460                            insightArticle.updateArticleInsights(data,parentEle,templateId,elementId)
20461                            $(parentEle).show()
20462                        }else{
20463                            $(parentEle).hide()
20464                        }
20465                    },
20466                    error: function(err){
20467                      console.log("Error getting article info")
20468                    }
20469                });
20470                
20471            }
20472        })
20473    }
20474    if($('.card-insight-secondary-wrapper').length && ($('.card-insight-secondary-wrapper').find('.article_1').data('isautopopulate1') || $('.card-insight-secondary-wrapper').find('.article_2').data('isautopopulate2'))){
20475        $('.card-insight-secondary-wrapper').each(function(){
20476            const isAutoPopulate1 = $(this).find('.article_1').data('isautopopulate1');
20477            const isAutoPopulate2 = $(this).find('.article_2').data('isautopopulate2');
20478            const pagepath2 = $(this).find('.article_1').data('pagepath2');
20479            if(isAutoPopulate1){
20480                const pagePath1 = $(this).find('.article_1').data('pagepath1');
20481                const parentEle = $(this);
20482                const article_1_element = $(this).find('.article_1');
20483                let payLoad={"articlePagePath":[]};
20484                let articlePagePath = pagePath1 || null;
20485                const templateId = $(this).find('#mustache-templ-card-insight-secondary-article1');
20486                const elementId= $(this).find('#cardInsightPrimary_Article1');
20487                const ajaxUrl = '/content.automaticPopulate.fetchProperties';
20488                payLoad.articlePagePath.push({"articlePagePath":articlePagePath});
20489                $.ajax({
20490                    url: ajaxUrl,
20491                    type: 'post',
20492                    data:{
20493                        "jsonData":JSON.stringify(payLoad)
20494                    },
20495                    success: function(data) {
20496                        if(data.length){
20497                            insightArticle.updateArticleInsights(data,parentEle,templateId,elementId)
20498                            $(article_1_element).show();
20499                        }else{
20500                            $(article_1_element).hide();
20501                        }
20502                    },
20503                    error: function(err){
20504                      console.log("Error getting article info")
20505                    }
20506                });
20507                
20508            }
20509            if(isAutoPopulate2){
20510                const pagePath2 = $(this).find('.article_2').data('pagepath2');
20511                const parentEle = $(this);
20512                const article_2_element = $(this).find('.article_2');
20513                let payLoad={"articlePagePath":[]};
20514                let articlePagePath = pagePath2 || null;
20515                const templateId = $(this).find('#mustache-templ-card-insight-secondary-article2');
20516                const elementId= $(this).find('#cardInsightPrimary_Article2');
20517                const ajaxUrl = '/content.automaticPopulate.fetchProperties';
20518                payLoad.articlePagePath.push({"articlePagePath":articlePagePath});
20519                $.ajax({
20520                    url: ajaxUrl,
20521                    type: 'post',
20522                    data:{
20523                        "jsonData":JSON.stringify(payLoad)
20524                    },
20525                    success: function(data) {
20526                        if(data.length){
20527                            insightArticle.updateArticleInsights(data,parentEle,templateId,elementId)
20528                            $(article_2_element).show();
20529                        }else{
20530                            $(article_2_element).hide();
20531                        }
20532                    },
20533                    error: function(err){
20534                      console.log("Error getting article info")
20535                    }
20536                });
20537            }
20538        });
20539    }
20540});
20541
20542
20543const insightArticle = {
20544    finalArticleInfo: [],
20545    updateArticleInsights: function(articleData,parentelement,templateId,elementId){
20546        insightArticle.finalArticleInfo=[];
20547        for(var i in articleData){
20548            let parsed_array = articleData[i];
20549
20550            if (parsed_array.articleType === 'article') {
20551                parsed_array.article = true;
20552            } else if (parsed_array.articleType === 'video') {
20553                parsed_array.video = true;
20554            } else if (parsed_array.articleType === 'graph') {
20555                parsed_array.graph = true;
20556            } else if (parsed_array.articleType === 'quiz') {
20557                parsed_array.quiz = true;
20558            } else if (parsed_array.articleType === 'house') {
20559                parsed_array.house = true;
20560            } else if (parsed_array.articleType === 'panel') {
20561                parsed_array.panel = true;
20562            } else if (parsed_array.articleType === 'podcast') {
20563                parsed_array.podcast = true;
20564            }
20565
20566            var tag_list = parsed_array.tagDetailsList;
20567            if (tag_list.length > 0) {
20568                var first_tag = tag_list[0];
20569                var last_tag = tag_list[tag_list.length - 1];
20570                last_tag.last = true;
20571                first_tag.first = true;
20572                tag_list[0] = first_tag;
20573                tag_list[tag_list.length - 1] = last_tag;
20574            }
20575    
20576            parsed_array.topicList = tag_list;
20577    
20578            var contributors_list = parsed_array.contributors;
20579            if (contributors_list.length > 0) {
20580                var first_contributor = contributors_list[0];
20581                var last_contributor = contributors_list[contributors_list.length - 1];
20582                last_contributor.last = true;
20583                first_contributor.first = true;
20584                contributors_list[0] = first_contributor;
20585                contributors_list[contributors_list.length - 1] = last_contributor;
20586            }
20587            parsed_array.contributors = contributors_list;
20588            insightArticle.finalArticleInfo.push(parsed_array);
20589        }
20590        insightArticle.generateArticleInsight(insightArticle.finalArticleInfo,parentelement,templateId,elementId)
20591    },
20592    generateArticleInsight: function(finalArticleInfo,parentelement,templateId,elementId){
20593        var template = $(parentelement).find(templateId).html();
20594        var html = Mustache.to_html(template,finalArticleInfo);
20595        $(parentelement).find(elementId).append(html);
20596        imageRendition.showRendition();
20597    }
20598}
20599$(document).ready(function () {
20600    if($('.advisor2.card-insight-primary-wrapper').length){
20601        $('.advisor2.card-insight-primary-wrapper').each(function(){
20602            let isCardClickable = $(this).attr('data-card-clickable');
20603            if(isCardClickable){
20604                $(this).css('cursor','pointer');
20605                $(this).off('click');
20606                $(this).on('click', function(event) {
20607                    let target = $(this).attr('data-buttonTarget');
20608                    if(target){
20609                        window.open($(this).find('.card-title-link').attr('href'),'_blank');
20610                    }else{
20611                        window.open($(this).find('.card-title-link').attr('href'),'_self');
20612                    }
20613                })
20614            }
20615            setTimeout(() => {
20616                $(this).find('.card-title-link').each(function(){
20617                    $(this).on('click',function(e){
20618                       e.stopPropagation();
20619                    })  
20620                });
20621                $(this).find('.article-tag-name').each(function(){
20622                    $(this).on('click',function(e){
20623                       e.stopPropagation();
20624                    })  
20625                })
20626                $(this).find('.article-user-name').each(function(){
20627                    $(this).on('click',function(e){
20628                       e.stopPropagation();
20629                    })  
20630                })
20631            }, 1000);
20632            
20633        })
20634    }
20635});
20636$(document).ready(function () {
20637    if($('.advisor2.card-insight-secondary-wrapper').length){
20638        $('.cardInsight_Secondary.article_1').each(function(){
20639            let isCardClickable = $(this).attr('data-card-clickable');
20640            if(isCardClickable){
20641                $(this).css('cursor','pointer');
20642                $(this).off('click');
20643                $(this).on('click', function(event) {
20644                    let target = $(this).attr('data-buttonTarget');
20645                    if(target){
20646                        window.open($(this).find('.card-title-link').attr('href'),'_blank');
20647                    }else{
20648                        window.open($(this).find('.card-title-link').attr('href'),'_self');
20649                    }
20650                })
20651            }
20652
20653            setTimeout(() => {
20654                $(this).find('.card-title-link').each(function(){
20655                    $(this).on('click',function(e){
20656                       e.stopPropagation();
20657                    })  
20658                });
20659                $(this).find('.article-tag-name').each(function(){
20660                    $(this).on('click',function(e){
20661                       e.stopPropagation();
20662                    })  
20663                })
20664                $(this).find('.article-user-name').each(function(){
20665                    $(this).on('click',function(e){
20666                       e.stopPropagation();
20667                    })  
20668                })
20669            }, 1000);
20670        })
20671
20672        $('.cardInsight_Secondary.article_2').each(function(){
20673            let isCardClickable = $(this).attr('data-card-clickable');
20674            if(isCardClickable){
20675                $(this).css('cursor','pointer');
20676                $(this).off('click');
20677                $(this).on('click', function(event) {
20678                    let target = $(this).attr('data-buttonTarget');
20679                    if(target){
20680                        window.open($(this).find('.card-title-link').attr('href'),'_blank');
20681                    }else{
20682                        window.open($(this).find('.card-title-link').attr('href'),'_self');
20683                    }
20684                })
20685            }
20686
20687            setTimeout(() => {
20688                $(this).find('.card-title-link').each(function(){
20689                    $(this).on('click',function(e){
20690                       e.stopPropagation();
20691                    })  
20692                });
20693                $(this).find('.article-tag-name').each(function(){
20694                    $(this).on('click',function(e){
20695                       e.stopPropagation();
20696                    })  
20697                })
20698                $(this).find('.article-user-name').each(function(){
20699                    $(this).on('click',function(e){
20700                       e.stopPropagation();
20701                    })  
20702                })
20703            }, 1000);
20704        })
20705    }
20706});
20707
20708$(window).load(function() {
20709    if($('.equalizeInsightCard').children().length >0)  cardInsightGrid.customEqualiser();
20710});
20711$(document).ready(function () {
20712    if($('.advisor2.card-insight-tertiary-wrapper').length){
20713        $('.advisor2.card-insight-tertiary-wrapper').each(function(){
20714            let isCardClickable = $(this).attr('data-card-clickable');
20715            if(isCardClickable){
20716                $(this).css('cursor','pointer');
20717                $(this).off('click');
20718                $(this).on('click', function(event) {
20719                    let target = $(this).attr('data-buttonTarget');
20720                    if(target){
20721                        window.open($(this).find('.card-title-link').attr('href'),'_blank');
20722                    }else{
20723                        window.open($(this).find('.card-title-link').attr('href'),'_self');
20724                    }
20725                })
20726            }
20727            $('.article-tag-name').each(function(){
20728                $(this).on('click',function(e){
20729                   e.stopPropagation();
20730                })  
20731            })
20732    
20733            $('.article-user-name').each(function(){
20734                $(this).on('click',function(e){
20735                   e.stopPropagation();
20736                })  
20737            })
20738        })
20739    }
20740});
20741const eformsLoadMoreMethods={
20742    startIndex:0,
20743    showCount :0,
20744    hiddenResults:'',
20745    eformsLoadMoreData:'',
20746    eformsLoadMoreDataElements:'',
20747    eformsLoadMoreDataLength:0,
20748    loadMoreResults:function(){
20749        if($('.eforms-load-more-btn').length>0){
20750            $('.eforms-load-more-btn').on('click',function(){
20751                eformsLoadMoreMethods.hiddenResults.forEach((element,index) => {
20752                    if(index<eformsLoadMoreMethods.startIndex){
20753                      element.classList.remove('display-none');
20754                    }
20755                });
20756                eformsLoadMoreMethods.startIndex+=eformsLoadMoreMethods.showCount;
20757                if(eformsLoadMoreMethods.startIndex >= eformsLoadMoreMethods.eformsLoadMoreDataLength){
20758                    $('.eforms-load-more-btn').addClass('display-none');
20759                    $('.eforms-data-table').addClass('border-bottom');
20760                    $('.search-result-count').html(`Showing 1-${eformsLoadMoreMethods.eformsLoadMoreDataLength} of ${eformsLoadMoreMethods.eformsLoadMoreDataLength}`);
20761                }
20762                else{
20763                    $('.search-result-count').html(`Showing 1-${eformsLoadMoreMethods.startIndex} of ${eformsLoadMoreMethods.eformsLoadMoreDataLength}`);
20764                    $('.eforms-data-table').removeClass('border-bottom');
20765                }
20766            })
20767        }
20768    },
20769    hiddenSearchResults:function(arr){
20770        arr.forEach(el =>{
20771          el.classList.add('display-none');
20772        });
20773    },
20774    searchResultsBuilder:function(){
20775        eformsLoadMoreMethods.startIndex=0;
20776        eformsLoadMoreMethods.showCount=parseInt($('.eforms-load-more-container').attr('loadMoreCount'));
20777        eformsLoadMoreMethods.eformsLoadMoreDataElements=$('.eforms-data-table tbody tr');
20778        eformsLoadMoreMethods.eformsLoadMoreDataLength=eformsLoadMoreMethods.eformsLoadMoreDataElements.length;
20779        if(eformsLoadMoreMethods.eformsLoadMoreDataLength>0){
20780            if(eformsLoadMoreMethods.eformsLoadMoreDataLength > 0 && $('.search-result-count').length>0){
20781                if(eformsLoadMoreMethods.showCount < eformsLoadMoreMethods.eformsLoadMoreDataLength){
20782                    $('.search-result-count').html(`Showing 1-${eformsLoadMoreMethods.showCount} of ${eformsLoadMoreMethods.eformsLoadMoreDataLength}`);
20783                    $('.eforms-load-more-btn').removeClass('display-none');
20784                }
20785                else if (eformsLoadMoreMethods.eformsLoadMoreDataLength == 1){
20786                    $('.search-result-count').html(`Showing 1 of ${eformsLoadMoreMethods.eformsLoadMoreDataLength}`);   
20787                    $('.eforms-load-more-btn').addClass('display-none');    
20788                }
20789                else{
20790                    $('.search-result-count').html(`Showing 1-${eformsLoadMoreMethods.eformsLoadMoreDataLength} of ${eformsLoadMoreMethods.eformsLoadMoreDataLength}`);   
20791                    $('.eforms-load-more-btn').addClass('display-none'); 
20792                }
20793            
20794            }
20795            else{
20796                $('.search-result-count').html(''); 
20797            }
20798            eformsLoadMoreMethods.startIndex+=eformsLoadMoreMethods.showCount;
20799            eformsLoadMoreMethods.hiddenResults = Array.from(eformsLoadMoreMethods.eformsLoadMoreDataElements).slice(eformsLoadMoreMethods.startIndex,eformsLoadMoreMethods.eformsLoadMoreDataLength);
20800            eformsLoadMoreMethods.hiddenSearchResults(eformsLoadMoreMethods.hiddenResults);
20801        }
20802    },
20803    displayAll: function(){
20804        Array.from($('.eforms-data-table tbody tr')).forEach(tr=>{
20805            tr.classList.remove('display-none');
20806        })
20807    },
20808    sortedSearchResultBuilder:function(){
20809        if($('.eforms-data-table th').length>0){
20810            Array.from($('.eforms-data-table th')).forEach(th =>{
20811                $(th).on('click',function(){
20812                    eformsLoadMoreMethods.displayAll();
20813                    eformsLoadMoreMethods.eformsLoadMoreDataElements=$('.eforms-data-table tbody tr');
20814                    eformsLoadMoreMethods.eformsLoadMoreDataLength=eformsLoadMoreMethods.eformsLoadMoreDataElements.length;
20815                    if(eformsLoadMoreMethods.eformsLoadMoreDataLength > eformsLoadMoreMethods.startIndex){
20816                        $('.eforms-load-more-btn').removeClass('display-none');
20817                        $('.eforms-data-table').removeClass('border-bottom');
20818                    }
20819                    else{
20820                        $('.eforms-load-more-btn').addClass('display-none');
20821                        $('.eforms-data-table').addClass('border-bottom');
20822                    }
20823                    eformsLoadMoreMethods.hiddenResults = Array.from(eformsLoadMoreMethods.eformsLoadMoreDataElements).slice(eformsLoadMoreMethods.startIndex,eformsLoadMoreMethods.eformsLoadMoreDataLength);
20824                    eformsLoadMoreMethods.hiddenSearchResults(eformsLoadMoreMethods.hiddenResults);
20825                })
20826            });
20827        }
20828    }
20829};
20830
20831const toolTipMethods = {
20832    adjustTooltipHeight : function(){
20833        $('.tooltip-text').css('top',-($('.tooltip-text').height()/2) + "px");
20834    }
20835}
20836$(document).ready(function(){
20837    if($('.tool-tip').length > 0){
20838        toolTipMethods.adjustTooltipHeight();
20839    }
20840})
20841const multipleProductsModalMethods = {
20842    productList: {}, 
20843    filteredList: [], 
20844    filteredProductMap: {}, 
20845    showFilteredProduct: false, 
20846    sortListAscending: function () {
20847        const sortedEntries = Object.entries(multipleProductsModalMethods.productList)
20848            .sort((a, b) => a[1].toLowerCase().localeCompare(b[1].toLowerCase()));
20849        multipleProductsModalMethods.productList = Object.fromEntries(sortedEntries); 
20850        multipleProductsModalMethods.displayMultipleProducts();
20851        $('.sort-asc-btn').addClass('eforms-disabled');
20852        $('.sort-dsc-btn').removeClass('eforms-disabled');
20853    },
20854
20855    sortListDescending: function () {
20856        const sortedEntries = Object.entries(multipleProductsModalMethods.productList)
20857            .sort((a, b) => b[1].toLowerCase().localeCompare(a[1].toLowerCase()));
20858        multipleProductsModalMethods.productList = Object.fromEntries(sortedEntries); 
20859        multipleProductsModalMethods.displayMultipleProducts();
20860        $('.sort-asc-btn').removeClass('eforms-disabled');
20861        $('.sort-dsc-btn').addClass('eforms-disabled');
20862    },
20863 
20864    displayMultipleProducts: function () {
20865    const productListContainer = $('#product-list-container');
20866    let products = '';
20867 
20868    for (const [key, value] of Object.entries(multipleProductsModalMethods.productList)) {
20869        if (multipleProductsModalMethods.isStateView) {
20870            products += `<li>${value}</li>`;
20871        } else {
20872            products += `<li><span>${key}</span><span>${value}</span></li>`;
20873        }
20874    }
20875    if (multipleProductsModalMethods.filteredList.length > 0 && multipleProductsModalMethods.showFilteredProduct) {
20876        multipleProductsModalMethods.filteredList.forEach(key => {
20877            const value = multipleProductsModalMethods.filteredProductMap[key];
20878            if (value) {
20879                if (multipleProductsModalMethods.isStateView) {
20880                    products += `<li>${value}</li>`;
20881                } else {
20882                    products += `<li><span>${key}</span><span>${value}</span></li>`;
20883                }
20884            }
20885        });
20886    }
20887 
20888    	productListContainer.html(products);
20889	},
20890 
20891    showMultipleProductsModal: function () {
20892        $('#eforms-modal').removeClass('eforms-display-none');
20893
20894        $('#eforms-overlay').removeClass('eforms-display-none');
20895
20896    },
20897 
20898    hideMultipleProductsModal: function () {
20899        multipleProductsModalMethods.filteredList = [];
20900        multipleProductsModalMethods.filteredProductMap = {};
20901        $('#eforms-modal').addClass('eforms-display-none');
20902        $('#eforms-overlay').addClass('eforms-display-none');
20903    },
20904 
20905    calculateMaxHeight: function () {
20906        let productsLength = Object.keys(multipleProductsModalMethods.productList).length;
20907        if (multipleProductsModalMethods.showFilteredProduct) {
20908            productsLength += multipleProductsModalMethods.filteredList.length;
20909        }
20910 
20911        const productListContainer = document.getElementById('product-list-container');
20912        if (productListContainer) {
20913            let modalHeight;
20914            let columnCount; 
20915            const windowWidth = $(window).width(); 
20916            if (windowWidth > 768) {
20917                if (productsLength < 10) {
20918                    modalHeight = productsLength;
20919                    columnCount = 1;
20920                } else {
20921                    modalHeight = Math.floor(productsLength / 3);
20922                    columnCount = 3;
20923                }
20924
20925            } else if (windowWidth > 480 && windowWidth <= 768) {
20926                if (productsLength <= 30) {
20927                    modalHeight = productsLength;
20928                    columnCount = 1;
20929                } else {
20930                    modalHeight = Math.floor(productsLength / 2);
20931                    columnCount = 2;
20932                }
20933            } else {
20934                modalHeight = productsLength;
20935                columnCount = 2;
20936            } 
20937            productListContainer.setAttribute('style', `min-height:${modalHeight * 50}px;column-count:${columnCount}`);
20938        }
20939    },
20940 
20941    showMultipleStates: function (arr) {
20942        Array.from($('.form-multi-state')).forEach(st => {
20943            $(st).on('click', function () {
20944                $('.eforms-modal-state-heading').removeClass('eforms-display-none');
20945                $('.eforms-modal-prod-heading').addClass('eforms-display-none');
20946                $('.eforms-modal-state-title').removeClass('eforms-display-none');
20947                $('.eforms-modal-prod-title').addClass('eforms-display-none');
20948                $('.eforms-modal-policy-title').addClass('eforms-display-none'); 
20949                const clickedFormId = $(this).attr('formId'); 
20950                for (let i = 0; i < arr.length; i++) {
20951                    if (arr[i].formId === clickedFormId) {
20952                        multipleProductsModalMethods.showFilteredProduct = false;
20953                        multipleProductsModalMethods.isStateView = true;
20954                        multipleProductsModalMethods.productList = arr[i].states; 
20955                        if (Object.keys(multipleProductsModalMethods.productList).length > 1) {
20956                            multipleProductsModalMethods.sortListAscending();
20957                            multipleProductsModalMethods.showMultipleProductsModal();
20958                            $('body').css('overflow', 'hidden');
20959                            multipleProductsModalMethods.calculateMaxHeight();
20960                        }
20961                    }
20962                }
20963            });
20964        });
20965    },
20966 
20967    showMultipleProducts: function (arr) {
20968        let unsortedList = $('#tabelArea').attr('filteredProductList');
20969        unsortedList = unsortedList ? unsortedList.split(',') : []; 
20970        Array.from($('.form-multi-product')).forEach(pd => {
20971            $(pd).on('click', function () {
20972                $('.eforms-modal-state-heading').addClass('eforms-display-none');
20973                $('.eforms-modal-prod-heading').removeClass('eforms-display-none');
20974                $('.eforms-modal-state-title').addClass('eforms-display-none');
20975                $('.eforms-modal-prod-title').removeClass('eforms-display-none');
20976                $('.eforms-modal-policy-title').removeClass('eforms-display-none'); 
20977                const clickedFormId = $(this).attr('formId');
20978                 for (let i = 0; i < arr.length; i++) {
20979                    if (arr[i].formId === clickedFormId) {
20980                        multipleProductsModalMethods.showFilteredProduct = true;
20981                        multipleProductsModalMethods.isStateView = false;
20982                        multipleProductsModalMethods.filteredList = [];
20983                        multipleProductsModalMethods.filteredProductMap = {}; 
20984                        const newProductMap = {}; 
20985                        for (const [key, value] of Object.entries(arr[i].product)) {
20986                            if (unsortedList.includes(key)) {
20987                                multipleProductsModalMethods.filteredList.push(key);
20988                                multipleProductsModalMethods.filteredProductMap[key] = value;
20989                            } else {
20990                                newProductMap[key] = value;
20991                            }
20992                        }
20993 
20994                        multipleProductsModalMethods.productList = newProductMap;
20995                        if ((Object.keys(newProductMap).length + multipleProductsModalMethods.filteredList.length) > 1) {
20996                            multipleProductsModalMethods.sortListAscending();
20997                            multipleProductsModalMethods.showMultipleProductsModal();
20998                            $('body').css('overflow', 'hidden');
20999                            multipleProductsModalMethods.calculateMaxHeight();
21000                        }
21001                    }
21002                }
21003            });
21004        });
21005    },
21006};
21007
21008$(document).ready(function () {
21009    if ($('#eforms-overlay').length) {
21010        multipleProductsModalMethods.hideMultipleProductsModal(); 
21011        $('.close-eforms-modal').on('click', function () {
21012            multipleProductsModalMethods.hideMultipleProductsModal();
21013            $('body').css('overflow', 'auto');
21014        }); 
21015        $('.sort-asc-btn').on('click', function () {
21016            multipleProductsModalMethods.sortListAscending();
21017        }); 
21018        $('.sort-dsc-btn').on('click', function () {
21019            multipleProductsModalMethods.sortListDescending();
21020        });
21021        $(window).on('click', function (e) {
21022            if (e.target.id === "eforms-overlay") {
21023                multipleProductsModalMethods.hideMultipleProductsModal();
21024                $('body').css('overflow', 'auto');
21025            }
21026        });
21027    }
21028});
21029const searchSuggestionMethods = {
21030    showSuggestionTimer:null,
21031    count:0,
21032    isSearchTriggered:false,
21033    select(element){
21034        const searchWrapper = document.querySelector(".suggestive-search-input .wrapper .search-input-container");
21035        const inputBox = searchWrapper.querySelector("input");
21036        const suggestionBox = searchWrapper.querySelector(".autocomplete-box");
21037        let selectData = element.textContent.trim();
21038        inputBox.value = selectData;
21039        suggestionBox.blur();
21040        inputBox.focus();
21041        searchWrapper.classList.remove("active");
21042    },
21043    showSuggestions(list){
21044        const searchWrapper = document.querySelector(".suggestive-search-input .wrapper .search-input-container");
21045        const suggestionBox = searchWrapper.querySelector(".autocomplete-box");
21046        let listData = '';
21047        if(list.length>0){
21048            listData = list.join('');
21049        }
21050        suggestionBox.innerHTML = listData;
21051        
21052    },
21053    createSearchSuggestions(){
21054        const searchWrapper = document.querySelector(".suggestive-search-input .wrapper .search-input-container");
21055        const inputBox = searchWrapper.querySelector("input");
21056        const suggestionBox = searchWrapper.querySelector(".autocomplete-box");
21057        searchSuggestionMethods.count = 0;
21058        $(suggestionBox).on('focus',function(e){
21059            let len = $(suggestionBox).find('li').length;
21060            Array.from($(suggestionBox).find('li')).forEach((item,idx)=>{
21061                if(idx == searchSuggestionMethods.count){
21062                    $(item).addClass('active');
21063                    if(searchSuggestionMethods.count == 0){
21064                        suggestionBox.scrollTop = $(suggestionBox).scrollTop() + ($(item).offset().top - $(suggestionBox).offset().top);
21065                    }
21066                    else if(searchSuggestionMethods.count == len-1){
21067                        suggestionBox.scrollTop = $(suggestionBox).scrollTop() + ($(item).offset().top + $(item).outerHeight() -($(suggestionBox).offset().top + $(suggestionBox).outerHeight()));
21068                    }
21069                }
21070                else{
21071                    $(item).removeClass('active');
21072                }
21073            });
21074        });
21075        $(suggestionBox).on('scroll',function(e){
21076            if($(suggestionBox).scrollTop()<=0){
21077                $(suggestionBox).scrollTop(1);
21078            }
21079            else if($(suggestionBox).scrollTop()>= suggestionBox.scrollHeight-suggestionBox.clientHeight){
21080                $(suggestionBox).scrollTop($(suggestionBox).scrollTop()-1);
21081            }
21082        });
21083        $(suggestionBox).on('keyup',function(e){
21084            e.preventDefault();
21085            let len = $(suggestionBox).find('li').length;
21086            if(e.keyCode == 40){
21087                searchSuggestionMethods.count++;
21088                if(searchSuggestionMethods.count > len-1){
21089                    searchSuggestionMethods.count = 0;
21090                    inputBox.focus();
21091                    suggestionBox.blur();
21092                    Array.from($(suggestionBox).find('li')).forEach((item,idx)=>{
21093                        $(item).removeClass('active');
21094                    });
21095                }
21096                else{
21097                    Array.from($(suggestionBox).find('li')).forEach((item,idx)=>{
21098                        if(idx == searchSuggestionMethods.count){
21099                            $(item).addClass('active');
21100                            let container = $(suggestionBox);
21101                            let contHeight = container.height();
21102                            let elemTop = $(item).offset().top - container.offset().top;
21103                            let elemBottom = elemTop + $(item).height();
21104                            let isElementvisible = (elemTop >= 0 && elemBottom <=contHeight);
21105                            if(!isElementvisible)
21106                                suggestionBox.scrollTop = $(suggestionBox).scrollTop() + ($(item).offset().top + $(item).outerHeight() -($(suggestionBox).offset().top + $(suggestionBox).outerHeight()));    
21107                        }
21108                        else{
21109                            $(item).removeClass('active');
21110                        }
21111                    });
21112                }
21113            }
21114            else if(e.keyCode == 38){
21115                searchSuggestionMethods.count--;
21116                if(searchSuggestionMethods.count <0){
21117                    searchSuggestionMethods.count = 0;
21118                    inputBox.focus();
21119                    suggestionBox.blur();
21120                    Array.from($(suggestionBox).find('li')).forEac
21120h((item,idx)=>{
21121                        $(item).removeClass('active');
21122                    });
21123                }
21124                else{
21125                    Array.from($(suggestionBox).find('li')).forEach((item,idx)=>{
21126                        if(idx == searchSuggestionMethods.count){
21127                            $(item).addClass('active');
21128                            let container = $(suggestionBox);
21129                            let contHeight = container.height();
21130                            let elemTop = $(item).offset().top - container.offset().top;
21131                            let elemBottom = elemTop + $(item).height();
21132                            let isElementvisible = (elemTop >= 0 && elemBottom <=contHeight);
21133                            if(!isElementvisible)
21134                                suggestionBox.scrollTop = $(suggestionBox).scrollTop() + ($(item).offset().top - $(suggestionBox).offset().top);    
21135                        }
21136                        else{
21137                            $(item).removeClass('active');
21138                        }
21139                    });
21140                }
21141            }
21142        });
21143        $(inputBox).on("blur", function () {
21144            if (this.createTextRange) {
21145                let part = this.createTextRange();
21146                part.move("character", 0);
21147                part.select();
21148            } else if (this.setSelectionRange) {
21149                this.setSelectionRange(0, 0);
21150            }
21151        });
21152        $(inputBox).on('keyup',function(e){
21153            let userData = e.target.value;
21154            let emptyArray = [];
21155            if(userData.trim().length>0 && e.keyCode != 40 && e.keyCode != 38 && e.keyCode != 13){
21156                searchSuggestionMethods.count=0;
21157                searchSuggestionMethods.isSearchTriggered=false;
21158                if(searchSuggestionMethods.showSuggestionTimer!=null)
21159                { clearTimeout(searchSuggestionMethods.showSuggestionTimer);
21160                } 
21161                searchSuggestionMethods.showSuggestionTimer = setTimeout(()=>{
21162                  searchSuggestionMethods.showSuggestionTimer=null;
21163                    $.ajax({
21164                            type: "POST",
21165                            url: `/content.getSuggestions?searchKey=${e.target.value}`,
21166                            success:function(res){
21167                                if(res.length>0 && searchSuggestionMethods.isSearchTriggered == false){
21168                                    emptyArray = res;
21169                                    emptyArray = emptyArray.map((data)=>{
21170                                        return data = `<li tabindex = "-1">${data}</li>`;
21171                                    });
21172                                    searchWrapper.classList.add("active");
21173                                    searchSuggestionMethods.showSuggestions(emptyArray);
21174                                    let allList = suggestionBox.querySelectorAll("li");
21175                                    for (let i = 0; i < allList.length; i++) {
21176                                        allList[i].setAttribute("onclick", "searchSuggestionMethods.select(this)");
21177                                    }
21178                                }
21179                                else{
21180                                    searchWrapper.classList.remove("active");
21181                                }
21182                                    
21183                            },
21184                            error:function(error){
21185                            console.log(error);
21186                            }
21187                    });
21188                },500);  
21189            }
21190            else if(userData.trim().length>0 && e.keyCode == 40 ){
21191                searchSuggestionMethods.count=0;
21192                inputBox.blur();
21193                suggestionBox.focus({preventScroll:true});
21194            }
21195            else if(userData.trim().length>0 && e.keyCode == 38 ){
21196                searchSuggestionMethods.count=$(suggestionBox).find('li').length-1;
21197                inputBox.blur();
21198                suggestionBox.focus({preventScroll:true});
21199            }
21200            else if(userData.trim().length>0 && e.keyCode == 13){
21201                e.preventDefault();
21202                searchSuggestionMethods.select($(suggestionBox).find('li')[searchSuggestionMethods.count]);
21203            }
21204            else if(userData.trim().length<=0){
21205                searchWrapper.classList.remove("active");
21206            }
21207        });
21208    }
21209};
21210
21211let stateArr = ["Alabama",
21212"Alaska",
21213"Arizona",
21214"Arkansas",
21215"California",
21216"Colorado",
21217"Connecticut",
21218"Delaware",
21219"Florida",
21220"Georgia",
21221"Hawaii",
21222"Idaho",
21223"Illinois",
21224"Indiana",
21225"Iowa",
21226"Kansas",
21227"Kentucky",
21228"Louisiana",
21229"Maine",
21230"Maryland",
21231"Massachusetts",
21232"Michigan",
21233"Minnesota",
21234"Mississippi",
21235"Missouri",
21236"Montana",
21237"Nebraska",
21238"Nevada",
21239"New Hampshire",
21240"New Jersey",
21241"New Mexico",
21242"New York",
21243"North Carolina",
21244"North Dakota",
21245"Ohio",
21246"Oklahoma",
21247"Oregon",
21248"Pennsylvania",
21249"Rhode Island",
21250"South Carolina",
21251"South Dakota",
21252"Tennessee",
21253"Texas",
21254"Utah",
21255"Vermont",
21256"Virginia",
21257"Washington",
21258"West Virginia",
21259"Wisconsin",
21260"Wyoming",
21261"American Samoa",
21262"District Of Columbia",
21263"Federated States of Micronesia",
21264"Guam",
21265"Marshall Islands",
21266"Commonwealth of the Northern Mariana Islands",
21267"Palau",
21268"Puerto Rico",
21269"U.S. Virgin Islands"];
21270
21271const eFormSearchMethods = {
21272  productCategoryMap:{},
21273  lifeProductCategoryMap:{},
21274  isDataGetOnLoad: false,
21275  allCheckedDataPath: [],
21276  requiredDataPlacedTopDataSet: [],
21277  isPackageAvailable:false,
21278  availablePackageName: '',
21279  showSearchFilters : function(...filterList){
21280    if($('.search-filter-list ul').length>0){
21281      $('.search-filter-list').empty()
21282    }
21283       let filtersElements='<ul>';
21284       let filterCount=0;
21285       filterList.forEach((el)=>{
21286       if(el.property == 'radioBtnValue'){
21287           if(el.value != 'All' && el.value != ''){
21288               filterCount++;
21289               if(el.value == 'lifeInsurance'){
21290               filtersElements+=`<li>`+$('.life-insurance-label label').text().trim()+`</li>`;      
21291               }
21292               else if(el.value == 'Annuities'){
21293               filtersElements+=`<li>`+$('.annuities-label label').text().trim()+`</li>`;      
21294               }
21295               else{
21296               filtersElements+=`<li>${el.value}</li>`;
21297               }
21298               
21299           }
21300       }
21301       else {
21302           if(el.value !== '' && el.value){  
21303            const allState= $('.eforms-state option');
21304               if(el.property == 'state' && (typeof el.value == 'object')){
21305                if(el.value.length == allState.length-2){
21306                  filtersElements+='<li>'+$(".eforms-state").data("all-states-label")+'</li>';
21307                  filterCount++;
21308                }
21309                 else if(el.value.length>5){
21310                  filtersElements+=`<li>Multiple States Selected</li>`;
21311                  filterCount++;
21312                 }
21313                 else{
21314                    el.value.forEach(e=>{
21315                    filtersElements+=`<li>${e}</li>`;
21316                    filterCount++;   
21317                   });
21318                 }
21319                 
21320               }
21321               else if(el.property == 'productCategory'){
21322                if(el.value != 'Life'){
21323                  filtersElements+=`<li>${$('.product-category-annuties select').find(':selected').text()}</li>`
21324                  filterCount++;
21325                }else if(eformsLoadMoreMethods.isDataGetOnLoad){
21326                  filtersElements+=`<li>${$('.product-category-annuties select').find(':selected').text()}</li>`
21327                  filterCount++;
21328                }
21329                }
21330                else{
21331                  filtersElements+=`<li>${el.value}</li>`;
21332                  filterCount++;
21333                }
21334           }
21335       }
21336       eFormSearchMethods.showFilterCount(filterCount);   
21337       });
21338       filtersElements+='</ul>';
21339       if(filterCount>0){
21340        $('.search-filters-div').find('.search-filter-list').html(filtersElements);
21341       }
21342        if($(window).width()<=991){
21343          $('.accordian-tabe-content').css('margin-top',"48px");
21344        }
21345   },
21346   productCategoryMapBuilder:function(){
21347    Array.from($('.an-product-name select option')).forEach(options=>{
21348        let prodCategory = $(options).attr('product-category-menu');
21349        let productNameOption = $(options).text() ?  $(options).text().trim() : null;
21350        if(!!productNameOption){
21351          if(prodCategory in eFormSearchMethods.productCategoryMap){
21352            if(!eFormSearchMethods.productCategoryMap[prodCategory].includes(productNameOption)){
21353              eFormSearchMethods.productCategoryMap[prodCategory].push(productNameOption);
21354            }
21355          } else{
21356            eFormSearchMethods.productCategoryMap[prodCategory]=[productNameOption];
21357          }
21358        }
21359      });
21360  },
21361  lifeProductCategoryMapBuilder:function(){
21362    Array.from($('.life-product-name select option')).forEach(options=>{
21363      let prodCategory = $(options).attr('product-category-menu');
21364      let productNameOption = $(options).text() ?  $(options).text().trim() : null;
21365      if(!!productNameOption){
21366        if(prodCategory in eFormSearchMethods.lifeProductCategoryMap){
21367          if(!eFormSearchMethods.lifeProductCategoryMap[prodCategory].includes(productNameOption)){
21368            eFormSearchMethods.lifeProductCategoryMap[prodCategory].push(productNameOption)
21369          }
21370        } else{
21371          eFormSearchMethods.lifeProductCategoryMap[prodCategory]=[productNameOption];
21372        }
21373      }
21374    });
21375  },
21376  narrowDownProductNames:function(){
21377    $('.product-category-annuties select').on('change',function(val, event){
21378    if(event == 'life' || $('input[name="lineofbusiness"]:checked').val()=="lifeInsurance"){
21379      let productCategoryAnnuities = $('.product-category-annuties select').find(':selected').val();
21380      let productNames = eFormSearchMethods.lifeProductCategoryMap[productCategoryAnnuities];
21381      let productList;
21382      if(productNames && productCategoryAnnuities){
21383        let productCategoryOption = $('.product-category-annuties').attr('product-category-placeholder-an');
21384        productList = `<option value="">${productCategoryOption}</option>`;
21385        productNames = productNames.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
21386        productNames.forEach(productNameOption=>{
21387          productList+=`<option value="${productNameOption}">${productNameOption}</option>`
21388        });
21389      }
21390      if(!!productList){
21391        $('.product-name').removeClass('disabled-dropdown');
21392        $('.product-name select').html(productList);
21393      }else{
21394        $('.product-name select').html('');
21395        $('.product-name').addClass('disabled-dropdown');
21396      }
21397    }else{
21398      let productCategoryAnnuities = $('.product-category-annuties select').find(':selected').val();
21399      let productNames = eFormSearchMethods.productCategoryMap[productCategoryAnnuities];
21400      let productList;
21401      if(productNames && productCategoryAnnuities){
21402        let productCategoryOption = $('.product-category-annuties').attr('product-category-placeholder-life');
21403        productList = `<option value="">${productCategoryOption}</option>`;
21404        productNames = productNames.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
21405        productNames.forEach(productNameOption=>{
21406          productList+=`<option value="${productNameOption}">${productNameOption}</option>`
21407        });
21408      }
21409      if(!!productList){
21410        $('.product-name').removeClass('disabled-dropdown');
21411        $('.product-name select').html(productList);
21412        }else{
21413        $('.product-name select').html('');
21414        $('.product-name').addClass('disabled-dropdown');
21415      }
21416    }
21417    });
21418  },
21419  formTypeMapBuilder:function(event){
21420    let formTypeList;
21421    if(event === 'annuities'){
21422      if(!!$('.form-type select').attr('form-type-list-an')){
21423        $('.form-type').removeClass('display-none');
21424        $('.field-label-form-type-an').removeClass("display-none");
21425        $('.field-label-form-type-life').addClass("display-none");
21426        let annuitiesformTypeList = $('.form-type select').attr('form-type-list-an').replace("[","").replace("]","").split(',');
21427        annuitiesformTypeList = annuitiesformTypeList.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
21428        annuitiesformTypeList.forEach(productNameOption=>{
21429          if(productNameOption!== 'Choose One'){
21430            formTypeList+=`<option value="${productNameOption}">${productNameOption}</option>`
21431          $('.form-type select').html(formTypeList);
21432          }
21433        })
21434      }else{
21435        $('.form-type select').html('');
21436        $('.form-type').addClass('display-none');
21437        $('.field-label-form-type-an').addClass("display-none");
21438        $('.field-label-form-type-life').addClass("display-none");
21439      }
21440    }else{
21441      if(!!$('.form-type select').attr('form-type-list-life')){
21442        $('.form-type').removeClass('display-none');
21443        $('.field-label-form-type-life').removeClass("display-none");
21444        $('.field-label-form-type-an').addClass("display-none");
21445        let formTypeOption = $('.form-type select').attr('form-type-placeholder-life');
21446        formTypeList = `<option value="">${formTypeOption}</option>`;
21447        let lifeformTypeList = $('.form-type select').attr('form-type-list-life').replace("[","").replace("]","").split(',');
21448        lifeformTypeList = lifeformTypeList.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
21449        lifeformTypeList.forEach(productNameOption=>{
21450          if(productNameOption!== 'Choose One'){
21451            formTypeList+=`<option value="${productNameOption}">${productNameOption}</option>`
21452            $('.form-type select').html(formTypeList);
21453          }
21454        })
21455      }else{
21456        $('.form-type select').html('');
21457        $('.form-type').addClass('display-none');
21458        $('.field-label-form-type-an').addClass("display-none");
21459        $('.field-label-form-type-life').addClass("display-none");
21460      }
21461    }
21462},
21463
21464
21465
21466  productCategoryBindForLife:function(event){
21467    if(event == 'life'){
21468    $('.product-category-annuties select').html('');
21469    let productCategoryOptions = $('.product-category-annuties').attr('product-category-placeholder-life');
21470    productCategoryOptions = `<option value="">${productCategoryOptions}</option>`;
21471    let productNames = $('.product-category-annuties select').attr('form-category-list-life');
21472    if(productNames){
21473      productNames = productNames.replace("[","").replace("]","").split(',');
21474      productNames = productNames.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))
21475      productNames.forEach(productNameOption=>{
21476        if(productNameOption !== 'undefined' && productNameOption !== 'Choose One'){
21477          productCategoryOptions+=`<option value="${productNameOption}">${productNameOption}</option>`
21478        }
21479      });
21480      $('.product-category-annuties select').html(productCategoryOptions);
21481    }
21482    }else{
21483      let productCategoryOptions = $('.product-category-annuties').attr('product-category-placeholder-an');
21484      productCategoryOptions = `<option value="">${productCategoryOptions}</option>`;
21485      let productNames = $('.product-category-annuties select').attr('form-category-list-an');
21486      if(productNames){
21487        productNames = productNames.replace("[","").replace("]","").split(',');
21488        productNames = productNames.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))
21489          productNames.forEach(productNameOption=>{
21490            if(productNameOption !== 'undefined' && productNameOption !== 'Choose One'){
21491              productCategoryOptions+=`<option value="${productNameOption}">${productNameOption}</option>`
21492            }
21493         });  
21494        $('.product-category-annuties select').html(productCategoryOptions);
21495      }
21496    }
21497  },  
21498
21499  enableSearchButton:function(){
21500      $('input[name="lineofbusiness"], .product-category-annuties select, .product-name select, .form-type,.eforms-state').on('change',function(){
21501          let radioBtnValue = $('input[name="lineofbusiness"]:checked').val();
21502          let productCategoryAnnuities = $('.product-category-annuties select').find(':selected').val();
21503          let state = $('.eforms-state').find(':selected').val();
21504          let productAnNames = eFormSearchMethods.productCategoryMap[productCategoryAnnuities];
21505          let productLifeNames = eFormSearchMethods.lifeProductCategoryMap[productCategoryAnnuities];
21506          if(!!eFormSearchMethods.formTypeValidation(radioBtnValue)){
21507            $('.eforms-submit.button-primary').addClass('disabled-btn');
21508            return;
21509          }else{
21510            $('.eforms-submit.button-primary').removeClass('disabled-btn');
21511          }
21512          if((productCategoryAnnuities != '') && ((radioBtnValue === "lifeInsurance" && !!productLifeNames) || (radioBtnValue !== "lifeInsurance" && !!productAnNames))){
21513              $('.product-name').removeClass('disabled-dropdown');
21514          }
21515          else{
21516            $('.product-name').addClass('disabled-dropdown');
21517          }
21518          if(productCategoryAnnuities != '' || state != '' || radioBtnValue != '' || $('.eform-search-input.search-input.searchKeyword').val().length>0){
21519            $('.eforms-clear-filter').removeClass('disabled-link');
21520          }
21521          
21522          if(radioBtnValue == 'All' && !state  &&  $('.eform-search-input.search-input.searchKeyword').val().length<=0){
21523            $('.eforms-submit.button-primary').addClass('disabled-btn');
21524          }
21525          else if( productCategoryAnnuities != '' || state != '' || radioBtnValue != ''){
21526              $('.eforms-submit.button-primary').removeClass('disabled-btn');
21527          }
21528          else{
21529              $('.eforms-submit.button-primary').addClass('disabled-btn');
21530          }
21531      });
21532      $('.eform-search-input.search-input.searchKeyword').on('keyup',function(event){
21533          let keycode = (event.keyCode ? event.keyCode : event.which);
21534          if(keycode != '13'){
21535            let radioBtnValue = $('input[name="lineofbusiness"]:checked').val();
21536            let productCategoryAnnuities = $('.product-category-annuties select').find(':selected').val();
21537            let state = $('.eforms-state').find(':selected').val();
21538            if($(this).val().length == 0 && !state  && radioBtnValue == 'All'){
21539              $('.eforms-submit.button-primary').addClass('disabled-btn');  
21540            }
21541            else if($(this).val().length>0 || productCategoryAnnuities != '' || state != '' || radioBtnValue == 'Annuities' || radioBtnValue == 'lifeInsurance'){ 
21542                $('.eforms-submit.button-primary').removeClass('disabled-btn');
21543            }
21544            else{
21545                $('.eforms-submit.button-primary').addClass('disabled-btn');
21546            }
21547          }
21548      })
21549  }, 
21550  viewFilterAccordion:function(){   
21551      eFormSearchMethods.adjustFilterTagPosition();
21552      $('.search-filters-div').find('.accordion-item').addClass('is-active')
21553      $('.search-filters-div').find('.accordion-item').children('.show-accordion-title').addClass('display-none');
21554      $('.search-filters-div').find('.accordion-item').children('.edit-accordion-title').addClass('display-none');
21555  },
21556  changeFilterAccordionTitle:function(){
21557    eFormSearchMethods.adjustFilterTagPosition();
21558      if($('.search-filters-div').find('.accordion-item').hasClass('is-active')){
21559          $('.search-filters-div').find('.accordion-item').children('.hide-accordion-title').removeClass('display-none');
21560          $('.search-filters-div').find('.accordion-item').children('.show-accordion-title').addClass('display-none');
21561          $('.search-filters-div').find('.accordion-item').children('.edit-accordion-title').addClass('display-none');    
21562          $('.accordian-tabe-content').removeClass('display-none');
21563      }
21564      else{
21565          if($('.search-filters-div').find('.accordion-item').children('.search-filter-list').html().length>0){
21566              $('.search-filters-div').find('.accordion-item').children('.edit-accordion-title').removeClass('display-none');
21567              $('.search-filters-div').find('.accordion-item').children('.show-accordion-title').addClass('display-none');
21568          }
21569          else{
21570              $('.search-filters-div').find('.accordion-item').children('.edit-accordion-title').addClass('display-none');
21571              $('.search-filters-div').find('.accordion-item').children('.show-accordion-title').removeClass('display-none');
21572          }
21573          $('.search-filters-div').find('.accordion-item').children('.hide-accordion-title').addClass('display-none');
21574      }
21575  },
21576  showFilterCount:function(count){
21577      if(count>0){
21578          $('.search-filters-div').find('#search-filter-count').html(` (${count})`);
21579      }
21580  },
21581  adjustFilterTagPosition:function(){
21582    if($(window).width()>991){
21583      let maxWidthTitle=0;
21584      Array.from($('.search-filters-div .accordion-title')).forEac
21584h(el=>{
21585        if($(el).hasClass('display-none')){
21586          $(el).removeClass('display-none');
21587          maxWidthTitle=Math.max(maxWidthTitle,$(el).width());
21588          $(el).addClass('display-none');
21589        }
21590        else{
21591          maxWidthTitle=Math.max(maxWidthTitle,$(el).width());
21592        }
21593      });
21594      $('.search-filters-div .accordion-item .accordion-title').css('min-width',maxWidthTitle+"px");
21595    }
21596  },
21597  changeSearchText:function(){
21598    $('.post-search-btn').removeClass('display-none');
21599    $('.pre-search-btn').addClass('display-none');
21600    $('.post-search-btn').text($('.post-search-btn').data('post-search-label'));
21601    $('.pre-search-btn').text($('.post-search-btn').data('post-search-label'));
21602    if($('.search-filter-list ul').length>0){
21603      if($('.search-filter-list ul').html().length>0){
21604        $('.eforms-clear-filter').removeClass('disabled-link');
21605      }
21606      else{
21607        $('.eforms-clear-filter').addClass('disabled-link');
21608      }
21609    }
21610  },
21611  implementEllipsis:function(){
21612    const ellipsisText=$('#tabelArea').attr('ellipsisText');
21613    Array.from($('.eforms-data-table').find('.eforms-desc')).forEach(formDesc=>{
21614      let description =$(formDesc).text().trim();
21615      if(description.length>142){
21616        let subStr = description.substring(0, 143);
21617        let hiddenStr = description.substring(143,description.length);
21618        $(formDesc).empty().html(subStr);
21619        $(formDesc).append('<span class="eforms-ellipsis">...</span>')
21620        $(formDesc).append('<div class="eforms-ellipsis-link eforms-ellipsis-text">'+ellipsisText+'</div>');
21621        $(formDesc).append('<span class="eforms-more-text">'+hiddenStr+'</span>');
21622      }
21623    });
21624    Array.from($('.eforms-data-table').find('.eforms-name')).forEach(formName=>{
21625      let description =$(formName).text().trim();
21626      if(description.length>130){
21627        let subStr = description.substring(0, 130);
21628        let hiddenStr = description.substring(130,description.length);
21629        $(formName).empty().html(subStr);
21630        $(formName).append('<a href="javascript:void(0);" class="eforms-ellipsis-link">…</a>');
21631        $(formName).append('<span class="eforms-more-text">'+hiddenStr+'</span>');
21632      }
21633    });
21634    $('.eforms-ellipsis-link').click(function(){
21635      $(this).siblings(".eforms-more-text").contents().unwrap();
21636      $(this).prevAll('.eforms-ellipsis').remove();
21637      $(this).remove();
21638    })
21639  },
21640  clearSearchFilters:function(){
21641    $('input[value="All"]').trigger('click');
21642    $('.eforms-state').val(null).trigger('change');
21643    let statePlaceholder =$('.placeholder-div .state-value-span').attr('placeholder-text'); 
21644    $('.placeholder-div .state-value-span').text(statePlaceholder); 
21645    $('.product-category-annuties select').val(null).trigger('change');
21646    $('.product-name select').val(null).trigger('change');
21647    $('.form-type select').val(null).trigger('change');
21648    $('.eforms-clear-filter').addClass('disabled-link');
21649    $('.download-package-alert-section').addClass('display-none');
21650    $(".package-selected").text('');
21651    if($('.pre-search-btn').hasClass('display-none')){
21652      $(".eforms-submit").eq(1).trigger("click");
21653    }
21654  
21655  },
21656  focusOutSortingButtons:function(){
21657    let sortingIcons = $('#tabelArea thead').find('th');
21658    if(sortingIcons.length>0){
21659      Array.from(sortingIcons).forEach(icon=>{
21660        $(icon).on('click',function(event){
21661          if($(event.target).is('th')){
21662            if($(event.target).hasClass('sorting_desc') || $(event.target).hasClass('sorting')){
21663              $(event.target).find('.descending-icon').removeClass('disable-btn');
21664              $(event.target).find('.accending-icon').addClass('disable-btn');
21665            }
21666            else if ($(event.target).hasClass('sorting_asc')){
21667              $(event.target).find('.descending-icon').addClass('disable-btn');
21668              $(event.target).find('.accending-icon').removeClass('disable-btn');
21669            }
21670          }
21671          else{
21672            if($(event.target).closest('th').hasClass('sorting_desc') || $(event.target).closest('th').hasClass('sorting')){
21673              $(event.target).closest('th').find('.descending-icon').removeClass('disable-btn');
21674              $(event.target).closest('th').find('.accending-icon').addClass('disable-btn');
21675            }
21676            else if ($(event.target).closest('th').hasClass('sorting_asc')){
21677              $(event.target).closest('th').find('.descending-icon').addClass('disable-btn');
21678              $(event.target).closest('th').find('.accending-icon').removeClass('disable-btn');
21679            }
21680          }
21681         
21682        })
21683      })
21684    }
21685  },
21686  
21687  sendParamValue:function(val){
21688    return data = {
21689      id: val,
21690      text: val,
21691    };
21692  },
21693
21694  isValueExist:function(selector, data){
21695    let found = false;
21696    $(selector).each(function(key,value){
21697      if(value.text === data.trim()){
21698        found =  true
21699      }
21700    })
21701    return found;
21702  },
21703
21704  loadDataToParamState: function () {
21705    var formWrapperElement = $('.search-form-wrapper');
21706    if(formWrapperElement.attr('data-filters') != undefined) {
21707      const searchParams = new URLSearchParams(window.location.search);
21708      const searchResultData = JSON.parse(formWrapperElement.attr('data-filters'));
21709      const lineOfBusiness = searchResultData["lineOfBusiness"][0];
21710      const productCategory = searchResultData["productCategory"][0];
21711      const productName = searchResultData["product"][0];
21712      const formType = searchResultData["formType"][0];
21713      let states = searchParams.get("st");
21714      if((!!searchResultData && !!lineOfBusiness) && (lineOfBusiness==="Annuities" || lineOfBusiness==="Life Insurance")){
21715        eformsLoadMoreMethods.isDataGetOnLoad = true;
21716        if(lineOfBusiness==="Annuities") {
21717          $(".lineofbusiness-radionBtn-div input#lineOfBusinessAnnuities:nth(0)").trigger("click");
21718        } else{
21719          $( ".lineofbusiness-radionBtn-div input#lineOfBusinessLife:nth(0)").trigger("click");
21720        }
21721
21722        if (!!productCategory && !!eFormSearchMethods.isValueExist('.product-category-annuties select option', productCategory.trim())) {
21723          let data = eFormSearchMethods.sendParamValue(productCategory);
21724            $(".product-category-annuties select").val((data.id).trim()).trigger("change");
21725        }
21726
21727        if (!!productName) {
21728          let data = eFormSearchMethods.sendParamValue(productName);
21729            if(lineOfBusiness==="Annuities" && !!eFormSearchMethods.isValueExist('.product-name .an-product-name select option', productName.trim())){
21730              $(".product-name .an-product-name select").val((data.id).trim()).trigger("change");
21731            }else if(lineOfBusiness==="Life Insurance" && !!eFormSearchMethods.isValueExist('.product-name .life-product-name select option', productName.trim())){
21732              $(".product-name .life-product-name select").val((data.id).trim()).trigger("change");
21733            }
21734        }
21735
21736        if (!!formType && !!eFormSearchMethods.isValueExist('.form-type select option', formType.trim())) {
21737          let data = eFormSearchMethods.sendParamValue(formType);
21738          $(".form-type select").val((data.id).trim()).trigger("change");
21739        }
21740
21741        if (!!states) {
21742          let data = eFormSearchMethods.sendParamValue(states.trim());
21743          let stateName;
21744          let statesList = formWrapperElement.data('state-names');
21745          let territoriesList = formWrapperElement.data('territory-names');
21746          statesList =  {...statesList, ...territoriesList};
21747          for(let key in statesList){
21748            if(statesList[key]===data.id){
21749              stateName = key;
21750            }
21751          }
21752          if(!!stateName && !!$(".eforms-state").select2().find("option[value='" + (stateName).trim() + "']").length){
21753                $(".eforms-state").val((stateName).trim()).trigger("change");
21754                $(".placeholder-div .state-value-span").text(stateName);
21755          }
21756        }
21757
21758        $(".eforms-submit").eq(1).trigger("click", "onLoadEvent");
21759      }
21760    }
21761  },
21762
21763
21764  formTypeValidation: function(radioBtnValue){
21765    let productCategory = $('.product-category-annuties select').find(':selected').val();
21766    let productName = $('.life-product-name select').find(':selected').val() ? $('.life-product-name select').find(':selected').val().trim() : "";;
21767    let formType = $('.form-type').find(':selected').val();
21768    let state = $('.eforms-state').find(':selected').val()
21769    if(radioBtnValue==="lifeInsurance" && (formType==="New Business with Replacement" || formType==="New Business" || formType === "Replacement" || formType === "Term Conversion" || formType === "Policy Change" || formType === "Reinstatement")){
21770      if(!!productCategory && !!productName && !!state){
21771        return false;
21772      }else{
21773        return true;
21774      }
21775    }
21776  },
21777
21778  packagePath:function(packagePath){
21779    if(!!packagePath){
21780      return eFormSearchMethods.allCheckedDataPath.toString();
21781    }else{
21782      return eFormSearchMethods.requiredDataPlacedTopDataSet.toString()
21783    }
21784  },
21785
21786  packageZipDownload:function(path){
21787    const packname = eformsLoadMoreMethods.availablePackageName;
21788    const packagePath = eFormSearchMethods.packagePath(path);
21789    const params = { 'pdfPaths' : packagePath, 'packageName':packname};
21790    const form = document.createElement("form");
21791        form.setAttribute("method", "post");
21792        form.setAttribute("action", "/bin/zipForms");
21793         form.setAttribute("target", "NewFile");
21794          for (let i in params)
21795          {
21796            if (params.hasOwnProperty(i))
21797            {
21798              var input = document.createElement('input');
21799              input.type = 'hidden';
21800              input.name = i;
21801              input.value = params[i];
21802              form.appendChild(input);
21803            }
21804          }
21805          document.body.appendChild(form);
21806           form.submit();
21807           document.body.removeChild(form)
21808  },
21809
21810  openTab:function(){
21811    eFormSearchMethods.packageZipDownload('singlePdfZip')
21812  },
21813}
21814
21815 
21816$(document).on("change", "input[name='package']", function () {
21817  let arrayOfPackages = eFormSearchMethods.requiredDataPlacedTopDataSet;
21818  if(this.checked){
21819    arrayOfPackages.push($(this).attr("path_name"));
21820  }else{
21821   let index = arrayOfPackages.indexOf($(this).attr("path_name"));
21822   arrayOfPackages.splice(index, 1);
21823  }
21824  if(!!arrayOfPackages){
21825    $(".package-selected").text(arrayOfPackages.length);
21826  }
21827});
21828
21829 $(document).ready(function(){
21830    let radionBtnValue;
21831    let productCategory;
21832    let productName;
21833    let formType;
21834    let searchKey;
21835    let state = null;
21836    let lineOfBusiness;
21837    let arr = [];
21838    let dataTable;
21839    let divContentMob = '';
21840    let screenSize = $(window).width();
21841    $('.search-input-div .eform-search-input').attr('maxlength', 200);
21842    $(window).resize(function () {
21843        screenSize = $(window).width();
21844    });
21845    if($('.suggestive-search-input .search-input-container').data('enable-suggestive-search')){
21846      searchSuggestionMethods.createSearchSuggestions();
21847    }
21848    $(".eforms-state").select2({ 
21849    });
21850
21851    $('.eforms-state').on("select2:select", function (e) {
21852      var data = e.params.data.text;
21853      if(data==$(".eforms-state").data("all-states-label")){
21854      $(".eforms-state > option").prop("selected","selected");
21855      $(".eforms-state").trigger("change.select2");
21856      $('.placeholder-div .state-value-span').text($(".eforms-state").data("all-states-label"));
21857      }
21858      else{
21859        $(".eforms-state > option[value='"+$(".eforms-state").data("all-states-label")+"']").prop("selected",fal
21859se);
21860        e.params.data.selected=true;
21861        $(e.params.data.element).prop('selected',true);
21862        $(".eforms-state").trigger("change.select2");
21863        let arr = ($(".eforms-state").select2().val());
21864        if(arr.length == 0){
21865          let statePlaceholder =$('.placeholder-div .state-value-span').attr('placeholder-text'); 
21866          $('.placeholder-div .state-value-span').text(statePlaceholder); 
21867        }
21868        else if(arr.length == 1){
21869          $('.placeholder-div .state-value-span').text(arr[0]); 
21870        }
21871        else if(arr.length > 1){
21872          $('.placeholder-div .state-value-span').text('Multiple States Selected');
21873        }
21874      }
21875      });
21876
21877      $('.eforms-state').on("select2:unselect", function (e) {
21878        var data = e.params.data.text;
21879        if(data==$(".eforms-state").data("all-states-label")){
21880        $(".eforms-state > option").prop("selected","");
21881        $(".eforms-state").trigger("change.select2");
21882        let statePlaceholder =$('.placeholder-div .state-value-span').attr('placeholder-text'); 
21883        $('.placeholder-div .state-value-span').text(statePlaceholder); 
21884        }
21885        else{
21886          $(".eforms-state > option[value='"+$(".eforms-state").data("all-states-label")+"']").prop("selected",fal
21886se);
21887          e.params.data.selected=false;
21888          $(e.params.data.element).prop('selected',false);
21889          $(".eforms-state").trigger("change.select2");
21890          let arr = $(".eforms-state").select2().val();
21891           if(arr != null){
21892            if(arr.length == 0){
21893              let statePlaceholder =$('.placeholder-div .state-value-span').attr('placeholder-text'); 
21894              $('.placeholder-div .state-value-span').text(statePlaceholder); 
21895            }
21896            else if(arr.length == 1){
21897              $('.placeholder-div .state-value-span').text(arr[0]);
21898            }
21899            else if(arr.length > 1){
21900              $('.placeholder-div .state-value-span').text('Multiple States Selected');
21901            }
21902           }
21903           else{
21904            let statePlaceholder =$('.placeholder-div .state-value-span').attr('placeholder-text'); 
21905            $('.placeholder-div .state-value-span').text(statePlaceholder); 
21906          }
21907          
21908        }
21909        });
21910    $(".eforms-state").on('select2:close', function (e) {
21911      $('body').removeClass('state-select2');
21912      $('.placeholder-div .dropdown-icon').removeClass('rotate-icon');
21913    });
21914    $('.placeholder-div').on('click',function(){
21915      $('.eforms-state').select2('open');
21916    }) ;
21917    $(".eforms-state").on('select2:open', function (e) {
21918      $('body').addClass('state-select2');
21919      $('.placeholder-div .dropdown-icon').addClass('rotate-icon');
21920    });
21921    $('.eforms-clear-filter').on('click',eFormSearchMethods.clearSearchFilters);
21922    eFormSearchMethods.viewFilterAccordion();
21923    eFormSearchMethods.productCategoryMapBuilder();
21924    eFormSearchMethods.lifeProductCategoryMapBuilder();
21925    eFormSearchMethods.narrowDownProductNames();
21926    eFormSearchMethods.enableSearchButton();
21927    $('.search-filters-div').find('.accordion-item').children('.accordion-title').on('click',function(){
21928    eFormSearchMethods.changeFilterAccordionTitle();
21929    
21930  });
21931    $('.lineofbusiness-radionBtn-div input').click(function(){
21932      if($(this).val() == 'All'){
21933        $('.product-category-annuties').addClass("display-none");
21934        $('.product-name').addClass("display-none");
21935        $('.form-type').addClass("display-none");
21936        $('.life-product-name').addClass("display-none");
21937        $('.an-product-name').addClass("display-none");
21938        $('.product-category-annuties select').val(null).trigger('change');
21939        $('.product-name select').val(null).trigger('change');
21940        $('.form-type select').val(null).trigger('change');
21941      }
21942      else if($(this).val() == 'Annuities'){
21943      $('.form-type').removeClass("display-none");
21944      eFormSearchMethods.formTypeMapBuilder('annuities');
21945      eFormSearchMethods.productCategoryBindForLife('annuities');
21946      if(!!$('.product-category-annuties select').attr("form-category-list-an") && $('.product-category-annuties select').attr("form-category-list-an").length){
21947        $('.product-category-annuties').removeClass("display-none");
21948        $('.product-name').removeClass("display-none");
21949        $('.field-label-category-an').removeClass("display-none");
21950        $('.field-label-category-life').addClass("display-none");
21951        $('.field-label-product-name-an').removeClass("display-none");
21952        $('.field-label-product-name-life').addClass("display-none");
21953      }else{
21954        $('.product-name').addClass("display-none");
21955        $('.product-category-annuties').addClass("display-none");
21956      }
21957      $('.an-product-name').removeClass("display-none");
21958      $('.life-product-name').addClass("display-none");
21959      $('.product-category-annuties select').val(null).trigger('change', 'annuities');
21960      $('.form-type select').val(null).trigger('change');
21961      $('.form-select-custom.bhf-form-select.bhf-eforms-select.form-type-label').select2({
21962        tags: "true",
21963            placeholder: $('.form-type select').attr("form-type-placeholder-an"),
21964      });
21965      $('.form-select-custom.bhf-form-select.bhf-eforms-select.product-category-placeholder').select2({
21966        tags: "true",
21967            placeholder: $('.product-category-annuties').attr("product-category-placeholder-an"),
21968      });
21969      $('.form-select-custom.bhf-form-select.bhf-eforms-select.an-product-name-select').select2({
21970        tags: "true",
21971            placeholder: $('.an-product-name .an-product-name-select').attr("product-name-placeholder-an"),
21972      });
21973      }
21974      else{
21975      $('.form-type').removeClass("display-none");
21976      eFormSearchMethods.formTypeMapBuilder('life');
21977      eFormSearchMethods.productCategoryBindForLife('life');
21978      if(!!$('.product-category-annuties select').attr("form-category-list-life") && $('.product-category-annuties select').attr("form-category-list-life").length){
21979        $('.product-category-annuties').removeClass("display-none");
21980        $('.product-name').removeClass("display-none");
21981        $('.field-label-category-life').removeClass("display-none");
21982        $('.field-label-category-an').addClass("display-none");
21983        $('.field-label-product-name-life').removeClass("display-none");
21984        $('.field-label-product-name-an').addClass("display-none");
21985        
21986      }else{
21987        $('.product-name').addClass("display-none");
21988        $('.product-category-annuties').addClass("display-none");
21989      }
21990        $('.an-product-name').addClass("display-none");
21991        $('.life-product-name').removeClass("display-none"); 
21992        $('.product-category-annuties select').val(null).trigger('change', 'life');
21993        $('.product-name select').val(null).trigger('change');
21994        $('.form-select-custom.bhf-form-select.bhf-eforms-select.form-type-label').select2({
21995          tags: "true",
21996              placeholder: $('.form-type select').attr("form-type-placeholder-life"),
21997        });
21998        $('.form-select-custom.bhf-form-select.bhf-eforms-select.product-category-placeholder').select2({
21999          tags: "true",
22000              placeholder: $('.product-category-annuties').attr("product-category-placeholder-life"),
22001        });
22002        $('.form-select-custom.bhf-form-select.bhf-eforms-select.life-product-name-select').select2({
22003          tags: "true",
22004              placeholder: $('.life-product-name .life-product-name-select').attr("product-name-placeholder-life"),
22005        });
22006      }
22007  }); 
22008    $('.search-input-div input').focus(function(){
22009      $(this).data('placeholder',$(this).attr('placeholder'))
22010              .attr('placeholder','');
22011    }).blur(function(){
22012        $(this).attr('placeholder',$(this).data('placeholder'));
22013    });
22014    eformsLoadMoreMethods.loadMoreResults();
22015    let searchObj = {
22016      formSearch:function(event, onLoadEvent){
22017      $('.eforms-submit.button-primary').addClass('disabled-btn');
22018       $('.search-filter-list ul').empty();
22019      if($('.loader__bg').length>0){
22020       $('.loader__bg').show();
22021       $('.loader__content').css({ 'display': 'flex' });
22022       $('body').addClass('is-reveal-open');
22023       $('.eform-search-input.search-input').prop('disabled',true);
22024      }     
22025     radionBtnValue =  $('input[name="lineofbusiness"]:checked').val();
22026     if(radionBtnValue == 'All')  {
22027        productCategory = '';
22028        productName = '';
22029        formType = ''; 
22030     }  
22031     else if(radionBtnValue == 'Annuities'){
22032      productCategory = $('.product-category-annuties select').find(':selected').val();
22033      productName = $('.an-product-name select').find(':selected').val() ? $('.an-product-name select').find(':selected').val().trim() : "";
22034      formType = $('.form-type').find(':selected').val(); 
22035    }
22036    else{
22037      productCategory = $('.product-category-annuties select').find(':selected').val();
22038      productName = $('.life-product-name select').find(':selected').val() ? $('.life-product-name select').find(':selected').val().trim() : "";;
22039      formType = $('.form-type').find(':selected').val(); 
22040    }
22041 
22042     searchKey = $('.eform-search-input').val();
22043     lineOfBusiness = radionBtnValue;
22044     if($('.eforms-state').find(':selected').val() == [$(".eforms-state").data("all-states-label")]){
22045        state = stateArr;
22046     }
22047     else if($('.eforms-state').find(':selected').val() == []){
22048        state = null;
22049     }
22050     else{
22051       state = $(".eforms-state").select2().val();
22052     }
22053     eFormSearchMethods.showSearchFilters({property:"radioBtnValue",value:radionBtnValue},
22054                                          {property:"formType",value:formType},
22055                                          {property:"productCategory",value:productCategory},
22056                                          {property:"prductName",value:productName},
22057                                          {property:"state",value:state});
22058	   eFormSearchMethods.changeFilterAccordionTitle();
22059     eFormSearchMethods.focusOutSortingButtons();
22060     if(lineOfBusiness == 'All' && !state  && searchKey == ''){
22061       setTimeout(function(){
22062        $('.loader__bg').hide();
22063        $('.loader__content').hide();
22064        $('body').removeClass('is-reveal-open');
22065        $('.eform-search-input.search-input').prop('disabled', false);
22066        $('.post-search-btn').text($('.post-search-btn').data('pre-search-label'));
22067        $('.pre-search-btn').text($('.post-search-btn').data('pre-search-label'));
22068        $('.post-search-btn').addClass('display-none');
22069        $('.pre-search-btn').removeClass('display-none');
22070        $('.search-result-alert-wrapper').addClass('display-none');
22071        $('#tabelArea,.eforms-data-table-header, .eforms-load-more-btn, .data-table-div .search-result-heading, .data-table-div .search-result-count').addClass("display-none"); 
22072        dataTable = $("#tabelArea").DataTable();
22073       },2000);
22074     }
22075     else{
22076      searchSuggestionMethods.isSearchTriggered=true;
22077      const searchWrapper = document.querySelector(".suggestive-search-input .wrapper .search-input-container");
22078      searchWrapper.classList.remove('active');
22079      $.ajax({
22080        type: "POST",
22081        url: "/content.eFormSearch",
22082        data: {
22083          keyword: searchKey,
22084          lineOfBusiness: lineOfBusiness,
22085          productCategory: productCategory,
22086          productName: productName,
22087          formType: formType,
22088          states: state,
22089        },
22090        success: function (result) {
22091          if (result != "") {
22092            $('.loader__bg').hide();
22093            $('.loader__content').hide();
22094            $('body').removeClass('is-reveal-open'); 
22095            $('.eform-search-input.search-input').prop('disabled', false);
22096            eFormSearchMethods.changeSearchText();
22097            arr = result;
22098           if(!!arr.packageDetails && !!Object.values(arr.packageDetails).length){
22099            eformsLoadMoreMethods.isPackageAvailable = true;
22100            eformsLoadMoreMethods.availablePackageName = arr.packageDetails['packageTitle'];
22101            let FirstRequiredRow = [{
22102              "formId": "Multiple",
22103              "name": arr.packageDetails['packageTitle'],
22104              "description": arr.packageDetails['packageDescription'],
22105              "versionDate": "Multiple",
22106              "required": true,
22107              "states" : [],
22108              "product": [],
22109            }]
22110            eFormSearchMethods.allCheckedDataPath = [];
22111            eFormSearchMethods.allCheckedDataPath = [...eFormSearchMethods.allCheckedDataPath, ...arr.packageDetails["formPaths"]];
22112            eFormSearchMethods.requiredDataPlacedTopDataSet = arr.packageDetails["formPaths"];
22113            arr =  [...FirstRequiredRow,  ...arr['dataResult']];
22114            $(".download-package-alert-section").removeClass('display-none');
22115            $(".package-selected").text(eFormSearchMethods.allCheckedDataPath.length);
22116            $('.simple_search_results_heading ').addClass('display-none');
22117            $('.package_search_results_heading ').removeClass('display-none');
22118           }else{
22119            $(".download-package-alert-section").addClass('display-none');
22120            $('.simple_search_results_heading ').removeClass('display-none');
22121            $('.package_search_results_heading ').addClass('display-none');
22122            eformsLoadMoreMethods.isPackageAvailable = false;
22123            arr = arr.dataResult;
22124           }
22125            const formColumnLabel=$('#tabelArea').attr('formColumnLabel');
22126            const productsColumnLabel =$('#tabelArea').attr('productsColumnLabel');
22127            const versionDateColumnLabel=$('#tabelArea').attr('versionDateColumnLabel');
22128            const statesColumnLabel=$('#tabelArea').attr('statesColumnLabel');
22129            if(arr.length != 0){
22130                $('#tabelArea,.eforms-data-table-header, .eforms-load-more-btn, .data-table-div .search-result-heading, .data-table-div .search-result-count').removeClass("display-none"); 
22131                if (dataTable != undefined) {
22132                    dataTable.destroy();
22133                  }
22134                  if(eformsLoadMoreMethods.isPackageAvailable){
22135                    dataTable = $("#tabelArea").DataTable({
22136                        data: arr,
22137                        "info":false,
22138                        "paging":false,
22139                        "seaching":false,
22140                        "aoColumnDefs" : [],
22141                        "fnInitComplete": function() {
22142                        },
22143                      "fnDrawCallback": function() {
22144                          console.log("redrawn");
22145                          let allRequiredRows = [];
22146                          $('.dataTable tbody').find('tr').each(function(){
22147                                if($(this).find('td .eforms-checkbox').hasClass("checked")) {
22148                                    $(this).remove();
22149                                    allRequiredRows.push(this);
22150                                }
22151                          });
22152                          $('.dataTable tbody').prepend(allRequiredRows);
22153                      },
22154
22155                        columns: [
22156                          {
22157                            data: "checkbox",
22158                            data: function (data, type, row) {
22159                                if(data.required){
22160                                  return "<div class='eforms-checkbox checked'><input type='checkbox' checked disabled name='checked'><span class='checkmark'></span></div>";
22161                                }else{
22162                                  return "<div class='eforms-checkbox'><input type='checkbox' id='checkboxPackage' name='package' path_name='"+data.path +"'><span class='checkmark'></span></div>";
22163                                }
22164                            },
22165                            defaultContent: "",
22166                          },
22167                          {
22168                            data: function (data, type, row) {
22169                              console.log(row);
22170                              if(data.required){
22171                                return "<div><a class='eforms-name' onClick='eFormSearchMethods.openTab()' href='javascript:void(0)'>"+data.name+"</a></div><div class='eforms-desc'>
22171"+ data.description+"</div><div><span class='eforms-id-label'>Form ID</span><span class='eforms-id'>"+data.formId+"</span></div>";
22172                              }else{
22173                                return "<div><a class='eforms-name' target='_blank'  href='" + data.path +"'>"+data.name+"</a></div><div class='eforms-desc'>"+ data.description+"</div><div><span class='eforms-id-label'>Form ID</span><span class='eforms-id'>"+data.formId+"</span></div>";
22174                              }
22175                            },
22176                            defaultContent: "",
22177                          },
22178                          {
22179                            data: function (data, type, row) {
22180                                    let divContent = "";
22181                                    let productMap = data.product || {};
22182                                    let productKeys = Object.keys(productMap);                                 
22183                                    if (productKeys.length > 1) {
22184                                      divContent += `<span class="product-span">` + $('table.eforms-data-table').data('multiple-products') + `</span> <span class="multi-icon form-multi-product" formId='${data.formId}'></span>`;
22185                                    } else if (productKeys.length === 1) {
22186                                      let key = productKeys[0];
22187                                      divContent += `<span class="product-span">${key}</span>`;
22188                                    }
22189                                 
22190                                    const divData = '<div class="eform-product-div">' + divContent + "</div>";
22191                                    return divData;
22192                                  },
22193                            defaultContent: "",
22194
22195                          },
22196                          {
22197                            data: "versionDate",
22198                            data: function (data, type, row) {
22199                              return `<div class="eforms-version-date">${data.versionDate}</div>`;
22200                            },
22201                            defaultContent: "",
22202                          },
22203                          {
22204                            data: function (data, type, row) {
22205                              let divContent = "";
22206                                if (data.states.length > 1) {
22207                                      divContent += `<span class="state-span">`+$('table.eforms-data-table').data('multiple-states')+`</span><span class="multi-icon form-multi-state" formId='${data.formId}'></span>`;
22208                                  } else if (data.states.length == 1) {
22209                                      divContent += `<span class="state-span">`+data.states[0]+`</span>`;
22210                                  }
22211                                  let divData =
22212                                    `<div class="state-list-div">`+divContent+`</div>`;
22213                                  return divData;
22214                            },
22215                            defaultContent: "",
22216                          },
22217                        ],
22218                      });
22219                      $(".dataTables_wrapper").addClass('overflow-table');
22220                      $(".eforms-data-table-header").addClass('display-none');
22221                      $(".search-result-alert-wrapper").addClass('display-none');
22222                      dataTable.column( '.download-checkbox' ).visible(true);
22223                      dataTable.column( '.product-names-show ' ).visible(false);
22224                      dataTable.column( '.states-names-show ' ).visible(false);
22225                }else{
22226                  $(".eforms-data-table-header").removeClass('display-none');
22227                $("#tabelArea tbody").empty();
22228                if(screenSize <=640){
22229                  dataTable = $("#tabelArea").DataTable({
22230                      "drawCallback": function( settings ) {
22231                      $("#tabelArea thead").remove(); }, 
22232                      data: arr,
22233                      "info":false,
22234                      "paging":false,
22235                      "seaching":false,
22236                      "ordering":false,
22237                      "aaSorting": [],
22238                      columns: [
22239                        {
22240                          data: function (data, type, row) {
22241                              divContentMob = "";
22242                              if (data.states.length > 1) {
22243                                   divContentMob += `<span class="state-span">`+$('table.eforms-data-table').data('multiple-states')+`</span><span class="multi-icon form-multi-state" formId='${data.formId}'></span>`;
22244                                           } else if (data.states.length == 1) {
22245                                             divContentMob += `<span class="state-span">`+ data.states[0] + `</span>`;
22246                                           }
22247                                           let stateData =
22248                                             '<div class="state-list-div flex-column"><div class="eform-label">'+statesColumnLabel+'</div>' +
22249                                             `<div class="state-list">`+divContentMob+`</div>` +
22250                                             "</div>";
22251                                             divContentMob = "";
22252			                                   let productMap = data.product || {};
22253			                                   let productKeys = Object.keys(productMap);
22254			                                   if (productKeys.length > 1) {
22255			                                     divContentMob += `<div class="multi-product-div"><span class="product-span">`+$('table.eforms-data-table').data('multiple-products')+`</span> <span class="multi-icon form-multi-product" formId='${data.formId}'></span></div>`;
22256			                                   } else if (productKeys.length == 1){
22257												 let key = productKeys[0];
22258			                                     divContentMob += `<span class="product-span">${key}</span>`;
22259			                                   }
22260                                                let productContent =
22261                                                 '<div class="eform-product-div flex-column"><div class="eform-label">'+productsColumnLabel+'</div>' +divContentMob+"</div>";
22262
22263                           let firstRow =  "<div><div class='eform-name-label'>"+formColumnLabel+"</div> <a class='eforms-name'  target='_blank' href='" + data.path +"'>"+data.name+"</a></div><div class='eforms-desc' >"+ data.description+"</div>";
22264						   let secondRow = "<div class='second-row-div'>"; 
22265                               var formIdHtml = data.formId ? 
22266                                "<div class='flex-column'><span class='eforms-label'>Form ID</span><span class='eforms-id'>" + data.formId + "</span></div>" : ""; 
22267                                 secondRow += formIdHtml; 
22268                                 secondRow += "<div class='flex-column'><div class='eform-label'>" + versionDateColumnLabel + "</div><div class='eforms-version-date'>" + data.versionDate + "</div></div>"; 
22269                                 secondRow += "</div>";
22270                           let thirdRow = "<div class='third-row-div'>" +productContent+stateData+"</div>";
22271                           let fourthRow = "<div class='second-row-div'>"; 
22272                               var displayTitleHtml = data.displayTitle ? 
22273                                "<div class='flex-column'><span class='eforms-label'>Policy Numbers</span><span class='eforms-id'>" + data.displayTitle + "</span></div>" : ""; 
22274                                fourthRow += displayTitleHtml; 
22275                                fourthRow += "</div>";
22276
22277                           return firstRow + secondRow + thirdRow + fourthRow;
22278                          },
22279                          defaultContent: "",
22280                        },
22281                      ],
22282                    });
22283                  }
22284                else if(screenSize <= 991){
22285                      dataTable = $("#tabelArea").DataTable({
22286                          "drawCallback": function( settings ) {
22287                          $("#tabelArea thead").remove(); }, 
22288                          data: arr,
22289                          "info":false,
22290                          "paging":false,
22291                          "seaching":false,
22292                          "ordering":false,
22293                          "aaSorting": [],
22294                          columns: [
22295                            {
22296                              data: "checkbox",
22297                              data: function (data, type, row) {
22298                                    return "<div class='eforms-checkbox'></div>";
22299                              },
22300                              defaultContent: "",
22301                            },
22302                            {
22303                              data: function (data, type, row) {
22304                                var formIdHtml = data.formId ? 
22305        										"<div><span class='eforms-id-label'>Form ID</span><span class='eforms-id'>" + data.formId + "</span></div>" : "";
22306    							var displayTitleHtml = data.displayTitle ? 
22307        										"<div><span class='eforms-id-label'>Policy Numbers</span><span class='eforms-id'>" + data.displayTitle + "</span></div>" : "";
22308                                return "<div><div class='eform-name-label'>"+formColumnLabel+"</div> <a class='eforms-name'  target='_blank' href='" + data.path +"'>"+data.name+"</a></div><div class='eforms-desc'>
22308"+ data.description+"</div>"
22309                                +formIdHtml + displayTitleHtml;
22310                              },
22311                              defaultContent: "",
22312                            },
22313                            {
22314                              data: function (data, type, row) {
22315                                divContentMob = "";
22316                                  if (data.states.length > 1) {
22317                                      
22318                                     divContentMob += `<span class="state-span">`+$('table.eforms-data-table').data('multiple-states')+`</span><span class="multi-icon form-multi-state" formId='${data.formId}'></span>`;
22319                                   } else if (data.states.length == 1) {
22320                                     divContentMob += `<span class="state-span">`+data.states[0] + `</span>`;
22321                                   }
22322                                   let stateData =
22323                                     '<div class="state-list-div flex-column"><div class="eform-label">'+statesColumnLabel+'</div>' +
22324                                     `<div class="state-list">`+divContentMob+`</div>` +
22325                                     "</div>";
22326
22327                                  let versionData =`<div class="flex-column"><div class="eform-label">`+versionDateColumnLabel+`</div><div class="eforms-version-date">`+data.versionDate+`</div></div>`;
22328                                   divContentMob = "";
22329                                   let productMap = data.product || {};
22330                                   let productKeys = Object.keys(productMap);
22331                                   if (productKeys.length > 1) {
22332                                     divContentMob += `<div class="multi-product-div"><span class="product-span">`+$('table.eforms-data-table').data('multiple-products')+`</span> <span class="multi-icon form-multi-product" formId='${data.formId}'></span></div>`;
22333                                   } else if (productKeys.length == 1){
22334									 let key = productKeys[0];
22335                                     divContentMob += `<span class="product-span">${key}</span>`;
22336                                   }
22337                                   let productContent =
22338                                     '<div class="eform-product-div flex-column"><div class="eform-label">'+productsColumnLabel+'</div>' +divContentMob +"</div>";
22339                        
22340                                   return `<div>`+productContent + versionData + stateData+`</div>`;
22341                              },
22342                              defaultContent: "",
22343              
22344                            }
22345                          ],
22346                        });
22347                        dataTable.column( '.download-checkbox' ).visible(false);
22348                  }
22349                else if(screenSize > 991){
22350                      dataTable = $("#tabelArea").DataTable({
22351                          data: arr,
22352                          "info":false,
22353                          "paging":false,
22354                          "seaching":false,
22355                          "aaSorting": [],
22356                          columns: [
22357                            {
22358                              data: "checkbox",
22359                              data: function (data, type, row) {
22360                                    return "<div class='eforms-checkbox'></div>";
22361                              },
22362                              defaultContent: "",
22363                            },
22364                            {
22365                             data: function (data, type, row) {
22366                                    var formIdHtml = data.formId ? 
22367                                        "<div><span class='eforms-id-label'>Form ID</span><span class='eforms-id'>" + data.formId + "</span></div>" : "";
22368                                    var displayTitleHtml = data.displayTitle ? 
22369                                        "<div><span class='eforms-id-label'>Policy Numbers</span><span class='eforms-id'>" + data.displayTitle + "</span></div>" : "";
22370                                 
22371                                    return "<div><a class='eforms-name' target='_blank' href='" + data.path + "'>" + data.name + "</a></div>" +
22372                                           "<div class='eforms-desc'>" + data.description + "</div>" +
22373                                           displayTitleHtml +
22374                                           formIdHtml;		
22375                                },
22376                              defaultContent: "",
22377                            },
22378                             {
22379                                  data: function (data, type, row) {
22380                                    let divContent = "";
22381                                    let productMap = data.product || {};
22382                                    let productKeys = Object.keys(productMap);
22383                                 
22384                                    if (productKeys.length > 1) {
22385                                      divContent += `<span class="product-span">` + $('table.eforms-data-table').data('multiple-products') + `</span> <span class="multi-icon form-multi-product" formId='${data.formId}'></span>`;
22386                                    } else if (productKeys.length === 1) {
22387                                      let key = productKeys[0];
22388                                      divContent += `<span class="product-span">${key}</span>`;
22389                                    }
22390                                 
22391                                    const divData = '<div class="eform-product-div">' + divContent + "</div>";
22392                                    return divData;
22393                                  },
22394                                  defaultContent: "",
22395                                },
22396                            {
22397                              data: "versionDate",
22398                              data: function (data, type, row) {
22399                                return `<div class="eforms-version-date">${data.versionDate}</div>`;
22400                              },
22401                              defaultContent: "",
22402                            },
22403                            {
22404                              data: function (data, type, row) {
22405                                let divContent = "";
22406                                  if (data.states.length > 1) {
22407                                        divContent += `<span class="state-span">`+$('table.eforms-data-table').data('multiple-states')+`</span><span class="multi-icon form-multi-state" formId='${data.formId}'></span>`;
22408                                    } else if (data.states.length == 1) {
22409                                        divContent += `<span class="state-span">`+data.states[0]+`</span>`;
22410                                    }
22411                                    let divData =
22412                                      `<div class="state-list-div">`+divContent+`</div>`;
22413                                    return divData;
22414                              },
22415                              defaultContent: "",
22416                            },
22417                          ],
22418                        })
22419                   dataTable.column( '.download-checkbox' ).visible(false);
22420                  }
22421                  $(".dataTables_wrapper").removeClass('overflow-table');
22422                }
22423                  eFormSearchMethods.implementEllipsis();
22424                  eformsLoadMoreMethods.searchResultsBuilder();
22425                  eformsLoadMoreMethods.sortedSearchResultBuilder();
22426                  const resultLimit = parseInt($('.search-result-alert-wrapper').attr('resultCount'));
22427                  if(resultLimit < arr.length && $('.search-result-alert-wrapper .count-alert-info').length > 0){
22428                    $('.search-result-alert-wrapper').removeClass('display-none');
22429                    $('.search-result-alert-wrapper .count-alert-info').removeClass('display-none');
22430                    $('.search-result-alert-wrapper .no-result-error-info').addClass('display-none');
22431                    $('.search-result-alert-wrapper .technical-error-alert-info').addClass('display-none');
22432                    $('.search-result-alert-wrapper .connection-timeout-alert-info').addClass('display-none');
22433                  }
22434                  else{
22435                    $('.search-result-alert-wrapper').addClass('display-none');
22436                  }
22437                if(arr.length === 1 && (!!onLoadEvent && onLoadEvent=="onLoadEvent")){
22438                  const formPath = window.location.origin+arr[0].path;
22439                  window.open(formPath, '_blank');
22440                }
22441                $('.search-filters-div').find('.accordion-item').removeClass('is-active');
22442                $('.accordian-tabe-content').addClass('display-none');
22443                eFormSearchMethods.changeFilterAccordionTitle()
22444            }
22445            else{
22446                $('#tabelArea,.eforms-data-table-header, .eforms-load-more-btn, .data-table-div .search-result-heading, .data-table-div .search-result-count').addClass("display-none"); 
22447                $('.search-result-alert-wrapper').addClass('display-none');
22448                if($('.search-result-alert-wrapper .no-result-error-info').length>0){
22449                  $('.search-result-alert-wrapper').removeClass('display-none');
22450                  $('.search-result-alert-wrapper .count-alert-info').addClass('display-none');
22451                  $('.search-result-alert-wrapper .no-result-error-info').removeClass('display-none');
22452                  $('.search-result-alert-wrapper .technical-error-alert-info').addClass('display-none');
22453                  $('.search-result-alert-wrapper .connection-timeout-alert-info').addClass('display-none');
22454                }
22455            }
22456            multipleProductsModalMethods.showMultipleStates(arr);
22457            multipleProductsModalMethods.showMultipleProducts(arr);
22458            
22459          }
22460        },
22461        error: function (XMLHttpRequest, textStatus, errorThrown) {
22462          $('#tabelArea,.eforms-data-table-header, .eforms-load-more-btn, .data-table-div .search-result-heading, .data-table-div .search-result-count').addClass("display-none"); 
22463          $('.eform-search-input.search-input').prop('disabled', false);
22464          if(XMLHttpRequest.status == 504 && $('.search-result-alert-wrapper .connection-timeout-alert-info').length>0){
22465            $('.search-result-alert-wrapper').removeClass('display-none');
22466            $('.search-result-alert-wrapper .count-alert-info').addClass('display-none');
22467            $('.search-result-alert-wrapper .no-result-error-info').addClass('display-none');
22468            $('.search-result-alert-wrapper .technical-error-alert-info').addClass('display-none');
22469            $('.search-result-alert-wrapper .connection-timeout-alert-info').removeClass('display-none');             
22470          }
22471          else {
22472            if($('.search-result-alert-wrapper .technical-error-alert-info').length>0){
22473              $('.search-result-alert-wrapper').removeClass('display-none');
22474              $('.search-result-alert-wrapper .count-alert-info').addClass('display-none');
22475              $('.search-result-alert-wrapper .no-result-error-info').addClass('display-none');
22476              $('.search-result-alert-wrapper .technical-error-alert-info').removeClass('display-none');
22477              $('.search-result-alert-wrapper .connection-timeout-alert-info').addClass('display-none');   
22478            }
22479          }
22480        },
22481      });
22482
22483    }
22484  }
22485
22486}
22487     
22488  $(".eforms-submit").on('click', function(event, onLoadEvent){
22489    searchObj.formSearch(event, onLoadEvent);
22490  });
22491
22492  $(".form-package-download-button").on('click', function(){
22493    eFormSearchMethods.packageZipDownload();
22494  });
22495
22496  $(document).keypress(function(event){
22497    let checkClass = $( ".eforms-submit" ).hasClass('disabled-btn');
22498    let targetClass = $(event.target).hasClass('autocomplete-box');
22499    let keycode = (event.keyCode ? event.keyCode : event.which);
22500    if(keycode == '13' && !checkClass){
22501      if(targetClass){
22502        searchSuggestionMethods.select($(".suggestive-search-input .wrapper .autocomplete-box").find('li')[searchSuggestionMethods.count]);
22503      }
22504      else{
22505        $(".eforms-submit").eq(1).trigger("click");
22506        $('.eforms-submit.button-primary').addClass('disabled-btn');
22507        $(".suggestive-search-input .wrapper .search-input-container").removeClass("active");
22508      }
22509    }
22510  });
22511
22512  $('.eform-search-input ').keypress(function(event){
22513    let checkClass = $( ".eforms-submit" ).hasClass('disabled-btn');
22514    let targetClass = $(event.target).hasClass('autocomplete-box');
22515    let keycode = (event.keyCode ? event.keyCode : event.which);
22516    if(keycode == '13' && !checkClass){
22517      if(targetClass){
22518          searchSuggestionMethods.select($(".suggestive-search-input .wrapper .autocomplete-box").find('li')[searchSuggestionMethods.count]);
22519      }
22520      else{
22521        $(".eforms-submit").eq(1).trigger("click");
22522        $('.eforms-submit.button-primary').addClass('disabled-btn');
22523        $(".suggestive-search-input .wrapper .search-input-container").removeClass("active");
22524      }
22525    }
22526  });
22527  $(document).click(function(e){
22528      if($(e.target).parents('.suggestive-search-input').length==0 && $(".suggestive-search-input .wrapper .search-input-container")){
22529        $(".suggestive-search-input .wrapper .search-input-container").removeClass("active");
22530      }
22531  })
22532  eFormSearchMethods.loadDataToParamState();  
22533
22534
22535})
22536let assetPath = $('.asset-dropdown').val();
22537let selectValue = $('.asset-dropdown').val();
22538$(".asset-dropdown").select2({});
22539$(document).ready(function() {
22540  $('.bhf-eforms.eforms-author .asset-dropdown').on('change', function() {
22541    if ($('.asset-dropdown').val() == $('.asset-dropdown .others-value').text()) {
22542      $('.assetPath.text-after-dropdown').addClass("display-input");
22543      selectValue = $('.asset-dropdown').val();
22544    } else {
22545      $('.assetPath.text-after-dropdown').removeClass("display-input");
22546      $('.assetPath.text-after-dropdown').val('');
22547      assetPath = $('.asset-dropdown').val();
22548      selectValue = $('.asset-dropdown').val();
22549    }
22550  });
22551});
22552
22553$(".eform-asset-export").click(function() {
22554  if (selectValue == $('.asset-dropdown .others-value').text()) {
22555    assetPath = $(".assetPath").val();
22556  }
22557  if(assetPath === "" || !assetPath.startsWith("/content/dam/bhf/forms")) {
22558    $('.error-row').addClass("display-error");
22559    setTimeout(function() {
22560      $('.error-row').removeClass("display-error");
22561    }, 2000);
22562  } else {
22563  if($('.loader__bg').length>0){
22564      $('.loader__bg').show();
22565      $('.loader__content').css({ 'display': 'flex' });
22566    }
22567    $.ajax({
22568      type: "POST",
22569      url: "/content.eFormDamExport",
22570      data: {
22571        assetPath: assetPath,
22572      },
22573      success: function(result) {
22574        downloadJSON2CSV(result);
22575      },
22576      error: function(XMLHttpRequest, textStatus, errorThrown) {
22577        $('.loader__bg').hide();
22578        $('.loader__content').hide();
22579        $('.error-row').addClass("display-error");
22580        setTimeout(function() {
22581          $('.error-row').removeClass("display-error");
22582        }, 2000);
22583      },
22584    });
22585  }
22586});
22587
22588function downloadJSON2CSV(obj) {
22589  let arrays = JSON.parse(JSON.stringify(obj));
22590  let writeToExcelData = 'OID,Line of Business,File Name,Form ID,Form Name,Description,Product Category,Form Type,Version Date,Keywords,PACKAGE_IND,PACKAGE_LIST,Product,States,Third Party Site,URL Only,URL';
22591  writeToExcelData += "\r\n";
22592  for (let i = 0; i < arrays.dataResult.length; i++) {
22593    let line = new Array();
22594    line.push(getValueFromKey(arrays.dataResult[i]['oid']));
22595    line.push(getValueFromKey(arrays.dataResult[i]['lineOfBusinessAsString']));
22596    line.push(getValueFromKey(arrays.dataResult[i]['fileName']));
22597    line.push(getValueFromKey(arrays.dataResult[i]['formId']));
22598    line.push(getValueFromKey(arrays.dataResult[i]['formName']));
22599    line.push(getValueFromKey(arrays.dataResult[i]['description']));
22600    line.push(getValueFromKey(arrays.dataResult[i]['productCategoryAsString']));
22601    line.push(getValueFromKey(arrays.dataResult[i]['formTypeAsString']));
22602    line.push(getValueFromKey(arrays.dataResult[i]['versionDateAsString']));
22603    line.push(getValueFromKey(arrays.dataResult[i]['businessKeywords']));
22604    line.push(getValueFromKey(arrays.dataResult[i]['packageIndicator']));
22605    line.push(getValueFromKey(arrays.dataResult[i]['packageList']));
22606    line.push(getValueFromKey(arrays.dataResult[i]['productsAsString']));
22607    line.push(getValueFromKey(arrays.dataResult[i]['statesAsString']));
22608    line.push(getValueFromKey(arrays.dataResult[i]['thirdPartySite']));
22609    line.push(getValueFromKey(arrays.dataResult[i]['urlOnly']));
22610    line.push(getValueFromKey(arrays.dataResult[i]['url']));
22611    writeToExcelData += line.join(",");
22612    writeToExcelData += "\r\n";
22613  }
22614  let uri = "data:text/csv;charset=utf-8," + encodeURIComponent(writeToExcelData);
22615  let downloadLink = document.createElement("a");
22616  downloadLink.href = uri;
22617  downloadLink.download = $('.asset-dropdown').select2('data')[0].text + " - Metadata.csv";
22618  document.body.appendChild(downloadLink);
22619  downloadLink.click();
22620  document.body.removeChild(downloadLink);
22621  $('.loader__bg').hide();
22622  $('.loader__content').hide();
22623}
22624
22625function getValueFromKey(key) {
22626  return "\""+key.replaceAll("\n","").replaceAll("\r","").replace(/"/g, '')+"\"";
22627}

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.