PageSourceSearch

https://arnoldpalmerinvitational.com/wp-content/plugins/bravepopup-ultimate/assets/frontend/brave.js?ver=6.4.3

js arnoldpalmerinvitational.com collected 2026-10-02 16:57:49 UTC 129,304 bytes, 2,203 lines download raw bytes

1var brave_isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;
2var brave_isTab = window.matchMedia("screen and (max-width: 1200px) and (min-width: 760px)").matches;
3var brave_currentDevice = brave_isMobile ? 'mobile' : 'desktop';
4var brave_back_pressed = 0;
5
6function brave_number_padding(num) {  if(num){ var theNum = parseInt(num, 10); return theNum < 10 ? parseInt("0"+theNum, 10) : theNum } }
7
8function brave_change_slide(elementID, goto, slideWidth){
9   var sliderMargin = -(goto * slideWidth)+'px'
10   var theCarousel = document.getElementById('brave_carousel__slides-'+elementID);
11   var theCarouselNav = document.getElementById('brave_carousel__navs-'+elementID);
12   
13   if(theCarousel){
14      theCarousel.style.marginLeft = sliderMargin;
15      if(theCarouselNav){
16         var allCarouselNavs = theCarouselNav.querySelectorAll(":scope li");
17         for (var i = 0; i < allCarouselNavs.length; i++) { allCarouselNavs[i].classList.remove('slide__nav__active');  }
18         document.getElementById('brave_carousel__nav-'+elementID+'_'+goto).classList.add('slide__nav__active');         
19      }
20   }
21}
22
23function brave_autochange_slide(elementID){
24   var theSlider = document.getElementById('brave_carousel__slides-'+elementID);
25   var currentslide = document.querySelector('#brave_carousel__navs-'+elementID).dataset.currentslide;
26   currentslide = parseInt(currentslide, 10)
27   var slideWidth = parseInt(theSlider.dataset.width, 10);
28   var totalSlides = parseInt(theSlider.dataset.totalslides, 10);
29
30   var carouselHovered = theSlider.dataset.hovered;
31   if(carouselHovered === 'true'){ return }
32   //console.log(elementID, currentslide, slideWidth, totalSlides);
33   
34
35   brave_change_slide(elementID, currentslide, slideWidth);
36
37   if(totalSlides === (currentslide+1)){
38      document.querySelector('#brave_carousel__navs-'+elementID).dataset.currentslide = 0;
39   }else{
40      document.querySelector('#brave_carousel__navs-'+elementID).dataset.currentslide = currentslide + 1;
41   }
42}
43
44function brave_carousel_pause(elementID, resume=false){
45   var theSlider = document.getElementById('brave_carousel__slides-'+elementID);
46   if(theSlider){
47      theSlider.dataset.hovered = true;
48      if(resume){
49         theSlider.dataset.hovered = false;
50      }
51   }
52}
53function brave_toggle_item(elementID, itemClass){
54   var theToggleElm = document.getElementById('brave_carousel__slides-'+elementID);
55   var selectedItem = theToggleElm.getElementsByClassName(itemClass);
56   var allToggleDesc = theToggleElm.querySelectorAll('bravepopup_carousel__slide__content');
57   for (var i = 0; i < allToggleDesc.length; i++) { allToggleDesc[i].classList.remove('brave__toggle__active');  }
58   if(selectedItem[0]){ 
59      if(selectedItem[0].classList.contains('brave__toggle__active')){
60         selectedItem[0].classList.remove('brave__toggle__active');  
61      }else{
62         selectedItem[0].classList.add('brave__toggle__active');  
63      }
64   };
65}
66function brave_countdown(elementID, theDate, theHour, theMins, hideDays, hideHours, auto=null) {
67   if(!theDate) { return null}
68
69   //console.log(theDate, theHour, theMins, hideDays, auto);
70   
71   var dateString = theDate;
72   var time = {hour: theHour, minutes: theMins};
73   var brave_endDate;
74   if(!auto){
75       var parts = dateString.split('/');
76       var brave_day = parseInt(parts[0], 10);
77       var brave_month = parseInt(parts[1], 10) - 1;
78       var brave_year = parseInt(parts[2], 10);
79       brave_endDate =  new Date(brave_year, brave_month, brave_day);
80       brave_endDate.setHours(time.hour);
81       brave_endDate.setMinutes(time.minutes);
82       brave_endDate.setSeconds(0);
83   }else{
84       if(auto){
85         brave_endDate =  auto;
86       }
87
88   }
89
90   var brave_startDate = new Date().getTime();
91
92   var brave_days, brave_hours, brave_minutes, brave_seconds;
93   var timeRemaining = parseInt(((brave_endDate.getTime() - brave_startDate) / 1000), 10);
94   
95   //console.log( brave_endDate.getTime(), brave_startDate, timeRemaining);
96   
97   if (timeRemaining >= 0) {
98       if(!hideDays){
99         brave_days = parseInt(timeRemaining / 86400);
100         timeRemaining = (timeRemaining % 86400);
101       }
102       if(!hideHours){
103         brave_hours = parseInt(timeRemaining / 3600);
104         timeRemaining = (timeRemaining % 3600);
105       }
106
107       brave_minutes = parseInt(timeRemaining / 60);
108       timeRemaining = (timeRemaining % 60);
109       
110       brave_seconds = parseInt(timeRemaining);
111   }
112
113   var daySpan = document.getElementById('brave_rem_days-'+elementID);
114   var hourSpan = document.getElementById('brave_rem_hours-'+elementID);
115   var minSpan = document.getElementById('brave_rem_minutes-'+elementID);
116   var secSpan = document.getElementById('brave_rem_seconds-'+elementID);
117
118   if(daySpan){ daySpan.innerHTML = timeRemaining >= 0 ? brave_days : 0}
119   if(hourSpan){ hourSpan.innerHTML = timeRemaining >= 0 ? brave_hours : 0}
120   if(minSpan){ minSpan.innerHTML = timeRemaining >= 0 ? brave_minutes : 0}
121   if(secSpan){ secSpan.innerHTML = timeRemaining >= 0 ? brave_seconds : 0}
122
123}
124
125function brave_check_field_condition(event, fieldID, formID, fieldType='input'){
126
127   var brave_form_conditions = brave_popup_formData && brave_popup_formData[formID] && brave_popup_formData[formID].conditionsMatch || {};
128   var brave_form_cond_vals = brave_popup_formData && brave_popup_formData[formID] && brave_popup_formData[formID].conditionsVals || {};
129   var conditionRules = brave_popup_formData && brave_popup_formData[formID] && brave_popup_formData[formID].conditions || {};
130   var inputData = event.target.value;
131
132   if(fieldType === 'checkbox'){
133      inputData = '';
134      var checkBoxes =  document.querySelectorAll('#brave_form_field'+fieldID+' input');
135      for (var index = 0; index < checkBoxes.length; index++) {
136            var checkBoxDom = checkBoxes[index];
137            if(!inputData && checkBoxDom.checked){ inputData = checkBoxDom.value}
138      }
139   }
140
141   conditionRules.forEach(function(fieldCondition){ 
142      var fieldKey = fieldCondition.field; var depKey = fieldCondition.fieldDependent;
143      //console.log(fieldID, fieldCondition);
144      //console.log(depKey, brave_form_conditions[depKey]);
145      if(fieldKey === fieldID && brave_form_conditions[depKey]){
146         if(inputData && fieldCondition.action === 'exist' && !brave_form_conditions[depKey][fieldKey]){ brave_form_conditions[depKey][fieldKey] = true; }
147         if(!inputData && fieldCondition.action === 'exist' && brave_form_conditions[depKey][fieldKey]){ brave_form_conditions[depKey][fieldKey] = false; }
148         
149         if(fieldCondition.action === 'equal' && (inputData && (brave_form_cond_vals[depKey][fieldKey].includes(inputData))) ){ brave_form_conditions[depKey][fieldKey] = true; }
150         if(fieldCondition.action === 'equal' && (!inputData || (!brave_form_cond_vals[depKey][fieldKey].includes(inputData))) ){ brave_form_conditions[depKey][fieldKey] = false; }
151
152         if(fieldCondition.action === 'notequal' && (inputData && (!brave_form_cond_vals[depKey][fieldKey].includes(inputData))) && !brave_form_conditions[depKey][fieldKey]){ brave_form_conditions[depKey][fieldKey] = true; }
153         if(fieldCondition.action === 'notequal' && (!inputData || (brave_form_cond_vals[depKey][fieldKey].includes(inputData))) && brave_form_conditions[depKey][fieldKey]){ brave_form_conditions[depKey][fieldKey] = false;  }
154      }
155   });
156   //console.log(brave_popup_formData[formID].conditionsMatch);
157
158
159   Object.keys(brave_form_conditions).forEach(function(fieldKey){
160      var matchArray = Object.keys(brave_form_conditions[fieldKey]);
161      var matchedConditionsArray = matchArray.filter(function(depKey){ if(brave_form_conditions[fieldKey][depKey]){ return true; }else{ return false; } })
162      var allMatched = matchedConditionsArray.length === matchArray.length;
163      // console.log(matchedConditionsArray, matchArray);
164      var dependantField = document.getElementById('brave_form_field'+fieldKey);
165      if(dependantField){
166         if(allMatched){
167            dependantField.classList.remove('brave_form_field--hasCondition');
168         }else{
169            dependantField.classList.add('brave_form_field--hasCondition');
170         }
171         var formFieldsWrapper  = document.querySelector('#brave_form_'+formID+' .brave_form_fields');
172         var currentFormStep = formFieldsWrapper.dataset.step || undefined;
173         if(currentFormStep !== undefined && document.querySelector('#brave_form_'+formID+' .brave_form_fields .brave_form_fields_step'+currentFormStep)){
174            formFieldsWrapper.style.height = document.querySelector('#brave_form_'+formID+' .brave_form_fields .brave_form_fields_step'+currentFormStep).offsetHeight+'px';
175         }
176      }
177   });
178}
179
180function brave_select_imageField(fieldID, optionIndex, multi=false){
181   var optionField = document.getElementById('brave_form_field'+fieldID+'_opt-'+optionIndex);
182   if(optionField){
183      if(!multi){
184         var allOptsFields = document.getElementById('brave_form_field'+fieldID).querySelectorAll('input');
185         for (var i = 0; i < allOptsFields.length; i++) { allOptsFields[i].checked = false;  document.getElementById('brave_form_field'+fieldID+'_opt-'+i).classList.remove('formfield__inner__image--selected');  }
186      }
187      var optionFieldInput = optionField.querySelector('input');
188      if(optionFieldInput && (optionFieldInput.checked === false)){   optionFieldInput.checked = true;  optionField.classList.add('formfield__inner__image--selected'); 
189      }else if(optionFieldInput && (optionFieldInput.checked === true)){ optionFieldInput.checked = false; optionField.classList.remove('formfield__inner__image--selected'); }
190   }
191}
192function brave_select_form_ButtonGroup(fieldID, optionIndex, nextStep=false, formID='', totalSteps=0, goto=undefined){
193   brave_select_imageField(fieldID, optionIndex, false);
194   //console.warn(nextStep, formID, totalSteps, goto);
195   if(nextStep && formID && totalSteps && goto !== undefined){
196      brave_form_gotoStep(formID, totalSteps, goto);
197   }
198}
199function brave_form_rating_unhover(fieldID){
200   var allRatingFields = document.getElementById('brave_form_field'+fieldID).querySelectorAll('.formfield__inner__ratings_star, .formfield__inner__ratings_number');
201   for (var i = 0; i < allRatingFields.length; i++) { 
202      allRatingFields[i].classList.remove('formfield__inner__ratings--hovered'); 
203   }
204}
205function brave_form_rating_hover(fieldID, optionIndex){
206   var allRatingFields = document.getElementById('brave_form_field'+fieldID).querySelectorAll('.formfield__inner__ratings_star, .formfield__inner__ratings_number');
207   for (var i = 0; i < allRatingFields.length; i++) { 
208      allRatingFields[i].classList.remove('formfield__inner__ratings--hovered');  
209      if(i <= (optionIndex-1)){
210         allRatingFields[i].classList.add('formfield__inner__ratings--hovered'); 
211      }
212   }
213}
214
215function brave_form_rate(fieldID, optionIndex, smiley=false){
216   document.getElementById('brave_form_field'+fieldID).dataset.rated = optionIndex;
217   var allRatingFields = document.getElementById('brave_form_field'+fieldID).querySelectorAll('.formfield__inner__ratings_star, .formfield__inner__ratings_number, .formfield__inner__ratings_smiley');
218   for (var i = 0; i < allRatingFields.length; i++) { 
219      allRatingFields[i].classList.remove('formfield__inner__ratings--selected');
220      if(!smiley && (i <= (optionIndex-1))){    allRatingFields[i].querySelector('input').checked = true; allRatingFields[i].classList.add('formfield__inner__ratings--selected');   }
221      
222      if(smiley && (i === (optionIndex-1))){    
223         allRatingFields[i].querySelector('input').checked = true; 
224         allRatingFields[i].classList.add('formfield__inner__ratings--selected');   
225      }
226   }
227}
228
229function brave_form_progress(formID, goto=0, totalSteps=2){
230   if(document.querySelector('#'+formID+'__form_progress')){
231      var progressPercent =  Math.round(((goto+1)/ totalSteps) * 100) ;
232      var progStyle = document.querySelector('#'+formID+'__form_progress').dataset.style || 'style1';
233      if(progStyle === 'style2'){ progressPercent = Math.round(((goto)/ (totalSteps-1)) * 100) ;}
234      if(document.querySelector('#'+formID+'__form_progress .bravepopupform_theProgressbar_steps')){
235         document.querySelector('#'+formID+'__form_progress .bravepopupform_theProgressbar_steps').innerHTML = (goto+1)+'/'+(totalSteps);
236         document.querySelector('#'+formID+'__form_progress .bravepopupform_theProgressbar_progress').innerHTML = progressPercent+'%' ;
237      }
238
239      document.querySelector('#'+formID+'__form_progress .bravepopupform_theProgressbar__bar').style.width = progressPercent+'%';
240   }
241}
242
243function brave_form_goBack(formID, totalSteps){
244   var currentStep = document.querySelector('#brave_form_'+formID+' .brave_form_fields').dataset.step; currentStep = parseInt(currentStep, 10)
245   var formBackButton = document.querySelector('#brave_form_'+formID+' .brave_form_stepBack');
246   var goto = currentStep - 1;
247   document.querySelector('#brave_form_'+formID+' .brave_form_fields').dataset.step = goto;
248   brave_popup_formData[formID].currentStep = goto;
249
250   //Change The Popup and Form Height if specified
251   brave_form_changeHeight(formID, goto);
252   //Update ProgressBar
253   brave_form_progress(formID, goto, totalSteps);
254
255   if(formBackButton){
256      if(goto === 0 ){   
257         formBackButton.classList.add('brave_form_stepBack--hide');
258      }else{
259         formBackButton.classList.remove('brave_form_stepBack--hide');
260      }
261   }
262
263   // //Go to Prev Step
264   var allformSteps = document.querySelectorAll('#brave_form_'+formID+' .brave_form_fields_step');
265   for (var i = 0; i < allformSteps.length; i++) {   
266      if(i ===goto){
267         allformSteps[i].classList.add('brave_form_fields_step--show'); 
268
269      }else{
270         allformSteps[i].classList.remove('brave_form_fields_step--show');   
271      }
272      //if already filled the fields in next steps, reset them to preserve conditional logic
273      if(currentStep === i){
274         var nextFieldsWithVals =  allformSteps[i].querySelectorAll('.brave_form_field input, .brave_form_field select');
275         for (var k = 0; k < nextFieldsWithVals.length; k++) {
276            var fieldType = nextFieldsWithVals[k].getAttribute('type');
277            var fieldKey = nextFieldsWithVals[k].name.replace('[]');
278            if(['radio', 'checkbox'].includes(fieldType) && nextFieldsWithVals[k].checked){
279               nextFieldsWithVals[k].checked = false;
280            }      
281            if(fieldType === 'select' && nextFieldsWithVals[k].value){
282               nextFieldsWithVals[k].value = 'false';
283            }
284            brave_check_field_condition({target:{value:''}}, fieldKey, formID, fieldType)
285         }
286      }
287   }
288
289   if(goto === (totalSteps - 1) ){
290      document.querySelector('#brave_form_'+formID+' .brave_form_button').classList.remove('brave_form_button--hide');   
291   }else{
292      document.querySelector('#brave_form_'+formID+' .brave_form_button').classList.add('brave_form_button--hide'); 
293   }
294}
295
296function brave_form_gotoStep(formID, totalSteps, goto){
297   //console.log('gotoStep', goto,totalSteps, goto === (totalSteps - 1));
298   
299   //Get The form Fields Values
300   var braveForm = document.getElementById('brave_form_'+formID);
301   var fieldsData = brave_get_field_vals(braveForm, JSON.parse(brave_popup_formData[formID].fields))
302
303
304   var stepFieldIDs = [];
305   var currentStep = document.querySelector('#brave_form_'+formID+' .brave_form_fields_step'+(goto-1));
306   if(currentStep){
307      var allStepFields = currentStep.querySelectorAll('.brave_form_field');
308      for (var i = 0; i < allStepFields.length; i++) { 
309         if( !allStepFields[i].classList.contains('brave_form_field--step') ){
310            stepFieldIDs.push(allStepFields[i].getAttribute('id').replace('brave_form_field', ''));
311         }
312      }
313   }
314   var filteredFieldData = {}; var emailFields = [];
315   stepFieldIDs.forEach(function(fieldID){
316      if(fieldsData[fieldID]){ 
317         filteredFieldData[fieldID] = fieldsData[fieldID];
318         if(filteredFieldData[fieldID] && fieldsData[fieldID].required && fieldsData[fieldID].validation === 'email' && (!bravepop_emailSuggestions[fieldID])) { 
319            emailFields.push({ID: fieldID, value: fieldsData[fieldID].value});
320            //bravepop_emailSuggestions[fieldID] = true;
321         }
322      }
323   })
324   //console.log( fieldsData, filteredFieldData);
325
326   // //Check if Form Has Errors
327   var formErrors = [];
328   Object.keys(filteredFieldData).forEach(function(fieldID){
329      var fieldError = brave_validate_fields(fieldID, filteredFieldData[fieldID]);
330      if(fieldError){ formErrors.push(fieldError); }
331      document.querySelector('#brave_form_field'+fieldID).classList.remove('brave_form_field--hasError', 'brave_form_field--hasSuggestion', 'brave_form_field--hasError-firstname', 'brave_form_field--hasError-lastname');
332   });
333   brave_display_form_error(formErrors);
334
335   if(formErrors.length > 0){ return }
336
337   var braveFormNextStepActions = function(){
338      //Change The Popup and Form Height if specified
339      brave_form_changeHeight(formID, goto);
340
341      // //Go to NextStep
342      var allformSteps = document.querySelectorAll('#brave_form_'+formID+' .brave_form_fields_step');
343      for (var i = 0; i < allformSteps.length; i++) {   
344         if(i ===goto){
345            document.querySelector('#brave_form_'+formID+' .brave_form_fields').dataset.step = goto;
346            allformSteps[i].classList.add('brave_form_fields_step--show');   
347            document.querySelector('#brave_form_'+formID+' .brave_form_fields').style.height = allformSteps[i].offsetHeight+'px';
348            var formBackButton = document.querySelector('#brave_form_'+formID+' .brave_form_stepBack');
349            if(formBackButton){ formBackButton.classList.remove('brave_form_stepBack--hide'); }
350            brave_popup_formData[formID].currentStep = goto;
351         }else{
352            allformSteps[i].classList.remove('brave_form_fields_step--show');   
353         }
354      }
355      brave_form_progress(formID, goto, totalSteps, false);
356      if(goto === (totalSteps - 1) ){
357         setTimeout(function() {
358            document.querySelector('#brave_form_'+formID+' .brave_form_button').classList.remove('brave_form_button--hide');  
359         }, 250);
360      }
361
362   }
363
364   if(bravepop_emailValidation && emailFields.length > 0){
365      var ajaxurl = bravepop_global.ajaxURL;
366      var security = document.getElementById('brave_form_security'+formID).value;
367      var emailData = { formData: JSON.stringify(emailFields), freemailAllow: JSON.stringify(brave_popup_formData[formID].freemailAllow || false), security: security, action: 'bravepopup_validate_email'};
368      brave_ajax_send(ajaxurl, emailData, function(status, sentData){
369         var validatedData = JSON.parse(sentData);
370         console.log('Validation response:', validatedData); var emailValidationErrors = [];
371         if(Array.isArray(validatedData)){
372            validatedData.forEach(function(field){
373               if(field.validation && field.validation.status === 'invalid' && field.validation.errorMsg){
374                  emailValidationErrors.push({id:field.ID ,message: field.validation.errorMsg, type: "required"});
375               }
376               if(field.validation && field.suggestionMsg){
377                  emailValidationErrors.push({id:field.ID ,message: field.suggestionMsg, type: "info"});
378               }
379            });
380         }
381         if(emailValidationErrors.length > 0){
382            brave_display_form_error(emailValidationErrors);
383            if(brave_form){ brave_form.classList.remove('brave_form_form--loading');  }
384            if(brave_login_loader){  brave_login_loader.classList.remove('brave_form_loading--show'); }
385         }else{
386            braveFormNextStepActions();
387         }
388      });
389   }else{
390      braveFormNextStepActions();
391   }
392
393
394
395}
396
397function brave_form_changeHeight(formID, goto){
398   var changesFormHeight = brave_popup_formData[formID].changesFormHeight || false;
399   if(changesFormHeight){
400      var braveForm = document.getElementById('brave_element-'+formID);
401      var parentPopupStep = braveForm.closest('.brave_popup__step');
402      var initialHeight = brave_popup_formData[formID].heightData[0];
403      var diffHeight = brave_popup_formData[formID].heightData[goto] - initialHeight;
404      var newFormHeight = brave_popup_formData[formID].heightData[goto] || initialHeight;
405      braveForm.style.height = (parseInt(newFormHeight, 10))+'px';
406
407      if(parentPopupStep){
408         var parentPopupHeight = parentPopupStep.dataset.height;
409         //console.log(goto, parentPopupHeight, diffHeight, initialHeight, brave_popup_formData[formID].heightData[goto], brave_popup_formData[formID].heightData);
410         parentPopupStep.querySelector('.brave_popup__step__inner').style.height =  (parseInt(parentPopupHeight, 10) + diffHeight)+'px';
411      }
412   }
413   //console.log( changesFormHeight, newFormHeight, initialHeight, diffHeight);
414}
415
416function brave_get_field_vals(braveForm, fieldOpts, quiz){
417   var fieldsData = fieldOpts; var firstname_val ='';
418   for( var i=0; i<braveForm.elements.length; i++ ){
419      var fieldName = braveForm.elements[i].name.replace('[]', '');
420      var fieldOpts = fieldsData[fieldName] || {};
421      var fieldValue = braveForm.elements[i].value;
422      // console.log(fieldName, fieldOpts, fieldValue);
423      if(fieldOpts && fieldOpts.type && (fieldOpts.type ==='checkbox' || (fieldOpts.type ==='select' && fieldOpts.multi) || (fieldOpts.type ==='image' && fieldOpts.multi)) ){
424         var checkedVal = document.querySelectorAll('#brave_form_field'+fieldName+' input
424:checked, #brave_form_field'+fieldName+' option:checked');
425         fieldValue = Array.from(checkedVal).map(function(el){ return el.value});
426         if(fieldOpts.required && (fieldValue.length === 0 || fieldValue.includes('none')) ){ fieldValue =''; }
427      }
428      if(fieldOpts && fieldOpts.type && (fieldOpts.type ==='rating' || fieldOpts.type ==='radio' || fieldOpts.type ==='buttons') ){
429         var checkedVal = document.querySelectorAll('#brave_form_field'+fieldName+' input:checked, #brave_form_field'+fieldName+' option:checked');
430         var selectedfieldValue = Array.from(checkedVal).map(function(el){ return el.value});
431         fieldValue = Array.isArray(selectedfieldValue) && selectedfieldValue[0] ? selectedfieldValue[0] : '';
432         //console.log(fieldOpts.type, checkedVal );
433      }
434      if(fieldOpts && fieldOpts.type && fieldOpts.type ==='input' && fieldOpts.validation ==='name'){
435         if(braveForm.elements[i].classList.contains('brave_form_field_input-firstname')){   firstname_val = fieldValue; }
436         if(braveForm.elements[i].classList.contains('brave_form_field_input-lastname')){   
437            fieldsData[fieldName].value = [firstname_val,fieldValue];
438          }
439      }else if(fieldsData[fieldName]){
440         fieldsData[fieldName].value = fieldValue;
441      }
442
443      //If the Field is only set to show conditionally, and the condition does not need to match, set the required to fal
443se
444      if(fieldsData[fieldName] && fieldsData[fieldName].required && document.getElementById('brave_form_field'+fieldName).classList.contains('brave_form_field--hasCondition')){
445         fieldsData[fieldName].required = false;
446      }
447
448      if(fieldOpts && fieldOpts.type && fieldOpts.type ==='date' && fieldOpts.validation ==='multi'){
449         var dateVal = document.getElementById('brave_form_field'+fieldName+'-date') ? document.getElementById('brave_form_field'+fieldName+'-date').value : '';
450         var monthVal = document.getElementById('brave_form_field'+fieldName+'-month') ? document.getElementById('brave_form_field'+fieldName+'-month').value : '';
451         var yearVal = document.getElementById('brave_form_field'+fieldName+'-year') ? document.getElementById('brave_form_field'+fieldName+'-year').value : new Date().getFullYear();
452         if(dateVal || monthVal){
453            fieldsData[fieldName].value = dateVal+'/'+monthVal+'/'+yearVal;
454         }
455      }
456
457      if(quiz && fieldOpts.options){
458         var selectedOpt = false;
459         fieldOpts.options.forEach(function(opt) {
460            if( (fieldOpts.type ==='checkbox' || (fieldOpts.type ==='select' && fieldOpts.multi) || (fieldOpts.type ==='image' && fieldOpts.multi)) && fieldValue.includes(opt.value)){ selectedOpt = opt; }
461            if( (fieldOpts.type ==='radio' || fieldOpts.type ==='buttons')  && opt.value === fieldValue){ selectedOpt = opt; }
462         });
463         if(selectedOpt){
464            fieldsData[fieldName].score = selectedOpt.score ? selectedOpt.score : 0 ;
465            fieldsData[fieldName].correct = selectedOpt.correct ? selectedOpt.correct : false ;
466         }
467      }
468   }
469   return fieldsData;
470}
471
472function brave_submit_form(event, settings, supressErrors=false){
473   if(event){  event.preventDefault();  }
474   var braveForm = document.getElementById('brave_form_'+settings.formID);
475   var originalFields = JSON.parse(settings.fields);
476   var fieldsData = brave_get_field_vals(braveForm, originalFields, settings.quiz)
477   var ajaxurl = bravepop_global.ajaxURL;
478   var security = document.getElementById('brave_form_security'+settings.formID).value;
479   //console.log(settings.fields);
480   //Check if has Errrors
481   var formErrors = [];
482   Object.keys(fieldsData).forEach(function(fieldID){
483      var fieldError = brave_validate_fields(fieldID, fieldsData[fieldID]);
484      if(fieldError){ formErrors.push(fieldError); }
485      if(document.querySelector('#brave_form_field'+fieldID)){
486         document.querySelector('#brave_form_field'+fieldID).classList.remove('brave_form_field--hasError','brave_form_field--hasSuggestion', 'brave_form_field--hasError-firstname', 'brave_form_field--hasError-lastname');
487      }
488   });
489   brave_display_form_error(formErrors);
490
491   var finalFieldsData = {}; var quizData = {}; var emailFields = []; var quizScore = 0; var availableScore = 0; var quizCorrect = 0;
492   Object.keys(fieldsData).forEach(function(fieldID){  
493      if(fieldsData[fieldID]) {  finalFieldsData[fieldID] = fieldsData[fieldID].value; }
494      if(fieldsData[fieldID] && fieldsData[fieldID].validation === 'name' && Array.isArray(fieldsData[fieldID].value)) { 
495         finalFieldsData[fieldID] = fieldsData[fieldID].value.join(' ').trim();
496      }
497      if(fieldsData[fieldID] && fieldsData[fieldID].required && fieldsData[fieldID].validation === 'email' && (!bravepop_emailSuggestions[fieldID])) { 
498         emailFields.push({ID: fieldID, value: fieldsData[fieldID].value});
499         //bravepop_emailSuggestions[fieldID] = true;
500      }
501      if(settings.quiz && fieldsData[fieldID] && fieldsData[fieldID].score){ quizScore = quizScore + fieldsData[fieldID].score;}
502      if(settings.quiz && fieldsData[fieldID] && fieldsData[fieldID].correct){ quizCorrect = quizCorrect + 1;}
503      if(settings.quiz && fieldsData[fieldID] && fieldsData[fieldID].topScore){ availableScore = availableScore + fieldsData[fieldID].topScore; }
504   });
505
506   if(settings.quiz){
507      brave_popup_formData[settings.formID].totalScore = quizScore;
508      brave_popup_formData[settings.formID].totalCorrect = quizCorrect;
509      brave_popup_formData[settings.formID].availableScore = availableScore;
510      quizData = {availableScore: availableScore, userScore: quizScore, userCorrect: quizCorrect, totalQuestions: settings.totalQuestions, scoring: settings.quizScoring}
511   }
512
513   console.log('finalFieldsData: ', quizScore, quizCorrect, fieldsData);
514   console.log(formErrors);
515   //console.log('FORM ERRORS: ', formErrors);
516
517   if(supressErrors){ formErrors = []; }
518
519   if(formErrors.length === 0){
520      //console.log('NO ERRORS Sending to Backend!');
521      //SEND Data
522      if(!security || !ajaxurl) { return console.log('Security Failed or Ajax URL Missing!!!!', security, ajaxurl); }
523      var finalData = { formData: JSON.stringify(finalFieldsData), popupID: settings.popupID, formID: settings.formID, stepID: settings.stepID, quizData: JSON.stringify(quizData), cookieConditions:"", device: settings.device, userDevice: brave_currentDevice, pageURL: window.location, security: security, action: 'bravepop_form_submission' };
524      var brave_form = document.getElementById('brave_form_'+settings.formID);
525      var brave_login_loader = document.getElementById('brave_form_loading_'+settings.formID);
526      if(brave_login_loader){  brave_login_loader.classList.add('brave_form_loading--show'); }
527      if(brave_form){ brave_form.classList.add('brave_form_form--loading');  }
528
529      var cookiesToCheck = brave_form.dataset.cookies ? brave_form.dataset.cookies.split(',') : [];
530      if(cookiesToCheck.length > 0){
531         var cookiesData = {};
532         cookiesToCheck.forEach(function(cookieName){   cookiesData[cookieName] = localStorage.getItem(cookieName) ? true : false;  })
533         finalData.cookieConditions = JSON.stringify(cookiesData);
534      }
535      
536      if(window.location.href.includes('brave_popup') && window.location.href.includes('brave_preview') && location.search.split('brave_preview=')[1]){
537         finalData.brave_previewID = location.search.split('brave_preview=')[1];
538      }
539
540      //console.log(finalData);
541      var braveSubmitForm = function(){
542         return brave_ajax_send(ajaxurl, finalData, function(status, sentData){
543            //Remove The sending Status
544            if(brave_login_loader){  brave_login_loader.classList.remove('brave_form_loading--show'); }
545            if(brave_form){ brave_form.classList.remove('brave_form_form--loading');  }
546            if(document.querySelector('#bravepopupform_socialOptin-'+settings.formID)){
547               document.querySelector('#bravepopupform_socialOptin-'+settings.formID).classList.remove('bravepopupform_socialOptin--loading');
548               document.querySelector('#bravepopupform_socialOptin-'+settings.formID).classList.add('bravepopupform_socialOptin--hide');
549               document.querySelector('#brave_element-'+settings.formID+' .brave_element__form_inner').classList.remove('brave_element__form_inner--hide');
550            }
551   
552            var response = JSON.parse(sentData);
553            console.log(status, response);
554
555            if(response.error &&  typeof response.error === 'string'){
556               return alert(response.error);
557            }
558
559            localStorage.setItem('brave_popup_'+settings.popupID+'_formsubmitted', true);
560   
561            var braveFormSubmitEvent = new CustomEvent('brave_form_submitted', { detail: {popupId: parseInt(settings.popupID, 10), formId: settings.formID, formData: JSON.stringify(finalFieldsData)} });
562            document.dispatchEvent(braveFormSubmitEvent);
563   
564            // if(document.querySelector('#'+settings.formID+'__form_progress')){
565            //    document.querySelector('#'+settings.formID+'__form_progress').style.display = 'none';
566            // }
567
568            //Reset the Form
569            if(brave_form){  brave_form.reset();   }
570
571            //If Multistep Form, go to the First Step
572            if(brave_popup_formData[settings.formID] && brave_popup_formData[settings.formID].totalSteps > 0){
573               for (var findx = 1; findx < brave_popup_formData[settings.formID].totalSteps; findx++) {
574                  brave_form_goBack(settings.formID, brave_popup_formData[settings.formID].totalStep)
575               }
576            }
577
578            if(settings.track){
579               var formTrackingSettings = JSON.parse(settings.track);
580               //Send Ga Event
581               if( formTrackingSettings && formTrackingSettings.enable && formTrackingSettings.eventCategory && formTrackingSettings.eventAction){
582                  brave_send_ga_event(formTrackingSettings.eventCategory, formTrackingSettings.eventAction, formTrackingSettings.eventLabel || '');
583               }
584               if( formTrackingSettings && formTrackingSettings.enable && formTrackingSettings.fbq_event_type){
585                  brave_send_fbq_event(formTrackingSettings.fbq_event_type, formTrackingSettings.fbq_content_name, formTrackingSettings.fbq_content_category, formTrackingSettings.fbq_value, formTrackingSettings.fbq_currency);
586               }
587            }
588   
589            //Perform Goal
590            if(brave_popup_formData[settings.formID] && brave_popup_formData[settings.formID].goal){
591               brave_complete_goal(settings.popupID, 'form');
592            }
593            
594            //Save Field Value as Cookie
595            Object.keys(fieldsData).forEach(function(fieldID){  
596               var fieldVal = Array.isArray(fieldsData[fieldID].value) ? fieldsData[fieldID].value.join(',') : fieldsData[fieldID].value;
597               if(fieldVal && fieldsData[fieldID] && fieldsData[fieldID].save_cookie){ localStorage.setItem(fieldsData[fieldID].save_cookie, fieldVal)}
598            });
599   
600            //Show Content
601            if(response.sent && response.primaryAction === 'content' && response.contentMessage ){
602               if(brave_form){ brave_form.classList.add('brave_form_form--hide');  }
603               document.getElementById('brave_form_custom_content'+settings.formID).innerHTML = response.contentMessage;
604               //Auto Close Popup
605               if(response.autoclose && response.autoclosetime){
606                  setTimeout(function() {
607                     var thePopID = parseInt(settings.popupID, 10);
608                     brave_close_popup(thePopID, brave_popup_data[thePopID].currentStep||0);
609                  }, parseInt(response.autoclosetime, 10) * 1000);
610               }
611               //Also Download File
612               if(response.download && response.downloadURL){
613                  var downloadURI = response.downloadURL; var filename =  response.downloadURL.substring( response.downloadURL.lastIndexOf('/')+1);
614                  var link = document.createElement('a');
615                  if (typeof link.download === 'string') {
616                        document.body.appendChild(link); // Firefox requires the link to be in the body
617                        link.download = filename;
618                        link.href = downloadURI;
619                        link.target = '_blank';
620                        link.click();
621                        document.body.removeChild(link); // remove the link when done
622                  } else {
623                        location.replace(downloadURI);
624                  }
625               }
626            }
627
628            //Run Users own functions after submit
629            brave_popup_formData[settings.formID] && brave_popup_formData[settings.formID].onSubmit(fieldsData, response);
630   
631            //Redirect User
632            if(response.sent && response.primaryAction === 'redirect' && response.redirectURL ){
633               if(brave_form){ brave_form.classList.add('brave_form_form--hide');  }
634               document.getElementById('brave_form_custom_content'+settings.formID).innerHTML = response.redirectMessage;
635               var redirectTime = response.redirectAfter ? (response.redirectAfter *1000) : 6000;
636               setTimeout(function() {
637                  window.location.href = response.redirectURL;
638               }, redirectTime);
639            }
640   
641            //Go to Step
642            if(response.sent && response.primaryAction === 'step' && response.step && settings.popupID ){
643               var formStep = parseInt(response.step, 10);
644               formStep = formStep === 0 ? 0 : formStep - 1;
645               var selectedPopupStep = document.querySelector('#brave_popup_'+settings.popupID+'__step__'+(brave_popup_data[settings.popupID].currentStep||0)+' .brave_popup__step__'+brave_currentDevice)
646               if(selectedPopupStep){ selectedPopupStep.dataset.open = 'false'; }
647               brave_open_popup(settings.popupID, formStep);
648            }
649            //If has quiz Shortcode in the popup, insert the quiz scores inside the shortcodes
650            if(settings.quiz){
651               var quizShortcodes = document.querySelectorAll('.bravepop_quizScore-'+settings.formID);
652               if(quizShortcodes){
653                  for (var i = 0; i < quizShortcodes.length; i++) { 
654                     var showTotal = quizShortcodes[i].dataset.total && quizShortcodes[i].dataset.total === 'false' ? false : true;
655                     if(settings.quizScoring ==='points' ){
656                        var availableScoreVal = showTotal && brave_popup_formData[settings.formID].availableScore && brave_popup_formData[settings.formID].availableScore >= brave_popup_formData[settings.formID].totalScore ? '/'+brave_popup_formData[settings.formID].availableScore : '';
657                        quizShortcodes[i].innerHTML = '<span>'+brave_popup_formData[settings.formID].totalScore+'</span>'+availableScoreVal;
658                     }
659                     if(settings.quizScoring ==='answer'){
660                        var availableQuesVal = showTotal && brave_popup_formData[settings.formID].totalQuestions ?  '/'+brave_popup_formData[settings.formID].totalQuestions : '';
661                        quizShortcodes[i].innerHTML = '<span>'+brave_popup_formData[settings.formID].totalCorrect+'</span>'+availableQuesVal;
662                     }
663                  }
664               }
665            }
666
667         });
668      }
669
670      var braveSubmitWithEmailValidation = function(){
671         var emailData = { formData: JSON.stringify(emailFields), freemailAllow: JSON.stringify(brave_popup_formData[settings.formID].freemailAllow || false), security: security, action: 'bravepopup_validate_email' };
672         brave_ajax_send(ajaxurl, emailData, function(status, sentData){
673            var validatedData = JSON.parse(sentData);
674            console.log('Validation response:', validatedData); var emailValidationErrors = [];
675            if(Array.isArray(validatedData)){
676               validatedData.forEach(function(field){
677                  if(field.validation && field.validation.status === 'invalid' && field.validation.errorMsg){
678                     emailValidationErrors.push({id:field.ID ,message: field.validation.errorMsg, type: "required"});
679                  }
680                  if(field.validation && field.validation.suggestionMsg && field.validation.suggestion){
681                     emailValidationErrors.push({id:field.ID , message: field.validation.suggestionMsg, type: "suggestion", suggestion: field.validation.suggestion});
682                  }
683               });
684            }
685            if(emailValidationErrors.length > 0){
686               brave_display_form_error(emailValidationErrors);
687               if(brave_form){ brave_form.classList.remove('brave_form_form--loading');  }
688               if(brave_login_loader){  brave_login_loader.classList.remove('brave_form_loading--show'); }
689            }else{
690               braveSubmitForm();
691            }
692         });
693      }
694
695      if(settings.recaptcha && grecaptcha){
696         grecaptcha.execute(settings.recaptcha, {action: 'submit'}).then(function(token) {
697            if(token){
698               var recaptchaData = { token: token, security: security, action: 'bravepopup_validate_recaptcha' };
699               brave_ajax_send(ajaxurl, recaptchaData, function(status, valid){
700                  console.log('Google Recaptcha Verified!');
701                  if(valid === 'true'){
702                     if(bravepop_emailValidation && emailFields.length > 0){
703                        braveSubmitWithEmailValidation();
704                     }else{
705                        braveSubmitForm();
706                     }
707                  }else{
708                     console.error('Google Recaptcha Failed! Spammer Detected!');
709                  }
710               });
711            }else{ console.error('Google Recaptcha Failed! Could not Fetch Token!'); }
712        });
713      }else{
714         if(bravepop_emailValidation && emailFields.length > 0){
715            braveSubmitWithEmailValidation();
716         }else{
717            braveSubmitForm();
718         }
719      }
720
721   }
722
723}
724
725function brave_apply_email_suggestion(fieldID, suggestion){ document.querySelector('#brave_form_field'+fieldID+' input').value = suggestion; brave_dismiss_email_suggestion(fieldID); }
726function brave_dismiss_email_suggestion(fieldID){ document.querySelector('#brave_form_field'+fieldID).classList.remove('brave_form_field--hasError', 'brave_form_field--hasSuggestion'); }
727
728function brave_display_form_error(formErrors){
729      //console.log(formErrors);
730      
731      //Display The Errors
732      if(formErrors.length > 0){
733         formErrors.forEach(function(error){
734            if(error.fieldType && error.fieldType ==='name'){
735               if(error.firstname){
736                  document.querySelector('#brave_form_field'+error.id).classList.add('brave_form_field--hasError-firstname');
737                  document.querySelector('#brave_form_field'+error.id+' .brave_form_field_error--firstname').innerHTML = error.message;
738               }
739               if(error.lastname){
740                  document.querySelector('#brave_form_field'+error.id).classList.add('brave_form_field--hasError-lastname');
741                  document.querySelector('#brave_form_field'+error.id+' .brave_form_field_error--lastname').innerHTML = error.message;
742               }
743   
744            }else{
745               document.querySelector('#brave_form_field'+error.id).classList.add('brave_form_field--hasError');
746               document.querySelector('#brave_form_field'+error.id+' .brave_form_field_error').innerHTML = error.message;
747               if(error.type === 'suggestion' && error.suggestion ){
748                  document.querySelector('#brave_form_field'+error.id).classList.add('brave_form_field--hasSuggestion');
749                  var suggestionApplyBtn = '<span onclick="brave_apply_email_suggestion(\''+error.id+'\', \''+error.suggestion+'\')">'+bravepop_global.yes+'</span>';
750                  var suggestionDismissBtn = '<span onclick="brave_dismiss_email_suggestion(\''+error.id+'\', \''+error.suggestion+'\')">'+bravepop_global.no+'</span>';
751                  var suggestionActions = '<div id="brave_form_field_suggestion_actions-'+error.id+'" class="brave_form_field_suggestion_actions">'+suggestionApplyBtn+suggestionDismissBtn+'</div>'
752                  document.querySelector('#brave_form_field'+error.id+' .brave_form_field_error').setAttribute('id', 'brave_form_field_error--suggestion'+error.id)
753                  document.querySelector('#brave_form_field'+error.id+' .brave_form_field_error').classList.add('brave_form_field_error--suggestion');
754                  document.querySelector('#brave_form_field'+error.id+' .brave_form_field_error').innerHTML = (error.message)+suggestionActions;
755               }
756            }
757         });
758      }
759}
760
761
762function brave_validate_fields(fieldID, field){
763   if(!field){ return }
764
765   if(field.type==='input' && field.validation === 'name' && field.required) { 
766      if(!field.value[0] || !field.value[1]){
767         return {id: fieldID, type: 'required', fieldType: 'name', message: bravepop_global.field_required, firstname: !field.value[0] ? true : false, lastname:  !field.value[1] ? true : false}
768      }
769   }
770
771   if(!field.value && field.required) { 
772      return {id: fieldID, type: 'required', message: bravepop_global.field_required}
773   }
774   if(field.required && (field.type==='input' || field.type==='textarea' || field.type==='date' ) ) { 
775      if(field.validation !== 'name'  && !field.value.trim()){
776         return {id: fieldID, type: 'required', message: bravepop_global.field_required}
777      }
778   }
779
780   if(field.value && field.required && field.type==='select' && field.value === 'none') { 
781      return {id: fieldID, type: 'required', message: bravepop_global.field_required}
782   }
783
784   //Check HTML or Empty Value
785   if(field.value && ((field.type==='input' && field.validation === 'text') || field.type==='textarea' || field.type==='date'  ) ) { 
786
787      if(brave_hasHTML(field.value)){
788         return {id: fieldID, type: 'ho_html', message: bravepop_global.no_html_allowed};
789      }
790   }
791
792   //Validate number
793   if(field.value && field.type==='input' && field.validation === 'number' ) { 
794      if(brave_isNumber(field.value) === false){
795         return {id: fieldID, type: 'invalid', message: bravepop_global.invalid_number};
796      }
797   }
798   //Validate url
799   if(field.value && field.type==='input' && field.validation === 'url' ) { 
800      if(brave_isURL(field.value) === false){
801         return {id: fieldID, type: 'invalid', message: bravepop_global.invalid_url};
802      }
803   }
804
805   //Validate Date
806   if(field.value && field.type==='date' ) { 
807      if(brave_isDate(field.value) === false){
808         return {id: fieldID, type: 'invalid', message: bravepop_global.invalid_date};
809      }
810   }
811
812   //Validate email
813   if(field.value && field.type==='input' && field.validation === 'email' ) { 
814      if(brave_isEmail(field.value) === false){
815         return {id: fieldID, type: 'invalid', message: bravepop_global.invalid_email};
816      }
817   }
818
819}
820
821function brave_hasHTML(value) {
822   var doc = new DOMParser().parseFromString(value, "text/html");
823   return Array.from(doc.body.childNodes).some(function(node){ return node.nodeType === 1});
824}
825
826function brave_isNumber(value) {
827   var numberFormat = RegExp(/^[a-zA-Z]+$/);
828   return numberFormat.test(value) ? false : true;
829}
830
831function brave_isEmail(value) {
832   var mailformat = RegExp(/^\w+([\.+-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,8})+$/);
833   return mailformat.test(value) ? true : false;
834}
835
836function brave_isURL(value) {
837   var urlFormat = RegExp(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
838   return urlFormat.test(value) ? true : false;
839}
840
841function brave_isDate(value) {
842   var dateFormat = RegExp(/\d{1,4}[-/]\d{1,2}[-/]\d{1,4}/);
843   var dateFormatTwo = RegExp(/\d{1,4}[-/]\d{1,2}/);
844   var matchedDate = dateFormat.test(value);
845   if(!matchedDate){ matchedDate = dateFormatTwo.test(value);  }
846   //console.log(value, matchedDate);
847   return matchedDate ? true : false;
848}
849
850
851function brave_ajax_send(ajaxurl, ajaxData, callbackFunction){
852   //console.log(ajaxData);
853   var array = [];
854   Object.keys(ajaxData).forEach(function(element) {
855      array.push(  encodeURIComponent(element) + "=" + encodeURIComponent(ajaxData[element]) ) 
856   });
857   var dataToSend = array.join("&");
858   
859   var request = new XMLHttpRequest();
860   request.open('POST', ajaxurl, true);
861   request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded' );
862   request.onload = function () {  
863      if (this.status >= 200 && this.status < 400) { 
864         callbackFunction('success', this.response);
865      } else {   
866         callbackFunction('error', this.response);
867      }  
868   };
869   //request.onerror = function(error) {  console.log(error);   };
870   request.send(dataToSend);
871}
872
873
874function brave_action_step(popupID, currentStep, stepIndex){
875   //console.log(popupID, stepIndex);
876   var selectedPopupStep = document.querySelector('#brave_popup_'+popupID+'__step__'+stepIndex+' .brave_popup__step__'+brave_currentDevice)
877   var noMobileContent = selectedPopupStep && selectedPopupStep.dataset.nomobilecontent === 'true' ? true : false;
878   var currentDevice = noMobileContent ? 'desktop' : brave_currentDevice;
879   var selectedPopupStep = document.querySelector('#brave_popup_'+popupID+'__step__'+currentStep+' .brave_popup__step__'+currentDevice)
880   selectedPopupStep.dataset.open = 'false';
881   brave_open_popup(popupID, stepIndex);
882   
883}
884
885
886function brave_init_popup(popupID, popupData ){
887   //console.log(popupID, popupData);
888   if(!popupData){ return; }
889   brave_responsiveness(null, popupID, popupData);
890
891   //If is in Preview Mode force load the popup skinpping all the conditions
892   if(popupData.forceLoad){
893      return brave_load_popup(popupID, popupData);  
894   }
895
896   var triggerType = popupData.settings && popupData.settings.trigger && popupData.settings.trigger.triggerType ? popupData.settings.trigger.triggerType.split(',') : ['load'];
897
898   //Do not load if utm keywords dont match
899   var utmKeywords = [];
900   var containsKeyword = false;
901   if(popupData.settings && popupData.settings.placement && popupData.settings.placement.utm  && popupData.settings.placement.utmKeywords){
902      utmKeywords = popupData.settings.placement.utmKeywords.split(',');
903   } 
904   if(utmKeywords.length > 0){
905      var currentURL = window.location.href;
906      utmKeywords.forEach(function(key){
907         if(currentURL.includes(key)){   containsKeyword = true;  }
908      })
909      if(containsKeyword === false){
910         return console.log('Does Not Match UTM Keywords');
911      }
912   }
913   //Do not load if campaign has ad block detection enabled and user has Ad blocker Installed.
914   if(popupData.settings && popupData.settings.placement && popupData.settings.placement.adblock_check && window.brave_canRunAds){
915      return console.log('Visitor Doesnt have Ad Blocked Installed! Aborting..');
916   }
917   //Do not Load if embedded popups if the shortcode is not present in current page
918   if((popupData.hasDesktopEmbed || (popupData.hasMobileEmbed && brave_currentDevice === 'mobile')) && !document.getElementById('bravepopup_embedded_'+popupID)){
919      return console.log('Popup shortcode is not found in current page');
920   }
921
922   //Do not load if Popup is not in Scheduled Dates
923   if(popupData.schedule && popupData.schedule.active && popupData.schedule.type){
924      if(popupData.schedule.type === 'days' && popupData.schedule.days.length > 0){
925         var currentDay = new Date().getDay();
926         if(!popupData.schedule.days.includes(currentDay)){
927            return console.log('Popup Not Scheduled for Today!');
928         }
929      }
930      if(popupData.schedule.type === 'dates' && popupData.schedule.dates.length > 0){
931         var thecurrentDate = new Date().getTime();
932         var dateInRange = false;
933         popupData.schedule.dates.forEach(function(date){
934            var theTimes = []; var timeTypes = ['start', 'end'];
935            timeTypes.forEach(function(val){
936               var theDate = date[val].date.split('/');
937               var theHour = date[val].time && date[val].time.hour ? date[val].time.hour : '00';
938               var theMinutes = date[val].time && date[val].time.minutes ? date[val].time.minutes : '00';
939               theTimes.push(new Date(theDate[2]+'/'+theDate[1]+'/'+theDate[0]+' '+theHour+':'+theMinutes+':00').getTime());
940            })
941            if(theTimes[0] < thecurrentDate && theTimes[1] > thecurrentDate){
942               dateInRange = true;
943            }
944         });
945         if(!dateInRange){
946            return console.log('Popup Not Scheduled these dates!');
947         }
948      }
949   }
950
951   //Do not Load if Device Settings doesnt Match
952   if(popupData.settings && popupData.settings.audience && popupData.settings.audience.devices && popupData.settings.audience.devices === "desktop" && brave_currentDevice === 'mobile'){   return console.log('Device Settings doesnt Match');  }
953   if(popupData.settings && popupData.settings.audience && popupData.settings.audience.devices && popupData.settings.audience.devices === "mobile" && brave_currentDevice === 'desktop'){   return console.log('Device Settings doesnt Match');  }
954
955
956   var popVariants = brave_popup_data[popupID] && brave_popup_data[popupID].variants ? brave_popup_data[popupID].variants : false;
957   var popupRepeatCountType = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeatCountType || 'lifetime';
958   var popupRepeatDelay = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeatDelay || false;
959   var popupRepeatDelayTime = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeatDelayTime ? parseInt(popupData.settings.frequency.repeatDelayTime, 10) : false;
960   var repeatCount = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeatCount ? parseInt(popupData.settings.frequency.repeatCount, 10) : 3;
961
962   //Do not load if Opened n Times already
963   var filterViewFreq = function(popID){
964      var popupOpenCount = localStorage.getItem('brave_popup_'+popID+'_viewed'); var popupOpenSessionCount = sessionStorage.getItem('brave_popup_'+popID+'_viewed');
965
966      if(popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeat && brave_popup_adminUser === false ){  
967         if(popupRepeatCountType === 'lifetime' && parseInt(popupOpenCount, 10) >= repeatCount){
968            return 'Already Viewed '+repeatCount+' Times. Hiding..';  
969         }
970         var popupViewStat = localStorage.getItem('brave_popup_'+popID+'_view_stat'); popupViewStat = popupViewStat ? JSON.parse(popupViewStat) : [];
971         var thecurrentDate = new Date(); var thecurrentDay = thecurrentDate.getDate();  var thecurrentHour = thecurrentDate.getHours(); var thecurrentMonth = thecurrentDate.getMonth(); var thecurrentYear = thecurrentDate.getFullYear();
972         var popupViewDayCount = 0; var popupViewMonthCount = 0; var popupView12hCount = 0; var popupView6hCount = 0; var popupView1hCount = 0; var matchedStats = [];
973         if(popupViewStat){
974            popupViewStat.forEach(function(stat){
975               var statDate = new Date(stat); var statDay = statDate.getDate(); var statHour = statDate.getHours();  var statMonth = statDate.getMonth(); var statYear = statDate.getFullYear();
976               if((statDay === thecurrentDay) && (statMonth === thecurrentMonth) && (statYear === thecurrentYear)){  popupViewDayCount = popupViewDayCount + 1;   }
977               if((statMonth === thecurrentMonth) && (statYear === thecurrentYear)){  popupViewMonthCount = popupViewMonthCount + 1;   }
978               if((thecurrentHour - statHour) < 12 && (statDay === thecurrentDay) && (statMonth === thecurrentMonth) && (statYear === thecurrentYear)){  popupView12hCount = popupView12hCount + 1;   }
979               if((thecurrentHour - statHour) < 6 && (statDay === thecurrentDay) && (statMonth === thecurrentMonth) && (statYear === thecurrentYear)){   popupView6hCount = popupView6hCount + 1;   }
980               if((thecurrentHour - statHour) < 1 && (statDay === thecurrentDay) && (statMonth === thecurrentMonth) && (statYear === thecurrentYear)){   popupView1hCount = popupView1hCount + 1;   }
981               if(!matchedStats.includes(stat)){   matchedStats.push(stat);   }
982            })
983         }
984         matchedStats = matchedStats.sort();
985         var lastViewedTime = matchedStats.length > 0 ? matchedStats[matchedStats.length - 1] : 0;
986         var viewDelayMatched = popupRepeatDelay && popupRepeatDelayTime ? (thecurrentDate.getTime() - lastViewedTime) > popupRepeatDelayTime : true;
987         var viewCountError = 'Already Viewed '+repeatCount+' Times in last '+popupRepeatCountType+' Hiding..'
988         console.log(lastViewedTime, thecurrentDate.getTime(), popupRepeatDelayTime, (thecurrentDate.getTime() - lastViewedTime) > popupRepeatDelayTime);
989         if(viewDelayMatched){
990            console.log(lastViewedTime, thecurrentDate.getTime(), popupRepeatDelayTime, (thecurrentDate.getTime() - lastViewedTime) > popupRepeatDelayTime);
991            if(popupRepeatCountType === '12h' && (parseInt(popupView12hCount, 10) >= repeatCount)){   return viewCountError;    }
992            if(popupRepeatCountType === '6h' && (parseInt(popupView6hCount, 10) >= repeatCount)){   return viewCountError;    }
993            if(popupRepeatCountType === '1h' && (parseInt(popupView1hCount, 10) >= repeatCount)){   return viewCountError;    }
994            if(popupRepeatCountType === 'session' && (parseInt(popupOpenSessionCount, 10) >= repeatCount) ){   return viewCountError;    }
995            if(popupRepeatCountType === 'day' && (parseInt(popupViewDayCount, 10) >= repeatCount)){   return viewCountError;    }
996            if(popupRepeatCountType === 'month' && (parseInt(popupViewMonthCount, 10) >= repeatCount) ){   return viewCountError;    }
997         }else{
998            return 'Repeat Delay Doesnt Match! Hiding....';
999         }
1000      }
1001
1002      return false;
1003   }
1004
1005   //Do not load if Closed n Times already
1006   var filterCloseFreq = function(popID){
1007      var popupCloseStat = localStorage.getItem('brave_popup_'+popID+'_closed') ? JSON.parse(localStorage.getItem('brave_popup_'+popID+'_closed')) : null;
1008      if(popupData.settings && popupData.settings.frequency && popupData.settings.frequency.close && popupCloseStat && popupCloseStat.closed){   
1009         var popupCloseCount = popupData.settings.frequency.closeCount ? popupData.settings.frequency.closeCount : 2; 
1010         var popupCloseFor = popupData.settings.frequency.closeFor ? parseInt(popupData.settings.frequency.closeFor, 10) * 86400 * 1000 : 86400 * 1000 * 30;
1011         var userCloseCount = parseInt(popupCloseStat.closed, 10);
1012         var userCloseDate = parseInt(popupCloseStat.closeTime, 10);
1013         var currentDate = new Date().getTime();
1014         var closeTimeDiff = currentDate - userCloseDate;
1015         var closeDelayMatched = popupRepeatDelay && popupRepeatDelayTime ? (currentDate - userCloseDate) > popupRepeatDelayTime : true;
1016         console.log('##### CLOSING STATS',userCloseCount, popupCloseFor,closeTimeDiff, closeTimeDiff >= popupCloseFor, userCloseCount >= popupCloseCount, closeDelayMatched, currentDate - userCloseDate);
1017         if((closeTimeDiff <= popupCloseFor && (userCloseCount >= popupCloseCount )) || !closeDelayMatched){
1018            return 'Close Time Settings Do not Match';
1019         }
1020      }
1021   }
1022
1023
1024   var viewFreqMatch = false; var closeFreqMatch = false; var formFreqMatch = false; goalFreqmatch = false;
1025   var hasViewFreqSetting = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeat && brave_popup_adminUser === false;
1026   var hasCloseFreqSetting = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.close && brave_popup_adminUser === false;
1027   var formFreqSetting = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.formSubmit && brave_popup_adminUser === false;
1028   var goalFreqSetting = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.goalComplete && brave_popup_adminUser === false;
1029
1030   if(popVariants.length > 0){
1031      popVariants.forEach(function(popID){
1032         if(!viewFreqMatch && hasViewFreqSetting){
1033            var popViewFreqMatch = filterViewFreq(popID);
1034            if(popViewFreqMatch){
1035               viewFreqMatch = popViewFreqMatch;
1036            }
1037         }
1038         if(!closeFreqMatch && hasCloseFreqSetting){
1039            var popCloseFreqMatch = filterCloseFreq(popID);
1040            if(popCloseFreqMatch){
1041               closeFreqMatch = popCloseFreqMatch;
1042            }
1043         }
1044         if(!formFreqMatch && formFreqSetting && localStorage.getItem('brave_popup_'+popID+'_formsubmitted')){
1045            formFreqMatch = true;
1046         }
1047         if(!goalFreqmatch && goalFreqSetting && localStorage.getItem('brave_popup_'+popID+'_goal_complete')){
1048            goalFreqmatch = true;
1049         }
1050      })
1051   }else{
1052      if(hasViewFreqSetting){
1053         viewFreqMatch = filterViewFreq(popupID);
1054      }
1055      if(hasCloseFreqSetting){
1056         closeFreqMatch = filterCloseFreq(popupID);
1057      }
1058      if(!formFreqMatch && formFreqSetting && localStorage.getItem('brave_popup_'+popupID+'_formsubmitted')){
1059         formFreqMatch = true;
1060      }
1061      if(!goalFreqmatch && goalFreqSetting && localStorage.getItem('brave_popup_'+popupID+'_goal_complete')){
1062         goalFreqmatch = true;
1063      }
1064   }
1065
1066   //Do not Load if the popup is already viewed x times.
1067   if(viewFreqMatch && hasViewFreqSetting){
1068      return console.log('[Viewed Frequency]',  popupID, viewFreqMatch);;
1069   }
1070   //Do not Load if the popup is already closed x times.
1071   if(closeFreqMatch && hasCloseFreqSetting){
1072      return console.log('[Closed Frequency]',  popupID, closeFreqMatch);;
1073   }
1074   //Do not Load if a Form Submitted in this Popup
1075   if(formFreqMatch && formFreqSetting){
1076      return console.log('[Form Frequency]',  popupID, 'Form in this Popup already Submitted! Hiding..');
1077   }
1078   //Do not Load if a Campaign Goal is completed already
1079   if(goalFreqmatch && goalFreqSetting){
1080      return console.log('[Goal Frequency]',  popupID, 'Popup Goal Already Completed..');
1081   }
1082
1083   //Do not Load if Popups Countdown Timer has ended
1084   if(popupData.settings && popupData.settings.frequency && popupData.settings.frequency.timerEnded && popupData.timers.length > 0 && popupData.timers[0].ended){
1085      return console.log('Popup Countdown Timer Ended! Hiding..');
1086   }
1087
1088   //Do not Load if a certain popup was not viewed/goaled/closed before
1089   if(popupData.settings && popupData.settings.filters && popupData.settings.filters.popups_before && popupData.settings.filters.popups.length > 0){
1090      var popupFilterFulfilled = false;
1091      popupData.settings.filters.popups.forEach(function (popup) {
1092         if(!popupFilterFulfilled && popup.id && popup.action){
1093            var popupActionNegative = popup.action.includes('not_')
1094            var popActionKey = popupActionNegative ? popup.action.replace('not_', '') : popup.action
1095            var popupActionMatched = localStorage.getItem('brave_popup_'+popup.id+'_'+popActionKey);
1096            if(!popupActionNegative && popupActionMatched){  popupFilterFulfilled = true;  }
1097            if(popupActionNegative && !popupActionMatched){  popupFilterFulfilled = true;  }
1098         }
1099      })
1100      if(!popupFilterFulfilled){
1101         return console.log('A selected Popup was not viewed before! Hiding..');
1102      }
1103   }
1104
1105   //Custom Cookie Conditions 
1106   if(popupData.settings && popupData.settings.filters && popupData.settings.filters.cookieFilter && popupData.settings.filters.cookies && popupData.settings.filters.cookies.length > 0 ){
1107      var cookieMatched = false;
1108      popupData.settings.filters.cookies.forEach(function(cookie){
1109         if(!cookieMatched && cookie.action === 'has' && cookie.key  && localStorage.getItem(cookie.key) ){   cookieMatched = true; }
1110         if(!cookieMatched && cookie.action === 'nothas' && cookie.key  && !localStorage.getItem(cookie.key) ){   cookieMatched = true; }
1111         if(!cookieMatched && cookie.action === 'equal' && cookie.key && cookie.value && localStorage.getItem(cookie.ke
1111y) === cookie.value ){   cookieMatched = true; }
1112         if(!cookieMatched && cookie.action === 'notequal' && cookie.key && cookie.value && localStorage.getItem(cookie.key) !== cookie.value ){   cookieMatched = true; }
1113      })
1114      if(cookieMatched === false){   return console.log('Visitor Cookie did not match! Hiding..'); }
1115   }
1116
1117   //Do not Load if page view count did not match
1118   if(popupData.settings && popupData.settings.filters && ((popupData.settings.filters.pages_count_filter && popupData.settings.filters.pagecount) || (popupData.settings.filters.pages_before && popupData.settings.filters.pages)) ){
1119      var viewCountLimit = parseInt(popupData.settings.filters.pagecount, 10);
1120      var current_page_view_data = localStorage.getItem('brave_page_visited'); 
1121      current_page_view_data = current_page_view_data ? JSON.parse(current_page_view_data) : [];
1122      if(popupData.settings.filters.pages_count_filter && popupData.settings.filters.pagecount && current_page_view_data && (current_page_view_data.length < viewCountLimit)){
1123         return console.log('Visitor did not view enough pages to show the popup! Hiding..');
1124      }
1125      //Do not Load if Visitor Did Not View selected pages before
1126      var pageConditionMatch = []; var viewConditionMatched = true;
1127      if(popupData.settings.filters.pages_before && popupData.settings.filters.pages && popupData.settings.filters.pages.length > 0){
1128         var pagesmatched = [];
1129         var braveMatchPageViewTime = function(timeLimit, viewTime){
1130            if(!timeLimit){ return true; }
1131            if(viewTime > timeLimit){ return true; }else{ return false; }
1132         }
1133         var braveCheckIfViewedPageMatch = function(pageCond, checkExistence=true, timeLimit) {
1134            var pageCondID = pageCond.id; var pageCondType = pageCond.type; var conditionMatched = false;
1135            current_page_view_data.forEach(function(pgView){
1136               var timeMatch = braveMatchPageViewTime(timeLimit, pgView.time);
1137               var pageMatch = pgView.PID === pageCondID && pgView.type === pageCondType && timeMatch;
1138               if(pageMatch && checkExistence){ conditionMatched = true;  }  
1139            })
1140            return conditionMatched;
1141         }
1142         var braveCheckIfNotViewedPageMatch = function(pageCond, checkExistence=false, timeLimit) {
1143            var pageCondID = pageCond.id; var pageCondType = pageCond.type; var conditionMatched = true;
1144            current_page_view_data.forEach(function(pgView){
1145               var timeMatch = braveMatchPageViewTime(timeLimit, pgView.time);
1146               var pageMatch = pgView.PID === pageCondID && pgView.type === pageCondType && timeMatch;
1147               if(pageMatch && !checkExistence){ conditionMatched = false;  }
1148            })
1149            return conditionMatched;
1150         }
1151         popupData.settings.filters.pages.forEach(function(pageCond){
1152            var currentTime = new Date().getTime(); var timeLimit  =  currentTime - 10800000;  if(pageCond.duration === 'lifetime' ){ timeLimit = false;}
1153            if(pageCond.duration === '1day' ){ timeLimit = currentTime - 86400000;} if(pageCond.duration === '7days' ){ timeLimit = currentTime - 604800000;} if(pageCond.duration === '30days' ){ timeLimit = currentTime - 2592000000;}
1154            var condMatch = pageCond.action.includes('not_viewed') ? braveCheckIfNotViewedPageMatch(pageCond, false, timeLimit) : braveCheckIfViewedPageMatch(pageCond, true, timeLimit);
1155            pagesmatched.push({matched: condMatch, forced: pageCond.condition === 'and' ? true : false });
1156         })
1157
1158         pagesmatched.forEach(function(matchItm) {
1159            if(matchItm.forced === true &&  matchItm.matched === true){ pageConditionMatch.push(true); }
1160            if(matchItm.forced === true &&  matchItm.matched === false){ pageConditionMatch.push(false); }
1161            if(matchItm.forced === false &&  (matchItm.matched === true || matchItm.matched === false )){ pageConditionMatch.push(true); }
1162         })
1163         pageConditionMatch.forEach(function(bool){ if(bool===false){ viewConditionMatched = false; } })
1164
1165         if(!viewConditionMatched){
1166            return console.log('Visitor did not view the selected pages before to show the popup! Hiding..');
1167         }
1168
1169      }
1170   }
1171
1172   if(triggerType.includes('load')){   brave_load_popup(popupID, popupData, 'load');   }
1173
1174   if(triggerType.includes('exit')){
1175      if(brave_currentDevice === 'mobile'){
1176         if(!popupData.settings.trigger.exitMobileFallback || (popupData.settings.trigger.exitMobileFallback && popupData.settings.trigger.exitMobileFallback.type && popupData.settings.trigger.exitMobileFallback.type === 'load')){
1177            brave_load_popup(popupID, popupData,'load');
1178         }
1179         if(popupData.settings.trigger.exitMobileFallback && popupData.settings.trigger.exitMobileFallback.type && popupData.settings.trigger.exitMobileFallback.type === 'time'){
1180            var exitMobileDelay = popupData.settings.trigger.exitMobileFallback.time || 2000;
1181            setTimeout(function() {    brave_load_popup(popupID, popupData , 'time');  }, (exitMobileDelay * 1000));
1182         }
1183      }else{
1184         document.addEventListener("mouseout", function(evt){
1185            if((evt.toElement === null || evt.toElement === undefined) && (evt.relatedTarget === null)) {
1186                brave_load_popup(popupID, popupData, 'exit');
1187            }
1188         });
1189      }
1190   }
1191
1192   if(triggerType.includes('scroll') || (brave_isMobile && popupData.settings.trigger.exitMobileFallback && popupData.settings.trigger.exitMobileFallback.type  && popupData.settings.trigger.exitMobileFallback.type ==='scroll')){
1193      var currentPopup = document.getElementById('brave_popup_'+popupID+'__step__0'); 
1194      var noMobileContent = currentPopup && currentPopup.classList.contains('brave_popup__step--mobile-noContent') === true ? true : false;
1195      var currentDevice = noMobileContent ? 'desktop' : brave_currentDevice;
1196      var scrollHide = popupData.settings && popupData.settings.trigger && popupData.settings.trigger.scrollHide ? true : false;
1197      var scrollTriggerPopup = function(scrollPercent, percentLimit=20, currentPopStep, currentPopStepVisible, between=false){
1198         var scrollPercentVal = between && percentLimit.split('-');
1199         var startScrollPercent = scrollPercentVal && scrollPercentVal[0] && parseInt(scrollPercentVal[0], 10);
1200         var endScrollPercent = scrollPercentVal && scrollPercentVal[1] && parseInt(scrollPercentVal[1], 10);
1201
1202         if(brave_popup_data[popupID].userClosed){ return; }
1203         if((!between && (scrollPercent >= percentLimit)) || ((between && !isNaN(startScrollPercent) && !isNaN(endScrollPercent)) && ((scrollPercent >= startScrollPercent) && (scrollPercent <= endScrollPercent)) )){  
1204            if(!brave_popup_data[popupID].loaded){   brave_load_popup(popupID, popupData, 'scroll'); }else{  if(!currentPopStepVisible){brave_open_animation(popupID, 0, currentDevice);   currentPopStep.dataset.open = true; } } 
1205         }else{ 
1206            if((between || scrollHide) && currentPopStepVisible){  brave_close_animation(popupID, 0, currentDevice); currentPopStep.dataset.open = false; brave_popup_data[popupID].isOpen = false;  } 
1207         }
1208      }
1209      document.addEventListener("scroll", function(evt){
1210         var h = document.documentElement,  b = document.body, st = 'scrollTop', sh = 'scrollHeight';
1211         var scrollPercent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
1212         var currentPopStep = document.querySelector('#brave_popup_'+popupID+'__step__0 .brave_popup__step__'+currentDevice); 
1213         var currentPopStepVisible = currentPopStep && currentPopStep.dataset.open === 'true' ? true : false;
1214
1215         if( brave_isMobile && (popupData.settings.trigger.exitMobileFallback && popupData.settings.trigger.exitMobileFallback.type && popupData.settings.trigger.exitMobileFallback.type ==='scroll')){
1216            var exitMobielScroll = popupData.settings.trigger.exitMobileFallback.scroll || 15;
1217            if(scrollPercent >= exitMobielScroll){   brave_load_popup(popupID, popupData, 'scroll');   }
1218         }
1219
1220         if(popupData.settings && popupData.settings.trigger.scrolltype && popupData.settings.trigger.scrolltype !== 'between'){
1221            var srollTargetAmnt = 0;
1222            if(popupData.settings.trigger.scrolltype === 'ten') {  srollTargetAmnt = 10}
1223            if(popupData.settings.trigger.scrolltype === 'twenty') {  srollTargetAmnt = 20}
1224            if(popupData.settings.trigger.scrolltype === 'thirty') {  srollTargetAmnt = 30}
1225            if(popupData.settings.trigger.scrolltype === 'forty') {  srollTargetAmnt = 40}
1226            if(popupData.settings.trigger.scrolltype === 'half') {  srollTargetAmnt = 50}
1227            if(popupData.settings.trigger.scrolltype === 'sixty') {  srollTargetAmnt = 60}
1228            if(popupData.settings.trigger.scrolltype === 'seventy') {  srollTargetAmnt = 70}
1229            if(popupData.settings.trigger.scrolltype === 'eighty') {  srollTargetAmnt = 80}
1230            if(popupData.settings.trigger.scrolltype === 'end') {  srollTargetAmnt = 95}
1231            scrollTriggerPopup(scrollPercent, srollTargetAmnt, currentPopStep, currentPopStepVisible);
1232         }
1233         if(popupData.settings && popupData.settings.trigger && popupData.settings.trigger.scrolltype === 'between' && popupData.settings.trigger.scrollBetween && popupData.settings.trigger.scrollBetween.includes('-')){
1234            scrollTriggerPopup(scrollPercent, popupData.settings.trigger.scrollBetween, currentPopStep, currentPopStepVisible, true);
1235         }
1236
1237         if(popupData.settings && popupData.settings.trigger.scrolltype && popupData.settings.trigger.scrollto && popupData.settings.trigger.scrolltype === 'custom' ){
1238            var scrollToIDs = popupData.settings.trigger.scrollto || ''; 
1239            var scrolltoElms = scrollToIDs && document.querySelectorAll(scrollToIDs);
1240            //console.log(scrolltoElms);
1241            if(scrollToIDs && scrolltoElms){
1242               for (var i = 0; i < scrolltoElms.length; i++) { 
1243                  var scrolltoElm = scrolltoElms[i]; 
1244                  if(scrolltoElm && brave_is_in_view(scrolltoElm)){
1245                     brave_load_popup(popupID, popupData, 'scroll');  
1246                  }
1247               }
1248            }
1249         }
1250      }, {passive: true});
1251   }
1252
1253   if(popupData.settings && popupData.settings.content && popupData.settings.content.highlight){
1254      document.addEventListener("scroll", function(evt){
1255         var contentElm = document.querySelector('.bravepopup_embedded--highlight_'+popupID);
1256         var contenthlElm = document.getElementById('bravepopup_embedded__bg_'+popupID);
1257         var contentAlreadyHighlighted = false; 
1258         if(popupData.settings.content.highlight === 'once'){ contentAlreadyHighlighted = contentElm.classList.contains('bravepopup_embedded__highlight--done') ? true : false;}
1259         if(contentElm && (popupData.settings.content.highlight === 'always' || (!contentAlreadyHighlighted && popupData.settings.content.highlight === 'once'))){
1260            var embeddedContentRect = contentElm.getBoundingClientRect();
1261            var embeddedViewRatio = (embeddedContentRect.top / document.documentElement.clientHeight)*100;
1262            if((embeddedViewRatio < 50 && embeddedViewRatio > -20 ) && !contenthlElm.classList.contains('bravepopup_embedded__bg--active')){
1263               contenthlElm.classList.add('bravepopup_embedded__bg--active'); contentElm.classList.add('bravepopup_embedded__highlight--active');
1264            }
1265            if((embeddedViewRatio < -20 || embeddedViewRatio > 50) && contenthlElm.classList.contains('bravepopup_embedded__bg--active')){
1266               contenthlElm.classList.remove('bravepopup_embedded__bg--active'); contentElm.classList.remove('bravepopup_embedded__highlight--active');
1267               if(popupData.settings.content.highlight){   contentElm.classList.add('bravepopup_embedded__highlight--done');  }
1268            }
1269         }
1270      }, {passive: true});
1271   }
1272
1273
1274   if(triggerType.includes('click') && popupData.settings && popupData.settings.trigger.clickElements){
1275      var clickElms = document.querySelectorAll(popupData.settings.trigger.clickElements);
1276      //console.log(clickElms);
1277      
1278      if(clickElms){
1279         for (var i = 0; i < clickElms.length; i++) { 
1280            var clickElm = clickElms[i]; 
1281            clickElm.addEventListener("click", function(evt){
1282               evt.preventDefault();
1283               document.getElementById('brave_popup_'+popupID).style.zIndex = 9999999999;
1284               brave_load_popup(popupID, popupData, 'click');
1285            });
1286         }
1287      }
1288   }
1289
1290   if(triggerType.includes('time') && popupData.settings && popupData.settings.trigger.time && (popupData.settings.trigger.time.hours || popupData.settings.trigger.time.minutes || popupData.settings.trigger.time.seconds)){
1291      var triggerHours = popupData.settings.trigger.time.hours ? parseInt(popupData.settings.trigger.time.hours, 10) : 0;
1292      var triggerMinutes = popupData.settings.trigger.time.minutes ? parseInt(popupData.settings.trigger.time.minutes, 10) : 0;
1293      var triggerSeconds = popupData.settings.trigger.time.seconds ? parseInt(popupData.settings.trigger.time.seconds, 10) : 0;
1294
1295      var totalTriggerDelay = (triggerHours * 3600) + (triggerMinutes * 60) + (triggerSeconds);
1296      totalTriggerDelay = totalTriggerDelay * 1000;
1297      //console.log(triggerHours, triggerMinutes, triggerSeconds, totalTriggerDelay);
1298      
1299      setTimeout(function() {
1300          brave_load_popup(popupID, popupData , 'time');
1301      }, totalTriggerDelay);
1302
1303   }
1304
1305
1306   
1307}
1308
1309function brave_load_popup(popupID, popupData, triggerType='load'){
1310   if(brave_popup_data[popupID] && brave_popup_data[popupID].ajaxLoad && !brave_popup_data[popupID].ajaxLoaded){
1311      var loadData = { popupID: popupID, type: brave_popup_data[popupID].type, security: bravepop_global.security, current_url: location.href ,action: 'bravepop_ajax_load_popup_content' };
1312      brave_ajax_send(bravepop_global.ajaxURL, loadData, function(status, sentData){
1313         // console.warn('Load Popup!!', popupID);
1314         brave_popup_data[popupID].ajaxLoaded = true;
1315         var selectedPopup = document.getElementById('brave_popup_'+popupID);
1316         if(selectedPopup){
1317            selectedPopup.innerHTML = sentData;
1318            brave_process_open_popup(popupID, popupData, triggerType);
1319         }
1320      });
1321   }else{
1322      brave_process_open_popup(popupID, popupData, triggerType);
1323   }
1324}
1325
1326
1327function brave_process_open_popup(popupID, popupData, triggerType='load'){
1328   var selectedPopup = document.getElementById('brave_popup_'+popupID);
1329   var popupLoadStatus = selectedPopup ? selectedPopup.dataset.loaded : 'fal
1329se';
1330   if(popupLoadStatus === 'false'){
1331      //LOAD ASSETS
1332      //--------------------
1333         //Load Video Scripts
1334         if(popupData.hasYoutube){
1335            var YTtag = document.createElement('script'); YTtag.src = "https://www.youtube.com/iframe_api";
1336            var PageFirstScript_YT = document.getElementsByTagName('script')[0]; PageFirstScript_YT.parentNode.insertBefore(YTtag, PageFirstScript_YT);
1337         }
1338         if(popupData.hasVimeo){
1339            var VimTag = document.createElement('script'); VimTag.src = "https://player.vimeo.com/api/player.js";
1340            var PageFirstScript_Vim = document.getElementsByTagName('script')[0]; PageFirstScript_Vim.parentNode.insertBefore(VimTag, PageFirstScript_Vim);
1341         }
1342         
1343         //Load the DatePicker
1344         var dateFields = document.querySelectorAll('.brave_form_field--date');
1345         if(window.brave_initPikaday && dateFields && dateFields.length > 0 ){
1346            for (var i = 0, len = dateFields.length; i < len; i++) {
1347               var dateField = dateFields[i];
1348               var startDate = dateField.dataset.startdate ? dateField.dataset.startdate : '';
1349               var endDate = dateField.dataset.enddate ? dateField.dataset.enddate : '';
1350               var dateInput = dateField.querySelector('input');
1351               brave_initPikaday(dateInput, startDate, endDate);
1352            }
1353         }
1354
1355         selectedPopup.dataset.loaded = true;
1356   }
1357
1358   //Open Popup
1359   //---------------------
1360   let step = popupData.forceLoad && popupData.forceStep? parseInt(popupData.forceStep, 10) - 1 : 0;
1361   if(brave_popup_data[popupID].settings && brave_popup_data[popupID].settings.frequency && brave_popup_data[popupID].settings.frequency.rememberLastStep){
1362      let foundLastStep = localStorage.getItem('brave_popup_'+popupID+'_last_viewed_step');
1363      if(foundLastStep !==undefined && foundLastStep !==null){
1364         step = foundLastStep;
1365      }
1366   }
1367   if(triggerType === 'exit' || triggerType === 'scroll' || triggerType === 'time'){
1368      var triggerFulFilled = document.getElementById('brave_popup_'+popupID).dataset.triggerfulfilled;
1369      if(!triggerFulFilled){
1370         document.getElementById('brave_popup_'+popupID).dataset.triggerfulfilled = true;
1371         brave_open_popup(popupID, step);
1372      }
1373   }else{
1374      brave_open_popup(popupID, step);
1375   }
1376
1377   if(brave_popup_data[popupID] && !brave_popup_data[popupID].loaded){  brave_popup_data[popupID].loaded = true; }
1378}
1379
1380
1381function brave_open_popup(popupID, step=0){
1382   var popupData = brave_popup_data[popupID];
1383   var selectedPopupStep = document.querySelector('#brave_popup_'+popupID+'__step__'+step+' .brave_popup__step__'+brave_currentDevice)
1384   var noMobileContent = selectedPopupStep && selectedPopupStep.dataset.nomobilecontent === 'true' ? true : false;
1385   var currentDevice = noMobileContent ? 'desktop' : brave_currentDevice;
1386   var selectedPopupStep = document.querySelector('#brave_popup_'+popupID+'__step__'+step+' .brave_popup__step__'+currentDevice);
1387   var popupStepOpen = selectedPopupStep ? selectedPopupStep.dataset.open : 'false';
1388   var hasLockScroll = selectedPopupStep.dataset.scrollock ?  true : false;
1389   var stickyBar = selectedPopupStep && selectedPopupStep.dataset.layout === 'float' && selectedPopupStep.dataset.position === 'top_center' ? true : false;
1390   
1391   if(popupStepOpen !== 'false'){ return }
1392   if(!popupData){ return }
1393   if(popupData && popupData.forceHide){ return console.log(popupID, 'Force Hidden'); }
1394
1395   console.log('Opening ', popupID, step, popupStepOpen, stickyBar, noMobileContent, currentDevice);
1396   //Set Current Step
1397   brave_popup_data[popupID].currentStep = step;
1398
1399   //Send Ajax View Stat Data
1400   if(window.location.href.includes('brave_popup') === false && window.location.href.includes('braveshot') === false && !brave_popup_data[popupID].viewStatSent){ 
1401      var viewDate = new Date(); var viewYear = viewDate.getFullYear(); var viewMonth = brave_number_padding(viewDate.getMonth() + 1);  var viewDate = brave_number_padding(viewDate.getDate()); var goalIsFirstView = false;
1402      if(brave_popup_data[popupID] && brave_popup_data[popupID].settings && brave_popup_data[popupID].settings.goalAction && 
1403      brave_popup_data[popupID].settings.goalAction.type === 'step' && brave_popup_data[popupID].settings.goalAction.step === 0 ){  goalIsFirstView = true;  } 
1404      var viewData = { popupID: popupID, date: viewYear+'-'+viewMonth+'-'+viewDate, goalIsFirstView: goalIsFirstView, pageURL: window.location, goalUTCTime: new Date().toUTCString(), security: bravepop_global.security, action: 'bravepop_ajax_popup_viewed' };
1405      brave_ajax_send(bravepop_global.ajaxURL, viewData, function(status, sentData){
1406         // console.log('Popup View Updated: ', status, JSON.parse(sentData));
1407         brave_popup_data[popupID].viewStatSent = true;
1408      });
1409   }
1410   //Set Popup Viewed Cookie
1411   var currentPopupStat = localStorage.getItem('brave_popup_'+popupID+'_viewed');
1412   localStorage.setItem('brave_popup_'+popupID+'_viewed', currentPopupStat ? parseInt(currentPopupStat, 10) + 1 : 1);
1413   var popupRepeat =popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeat
1414   var popupRepeatCountType = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeatCountType || 'lifetime';
1415   if(popupRepeat && popupRepeatCountType !== 'lifetime'){
1416      var theViewStat = localStorage.getItem('brave_popup_'+popupID+'_view_stat'); theViewStat = theViewStat ? JSON.parse(theViewStat) : [];
1417      theViewStat.push(new Date().getTime());      
1418      localStorage.setItem('brave_popup_'+popupID+'_view_stat', JSON.stringify(theViewStat));
1419   }
1420
1421   if(popupRepeat && popupRepeatCountType === 'session'){
1422      var currentSessionPopupViews = sessionStorage.getItem('brave_popup_'+popupID+'_viewed') || 0;
1423      sessionStorage.setItem('brave_popup_'+popupID+'_viewed', parseInt(currentSessionPopupViews, 10)+1);
1424   }
1425
1426   //Scroll Lock
1427   if(hasLockScroll){
1428      document.body.classList.add('brave_scroll_lock')
1429   }
1430
1431   //Stickybar - Add html top margin
1432   if(stickyBar){
1433      //console.log('Apply Sticky Margin');
1434      var popupHeight = selectedPopupStep.dataset.height;
1435      document.documentElement.style.setProperty('margin-top', popupHeight+'px', 'important');
1436   } 
1437
1438   //LazyLoad Images
1439   if(popupData.type !== 'content'){
1440      var allImages = selectedPopupStep.querySelectorAll('img');
1441      for (var i = 0; i < allImages.length; i++) { 
1442         if(allImages[i].dataset.lazy){
1443            allImages[i].src = allImages[i].dataset.lazy;
1444         }
1445      }
1446   }
1447
1448   //Stop currently Playing Videos First
1449   if(brave_popup_videos && brave_popup_videos[popupID] && Object.keys(brave_popup_videos).length > 0){
1450      Object.keys(brave_popup_videos[popupID]).forEach(function(playerID){
1451         if(playerID.includes('youtube') && brave_popup_videos[popupID][playerID] && brave_popup_videos[popupID][playerID].stopVideo){   brave_popup_videos[popupID][playerID].stopVideo();  }
1452         if(playerID.includes('vimeo') && brave_popup_videos[popupID][playerID] && brave_popup_videos[popupID][playerID].pause){   brave_popup_videos[popupID][playerID].pause();  }
1453         if(playerID.includes('custom') && brave_popup_videos[popupID][playerID] && brave_popup_videos[popupID][playerID].pause){   brave_popup_videos[popupID][playerID].pause();  }
1454      });
1455   }
1456   if(popupData.videoData && popupData.videoData[step] && popupData.videoData[step][currentDevice]){
1457      //console.log('HAS VIDEO!!!!!!!!!!!', popupData.videoData[step][currentDevice]);
1458      var videoObj = popupData.videoData[step][currentDevice];
1459      var videoType = videoObj.videoType ? videoObj.videoType : 'youtube';
1460      var videoURL = videoObj.videoUrl ? videoObj.videoUrl : 'youtube';
1461      var videoTracking = videoObj.action && videoObj.action.track && videoObj.action.trackData ? videoObj.action.trackData : null;
1462      var videoSettings = {id: videoObj.id, autoplay: videoObj.autoplay || false, controls: videoObj.controls || false, mute: videoObj.mute || false, tracking: videoTracking }
1463      brave_load_video(videoType, videoURL, videoSettings, popupID);
1464   }
1465
1466   //Replace Text element Shortcodes
1467   var elmsWithCookie = selectedPopupStep && selectedPopupStep.querySelectorAll('.brave_element--text_hasCookie .brave_element__text_inner');
1468   if(elmsWithCookie && elmsWithCookie.length > 0){
1469      brave_replace_dynamic_text_cookie(elmsWithCookie);
1470   }
1471
1472   var hasAnimation = popupData.hasAnimation ?  popupData.hasAnimation : false;
1473   var advancedAnimation = popupData.advancedAnimation ?  popupData.advancedAnimation : false;
1474   var hasContAnim = popupData.hasContAnim ?  popupData.hasContAnim : false;
1475   var animationData = popupData.animationData ?  popupData.animationData : {};
1476   var selectedStep = document.getElementById('brave_popup_'+popupID+'__step__'+step);
1477   if(!selectedStep){ return;}
1478
1479   var focusableElm = selectedStep.querySelector('.brave_popup--popup .brave_popupMargin__wrap');
1480   var closableFocus = selectedStep.querySelector('.brave_popup--popup .brave_popup__close');  
1481   if(closableFocus){   closableFocus.tabIndex = 0;  }
1482   if(focusableElm){ focusableElm.tabIndex = 0; setTimeout(() => {   focusableElm.focus();   }, 200);  }
1483   
1484   if(selectedStep){
1485      var allSteps = document.querySelectorAll('#brave_popup_'+popupID+' .brave_popup__step_wrap');
1486      if(allSteps){
1487         for (var i = 0; i < allSteps.length; i++) { 
1488            allSteps[i].classList.remove('brave_popup__step_wrap--show');
1489         }
1490      }
1491      var braveOpenEvent = new CustomEvent('brave_popup_open', { detail: {popupId: parseInt(popupID, 10), step: step} });
1492      document.dispatchEvent(braveOpenEvent);
1493
1494      //Open Animation
1495      if(!advancedAnimation){
1496         brave_open_animation(popupID, step, currentDevice);
1497      }
1498
1499      //Advanced Animation
1500      if(advancedAnimation && hasAnimation && animationData && brave_animate_popup){
1501         selectedStep.classList.add('brave_popup__step_wrap--show');
1502         brave_animate_popup(animationData, popupID, step, 'load');
1503      }
1504      //Continious Animation
1505      if(hasContAnim && animationData && animationData[step][currentDevice] && animationData[step][currentDevice].elements){
1506         var initialDelay = (animationData[step][currentDevice].totalDuration || 0) + 1200;
1507         animationData[step][currentDevice].elements.forEach(function(element){
1508            //console.log(element);
1509            
1510            if(element && element.animation && element.animation.continious){
1511               //console.log(element.id,element.animation.continious);
1512               var theElement = element.id === 'popup' ? document.querySelector('#brave_popup_'+popupID+'__step__'+step+' .brave_popup__step__inner .brave_popupSections__wrap') : document.getElementById('brave_element-'+element.i
1512d);
1513               var elementID = element.id === 'popup' ? popupID : element.id;
1514               var contAnimType = element.animation.continious.preset || 'none';
1515               var contAnimDuration = element.animation.continious.duration || 500;
1516               var contAnimDelay = element.animation.continious.delay || 0;
1517               if(theElement){
1518                  setTimeout(function() {
1519                     theElement.classList.add('brave_element-'+elementID+'_contAnim'); 
1520                     if(contAnimDelay > 0){
1521                        setInterval(function() {
1522                           theElement.classList.add('brave_element-'+elementID+'_contAnim'); 
1523                           setTimeout(function() {
1524                              theElement.classList.remove('brave_element-'+elementID+'_contAnim');
1525                           }, contAnimDuration);
1526                        }, ((contAnimDelay > contAnimDuration) ? contAnimDelay : contAnimDuration + contAnimDelay))
1527                     }
1528                  }, initialDelay);
1529               }
1530            }
1531
1532         })
1533
1534      }
1535
1536   }
1537   //Show Vertical Scrollbar if Necessary
1538   setTimeout(function() {
1539      var currentPopupDimension = selectedPopupStep.querySelector('.brave_popup__step__inner').getBoundingClientRect();
1540      if((window.innerHeight < currentPopupDimension.height) && selectedPopupStep.classList.contains('brave_popup__step--boxed') && selectedPopupStep.classList.contains('position_center')){
1541         selectedPopupStep.classList.add('brave_popup_exceeds_windowHeight');
1542         selectedPopupStep.classList.add('brave_popup_show_scrollbar');
1543         //document.body.classList.add('brave_HideBodyScroll-'+popupID);
1544      }
1545   }, 100);
1546
1547
1548   //Popup AutoClose
1549   //console.warn(popupData);
1550   if(popupData.close[0] && popupData.close[0][currentDevice] && popupData.close[0][currentDevice].autoClose && popupData.close[0][currentDevice].autoCloseDuration){
1551      setTimeout(function() {
1552         if(!brave_popup_data[popupID].autoClosed){
1553            brave_close_popup(popupID, step);
1554            if(popupData.close[0][currentDevice].closeStep !== 'undefined' && Number.isInteger(popupData.close[0][currentDevice].closeStep)){
1555               brave_open_popup(popupID, popupData.close[0][currentDevice].closeStep);
1556            }
1557         }
1558         brave_popup_data[popupID].autoClosed = true;
1559      }, parseInt(popupData.close[0][currentDevice].autoCloseDuration) * 1000);
1560   }
1561
1562   //Change the Popup Step open status
1563   selectedPopupStep.dataset.open = true;
1564   brave_popup_data[popupID].opened = new Date().getTime();
1565   brave_popup_data[popupID].isOpen = true;
1566
1567   //Complete Step Open Goal
1568   if((popupData.settings && !popupData.settings.goalAction) || (popupData.settings && popupData.settings.goalAction && popupData.settings.goalAction.type  && popupData.settings.goalAction.type==='step' && popupData.settings.goalAction.step !== undefined )){
1569      var goalStep = popupData.settings.goalAction && popupData.settings.goalAction.step ? popupData.settings.goalAction.step.toString().split(',') :['0'];
1570      if(goalStep.includes(step.toString()) && step !== 0){
1571         brave_complete_goal(popupID, 'view');
1572      }
1573   }
1574
1575   //If Code element is set to goal, attach submit event listener to complete goal
1576   var allCodeElmGoals = document.querySelectorAll('.brave_element__code--goaled form');
1577   if(allCodeElmGoals.length > 0){
1578      for (var i = 0; i < allCodeElmGoals.length; ++i) {
1579         allCodeElmGoals[i].addEventListener('submit', function () {    brave_complete_goal(popupID, 'form');    })
1580       }
1581   }
1582   if(brave_popup_data[popupID].settings && brave_popup_data[popupID].settings.frequency && brave_popup_data[popupID].settings.frequency.rememberLastStep){
1583      localStorage.setItem('brave_popup_'+popupID+'_last_viewed_step', step);
1584   }
1585
1586}
1587
1588function brave_open_animation(popupID, step, currentDevice){
1589   var totalDuration = brave_popup_data[popupID].animationData[step][currentDevice].totalDuration;
1590   var openAnimData = brave_popup_data[popupID].animationData[step][currentDevice].elements ? brave_popup_data[popupID].animationData[step][currentDevice].elements : [];
1591   var hasAnimation = brave_popup_data[popupID].hasAnimation;
1592   var selectedStep = document.querySelector('#brave_popup_'+popupID+'__step__'+step);
1593
1594   if(window.location.href.includes('braveshot') === true && window.location.href.includes('brave_id') === true){
1595      return selectedStep.classList.add('brave_popup__step_wrap--show');
1596   }
1597
1598   //console.log(popupID, step, currentDevice, openAnimData, selectedStep);
1599
1600   var brave_animateElement = function(elementID, selectedStep, elementDom, step, animType) {
1601      selectedStep.classList.add('brave_popup__step_wrap--show');
1602      if(animType === 'text'){
1603         var selected_text_element =  document.querySelector('#brave_element-'+elementID+' .brave_element__text_inner');
1604         var selected_text_element_HTML = selected_text_element.innerHTML;
1605         var selected_text_element_content = selected_text_element.textContent;
1606         var newHTLArray = selected_text_element_content.toString().split('');
1607         var selected_text_element_clone = selected_text_element; 
1608         
1609         selected_text_element_clone.innerHTML ='';
1610         for (var i=0;i<=(newHTLArray.length - 1);i++) {
1611            (function(ind) {
1612               setTimeout(function(){
1613                  selected_text_element_clone.innerHTML = selected_text_element_clone.innerHTML+newHTLArray[ind];
1614               }, 1000 + (50 * ind));
1615            })(i);
1616         }
1617         setTimeout(function(){
1618            selected_text_element_clone.innerHTML = selected_text_element_HTML;
1619         }, 1000 + (50 * (newHTLArray.length -1)));
1620      }else{
1621         //console.log(elementID, selectedStep, elementDom, step, animType);
1622         if(!elementDom.classList.contains('brave_element-'+elementID+'_'+step+'_openAnim')){ elementDom.classList.add('brave_element-'+elementID+'_'+step+'_openAnim'); }
1623      }
1624   }
1625
1626   if(hasAnimation && openAnimData.length > 0){
1627      selectedStep.classList.add('brave_popup__step_wrap--show');
1628      openAnimData.forEach( function(element){
1629         if(element.animation && element.animation.load && element.animation.load.preset){
1630            var animType = element.animation.load.preset;
1631            var animDuration = element.animation.load.duration;
1632            var animDelay = element.animation.load.delay || 0;
1633            var elementID = element.id === 'popup' ? popupID : element.id;
1634            var elementDom = element.id === 'popup' ? selectedStep.querySelector('.brave_popup__step__'+currentDevice+' .brave_popupSections__wrap') : selectedStep.querySelector('.brave_popup__step__'+currentDevice+' #brave_element-'+element.id);
1635            elementDom.style.opacity = 0;
1636            selectedStep.classList.remove('brave_popup__step_wrap--show');
1637            if(animDelay){
1638               // setTimeout(function(){    brave_animateElement(elementID, selectedStep, elementDom, step, animType);  }, animDelay);
1639               brave_animateElement(elementID, selectedStep, elementDom, step, animType);
1640            }else{
1641               brave_animateElement(elementID, selectedStep, elementDom, step, animType);
1642            }
1643            if(element.id === 'popup'){  animDelay = 0; } //Disable Popup Animation Delay
1644            setTimeout(function() { elementDom.style.opacity = ''; }, animDelay+ animDuration - 100);
1645            setTimeout(function(){
1646               elementDom.classList.remove('brave_element-'+elementID+'_'+step+'_openAnim');
1647            }, animDelay+ animDuration + 500);
1648         }
1649      })
1650
1651   }else{
1652      selectedStep.classList.add('brave_popup__step_wrap--show');
1653   }
1654
1655}
1656
1657function brave_close_animation(popupID, step, currentDevice){
1658   //Close Animation
1659   var selectedStep = document.getElementById('brave_popup_'+popupID+'__step__'+step);
1660   var selectedStepDevice = selectedStep.querySelector('.brave_popup__step__'+currentDevice);
1661   var exitAnimation = selectedStepDevice.dataset.exitanimtype || '';
1662   var exitAnimationDuration = selectedStepDevice.dataset.exitanimlength ? parseFloat(selectedStepDevice.dataset.exitanimlength, 10) : 0.5;
1663   var hasAnimation = brave_popup_data[popupID].hasAnimation ?  brave_popup_data[popupID].hasAnimation : false;
1664   var advancedAnimation = brave_popup_data[popupID].advancedAnimation ?  brave_popup_data[popupID].advancedAnimation : false;
1665   var animationData = brave_popup_data[popupID].animationData ?  brave_popup_data[popupID].animationData : {};
1666   var hasCustomExitAnimation = animationData[step][currentDevice].totalDuration['exit'];
1667   //console.warn(currentDevice, exitAnimation, exitAnimationDuration, hasAnimation, selectedStepDevice);
1668
1669   if(selectedStep){
1670      if(exitAnimation){
1671         selectedStepDevice.querySelector('.brave_popupSections__wrap').classList.add('brave_element-'+popupID+'_'+step+'_exitAnim');
1672         setTimeout(function() { selectedStep.classList.remove('brave_popup__step_wrap--show');}, (exitAnimationDuration * 1000));
1673         setTimeout(function() { selectedStepDevice.querySelector('.brave_popupSections__wrap').classList.remove('brave_element-'+popupID+'_'+step+'_exitAnim'); }, (exitAnimationDuration * 1000)+500);
1674         if(selectedStep.querySelector('.brave_popup__step__'+currentDevice+' .brave_popup__step__overlay')){
1675            setTimeout(function() { 
1676               selectedStepDevice.querySelector('.brave_popup__step__overlay').classList.add('brave_popup__step__overlay--hide');
1677            }, (exitAnimationDuration > 0.3 ? ((exitAnimationDuration * 1000) - 200) : 200));
1678            setTimeout(function() { selectedStepDevice.querySelector('.brave_popup__step__overlay').classList.remove('brave_popup__step__overlay--hide'); }, (exitAnimationDuration * 1000)+500);
1679         }
1680      }else if(advancedAnimation && hasCustomExitAnimation){
1681         if(advancedAnimation && hasAnimation && animationData && brave_animate_popup){
1682            brave_animate_popup(animationData, popupID, step, 'exit');
1683         }
1684      }else{
1685         selectedStep.classList.add('brave_popup__step_wrap--hide');
1686         setTimeout(function() { selectedStep.classList.remove('brave_popup__step_wrap--show');}, 500);
1687         setTimeout(function() { selectedStep.classList.remove('brave_popup__step_wrap--hide');}, 800);
1688      }
1689   }
1690         
1691}
1692
1693function brave_close_popup(popupID, step=0, gotoStep=false, updateStat=true){
1694   var selectedStep = document.getElementById('brave_popup_'+popupID+'__step__'+step);
1695   var selectedPopupStep = selectedStep.querySelector('.brave_popup__step__'+brave_currentDevice);
1696   var noMobileContent = selectedPopupStep.dataset.nomobilecontent === 'true' ? true : false;
1697   var currentDevice = noMobileContent ? 'desktop' : brave_currentDevice;
1698   var hasLockScroll = selectedStep.querySelector('.brave_popup__step__'+currentDevice) && selectedStep.querySelector('.brave_popup__step__'+currentDevice).dataset.scrollock ?  true : false;
1699   var exitAnimation = selectedStep.querySelector('.brave_popup__step__'+currentDevice).dataset.exitanimtype || '';
1700   var exitAnimationDuration = selectedStep.dataset.exitanimlength ? parseFloat(selectedStep.dataset.exitanimlength, 10) : 0.5;
1701
1702   //Scroll Lock
1703   if(hasLockScroll){
1704      document.body.classList.remove('brave_scroll_lock')
1705   }
1706
1707   if(selectedStep){
1708
1709      if(updateStat){
1710         var currentPopupCloseStat = localStorage.getItem('brave_popup_'+popupID+'_closed') ? JSON.parse(localStorage.getItem('brave_popup_'+popupID+'_closed')) : {};
1711         var newCloseStat = {closed: currentPopupCloseStat.closed ? currentPopupCloseStat.closed + 1 : 1, closeTime: new Date().getTime()}
1712         localStorage.setItem('brave_popup_'+popupID+'_closed', JSON.stringify(newCloseStat));
1713      }
1714      
1715      //Set the Popup Open status to False 
1716      var selectedPopupStep = selectedStep.querySelector('.brave_popup__step__'+currentDevice);
1717      selectedPopupStep.dataset.open = 'false';
1718
1719      //Stop All Videos
1720      if(brave_popup_videos && Object.keys(brave_popup_videos).length > 0){
1721         Object.keys(brave_popup_videos).forEach(function(popupID){
1722            Object.keys(brave_popup_videos[popupID]).forEach(function(playerID){
1723               if(brave_popup_videos[popupID][playerID]){
1724                  if(playerID.includes('youtube') && brave_popup_videos[popupID][playerID] && brave_popup_videos[popupID][playerID].stopVideo){   brave_popup_videos[popupID][playerID].stopVideo();  }
1725                  if(playerID.includes('vimeo') && brave_popup_videos[popupID][playerID] && brave_popup_videos[popupID][playerID].pause){   brave_popup_videos[popupID][playerID].pause();  }
1726                  if(playerID.includes('custom') && brave_popup_videos[popupID][playerID] && brave_popup_videos[popupID][playerID].pause){   brave_popup_videos[popupID][playerID].pause();  }
1727               }
1728            });
1729         });
1730      }
1731
1732      brave_popup_data[popupID].userClosed = true;
1733      brave_popup_data[popupID].isOpen = false;
1734      var braveCloseEvent = new CustomEvent('brave_popup_close', { detail: {popupId: parseInt(popupID, 10), step: step} });
1735      document.dispatchEvent(braveCloseEvent);
1736
1737      //Play Exit Animation
1738      brave_close_animation(popupID, step, currentDevice);
1739
1740      //If has gotoStep Command, go there
1741      setTimeout(function() {
1742         if(gotoStep !== false && gotoStep >=0){
1743            //First set the Taget Step's Open status to false
1744            var targetStep = document.getElementById('brave_popup_'+popupID+'__step__'+gotoStep);
1745            targetStep.querySelector('.brave_popup__step__desktop').dataset.open = false;
1746            targetStep.querySelector('.brave_popup__step__mobile').dataset.open = false;
1747            
1748            //Then Open the Popup
1749            brave_open_popup(popupID, gotoStep);
1750         }
1751         var stickyBar = selectedPopupStep.dataset.layout === 'float' && selectedPopupStep.dataset.position === 'top_center' ? true : false;
1752         if(stickyBar){
1753            var newHeight = document.querySelector('body.admin-bar') ? '32px' : '0px';
1754            document.documentElement.style.setProperty('margin-top', newHeight, 'important');
1755         }
1756
1757         //Reset the zIndex that was set for click triggered Popups
1758         document.getElementById('brave_popup_'+popupID).style.zIndex = 9999999999;
1759         
1760      }, ( exitAnimation && exitAnimationDuration ? (exitAnimationDuration * 1000) : 10));
1761   }
1762
1763}
1764
1765function brave_send_ga_event(eventCategory, eventAction, eventLabel){
1766   //console.log('ga Event: ', eventCategory, eventAction, eventLabel);
1767   if ("ga" in window && eventCategory && eventAction) {
1768      var tracker = ga.getAll()[0];
1769      if (tracker){
1770         tracker.send('event', eventCategory, eventAction, eventLabel);
1771      }
1772   }
1773}
1774function brave_send_fbq_event(eventType, fbq_content_name, fbq_content_category, fbq_value, fbq_currency){
1775   //console.log('fbq Event: ', eventType, fbq_content_name, fbq_content_category, fbq_value, fbq_currency);
1776   if (window.fbq && eventType) {
1777      var fbqData = {};
1778      if(fbq_content_name){ fbqData.content_name = fbq_content_name }
1779      if(fbq_content_category){ fbqData.content_category = fbq_content_category }
1780      if(fbq_value){ fbqData.value = parseFloat(fbq_value, 10) }
1781      if(fbq_currency){ fbqData.currency = fbq_currency }
1782
1783      if(eventType === 'Contact'){
1784         fbq('track', 'Contact');
1785      }
1786      if(eventType === 'Lead'){
1787         fbq('track', 'Lead', fbqData);
1788         console.log(fbqData);
1789      }
1790  }
1791}
1792
1793
1794
1795function brave_load_video(videoType, videoURL, videoSettings, popupID){
1796   //console.log(videoType, videoURL, videoSettings, videoSettings.tracking);
1797
1798   var elmID = videoSettings.id.replace(/[^a-zA-Z0-9]+/g, '');
1799   if(!brave_popup_videos[popupID]){
1800      brave_popup_videos[popupID] = {}
1801   }
1802   if(videoType ==='custom'){
1803      brave_popup_videos[popupID]['video_'+videoType+elmID] = document.getElementById('brave_video_custom_'+videoSettings.id);
1804      if(videoSettings.autoplay){
1805         brave_play_video(popupID, videoSettings.id, 'custom', videoSettings.tracking);
1806      }
1807   }
1808
1809   if(videoType ==='youtube'){
1810      var youtube_regex = new RegExp(/^.*(youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\\&vi?=)([^#\\&\\?]*).*/);
1811      var parsed = videoURL.match(youtube_regex);
1812      var videoID = parsed && parsed[2] ? parsed[2]:null;
1813   
1814      if(!brave_popup_videos[popupID]['video_'+videoType+elmID]){
1815         setTimeout(function() {
1816            brave_popup_videos[popupID]['video_'+videoType+elmID] = new YT.Player('brave_video_iframe'+elmID, {
1817               videoId: videoID,
1818               playerVars: { 'autoplay': false, 'controls': videoSettings.controls ? 1 : 0, mute: videoSettings.mute ? videoSettings.mute : false  },
1819               events: {
1820                  'onReady': function(){
1821                     return videoSettings.autoplay && brave_play_video(popupID, videoSettings.id, 'youtube', videoSettings.tracking)
1822                  }
1823               }
1824            });
1825         }, 1000);
1826      }else{
1827         if(videoSettings.autoplay) { brave_play_video(popupID, videoSettings.id, 'youtube', videoSettings.tracking); }
1828      } 
1829   }
1830
1831   if(videoType ==='vimeo'){
1832      var vimeo_regex = new RegExp(/https?:\/\/(?:www\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/);
1833      var parsed = videoURL.match(vimeo_regex);
1834      var videoID = parsed && parsed[3] ? parsed[3] : null;
1835      
1836      if(!brave_popup_videos[popupID]['video_'+videoType+elmID]){
1837         setTimeout(function() {
1838            brave_popup_videos[popupID]['video_'+videoType+elmID] = new Vimeo.Player('brave_video_iframe'+elmID, {  id: videoID, background: videoSettings.controls ===false ? true : false });
1839            setTimeout(function() {
1840               if(videoSettings.mute){
1841                  brave_popup_videos[popupID]['video_'+videoType+elmID].setVolume(0);
1842               }
1843               if(videoSettings.autoplay){
1844                  brave_play_video(popupID, videoSettings.id, 'vimeo', videoSettings.tracking);
1845               }
1846            }, 2000);
1847         }, 1000);
1848      }else{
1849         if(videoSettings.autoplay) { brave_play_video(popupID, videoSettings.id, 'vimeo', videoSettings.tracking); }
1850      }
1851      
1852   }
1853
1854}
1855
1856function brave_play_video(popupID, elmentID, videoType, track=null, inline=false){
1857   console.log('brave_play_video', elmentID, videoType, track );
1858   var elmID = elmentID.replace(/[^a-zA-Z0-9]+/g, '');
1859   if(!brave_popup_videos[popupID]['video_'+videoType+elmID]){ return; }
1860
1861   if(document.getElementById("brave_element-"+elmentID)){
1862      document.getElementById("brave_element-"+elmentID).classList.add('brave_element--video-show');
1863   }
1864
1865   //Custom Video Playback
1866   if(videoType === 'custom' ){
1867      brave_popup_videos[popupID]['video_'+videoType+elmID].muted = true; //Video doesnt autoplay if not muted
1868      brave_popup_videos[popupID]['video_'+videoType+elmID].play();
1869      var videoMuted = brave_popup_videos[popupID]['video_'+videoType+elmID].classList.contains('brave_video_muted');
1870      if(!videoMuted){
1871         setTimeout(function() {
1872            brave_popup_videos[popupID]['video_'+videoType+elmID].muted=false;  brave_popup_videos[popupID]['video_'+videoType+elmID].volume=1; 
1873            brave_popup_videos[popupID]['video_'+videoType+elmID].play(); 
1874         }, 100);
1875      }
1876   }
1877   //Youtube and Vimeo Playback
1878   if(videoType === 'youtube' || videoType === 'vimeo'){
1879      if(videoType === 'youtube' && brave_popup_videos[popupID]['video_'+videoType+elmID]){   brave_popup_videos[popupID]['video_'+videoType+elmID].playVideo();   }
1880      if(videoType === 'vimeo' && brave_popup_videos[popupID]['video_'+videoType+elmID]){     brave_popup_videos[popupID]['video_'+videoType+elmID].play().then(); }
1881   }
1882
1883   //Track Video Playback
1884   if(inline && !track){
1885      var playButton = document.getElementById('brave_play_video-'+elmentID)
1886      if(playButton){
1887         var eventCategory = playButton.dataset.trackcategory || '';
1888         var eventAction = playButton.dataset.trackcategory || '';
1889         var eventLabel = playButton.dataset.tracklabel || '';
1890         track = {eventCategory: eventCategory, eventAction:eventAction, eventLabel: eventLabel}
1891      }
1892   }
1893   
1894   if(track && track.eventCategory && track.eventAction){
1895      brave_send_ga_event(track.eventCategory, track.eventAction, track.eventLabel || '');
1896   }
1897   
1898}
1899
1900function brave_complete_goal(popupID, goalType='view', auto=false){
1901   if(window.location.href.includes('brave_popup') === false && !brave_popup_data[popupID].goaled){ 
1902      var goalDate = new Date(); var goalYear = goalDate.getFullYear(); var goalMonth = brave_number_padding(goalDate.getMonth() + 1);  var goalDay = brave_number_padding(goalDate.getDate()); 
1903      var goalData = { 
1904         popupID: popupID, 
1905         pageURL: window.location, 
1906         security: bravepop_global.security, 
1907         goalType: goalType, 
1908         //viewTime: brave_popup_data[popupID].opened, 
1909         views: localStorage.getItem('brave_popup_'+popupID+'_viewed') || 1, 
1910         goalTime: new Date().getTime(), 
1911         goalDate: goalYear+'-'+goalMonth+'-'+goalDay,
1912         goalUTCTime: new Date().toUTCString(), 
1913         device: brave_currentDevice, 
1914         auto: auto,
1915         action: 'bravepop_ajax_popup_complete_goal' 
1916      };
1917
1918      brave_ajax_send(bravepop_global.ajaxURL, goalData, function(status, sentData){   brave_popup_data[popupID].goaled = true; console.log('Goal Complete!!!!!!', sentData);  });
1919      localStorage.setItem('brave_popup_'+popupID+'_goal_complete', true);
1920      var braveGoalCompletEvent = new CustomEvent('brave_goal_complete', { detail: {popupId: parseInt(popupID, 10), goalType: goalType} });
1921      document.dispatchEvent(braveGoalCompletEvent);
1922      if(brave_popup_data[popupID].settings && brave_popup_data[popupID].settings.notification && brave_popup_data[popupID].settings.notification.analyticsGoal){
1923         setTimeout(function() {
1924            //console.log('##### Send Goal Event to GA!');
1925            brave_send_ga_event('popup', 'goal', brave_popup_data[popupID].title+' ('+popupID+')' || popupID);
1926         }, 2000);
1927      }
1928   }
1929}
1930
1931function brave_load_fonts(fontArray){
1932   var googleFonts  = []; var customFonts = [];
1933   fontArray.forEach(function(font){ 
1934      const inCustomFontList = bravepop_global && bravepop_global.customFonts.find((fnt)=> fnt.name === font);
1935      if(inCustomFontList){ customFonts.push(font); }else{ googleFonts.push(font); }
1936   })
1937    if(googleFonts.length > 0){
1938      WebFontConfig = {
1939         google: { families: googleFonts }
1940       };
1941       (function() {
1942          if(!document.getElementById('bravePopu_webfontLoader')){
1943               var wf = document.createElement('script');
1944               wf.setAttribute("id", "bravePopu_webfontLoader");
1945               wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +'://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js';
1946               wf.type = 'text/javascript';
1947               wf.async = 'true';
1948               var s = document.getElementsByTagName('script')[0];
1949               s.parentNode.insertBefore(wf, s);
1950          }
1951       })();
1952    }
1953   //  console.log(googleFonts, customFonts);
1954   //Load Custom Fonts
1955   if(bravepop_global.customFonts.length > 0 && customFonts.length > 0){
1956      customFonts.map((font)=> {
1957         var foundFont = bravepop_global.customFonts.find((fnt)=> font === fnt.name  );
1958         if(foundFont && foundFont.url && foundFont.url !=='UAF' && foundFont.name  && foundFont.name.includes('brave_custom-')){
1959            var custom_font = new FontFace(foundFont.name, 'url('+foundFont.url+')');
1960            custom_font.load().then(function(loaded_face) {
1961               document.fonts.add(loaded_face)
1962            }).catch(function(error) {
1963               console.error(error);
1964            });
1965         }
1966      })
1967   }
1968	//return fontArray;
1969};
1970
1971function brave_is_in_view(elem) {
1972   var rect = elem.getBoundingClientRect();
1973   return (rect.bottom >= 0 && rect.right >= 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth));
1974};
1975
1976
1977function brave_save_visitor_pageviews(){
1978   //Save Page View Data
1979   if(brave_popup_pageInfo.type === 'front' || brave_popup_pageInfo.pageID){
1980      var brave_page_visited = localStorage.getItem('brave_page_visited'); var currentPageType = 'page';
1981      if(brave_popup_pageInfo.type === 'front'){ currentPageType = 'front'; } 
1982      var brave_page_visited_new = {type: brave_popup_pageInfo.type === 'front'? 'front' :(brave_popup_pageInfo.singleType || brave_popup_pageInfo.type), PID: brave_popup_pageInfo.pageID, time: new Date().getTime() };
1983      if(brave_page_visited){
1984         var brave_page_visited_newData = JSON.parse(brave_page_visited);
1985         brave_page_visited_newData.push(brave_page_visited_new);
1986         localStorage.setItem('brave_page_visited', JSON.stringify(brave_page_visited_newData));
1987      }else{
1988         localStorage.setItem('brave_page_visited', JSON.stringify([brave_page_visited_new]));
1989      }
1990   }
1991}
1992
1993function brave_add_to_cart(elementID){
1994   brave_tooltip_open(elementID, 'Adding to Cart...', 'top');
1995   setTimeout(function() {   brave_tooltip_close();  }, 2000);
1996}
1997function brave_close_on_add_to_cart(popupID){
1998   setTimeout(function() { popupID &&  brave_close_popup(popupID);  }, 2000);
1999}
2000function brave_apply_woo_coupon(coupon, popupID, elementID, onCouponApply){
2001   if(elementID){ document.querySelector('#brave_button_loading_'+elementID).classList.add('brave_button_loading--show') }
2002   brave_ajax_send(location.href+'/?wc-ajax=apply_coupon', { coupon_code: coupon, security: bravepop_global.couponSecurity}, function(status, response){
2003      if(onCouponApply==='reload'){ location.reload(); }
2004      if(onCouponApply==='close' && popupID){ brave_close_popup(popupID); } 
2005      if(onCouponApply==='cart' && bravepop_global.cartURL){ location.href = bravepop_global.cartURL}
2006      if(onCouponApply==='checkout' && bravepop_global.checkoutURL){ location.href = bravepop_global.checkoutURL}
2007      if(elementID){ document.querySelector('#brave_button_loading_'+elementID).classList.remove('brave_button_loading--show') }
2008   })
2009}
2010function brave_copy_to_clipboard(elementID, tooltipData, position){
2011   var copyText = document.getElementById('bravepopup_text_copy-'+elementID);
2012   copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy");
2013   brave_tooltip_open(elementID, '✓ '+tooltipData, position);
2014   setTimeout(function() {   brave_tooltip_close();  }, 2000);
2015}
2016function brave_tooltip_open(elementID, tooltipData, position){
2017   var tooltipDiv = document.getElementById('bravepop_element_tooltip'); var tooltipElm = document.getElementById('brave_element-'+elementID); var elmPos = tooltipElm.getBoundingClientRect();
2018   if(tooltipDiv){
2019      tooltipDiv.innerHTML = tooltipData; tooltipDiv.className = 'bravepop_element_tooltip-show bravepop_element_tooltip-'+position; var tooltipWidth = tooltipDiv.offsetWidth;
2020      tooltipDiv.style.top = (elmPos.top + (elmPos.height/2) - 10)+'px'; tooltipDiv.style.left = (elmPos.left - (tooltipWidth) - 8)+'px';
2021      if(position === 'right'){ tooltipDiv.style.left = (elmPos.left + elmPos.width + 8)+'px';  }
2022      if(position === 'top'){ tooltipDiv.style.top = (elmPos.top - (tooltipDiv.offsetHeight) - 4 )+'px'; tooltipDiv.style.left = (elmPos.left - (tooltipWidth/2) + (elmPos.width/2) - 4)+'px';  }
2023      if(position === 'bottom'){ tooltipDiv.style.top = (elmPos.top + elmPos.height + 8)+'px'; tooltipDiv.style.left = (elmPos.left - (tooltipWidth/2) + (elmPos.width/2) + 8)+'px';  }
2024   }
2025}
2026function brave_tooltip_close(){
2027   var tooltipDiv = document.getElementById('bravepop_element_tooltip');
2028   if(tooltipDiv){   tooltipDiv.innerHTML = ''; tooltipDiv.className = '';  tooltipDiv.style.left = ''; tooltipDiv.style.top = ''; }
2029}
2030
2031function brave_lightbox_open(elementID, contentType, content){
2032   var bravelightbox = document.getElementById('bravepop_element_lightbox');  var bravelightboxContent = document.getElementById('bravepop_element_lightbox_content'); 
2033   if(contentType === 'image' && bravelightboxContent){ bravelightboxContent.innerHTML = '<img src="'+content+'" />';bravelightbox.classList.add('bravepop_element_lightbox--open');}
2034}
2035function brave_lightbox_close(){
2036   var bravelightbox = document.getElementById('bravepop_element_lightbox');  var bravelightboxContent = document.getElementById('bravepop_element_lightbox_content'); 
2037   if(bravelightbox && bravelightboxContent){ bravelightbox.classList.remove('bravepop_element_lightbox--open'); bravelightboxContent.innerHTML = ''; }
2038}
2039
2040function brave_responsiveness(event, popupID, popupData){
2041   if(window.location.href.includes('braveshot') === true && window.location.href.includes('brave_id') === true){ return; }
2042   //If a step has no Mobile Content is set, make the Desktop Content mobile friendly and display that instead
2043   var stepsWithNoMobile = document.querySelectorAll('.brave_popup__step--mobile-noContent');
2044   if(brave_isTab || (brave_currentDevice === 'mobile' && document.body.clientWidth < 350 )){ stepsWithNoMobile = document.querySelectorAll('.brave_popup__step_wrap'); }
2045   for (var i = 0; i < stepsWithNoMobile.length; i++) {
2046      var desktopStep =  stepsWithNoMobile[i].querySelector('.brave_popup__step__desktop');
2047      var mobileStep =  stepsWithNoMobile[i].querySelector('.brave_popup__step__mobile');
2048      var popupLayout = desktopStep.dataset.layout;
2049      var popupPosition = popupLayout === 'landing' ? 'top_center' :desktopStep.dataset.position;
2050      var popupWidth = parseInt(desktopStep.dataset.width, 10);
2051      var popupHeight = parseInt(desktopStep.dataset.height, 10);
2052      var windowWidth = document.body.clientWidth || window.innerWidth;  //window.innerWidth
2053      var windowHeight = window.innerHeight;
2054      
2055      if(brave_currentDevice === 'mobile' || brave_isTab){
2056         if(((windowWidth < popupWidth) && popupLayout == 'boxed')){
2057            var scale =  desktopStep ? windowWidth/ desktopStep.dataset.width : 0;
2058            var tansformOrigin = popupPosition.includes('top') ? 'top' : 'center';
2059            desktopStep.querySelector('.brave_popup__step__inner').style.transform = 'scale('+((scale*95)/100)+')';
2060            desktopStep.querySelector('.brave_popup__step__inner').style.transformOrigin = ((scale*95)/2)+'px '+tansformOrigin;
2061            if(windowWidth < popupWidth && windowHeight < popupHeight){
2062               desktopStep.querySelector('.brave_popup__step__inner').style.transformOrigin = 'left top';
2063               desktopStep.querySelector('.brave_popup__step__inner').style.marginTop = 0;
2064               desktopStep.querySelector('.brave_popup__step__inner').style.top = 0;
2065            }
2066            if(popupPosition.includes('center') ){
2067               var widthRemainder = windowWidth - (popupWidth * (scale*95)/100) ;
2068               var heightRemainder = windowHeight - (popupHeight * (scale*95)/100) ;
2069               desktopStep.querySelector('.brave_popup__step__inner').style.left = widthRemainder > 0 ? (widthRemainder/2)+'px' : '0';
2070               //if(popupPosition === 'center'){ desktopStep.querySelector('.brave_popup__step__inner').style.top = heightRemainder > 0 ? (heightRemainder/2)+'px' : '0'; }
2071            }
2072            // if(windowHeight < (popupHeight * (scale*95)/100) ){
2073            //    console.log('Window Height vs Popup Height', windowHeight < (popupHeight * (scale*95)/100), windowHeight , (popupHeight * (scale*95)/100) );
2074            // }
2075         }
2076
2077         if(brave_currentDevice === 'mobile'&& windowWidth < 321 && ((290 < popupWidth) || windowHeight < popupHeight) && (popupLayout == 'boxed' ) && (popupPosition === 'bottom_right') ){
2078            desktopStep.querySelector('.brave_popup__step__inner').style.transform = 'scale(0.8)';
2079            desktopStep.querySelector('.brave_popup__step__inner').style.transformOrigin = '100% bottom';
2080         }
2081         //Top/bottom bar on mobile phones, If no Mobile layout exists
2082         if(brave_currentDevice === 'mobile' && (popupLayout == 'float' ) && windowWidth < 750 ){
2083            desktopStep.querySelector('.brave_popup__step__elements').style.transform = 'scale('+(((windowWidth / 1024)*100)/100)+')';
2084            desktopStep.querySelector('.brave_popup__step__elements').style.transformOrigin = (((windowWidth / 1024)*100)/2)+'px center';
2085         }
2086         //Top/bottom bar ipad/iphone5 fix
2087         if(popupLayout == 'float' && ((brave_isTab && windowWidth < 1024 && windowWidth > 760) || (brave_currentDevice === 'mobile' && windowWidth < 360 && mobileStep))){
2088            if(brave_isTab && windowWidth < 1024 && windowWidth > 760){ popupWidth = 1024; }   var scale =  desktopStep ? windowWidth/ popupWidth : 0;
2089            if(!brave_isTab && windowWidth < 360 && mobileStep){ popupWidth = 360; scale =  windowWidth / popupWidth; desktopStep = mobileStep; } 
2090            desktopStep.querySelector('.brave_popup__step__elements').style.transform = 'scale('+((scale*100)/100)+')';
2091            desktopStep.querySelector('.brave_popup__step__elements').style.transformOrigin = ((scale*100)/2)+'px center';
2092         }
2093
2094      }
2095   }
2096   var allPopups = document.querySelectorAll('.brave_popup__step');
2097   for (var i = 0; i < allPopups.length; i++) {
2098      var aPopupHeight = allPopups[i].dataset.height ? parseInt(allPopups[i].dataset.height, 10) : 400;
2099      var aPopupPosition = allPopups[i].dataset.position; var aPopupLayout = allPopups[i].dataset.layout;
2100      if((window.innerHeight < aPopupHeight) && aPopupPosition.includes('center') && aPopupLayout === 'boxed' && !allPopups[i].classList.contains('brave_popup_show_scrollbar')){
2101         allPopups[i].classList.add('brave_popup_show_scrollbar', 'brave_popup_exceeds_windowHeight');
2102      }
2103   }
2104
2105   //Embedded Popup Resonsiveness
2106   var allEmbeddedPopups = document.querySelectorAll('.bravepopup_embedded');
2107   for (var x = 0; x < allEmbeddedPopups.length; x++) {
2108      var popupID = allEmbeddedPopups[x].dataset.popupid; var parentElm = allEmbeddedPopups[x].parentNode;  var popup_parent_width = parentElm.clientWidth;
2109      //Resize the embedded popup
2110      var allEmbeddedSteps = allEmbeddedPopups[x].querySelectorAll('.brave_popup__step_wrap');
2111      for (var i = 0; i < allEmbeddedSteps.length; i++) {
2112         var currentDevice = allEmbeddedSteps[i].classList.contains('brave_popup__step--mobile-noContent') ? 'desktop' : brave_currentDevice;
2113         var selectedStep =  allEmbeddedSteps[i].querySelector('.brave_popup__step__'+currentDevice+'.brave_popup__step--embedded');
2114         if(selectedStep){
2115            var stepWidth = parseInt(selectedStep.dataset.width, 10); var stepHeight = parseInt(selectedStep.dataset.height, 10);
2116            if(popup_parent_width && (popup_parent_width < stepWidth)){
2117               var scale =  Math.min( popup_parent_width / stepWidth);
2118               selectedStep.querySelector('.brave_popup__step__inner').style.transform = 'scale('+((scale*98)/100)+')';
2119               selectedStep.querySelector('.brave_popup__step__inner').style.transformOrigin = 'left top';
2120               selectedStep.querySelector('.brave_popup__step__inner').parentNode.classList.add('brave_popup__step__inner--scaled');
2121               selectedStep.style.height = ((stepHeight * (scale*98)/100 ))+'px';
2122            }
2123         }
2124      }
2125   }
2126
2127}
2128
2129
2130//Click Open Popup
2131function brave_click_open_popups(){
2132   var braveFoundOpenElems = document.querySelectorAll('a[href*="#brave_open_popup_"]');
2133   if(braveFoundOpenElems.length > 0){
2134      for (var i = 0; i < braveFoundOpenElems.length; i++) { 
2135         var rawOpenElmHref = braveFoundOpenElems[i].href; 
2136         var braveOpenPopupID = rawOpenElmHref && rawOpenElmHref.split('#brave_open_popup_')[1] ? parseInt(rawOpenElmHref.split('#brave_open_popup_')[1], 10) : false;
2137         //console.log(braveOpenPopupID);
2138         if(braveOpenPopupID && brave_popup_data[braveOpenPopupID] && document.getElementById('brave_popup_'+braveOpenPopupID)){
2139            braveFoundOpenElems[i].addEventListener( 'click', function(event){ event.preventDefault(); if(document.getElementById('brave_popup_'+braveOpenPopupID)) document.getElementById('brave_popup_'+braveOpenPopupID).style.zIndex = 9999999999;  });
2140            braveFoundOpenElems[i].setAttribute('onclick','brave_load_popup('+braveOpenPopupID+', brave_popup_data['+parseInt(braveOpenPopupID, 10)+'])');
2141         }
2142      }
2143   }
2144}
2145
2146//Replace Dynamic Text Cookie value
2147function brave_replace_dynamic_text_cookie(elmsWithCookie){
2148   if(elmsWithCookie.length > 0){
2149      for (var i = 0; i < elmsWithCookie.length; i++) { 
2150         var finalContent = elmsWithCookie[i].innerHTML;
2151         var allShortCodes =  finalContent.match(/({{cookie-)+([a-zA-Z0-9_]).+?}}
2151/gi);
2152         if(allShortCodes && allShortCodes.length > 0){
2153            allShortCodes.forEach(function(shortcode){
2154               var theShortcode = shortcode.replace('{{cookie-', '').replace('}}', '');
2155               var cookieVal = localStorage.getItem(theShortcode);
2156               finalContent = finalContent.replace(shortcode, cookieVal ? cookieVal : '');
2157            })
2158            elmsWithCookie[i].innerHTML = finalContent;
2159         }
2160      }
2161   }
2162}
2163
2164function brave_lazyLoad_content_images(emebeddedCampain){
2165   if(emebeddedCampain && !emebeddedCampain.classList.contains('bravepopup_embedded--lazyload_done') && brave_is_in_view(emebeddedCampain)){
2166      var allImages = emebeddedCampain.querySelectorAll('img');
2167      for (var i = 0; i < allImages.length; i++) { 
2168         if(allImages[i].dataset.lazy){
2169            allImages[i].src = allImages[i].dataset.lazy;
2170         }
2171      }
2172      emebeddedCampain.classList.add('bravepopup_embedded--lazyload_done');
2173   }
2174}
2175
2176function brave_after_page_load(){
2177   var allBraveFonts = []
2178   if(!brave_popup_data){ return; }
2179   Object.keys(brave_popup_data).forEach(function(popID) {
2180      brave_popup_data[popID].fonts.forEach(function(fontName) {
2181         if(!allBraveFonts.includes(fontName)){
2182               allBraveFonts.push(fontName);
2183         }
2184      })
2185   });
2186   brave_save_visitor_pageviews();
2187   brave_load_fonts(allBraveFonts);
2188   brave_click_open_popups();
2189   //brave_replace_dynamic_text_cookie();
2190   var emebddedContent = document.querySelectorAll('.bravepopup_embedded');
2191   if(emebddedContent && emebddedContent.length > 0){
2192      for (var i = 0; i < emebddedContent.length; i++) { 
2193         var emebeddedCampain = emebddedContent[i];
2194         if(emebeddedCampain){
2195            brave_lazyLoad_content_images(emebeddedCampain); //Load the images if they are in view on page load.
2196            document.addEventListener("scroll", function(){ brave_lazyLoad_content_images(emebeddedCampain) }, {passive: true});
2197         }
2198      }
2199   }
2200}
2201
2202window.addEventListener( 'DOMContentLoaded', brave_after_page_load );
2203window.addEventListener( 'resize', brave_responsiveness );

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.