PageSourceSearch

https://natureswaymedicine.com/wp-content/plugins/brave-popup-builder/assets/frontend/brave.js?ver=6.8.3

js natureswaymedicine.com collected 2026-10-04 12:31:59 UTC 131,685 bytes, 2,248 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 brave_lightbox_open(null, 'html', response.error)
557            }
558
559            if(response.subscribed === false && response.subscriptionError && typeof response.subscriptionError === 'string'){
560               // return alert(response.subscriptionError);
561               return brave_lightbox_open(null, 'html', response.subscriptionError)
562            }
563
564            localStorage.setItem('brave_popup_'+settings.popupID+'_formsubmitted', true);
565   
566            var braveFormSubmitEvent = new CustomEvent('brave_form_submitted', { detail: {popupId: parseInt(settings.popupID, 10), formId: settings.formID, formData: JSON.stringify(finalFieldsData)} });
567            document.dispatchEvent(braveFormSubmitEvent);
568   
569            // if(document.querySelector('#'+settings.formID+'__form_progress')){
570            //    document.querySelector('#'+settings.formID+'__form_progress').style.display = 'none';
571            // }
572
573            //Reset the Form
574            if(brave_form){  brave_form.reset();   }
575
576            //If Multistep Form, go to the First Step
577            if(brave_popup_formData[settings.formID] && brave_popup_formData[settings.formID].totalSteps > 0){
578               for (var findx = 1; findx < brave_popup_formData[settings.formID].totalSteps; findx++) {
579                  brave_form_goBack(settings.formID, brave_popup_formData[settings.formID].totalStep)
580               }
581            }
582
583            if(settings.track){
584               var formTrackingSettings = JSON.parse(settings.track);
585               //Send Ga Event
586               if( formTrackingSettings && formTrackingSettings.enable && formTrackingSettings.eventCategory && formTrackingSettings.eventAction){
587                  brave_send_ga_event(formTrackingSettings.eventCategory, formTrackingSettings.eventAction, formTrackingSettings.eventLabel || '');
588               }
589               if( formTrackingSettings && formTrackingSettings.enable && formTrackingSettings.fbq_event_type){
590                  brave_send_fbq_event(formTrackingSettings.fbq_event_type, formTrackingSettings.fbq_content_name, formTrackingSettings.fbq_content_category, formTrackingSettings.fbq_value, formTrackingSettings.fbq_currency);
591               }
592            }
593   
594            //Perform Goal
595            if(brave_popup_formData[settings.formID] && brave_popup_formData[settings.formID].goal){
596               brave_complete_goal(settings.popupID, 'form');
597            }
598            
599            //Save Field Value as Cookie
600            Object.keys(fieldsData).forEach(function(fieldID){  
601               var fieldVal = Array.isArray(fieldsData[fieldID].value) ? fieldsData[fieldID].value.join(',') : fieldsData[fieldID].value;
602               if(fieldVal && fieldsData[fieldID] && fieldsData[fieldID].save_cookie){ localStorage.setItem(fieldsData[fieldID].save_cookie, fieldVal)}
603            });
604   
605            //Show Content
606            if(response.sent && response.primaryAction === 'content' && response.contentMessage ){
607               if(brave_form){ brave_form.classList.add('brave_form_form--hide');  }
608               document.getElementById('brave_form_custom_content'+settings.formID).innerHTML = response.contentMessage;
609               //Auto Close Popup
610               if(response.autoclose && response.autoclosetime){
611                  setTimeout(function() {
612                     var thePopID = parseInt(settings.popupID, 10);
613                     brave_close_popup(thePopID, brave_popup_data[thePopID].currentStep||0);
614                  }, parseInt(response.autoclosetime, 10) * 1000);
615               }
616               //Also Download File
617               if(response.download && response.downloadURL){
618                  var downloadURI = response.downloadURL; var filename =  response.downloadURL.substring( response.downloadURL.lastIndexOf('/')+1);
619                  var link = document.createElement('a');
620                  if (typeof link.download === 'string') {
621                        document.body.appendChild(link); // Firefox requires the link to be in the body
622                        link.download = filename;
623                        link.href = downloadURI;
624                        link.target = '_blank';
625                        link.click();
626                        document.body.removeChild(link); // remove the link when done
627                  } else {
628                        location.replace(downloadURI);
629                  }
630               }
631            }
632
633            //Run Users own functions after submit
634            brave_popup_formData[settings.formID] && brave_popup_formData[settings.formID].onSubmit(fieldsData, response);
635   
636            //Redirect User
637            if(response.sent && response.primaryAction === 'redirect' && response.redirectURL ){
638               if(brave_form){ brave_form.classList.add('brave_form_form--hide');  }
639               document.getElementById('brave_form_custom_content'+settings.formID).innerHTML = response.redirectMessage;
640               var redirectTime = response.redirectAfter ? (response.redirectAfter *1000) : 6000;
641               setTimeout(function() {
642                  window.location.href = response.redirectURL;
643               }, redirectTime);
644            }
645   
646            //Go to Step
647            if(response.sent && response.primaryAction === 'step' && response.step && settings.popupID ){
648               var formStep = parseInt(response.step, 10);
649               formStep = formStep === 0 ? 0 : formStep - 1;
650               var selectedPopupStep = document.querySelector('#brave_popup_'+settings.popupID+'__step__'+(brave_popup_data[settings.popupID].currentStep||0)+' .brave_popup__step__'+brave_currentDevice)
651               if(selectedPopupStep){ selectedPopupStep.dataset.popopen = 'false'; }
652               brave_open_popup(settings.popupID, formStep);
653            }
654            //If has quiz Shortcode in the popup, insert the quiz scores inside the shortcodes
655            if(settings.quiz){
656               var quizShortcodes = document.querySelectorAll('.bravepop_quizScore-'+settings.formID);
657               if(quizShortcodes){
658                  for (var i = 0; i < quizShortcodes.length; i++) { 
659                     var showTotal = quizShortcodes[i].dataset.total && quizShortcodes[i].dataset.total === 'false' ? false : true;
660                     if(settings.quizScoring ==='points' ){
661                        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 : '';
662                        quizShortcodes[i].innerHTML = '<span>'+brave_popup_formData[settings.formID].totalScore+'</span>'+availableScoreVal;
663                     }
664                     if(settings.quizScoring ==='answer'){
665                        var availableQuesVal = showTotal && brave_popup_formData[settings.formID].totalQuestions ?  '/'+brave_popup_formData[settings.formID].totalQuestions : '';
666                        quizShortcodes[i].innerHTML = '<span>'+brave_popup_formData[settings.formID].totalCorrect+'</span>'+availableQuesVal;
667                     }
668                  }
669               }
670            }
671
672         });
673      }
674
675      var braveSubmitWithEmailValidation = function(){
676         var emailData = { formData: JSON.stringify(emailFields), freemailAllow: JSON.stringify(brave_popup_formData[settings.formID].freemailAllow || false), security: security, action: 'bravepopup_validate_email' };
677         brave_ajax_send(ajaxurl, emailData, function(status, sentData){
678            var validatedData = JSON.parse(sentData);
679            console.log('Validation response:', validatedData); var emailValidationErrors = [];
680            if(Array.isArray(validatedData)){
681               validatedData.forEach(function(field){
682                  if(field.validation && field.validation.status === 'invalid' && field.validation.errorMsg){
683                     emailValidationErrors.push({id:field.ID ,message: field.validation.errorMsg, type: "required"});
684                  }
685                  if(field.validation && field.validation.suggestionMsg && field.validation.suggestion){
686                     emailValidationErrors.push({id:field.ID , message: field.validation.suggestionMsg, type: "suggestion", suggestion: field.validation.suggestion});
687                  }
688               });
689            }
690            if(emailValidationErrors.length > 0){
691               brave_display_form_error(emailValidationErrors);
692               if(brave_form){ brave_form.classList.remove('brave_form_form--loading');  }
693               if(brave_login_loader){  brave_login_loader.classList.remove('brave_form_loading--show'); }
694            }else{
695               braveSubmitForm();
696            }
697         });
698      }
699
700      if(settings.recaptcha && grecaptcha){
701         grecaptcha.execute(settings.recaptcha, {action: 'submit'}).then(function(token) {
702            if(token){
703               var recaptchaData = { token: token, security: security, action: 'bravepopup_validate_recaptcha' };
704               brave_ajax_send(ajaxurl, recaptchaData, function(status, valid){
705                  console.log('Google Recaptcha Verified!');
706                  if(valid === 'true'){
707                     if(bravepop_emailValidation && emailFields.length > 0){
708                        braveSubmitWithEmailValidation();
709                     }else{
710                        braveSubmitForm();
711                     }
712                  }else{
713                     console.error('Google Recaptcha Failed! Spammer Detected!');
714                  }
715               });
716            }else{ console.error('Google Recaptcha Failed! Could not Fetch Token!'); }
717        });
718      }else{
719         if(bravepop_emailValidation && emailFields.length > 0){
720            braveSubmitWithEmailValidation();
721         }else{
722            braveSubmitForm();
723         }
724      }
725
726   }
727
728}
729
730function brave_apply_email_suggestion(fieldID, suggestion){ document.querySelector('#brave_form_field'+fieldID+' input').value = suggestion; brave_dismiss_email_suggestion(fieldID); }
731function brave_dismiss_email_suggestion(fieldID){ document.querySelector('#brave_form_field'+fieldID).classList.remove('brave_form_field--hasError', 'brave_form_field--hasSuggestion'); }
732
733function brave_display_form_error(formErrors){
734      //console.log(formErrors);
735      
736      //Display The Errors
737      if(formErrors.length > 0){
738         formErrors.forEach(function(error){
739            if(error.fieldType && error.fieldType ==='name'){
740               if(error.firstname){
741                  document.querySelector('#brave_form_field'+error.id).classList.add('brave_form_field--hasError-firstname');
742                  document.querySelector('#brave_form_field'+error.id+' .brave_form_field_error--firstname').innerHTML = error.message;
743               }
744               if(error.lastname){
745                  document.querySelector('#brave_form_field'+error.id).classList.add('brave_form_field--hasError-lastname');
746                  document.querySelector('#brave_form_field'+error.id+' .brave_form_field_error--lastname').innerHTML = error.message;
747               }
748   
749            }else{
750               document.querySelector('#brave_form_field'+error.id).classList.add('brave_form_field--hasError');
751               document.querySelector('#brave_form_field'+error.id+' .brave_form_field_error').innerHTML = error.message;
752               if(error.type === 'suggestion' && error.suggestion ){
753                  document.querySelector('#brave_form_field'+error.id).classList.add('brave_form_field--hasSuggestion');
754                  var suggestionApplyBtn = '<span onclick="brave_apply_email_suggestion(\''+error.id+'\', \''+error.suggestion+'\')">'+bravepop_global.yes+'</span>';
755                  var suggestionDismissBtn = '<span onclick="brave_dismiss_email_suggestion(\''+error.id+'\', \''+error.suggestion+'\')">'+bravepop_global.no+'</span>';
756                  var suggestionActions = '<div id="brave_form_field_suggestion_actions-'+error.id+'" class="brave_form_field_suggestion_actions">'+suggestionApplyBtn+suggestionDismissBtn+'</div>'
757                  document.querySelector('#brave_form_field'+error.id+' .brave_form_field_error').setAttribute('id', 'brave_form_field_error--suggestion'+error.id)
758                  document.querySelector('#brave_form_field'+error.id+' .brave_form_field_error').classList.add('brave_form_field_error--suggestion');
759                  document.querySelector('#brave_form_field'+error.id+' .brave_form_field_error').innerHTML = (error.message)+suggestionActions;
760               }
761            }
762         });
763      }
764}
765
766
767function brave_validate_fields(fieldID, field){
768   if(!field){ return }
769
770   if(field.type==='input' && field.validation === 'name' && field.required) { 
771      if(!field.value[0] || !field.value[1]){
772         return {id: fieldID, type: 'required', fieldType: 'name', message: bravepop_global.field_required, firstname: !field.value[0] ? true : false, lastname:  !field.value[1] ? true : false}
773      }
774   }
775
776   if(!field.value && field.required) { 
777      return {id: fieldID, type: 'required', message: bravepop_global.field_required}
778   }
779   if(field.required && (field.type==='input' || field.type==='textarea' || field.type==='date' ) ) { 
780      if(field.validation !== 'name'  && !field.value.trim()){
781         return {id: fieldID, type: 'required', message: bravepop_global.field_required}
782      }
783   }
784
785   if(field.value && field.required && field.type==='select' && field.value === 'none') { 
786      return {id: fieldID, type: 'required', message: bravepop_global.field_required}
787   }
788
789   //Check HTML or Empty Value
790   if(field.value && ((field.type==='input' && field.validation === 'text') || field.type==='textarea' || field.type==='date'  ) ) { 
791
792      if(brave_hasHTML(field.value)){
793         return {id: fieldID, type: 'ho_html', message: bravepop_global.no_html_allowed};
794      }
795   }
796
797   //Validate number
798   if(field.value && field.type==='input' && field.validation === 'number' ) { 
799      if(brave_isNumber(field.value) === false){
800         return {id: fieldID, type: 'invalid', message: bravepop_global.invalid_number};
801      }
802   }
803   //Validate url
804   if(field.value && field.type==='input' && field.validation === 'url' ) { 
805      if(brave_isURL(field.value) === false){
806         return {id: fieldID, type: 'invalid', message: bravepop_global.invalid_url};
807      }
808   }
809
810   //Validate Date
811   if(field.value && field.type==='date' ) { 
812      if(brave_isDate(field.value) === false){
813         return {id: fieldID, type: 'invalid', message: bravepop_global.invalid_date};
814      }
815   }
816
817   //Validate email
818   if(field.value && field.type==='input' && field.validation === 'email' ) { 
819      if(brave_isEmail(field.value) === false){
820         return {id: fieldID, type: 'invalid', message: bravepop_global.invalid_email};
821      }
822   }
823
824}
825
826function brave_hasHTML(value) {
827   var doc = new DOMParser().parseFromString(value, "text/html");
828   return Array.from(doc.body.childNodes).some(function(node){ return node.nodeType === 1});
829}
830
831function brave_isNumber(value) {
832   var numberFormat = RegExp(/^[a-zA-Z]+$/);
833   return numberFormat.test(value) ? false : true;
834}
835
836function brave_isEmail(value) {
837   var mailformat = RegExp(/^\w+([\.+-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,8})+$/);
838   return mailformat.test(value) ? true : false;
839}
840
841function brave_isURL(value) {
842   var urlFormat = RegExp(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
843   return urlFormat.test(value) ? true : false;
844}
845
846function brave_isDate(value) {
847   var dateFormat = RegExp(/\d{1,4}[-/]\d{1,2}[-/]\d{1,4}/);
848   var dateFormatTwo = RegExp(/\d{1,4}[-/]\d{1,2}/);
849   var matchedDate = dateFormat.test(value);
850   if(!matchedDate){ matchedDate = dateFormatTwo.test(value);  }
851   //console.log(value, matchedDate);
852   return matchedDate ? true : false;
853}
854
855
856function brave_ajax_send(ajaxurl, ajaxData, callbackFunction){
857   //console.log(ajaxData);
858   var array = [];
859   Object.keys(ajaxData).forEach(function(element) {
860      array.push(  encodeURIComponent(element) + "=" + encodeURIComponent(ajaxData[element]) ) 
861   });
862   var dataToSend = array.join("&");
863   
864   var request = new XMLHttpRequest();
865   request.open('POST', ajaxurl, true);
866   request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded' );
867   request.onload = function () {  
868      if (this.status >= 200 && this.status < 400) { 
869         callbackFunction('success', this.response);
870      } else {   
871         callbackFunction('error', this.response);
872      }  
873   };
874   //request.onerror = function(error) {  console.log(error);   };
875   request.send(dataToSend);
876}
877
878
879function brave_action_step(popupID, currentStep, stepIndex){
880   //console.log(popupID, stepIndex);
881   var selectedPopupStep = document.querySelector('#brave_popup_'+popupID+'__step__'+stepIndex+' .brave_popup__step__'+brave_currentDevice)
882   var noMobileContent = selectedPopupStep && selectedPopupStep.dataset.nomobilecontent === 'true' ? true : false;
883   var currentDevice = noMobileContent ? 'desktop' : brave_currentDevice;
884   var selectedPopupStep = document.querySelector('#brave_popup_'+popupID+'__step__'+currentStep+' .brave_popup__step__'+currentDevice)
885   selectedPopupStep.dataset.popopen = 'false';
886   brave_open_popup(popupID, stepIndex);
887   
888}
889
890
891function brave_init_popup(popupID, popupData ){
892   //console.log(popupID, popupData);
893   if(!popupData){ return; }
894   brave_responsiveness(null, popupID, popupData);
895
896   //If is in Preview Mode force load the popup skinpping all the conditions
897   if(popupData.forceLoad){
898      return brave_load_popup(popupID, popupData);  
899   }
900
901   var triggerType = popupData.settings && popupData.settings.trigger && popupData.settings.trigger.triggerType ? popupData.settings.trigger.triggerType.split(',') : ['load'];
902
903   //Do not load if campaign has ad block detection enabled and user has Ad blocker Installed.
904   if(popupData.settings && popupData.settings.placement && popupData.settings.placement.adblock_check && window.brave_canRunAds){
905      return console.log('Visitor Doesnt have Ad Blocked Installed! Aborting..');
906   }
907   //Do not Load if embedded popups if the shortcode is not present in current page
908   if((popupData.hasDesktopEmbed || (popupData.hasMobileEmbed && brave_currentDevice === 'mobile')) && !document.getElementById('bravepopup_embedded_'+popupID)){
909      return console.log('Popup shortcode is not found in current page');
910   }
911
912   //Do not load if Popup is not in Scheduled Dates
913   if(popupData.schedule && popupData.schedule.active && popupData.schedule.type){
914      if(popupData.schedule.type === 'days' && popupData.schedule.days.length > 0){
915         var currentDay = new Date().getDay();
916         if(!popupData.schedule.days.includes(currentDay)){
917            return console.log('Popup Not Scheduled for Today!');
918         }
919      }
920      if(popupData.schedule.type === 'dates' && popupData.schedule.dates.length > 0){
921         var thecurrentDate = new Date().getTime();
922         var dateInRange = false;
923         popupData.schedule.dates.forEach(function(date){
924            var theTimes = []; var timeTypes = ['start', 'end'];
925            timeTypes.forEach(function(val){
926               var theDate = date[val].date.split('/');
927               var theHour = date[val].time && date[val].time.hour ? date[val].time.hour : '00';
928               var theMinutes = date[val].time && date[val].time.minutes ? date[val].time.minutes : '00';
929               theTimes.push(new Date(theDate[2]+'/'+theDate[1]+'/'+theDate[0]+' '+theHour+':'+theMinutes+':00').getTime());
930            })
931            if(theTimes[0] < thecurrentDate && theTimes[1] > thecurrentDate){
932               dateInRange = true;
933            }
934         });
935         if(!dateInRange){
936            return console.log('Popup Not Scheduled these dates!');
937         }
938      }
939   }
940
941   //Do not Load if Device Settings doesnt Match
942   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');  }
943   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');  }
944
945
946   var popVariants = brave_popup_data[popupID] && brave_popup_data[popupID].variants ? brave_popup_data[popupID].variants : false;
947   var popupRepeatCountType = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeatCountType || 'lifetime';
948   var popupRepeatDelay = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeatDelay || false;
949   var popupRepeatDelayTime = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeatDelayTime ? parseInt(popupData.settings.frequency.repeatDelayTime, 10) : false;
950   var repeatCount = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeatCount ? parseInt(popupData.settings.frequency.repeatCount, 10) : 3;
951
952   //Do not load if Opened n Times already
953   var filterViewFreq = function(popID){
954      var popupOpenCount = localStorage.getItem('brave_popup_'+popID+'_viewed'); var popupOpenSessionCount = sessionStorage.getItem('brave_popup_'+popID+'_viewed');
955
956      if(popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeat && brave_popup_adminUser === false ){  
957         if(popupRepeatCountType === 'lifetime' && parseInt(popupOpenCount, 10) >= repeatCount){
958            return 'Already Viewed '+repeatCount+' Times. Hiding..';  
959         }
960         var popupViewStat = localStorage.getItem('brave_popup_'+popID+'_view_stat'); popupViewStat = popupViewStat ? JSON.parse(popupViewStat) : [];
961         var thecurrentDate = new Date(); var thecurrentDay = thecurrentDate.getDate();  var thecurrentHour = thecurrentDate.getHours(); var thecurrentMonth = thecurrentDate.getMonth(); var thecurrentYear = thecurrentDate.getFullYear();
962         var popupViewDayCount = 0; var popupViewMonthCount = 0; var popupView12hCount = 0; var popupView6hCount = 0; var popupView1hCount = 0; var matchedStats = [];
963         if(popupViewStat){
964            popupViewStat.forEach(function(stat){
965               var statDate = new Date(stat); var statDay = statDate.getDate(); var statHour = statDate.getHours();  var statMonth = statDate.getMonth(); var statYear = statDate.getFullYear();
966               if((statDay === thecurrentDay) && (statMonth === thecurrentMonth) && (statYear === thecurrentYear)){  popupViewDayCount = popupViewDayCount + 1;   }
967               if((statMonth === thecurrentMonth) && (statYear === thecurrentYear)){  popupViewMonthCount = popupViewMonthCount + 1;   }
968               if((thecurrentHour - statHour) < 12 && (statDay === thecurrentDay) && (statMonth === thecurrentMonth) && (statYear === thecurrentYear)){  popupView12hCount = popupView12hCount + 1;   }
969               if((thecurrentHour - statHour) < 6 && (statDay === thecurrentDay) && (statMonth === thecurrentMonth) && (statYear === thecurrentYear)){   popupView6hCount = popupView6hCount + 1;   }
970               if((thecurrentHour - statHour) < 1 && (statDay === thecurrentDay) && (statMonth === thecurrentMonth) && (statYear === thecurrentYear)){   popupView1hCount = popupView1hCount + 1;   }
971               if(!matchedStats.includes(stat)){   matchedStats.push(stat);   }
972            })
973         }
974         matchedStats = matchedStats.sort();
975         var lastViewedTime = matchedStats.length > 0 ? matchedStats[matchedStats.length - 1] : 0;
976         var viewDelayMatched = popupRepeatDelay && popupRepeatDelayTime ? (thecurrentDate.getTime() - lastViewedTime) > popupRepeatDelayTime : true;
977         var viewCountError = 'Already Viewed '+repeatCount+' Times in last '+popupRepeatCountType+' Hiding..'
978         console.log(lastViewedTime, thecurrentDate.getTime(), popupRepeatDelayTime, (thecurrentDate.getTime() - lastViewedTime) > popupRepeatDelayTime);
979         if(viewDelayMatched){
980            console.log(lastViewedTime, thecurrentDate.getTime(), popupRepeatDelayTime, (thecurrentDate.getTime() - lastViewedTime) > popupRepeatDelayTime);
981            if(popupRepeatCountType === '12h' && (parseInt(popupView12hCount, 10) >= repeatCount)){   return viewCountError;    }
982            if(popupRepeatCountType === '6h' && (parseInt(popupView6hCount, 10) >= repeatCount)){   return viewCountError;    }
983            if(popupRepeatCountType === '1h' && (parseInt(popupView1hCount, 10) >= repeatCount)){   return viewCountError;    }
984            if(popupRepeatCountType === 'session' && (parseInt(popupOpenSessionCount, 10) >= repeatCount) ){   return viewCountError;    }
985            if(popupRepeatCountType === 'day' && (parseInt(popupViewDayCount, 10) >= repeatCount)){   return viewCountError;    }
986            if(popupRepeatCountType === 'month' && (parseInt(popupViewMonthCount, 10) >= repeatCount) ){   return viewCountError;    }
987         }else{
988            return 'Repeat Delay Doesnt Match! Hiding....';
989         }
990      }
991
992      return false;
993   }
994
995   //Do not load if Closed n Times already
996   var filterCloseFreq = function(popID){
997      var popupCloseStat = localStorage.getItem('brave_popup_'+popID+'_closed') ? JSON.parse(localStorage.getItem('brave_popup_'+popID+'_closed')) : null;
998      if(popupData.settings && popupData.settings.frequency && popupData.settings.frequency.close && popupCloseStat && popupCloseStat.closed){   
999         var popupCloseCount = popupData.settings.frequency.closeCount ? popupData.settings.frequency.closeCount : 2; 
1000         var popupCloseFor = popupData.settings.frequency.closeFor ? parseInt(popupData.settings.frequency.closeFor, 10) * 86400 * 1000 : 86400 * 1000 * 30;
1001         var userCloseCount = parseInt(popupCloseStat.closed, 10);
1002         var userCloseDate = parseInt(popupCloseStat.closeTime, 10);
1003         var currentDate = new Date().getTime();
1004         var closeTimeDiff = currentDate - userCloseDate;
1005         var closeDelayMatched = popupRepeatDelay && popupRepeatDelayTime ? (currentDate - userCloseDate) > popupRepeatDelayTime : true;
1006         console.log('##### CLOSING STATS',userCloseCount, popupCloseFor,closeTimeDiff, closeTimeDiff >= popupCloseFor, userCloseCount >= popupCloseCount, closeDelayMatched, currentDate - userCloseDate);
1007         if((closeTimeDiff <= popupCloseFor && (userCloseCount >= popupCloseCount )) || !closeDelayMatched){
1008            return 'Close Time Settings Do not Match';
1009         }
1010      }
1011   }
1012
1013
1014   var viewFreqMatch = false; var closeFreqMatch = false; var formFreqMatch = false; goalFreqmatch = false;
1015   var hasViewFreqSetting = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeat && brave_popup_adminUser === false;
1016   var hasCloseFreqSetting = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.close && brave_popup_adminUser === false;
1017   var formFreqSetting = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.formSubmit && brave_popup_adminUser === false;
1018   var goalFreqSetting = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.goalComplete && brave_popup_adminUser === false;
1019
1020   if(popVariants.length > 0){
1021      popVariants.forEach(function(popID){
1022         if(!viewFreqMatch && hasViewFreqSetting){
1023            var popViewFreqMatch = filterViewFreq(popID);
1024            if(popViewFreqMatch){
1025               viewFreqMatch = popViewFreqMatch;
1026            }
1027         }
1028         if(!closeFreqMatch && hasCloseFreqSetting){
1029            var popCloseFreqMatch = filterCloseFreq(popID);
1030            if(popCloseFreqMatch){
1031               closeFreqMatch = popCloseFreqMatch;
1032            }
1033         }
1034         if(!formFreqMatch && formFreqSetting && localStorage.getItem('brave_popup_'+popID+'_formsubmitted')){
1035            formFreqMatch = true;
1036         }
1037         if(!goalFreqmatch && goalFreqSetting && localStorage.getItem('brave_popup_'+popID+'_goal_complete')){
1038            goalFreqmatch = true;
1039         }
1040      })
1041   }else{
1042      if(hasViewFreqSetting){
1043         viewFreqMatch = filterViewFreq(popupID);
1044      }
1045      if(hasCloseFreqSetting){
1046         closeFreqMatch = filterCloseFreq(popupID);
1047      }
1048      if(!formFreqMatch && formFreqSetting && localStorage.getItem('brave_popup_'+popupID+'_formsubmitted')){
1049         formFreqMatch = true;
1050      }
1051      if(!goalFreqmatch && goalFreqSetting && localStorage.getItem('brave_popup_'+popupID+'_goal_complete')){
1052         goalFreqmatch = true;
1053      }
1054   }
1055
1056   //Do not Load if the popup is already viewed x times.
1057   if(viewFreqMatch && hasViewFreqSetting){
1058      return console.log('[Viewed Frequency]',  popupID, viewFreqMatch);;
1059   }
1060   //Do not Load if the popup is already closed x times.
1061   if(closeFreqMatch && hasCloseFreqSetting){
1062      return console.log('[Closed Frequency]',  popupID, closeFreqMatch);;
1063   }
1064   //Do not Load if a Form Submitted in this Popup
1065   if(formFreqMatch && formFreqSetting){
1066      return console.log('[Form Frequency]',  popupID, 'Form in this Popup already Submitted! Hiding..');
1067   }
1068   //Do not Load if a Campaign Goal is completed already
1069   if(goalFreqmatch && goalFreqSetting){
1070      return console.log('[Goal Frequency]',  popupID, 'Popup Goal Already Completed..');
1071   }
1072
1073   //Do not Load if Popups Countdown Timer has ended
1074   if(popupData.settings && popupData.settings.frequency && popupData.settings.frequency.timerEnded && popupData.timers.length > 0){
1075      const timerData = popupData.timers.find(item => item.device === brave_currentDevice);
1076      let hasEnded = false;
1077      if(timerData && timerData.endTime && new Date() > new Date(timerData.endTime) && timerData.auto === false) {
1078         hasEnded = true;
1079      }
1080      if(timerData && timerData.auto){
1081         const autoEndTime = localStorage.getItem(timerData.auto);
1082         if(new Date() > new Date(autoEndTime)){
1083            hasEnded = true;
1084         }
1085      }
1086      if(hasEnded){
1087         return console.log('Popup Countdown Timer Ended! Hiding..');
1088      }
1089   }
1090
1091   //Do not Load if a certain popup was not viewed/goaled/closed before
1092   if(popupData.settings && popupData.settings.filters && popupData.settings.filters.popups_before && popupData.settings.filters.popups.length > 0){
1093      var popupFilterFulfilled = false;
1094      popupData.settings.filters.popups.forEach(function (popup) {
1095         if(!popupFilterFulfilled && popup.id && popup.action){
1096            var popupActionNegative = popup.action.includes('not_')
1097            var popActionKey = popupActionNegative ? popup.action.replace('not_', '') : popup.action
1098            var popupActionMatched = localStorage.getItem('brave_popup_'+popup.id+'_'+popActionKey);
1099            if(!popupActionNegative && popupActionMatched){  popupFilterFulfilled = true;  }
1100            if(popupActionNegative && !popupActionMatched){  popupFilterFulfilled = true;  }
1101         }
1102      })
1103      if(!popupFilterFulfilled){
1104         return console.log('A selected Popup was not viewed before! Hiding..');
1105      }
1106   }
1107
1108   //Custom Cookie Conditions 
1109   if(popupData.settings && popupData.settings.filters && popupData.settings.filters.cookieFilter && popupData.settings.filters.cookies && popupData.settings.filters.cookies.length > 0 ){
1110      var cookieMatched = false;
1111      popupData.settings.filters.cookies.forEach(function(cookie){
1112         if(!cookieMatched && cookie.action === 'has' && cookie.key  && localStorage.getItem(cookie.key) ){   cookieMatched = true; }
1113         if(!cookieMatched && cookie.action === 'nothas' && cookie.key  && !localStorage.getItem(cookie.key) ){   cookieMatched = true; }
1114         if(!cookieMatched && cookie.action === 'equal' && cookie.key && cookie.value && localStorage.getItem(cookie.key) === cookie.value ){   cookieMatched = true; }
1115         if(!cookieMatched && cookie.action === 'notequal' && cookie.key && cookie.value && localStorage.getItem(cookie.key) !== cookie.value ){   cookieMatched = true; }
1116      })
1117      if(cookieMatched === false){   return console.log('Visitor Cookie did not match! Hiding..'); }
1118   }
1119
1120   //Do not Load if page view count did not match
1121   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)) ){
1122      var viewCountLimit = parseInt(popupData.settings.filters.pagecount, 10);
1123      var current_page_view_data = localStorage.getItem('brave_page_visited'); 
1124      current_page_view_data = current_page_view_data ? JSON.parse(current_page_view_data) : [];
1125      if(popupData.settings.filters.pages_count_filter && popupData.settings.filters.pagecount && current_page_view_data && (current_page_view_data.length < viewCountLimit)){
1126         return console.log('Visitor did not view enough pages to show the popup! Hiding..');
1127      }
1128      //Do not Load if Visitor Did Not View selected pages before
1129      var pageConditionMatch = []; var viewConditionMatched = true;
1130      if(popupData.settings.filters.pages_before && popupData.settings.filters.pages && popupData.settings.filters.pages.length > 0){
1131         var pagesmatched = [];
1132         var braveMatchPageViewTime = function(timeLimit, viewTime){
1133            if(!timeLimit){ return true; }
1134            if(viewTime > timeLimit){ return true; }else{ return false; }
1135         }
1136         var braveCheckIfViewedPageMatch = function(pageCond, checkExistence=true, timeLimit) {
1137            var pageCondID = pageCond.id; var pageCondType = pageCond.type; var conditionMatched = false;
1138            current_page_view_data.forEach(function(pgView){
1139               var timeMatch = braveMatchPageViewTime(timeLimit, pgView.time);
1140               var pageMatch = pgView.PID === pageCondID && pgView.type === pageCondType && timeMatch;
1141               if(pageMatch && checkExistence){ conditionMatched = true;  }  
1142            })
1143            return conditionMatched;
1144         }
1145         var braveCheckIfNotViewedPageMatch = function(pageCond, checkExistence=false, timeLimit) {
1146            var pageCondID = pageCond.id; var pageCondType = pageCond.type; var conditionMatched = true;
1147            current_page_view_data.forEach(function(pgView){
1148               var timeMatch = braveMatchPageViewTime(timeLimit, pgView.time);
1149               var pageMatch = pgView.PID === pageCondID && pgView.type === pageCondType && timeMatch;
1150               if(pageMatch && !checkExistence){ conditionMatched = false;  }
1151            })
1152            return conditionMatched;
1153         }
1154         popupData.settings.filters.pages.forEach(function(pageCond){
1155            var currentTime = new Date().getTime(); var timeLimit  =  currentTime - 10800000;  if(pageCond.duration === 'lifetime' ){ timeLimit = false;}
1156            if(pageCond.duration === '1day' ){ timeLimit = currentTime - 86400000;} if(pageCond.duration === '7days' ){ timeLimit = currentTime - 604800000;} if(pageCond.duration === '30days' ){ timeLimit = currentTime - 2592000000;}
1157            var condMatch = pageCond.action.includes('not_viewed') ? braveCheckIfNotViewedPageMatch(pageCond, false, timeLimit) : braveCheckIfViewedPageMatch(pageCond, true, timeLimit);
1158            pagesmatched.push({matched: condMatch, forced: pageCond.condition === 'and' ? true : false });
1159         })
1160
1161         pagesmatched.forEach(function(matchItm) {
1162            if(matchItm.forced === true &&  matchItm.matched === true){ pageConditionMatch.push(true); }
1163            if(matchItm.forced === true &&  matchItm.matched === false){ pageConditionMatch.push(false); }
1164            if(matchItm.forced === false &&  (matchItm.matched === true || matchItm.matched === false )){ pageConditionMatch.push(true); }
1165         })
1166         pageConditionMatch.forEach(function(bool){ if(bool===false){ viewConditionMatched = false; } })
1167
1168         if(!viewConditionMatched){
1169            return console.log('Visitor did not view the selected pages before to show the popup! Hiding..');
1170         }
1171
1172      }
1173   }
1174
1175   if(triggerType.includes('load')){   brave_load_popup(popupID, popupData, 'load');   }
1176
1177   if(triggerType.includes('exit')){
1178      if(brave_currentDevice === 'mobile'){
1179         if(!popupData.settings.trigger.exitMobileFallback || (popupData.settings.trigger.exitMobileFallback && popupData.settings.trigger.exitMobileFallback.type && popupData.settings.trigger.exitMobileFallback.type === 'load')){
1180            brave_load_popup(popupID, popupData,'load');
1181         }
1182         if(popupData.settings.trigger.exitMobileFallback && popupData.settings.trigger.exitMobileFallback.type && popupData.settings.trigger.exitMobileFallback.type === 'time'){
1183            var exitMobileDelay = popupData.settings.trigger.exitMobileFallback.time || 2000;
1184            setTimeout(function() {    brave_load_popup(popupID, popupData , 'time');  }, (exitMobileDelay * 1000));
1185         }
1186      }else{
1187         document.addEventListener("mouseout", function(evt){
1188            if((evt.toElement === null || evt.toElement === undefined) && (evt.relatedTarget === null)) {
1189                brave_load_popup(popupID, popupData, 'exit');
1190            }
1191         });
1192      }
1193   }
1194
1195   if(triggerType.includes('scroll') || (brave_isMobile && popupData.settings.trigger.exitMobileFallback && popupData.settings.trigger.exitMobileFallback.type  && popupData.settings.trigger.exitMobileFallback.type ==='scroll')){
1196      var currentPopup = document.getElementById('brave_popup_'+popupID+'__step__0'); 
1197      var noMobileContent = currentPopup && currentPopup.classList.contains('brave_popup__step--mobile-noContent') === true ? true : false;
1198      var currentDevice = noMobileContent ? 'desktop' : brave_currentDevice;
1199      var scrollHide = popupData.settings && popupData.settings.trigger && popupData.settings.trigger.scrollHide ? true : false;
1200      var scrollTriggerPopup = function(scrollPercent, percentLimit=20, currentPopStep, currentPopStepVisible, between=false){
1201         var scrollPercentVal = between && percentLimit.split('-');
1202         var startScrollPercent = scrollPercentVal && scrollPercentVal[0] && parseInt(scrollPercentVal[0], 10);
1203         var endScrollPercent = scrollPercentVal && scrollPercentVal[1] && parseInt(scrollPercentVal[1], 10);
1204
1205         if(brave_popup_data[popupID].userClosed){ return; }
1206         if((!between && (scrollPercent >= percentLimit)) || ((between && !isNaN(startScrollPercent) && !isNaN(endScrollPercent)) && ((scrollPercent >= startScrollPercent) && (scrollPercent <= endScrollPercent)) )){  
1207            if(!brave_popup_data[popupID].loaded){   brave_load_popup(popupID, popupData, 'scroll'); }else{  if(!currentPopStepVisible){brave_open_animation(popupID, 0, currentDevice);   currentPopStep.dataset.popopen = true; } } 
1208         }else{ 
1209            if((between || scrollHide) && currentPopStepVisible){  brave_close_animation(popupID, 0, currentDevice); currentPopStep.dataset.popopen = false; brave_popup_data[popupID].isOpen = false;  } 
1210         }
1211      }
1212      document.addEventListener("scroll", function(evt){
1213         var h = document.documentElement,  b = document.body, st = 'scrollTop', sh = 'scrollHeight';
1214         var scrollPercent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
1215         var currentPopStep = document.querySelector('#brave_popup_'+popupID+'__step__0 .brave_popup__step__'+currentDevice); 
1216         var currentPopStepVisible = currentPopStep && currentPopStep.dataset.popopen === 'true' ? true : false;
1217
1218         if( brave_isMobile && (popupData.settings.trigger.exitMobileFallback && popupData.settings.trigger.exitMobileFallback.type && popupData.settings.trigger.exitMobileFallback.type ==='scroll')){
1219            var exitMobielScroll = popupData.settings.trigger.exitMobileFallback.scroll || 15;
1220            if(scrollPercent >= exitMobielScroll){   brave_load_popup(popupID, popupData, 'scroll');   }
1221         }
1222
1223         if(popupData.settings && popupData.settings.trigger.scrolltype && popupData.settings.trigger.scrolltype !== 'between'){
1224            var srollTargetAmnt = 0;
1225            if(popupData.settings.trigger.scrolltype === 'ten') {  srollTargetAmnt = 10}
1226            if(popupData.settings.trigger.scrolltype === 'twenty') {  srollTargetAmnt = 20}
1227            if(popupData.settings.trigger.scrolltype === 'thirty') {  srollTargetAmnt = 30}
1228            if(popupData.settings.trigger.scrolltype === 'forty') {  srollTargetAmnt = 40}
1229            if(popupData.settings.trigger.scrolltype === 'half') {  srollTargetAmnt = 50}
1230            if(popupData.settings.trigger.scrolltype === 'sixty') {  srollTargetAmnt = 60}
1231            if(popupData.settings.trigger.scrolltype === 'seventy') {  srollTargetAmnt = 70}
1232            if(popupData.settings.trigger.scrolltype === 'eighty') {  srollTargetAmnt = 80}
1233            if(popupData.settings.trigger.scrolltype === 'end') {  srollTargetAmnt = 95}
1234            scrollTriggerPopup(scrollPercent, srollTargetAmnt, currentPopStep, currentPopStepVisible);
1235         }
1236         if(popupData.settings && popupData.settings.trigger && popupData.settings.trigger.scrolltype === 'between' && popupData.settings.trigger.scrollBetween && popupData.settings.trigger.scrollBetween.includes('-')){
1237            scrollTriggerPopup(scrollPercent, popupData.settings.trigger.scrollBetween, currentPopStep, currentPopStepVisible, true);
1238         }
1239
1240         if(popupData.settings && popupData.settings.trigger.scrolltype && popupData.settings.trigger.scrollto && popupData.settings.trigger.scrolltype === 'custom' ){
1241            var scrollToIDs = popupData.settings.trigger.scrollto || ''; 
1242            var scrolltoElms = scrollToIDs && document.querySelectorAll(scrollToIDs);
1243            //console.log(scrolltoElms);
1244            if(scrollToIDs && scrolltoElms){
1245               for (var i = 0; i < scrolltoElms.length; i++) { 
1246                  var scrolltoElm = scrolltoElms[i]; 
1247                  if(scrolltoElm && brave_is_in_view(scrolltoElm)){
1248                     brave_load_popup(popupID, popupData, 'scroll');  
1249                  }
1250               }
1251            }
1252         }
1253      }, {passive: true});
1254   }
1255
1256   if(popupData.settings && popupData.settings.content && popupData.settings.content.highlight){
1257      document.addEventListener("scroll", function(evt){
1258         var contentElm = document.querySelector('.bravepopup_embedded--highlight_'+popupID);
1259         var contenthlElm = document.getElementById('bravepopup_embedded__bg_'+popupID);
1260         var contentAlreadyHighlighted = false; 
1261         if(popupData.settings.content.highlight === 'once'){ contentAlreadyHighlighted = contentElm.classList.contains('bravepopup_embedded__highlight--done') ? true : false;}
1262         if(contentElm && (popupData.settings.content.highlight === 'always' || (!contentAlreadyHighlighted && popupData.settings.content.highlight === 'once'))){
1263            var embeddedContentRect = contentElm.getBoundingClientRect();
1264            var embeddedViewRatio = (embeddedContentRect.top / document.documentElement.clientHeight)*100;
1265            if((embeddedViewRatio < 50 && embeddedViewRatio > -20 ) && !contenthlElm.classList.contains('bravepopup_embedded__bg--active')){
1266               contenthlElm.classList.add('bravepopup_embedded__bg--active'); contentElm.classList.add('bravepopup_embedded__highlight--active');
1267            }
1268            if((embeddedViewRatio < -20 || embeddedViewRatio > 50) && contenthlElm.classList.contains('bravepopup_embedded__bg--active')){
1269               contenthlElm.classList.remove('bravepopup_embedded__bg--active'); contentElm.classList.remove('bravepopup_embedded__highlight--active');
1270               if(popupData.settings.content.highlight){   contentElm.classList.add('bravepopup_embedded__highlight--done');  }
1271            }
1272         }
1273      }, {passive: true});
1274   }
1275
1276
1277   if(triggerType.includes('click') && popupData.settings && popupData.settings.trigger.clickElements){
1278      var clickElms = document.querySelectorAll(popupData.settings.trigger.clickElements);
1279      //console.log(clickElms);
1280      
1281      if(clickElms){
1282         for (var i = 0; i < clickElms.length; i++) { 
1283            var clickElm = clickElms[i]; 
1284            clickElm.addEventListener("click", function(evt){
1285               evt.preventDefault();
1286               document.getElementById('brave_popup_'+popupID).style.zIndex = 9999999999;
1287               brave_load_popup(popupID, popupData, 'click');
1288            });
1289         }
1290      }
1291   }
1292
1293   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)){
1294      var triggerHours = popupData.settings.trigger.time.hours ? parseInt(popupData.settings.trigger.time.hours, 10) : 0;
1295      var triggerMinutes = popupData.settings.trigger.time.minutes ? parseInt(popupData.settings.trigger.time.minutes, 10) : 0;
1296      var triggerSeconds = popupData.settings.trigger.time.seconds ? parseInt(popupData.settings.trigger.time.seconds, 10) : 0;
1297
1298      var totalTriggerDelay = (triggerHours * 3600) + (triggerMinutes * 60) + (triggerSeconds);
1299      totalTriggerDelay = totalTriggerDelay * 1000;
1300      //console.log(triggerHours, triggerMinutes, triggerSeconds, totalTriggerDelay);
1301      
1302      setTimeout(function() {
1303          brave_load_popup(popupID, popupData , 'time');
1304      }, totalTriggerDelay);
1305
1306   }
1307
1308
1309   
1310}
1311
1312function brave_load_popup(popupID, popupData, triggerType='load'){
1313   if(brave_popup_data[popupID] && brave_popup_data[popupID].ajaxLoad && !brave_popup_data[popupID].ajaxLoaded){
1314      if(brave_popup_data[popupID].ajaxLoading !== true){
1315         var loadData = { popupID: popupID, type: brave_popup_data[popupID].type, security: bravepop_global.security, current_url: location.href ,action: 'bravepop_ajax_load_popup_content' };
1316         brave_popup_data[popupID].ajaxLoading = true;
1317         brave_ajax_send(bravepop_global.ajaxURL, loadData, function(status, sentData){
1318            // console.warn('Ajax Load Popup!!', popupID, brave_popup_data[popupID].ajaxLoading);
1319            brave_popup_data[popupID].ajaxLoaded = true;
1320            brave_popup_data[popupID].ajaxLoading = false;
1321            var selectedPopup = document.getElementById('brave_popup_'+popupID);
1322            if(selectedPopup){
1323               selectedPopup.innerHTML = sentData;
1324               brave_process_open_popup(popupID, popupData, triggerType);
1325            }
1326         });
1327      }
1328   }else{
1329      brave_process_open_popup(popupID, popupData, triggerType);
1330   }
1331}
1332
1333
1334function brave_process_open_popup(popupID, popupData, triggerType='load'){
1335   var selectedPopup = document.getElementById('brave_popup_'+popupID);
1336   var popupLoadStatus = selectedPopup ? selectedPopup.dataset.loaded : 'fal
1336se';
1337   if(popupLoadStatus === 'false'){
1338      //LOAD ASSETS
1339      //--------------------
1340         //Load Video Scripts
1341         if(popupData.hasYoutube){
1342            var YTtag = document.createElement('script'); YTtag.src = "https://www.youtube.com/iframe_api";
1343            var PageFirstScript_YT = document.getElementsByTagName('script')[0]; PageFirstScript_YT.parentNode.insertBefore(YTtag, PageFirstScript_YT);
1344         }
1345         if(popupData.hasVimeo){
1346            var VimTag = document.createElement('script'); VimTag.src = "https://player.vimeo.com/api/player.js";
1347            var PageFirstScript_Vim = document.getElementsByTagName('script')[0]; PageFirstScript_Vim.parentNode.insertBefore(VimTag, PageFirstScript_Vim);
1348         }
1349         
1350         //Load the DatePicker
1351         var dateFields = document.querySelectorAll('.brave_form_field--date');
1352         if(window.brave_initPikaday && dateFields && dateFields.length > 0 ){
1353            for (var i = 0, len = dateFields.length; i < len; i++) {
1354               var dateField = dateFields[i];
1355               var startDate = dateField.dataset.startdate ? dateField.dataset.startdate : '';
1356               var endDate = dateField.dataset.enddate ? dateField.dataset.enddate : '';
1357               var dateInput = dateField.querySelector('input');
1358               brave_initPikaday(dateInput, startDate, endDate);
1359            }
1360         }
1361
1362         selectedPopup.dataset.loaded = true;
1363   }
1364
1365   //Open Popup
1366   //---------------------
1367   let step = popupData.forceLoad && popupData.forceStep? parseInt(popupData.forceStep, 10) - 1 : 0;
1368   if(brave_popup_data[popupID].settings && brave_popup_data[popupID].settings.frequency && brave_popup_data[popupID].settings.frequency.rememberLastStep){
1369      let foundLastStep = localStorage.getItem('brave_popup_'+popupID+'_last_viewed_step');
1370      if(foundLastStep !==undefined && foundLastStep !==null){
1371         step = foundLastStep;
1372      }
1373   }
1374   if(triggerType === 'exit' || triggerType === 'scroll' || triggerType === 'time'){
1375      var triggerFulFilled = document.getElementById('brave_popup_'+popupID).dataset.triggerfulfilled;
1376      console.log('triggerFulFilled: ', triggerFulFilled);
1377      if(!triggerFulFilled){
1378         document.getElementById('brave_popup_'+popupID).dataset.triggerfulfilled = true;
1379         brave_open_popup(popupID, step);
1380      }
1381   }else{
1382      brave_open_popup(popupID, step);
1383   }
1384
1385   if(brave_popup_data[popupID] && !brave_popup_data[popupID].loaded){  brave_popup_data[popupID].loaded = true; }
1386}
1387
1388
1389function brave_open_popup(popupID, step=0){
1390   var popupData = brave_popup_data[popupID];
1391   var selectedPopupStep = document.querySelector('#brave_popup_'+popupID+'__step__'+step+' .brave_popup__step__'+brave_currentDevice)
1392   var noMobileContent = selectedPopupStep && selectedPopupStep.dataset.nomobilecontent === 'true' ? true : false;
1393   var currentDevice = noMobileContent ? 'desktop' : brave_currentDevice;
1394   var selectedPopupStep = document.querySelector('#brave_popup_'+popupID+'__step__'+step+' .brave_popup__step__'+currentDevice);
1395   var popupStepOpen = selectedPopupStep ? selectedPopupStep.dataset.popopen : 'false';
1396   var hasLockScroll = selectedPopupStep.dataset.scrollock ?  true : false;
1397   var stickyBar = selectedPopupStep && selectedPopupStep.dataset.layout === 'float' && selectedPopupStep.dataset.position === 'top_center' ? true : false;
1398   
1399   if(popupStepOpen !== 'false'){ return }
1400   if(!popupData){ return }
1401   if(popupData && popupData.forceHide){ return console.log(popupID, 'Force Hidden'); }
1402
1403   console.log('Opening ', popupID, step, popupStepOpen, stickyBar, noMobileContent, currentDevice);
1404   //Set Current Step
1405   brave_popup_data[popupID].currentStep = step;
1406
1407   //Send Ajax View Stat Data
1408   if(window.location.href.includes('brave_popup') === false && window.location.href.includes('braveshot') === false && !brave_popup_data[popupID].viewStatSent){ 
1409      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;
1410      if(brave_popup_data[popupID] && brave_popup_data[popupID].settings && brave_popup_data[popupID].settings.goalAction && 
1411      brave_popup_data[popupID].settings.goalAction.type === 'step' && brave_popup_data[popupID].settings.goalAction.step === 0 ){  goalIsFirstView = true;  } 
1412      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' };
1413      brave_ajax_send(bravepop_global.ajaxURL, viewData, function(status, sentData){
1414         // console.log('Popup View Updated: ', status, JSON.parse(sentData));
1415         brave_popup_data[popupID].viewStatSent = true;
1416      });
1417   }
1418   //Set Popup Viewed Cookie
1419   var currentPopupStat = localStorage.getItem('brave_popup_'+popupID+'_viewed');
1420   localStorage.setItem('brave_popup_'+popupID+'_viewed', currentPopupStat ? parseInt(currentPopupStat, 10) + 1 : 1);
1421   var popupRepeat =popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeat
1422   var popupRepeatCountType = popupData.settings && popupData.settings.frequency && popupData.settings.frequency.repeatCountType || 'lifetime';
1423   if(popupRepeat && popupRepeatCountType !== 'lifetime'){
1424      var theViewStat = localStorage.getItem('brave_popup_'+popupID+'_view_stat'); theViewStat = theViewStat ? JSON.parse(theViewStat) : [];
1425      theViewStat.push(new Date().getTime());      
1426      localStorage.setItem('brave_popup_'+popupID+'_view_stat', JSON.stringify(theViewStat));
1427   }
1428
1429   if(popupRepeat && popupRepeatCountType === 'session'){
1430      var currentSessionPopupViews = sessionStorage.getItem('brave_popup_'+popupID+'_viewed') || 0;
1431      sessionStorage.setItem('brave_popup_'+popupID+'_viewed', parseInt(currentSessionPopupViews, 10)+1);
1432   }
1433
1434   //Scroll Lock
1435   if(hasLockScroll){
1436      document.body.classList.add('brave_scroll_lock')
1437   }
1438
1439   //Stickybar - Add html top margin
1440   if(stickyBar){
1441      //console.log('Apply Sticky Margin');
1442      var popupHeight = selectedPopupStep.dataset.height;
1443      document.documentElement.style.setProperty('margin-top', popupHeight+'px', 'important');
1444   } 
1445
1446   //LazyLoad Images
1447   if(popupData.type !== 'content'){
1448      var allImages = selectedPopupStep.querySelectorAll('img');
1449      for (var i = 0; i < allImages.length; i++) { 
1450         if(allImages[i].dataset.lazy){
1451            allImages[i].src = allImages[i].dataset.lazy;
1452         }
1453      }
1454   }
1455
1456   //Stop currently Playing Videos First
1457   if(brave_popup_videos && brave_popup_videos[popupID] && Object.keys(brave_popup_videos).length > 0){
1458      Object.keys(brave_popup_videos[popupID]).forEach(function(playerID){
1459         if(playerID.includes('youtube') && brave_popup_videos[popupID][playerID] && brave_popup_videos[popupID][playerID].stopVideo){   brave_popup_videos[popupID][playerID].stopVideo();  }
1460         if(playerID.includes('vimeo') && brave_popup_videos[popupID][playerID] && brave_popup_videos[popupID][playerID].pause){   brave_popup_videos[popupID][playerID].pause();  }
1461         if(playerID.includes('custom') && brave_popup_videos[popupID][playerID] && brave_popup_videos[popupID][playerID].pause){   brave_popup_videos[popupID][playerID].pause();  }
1462      });
1463   }
1464   if(popupData.videoData && popupData.videoData[step] && popupData.videoData[step][currentDevice]){
1465      //console.log('HAS VIDEO!!!!!!!!!!!', popupData.videoData[step][currentDevice]);
1466      var videoObj = popupData.videoData[step][currentDevice];
1467      var videoType = videoObj.videoType ? videoObj.videoType : 'youtube';
1468      var videoURL = videoObj.videoUrl ? videoObj.videoUrl : 'youtube';
1469      var videoTracking = videoObj.action && videoObj.action.track && videoObj.action.trackData ? videoObj.action.trackData : null;
1470      var videoSettings = {id: videoObj.id, autoplay: videoObj.autoplay || false, controls: videoObj.controls || false, mute: videoObj.mute || false, tracking: videoTracking }
1471      brave_load_video(videoType, videoURL, videoSettings, popupID);
1472   }
1473
1474   //Replace Text element Shortcodes
1475   var elmsWithCookie = selectedPopupStep && selectedPopupStep.querySelectorAll('.brave_element--text_hasCookie .brave_element__text_inner');
1476   if(elmsWithCookie && elmsWithCookie.length > 0){
1477      brave_replace_dynamic_text_cookie(elmsWithCookie);
1478   }
1479
1480   var hasAnimation = popupData.hasAnimation ?  popupData.hasAnimation : false;
1481   var advancedAnimation = popupData.advancedAnimation ?  popupData.advancedAnimation : false;
1482   var hasContAnim = popupData.hasContAnim ?  popupData.hasContAnim : false;
1483   var animationData = popupData.animationData ?  popupData.animationData : {};
1484   var selectedStep = document.getElementById('brave_popup_'+popupID+'__step__'+step);
1485   if(!selectedStep){ return;}
1486
1487   var focusableElm = selectedStep.querySelector('.brave_popup--popup .brave_popupMargin__wrap');
1488   var closableFocus = selectedStep.querySelector('.brave_popup--popup .brave_popup__close');  
1489   if(closableFocus){   closableFocus.tabIndex = 0;  }
1490   if(focusableElm){ focusableElm.tabIndex = 0; setTimeout(() => {   focusableElm.focus();   }, 200);  }
1491   
1492   if(selectedStep){
1493      var allSteps = document.querySelectorAll('#brave_popup_'+popupID+' .brave_popup__step_wrap');
1494      if(allSteps){
1495         for (var i = 0; i < allSteps.length; i++) { 
1496            allSteps[i].classList.remove('brave_popup__step_wrap--show');
1497         }
1498      }
1499      var braveOpenEvent = new CustomEvent('brave_popup_open', { detail: {popupId: parseInt(popupID, 10), step: step} });
1500      document.dispatchEvent(braveOpenEvent);
1501
1502      //Open Animation
1503      if(!advancedAnimation){
1504         brave_open_animation(popupID, step, currentDevice);
1505      }
1506
1507      //Advanced Animation
1508      if(advancedAnimation && hasAnimation && animationData && brave_animate_popup){
1509         selectedStep.classList.add('brave_popup__step_wrap--show');
1510         brave_animate_popup(animationData, popupID, step, 'load');
1511      }
1512      //Continious Animation
1513      if(hasContAnim && animationData && animationData[step][currentDevice] && animationData[step][currentDevice].elements){
1514         var initialDelay = (animationData[step][currentDevice].totalDuration || 0) + 1200;
1515         animationData[step][currentDevice].elements.forEach(function(element){
1516            //console.log(element);
1517            
1518            if(element && element.animation && element.animation.continious){
1519               //console.log(element.id,element.animation.continious);
1520               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
1520d);
1521               var elementID = element.id === 'popup' ? popupID : element.id;
1522               var contAnimType = element.animation.continious.preset || 'none';
1523               var contAnimDuration = element.animation.continious.duration || 500;
1524               var contAnimDelay = element.animation.continious.delay || 0;
1525               if(theElement){
1526                  setTimeout(function() {
1527                     theElement.classList.add('brave_element-'+elementID+'_contAnim'); 
1528                     if(contAnimDelay > 0){
1529                        setInterval(function() {
1530                           theElement.classList.add('brave_element-'+elementID+'_contAnim'); 
1531                           setTimeout(function() {
1532                              theElement.classList.remove('brave_element-'+elementID+'_contAnim');
1533                           }, contAnimDuration);
1534                        }, ((contAnimDelay > contAnimDuration) ? contAnimDelay : contAnimDuration + contAnimDelay))
1535                     }
1536                  }, initialDelay);
1537               }
1538            }
1539
1540         })
1541
1542      }
1543
1544   }
1545   //Show Vertical Scrollbar if Necessary
1546   setTimeout(function() {
1547      var currentPopupDimension = selectedPopupStep.querySelector('.brave_popup__step__inner').getBoundingClientRect();
1548      if((window.innerHeight < currentPopupDimension.height) && selectedPopupStep.classList.contains('brave_popup__step--boxed') && selectedPopupStep.classList.contains('position_center')){
1549         selectedPopupStep.classList.add('brave_popup_exceeds_windowHeight');
1550         selectedPopupStep.classList.add('brave_popup_show_scrollbar');
1551         //document.body.classList.add('brave_HideBodyScroll-'+popupID);
1552      }
1553   }, 100);
1554
1555
1556   //Popup AutoClose
1557   //console.warn(popupData);
1558   if(popupData.close[0] && popupData.close[0][currentDevice] && popupData.close[0][currentDevice].autoClose && popupData.close[0][currentDevice].autoCloseDuration){
1559      setTimeout(function() {
1560         if(!brave_popup_data[popupID].autoClosed){
1561            brave_close_popup(popupID, step);
1562            if(popupData.close[0][currentDevice].closeStep !== 'undefined' && Number.isInteger(popupData.close[0][currentDevice].closeStep)){
1563               brave_open_popup(popupID, popupData.close[0][currentDevice].closeStep);
1564            }
1565         }
1566         brave_popup_data[popupID].autoClosed = true;
1567      }, parseInt(popupData.close[0][currentDevice].autoCloseDuration) * 1000);
1568   }
1569
1570   //Change the Popup Step open status
1571   selectedPopupStep.dataset.popopen = true;
1572   brave_popup_data[popupID].opened = new Date().getTime();
1573   brave_popup_data[popupID].isOpen = true;
1574
1575   //Complete Step Open Goal
1576   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 )){
1577      var goalStep = popupData.settings.goalAction && popupData.settings.goalAction.step ? popupData.settings.goalAction.step.toString().split(',') :['0'];
1578      if(goalStep.includes(step.toString()) && step !== 0){
1579         brave_complete_goal(popupID, 'view');
1580      }
1581   }
1582
1583   //If Code element is set to goal, attach submit event listener to complete goal
1584   var allCodeElmGoals = document.querySelectorAll('.brave_element__code--goaled form');
1585   if(allCodeElmGoals.length > 0){
1586      for (var i = 0; i < allCodeElmGoals.length; ++i) {
1587         allCodeElmGoals[i].addEventListener('submit', function () {    brave_complete_goal(popupID, 'form');    })
1588       }
1589   }
1590   if(brave_popup_data[popupID].settings && brave_popup_data[popupID].settings.frequency && brave_popup_data[popupID].settings.frequency.rememberLastStep){
1591      localStorage.setItem('brave_popup_'+popupID+'_last_viewed_step', step);
1592   }
1593
1594   // Close Button Delayed Appearance
1595   const closeProgressBar = selectedStep.querySelector('.brave_popup__close__progress-circle'); 
1596   if(closeProgressBar){
1597      const closeDuration = parseInt(closeProgressBar.dataset.duration, 10);
1598      const closeCircle = selectedStep.querySelector('.brave_popup__close__progress-ring-circle');   
1599      const closeRadius = closeCircle.r.baseVal.value;
1600      const circumference = closeRadius * 2 * Math.PI;
1601      let currentSecond = 0;
1602   
1603      window.braveCloseProgrss = setInterval(function() {
1604       if (currentSecond >= closeDuration / 1000) {
1605         clearInterval(window.braveCloseProgrss);
1606         closeProgressBar.style.display = 'none';
1607         selectedStep.querySelector('.brave_popup__close__button').style.display = 'block';
1608       }else{
1609         currentSecond++;
1610         const percent = currentSecond / (closeDuration / 1000) * 100;
1611         closeCircle.style.strokeDashoffset = circumference - (percent / 100 * circumference);
1612         selectedStep.querySelector('.brave_popup__close__progress-text').textContent = Math.round(closeDuration / 1000 - currentSecond)+'s';
1613       }
1614      }, 1000);
1615   }
1616
1617}
1618
1619function brave_open_animation(popupID, step, currentDevice){
1620   var totalDuration = brave_popup_data[popupID].animationData[step][currentDevice].totalDuration;
1621   var openAnimData = brave_popup_data[popupID].animationData[step][currentDevice].elements ? brave_popup_data[popupID].animationData[step][currentDevice].elements : [];
1622   var hasAnimation = brave_popup_data[popupID].hasAnimation;
1623   var selectedStep = document.querySelector('#brave_popup_'+popupID+'__step__'+step);
1624
1625   if(window.location.href.includes('braveshot') === true && window.location.href.includes('brave_id') === true){
1626      return selectedStep.classList.add('brave_popup__step_wrap--show');
1627   }
1628
1629   //console.log(popupID, step, currentDevice, openAnimData, selectedStep);
1630
1631   var brave_animateElement = function(elementID, selectedStep, elementDom, step, animType) {
1632      selectedStep.classList.add('brave_popup__step_wrap--show');
1633      if(animType === 'text'){
1634         var selected_text_element =  document.querySelector('#brave_element-'+elementID+' .brave_element__text_inner');
1635         var selected_text_element_HTML = selected_text_element.innerHTML;
1636         var selected_text_element_content = selected_text_element.textContent;
1637         var newHTLArray = selected_text_element_content.toString().split('');
1638         var selected_text_element_clone = selected_text_element; 
1639         
1640         selected_text_element_clone.innerHTML ='';
1641         for (var i=0;i<=(newHTLArray.length - 1);i++) {
1642            (function(ind) {
1643               setTimeout(function(){
1644                  selected_text_element_clone.innerHTML = selected_text_element_clone.innerHTML+newHTLArray[ind];
1645               }, 1000 + (50 * ind));
1646            })(i);
1647         }
1648         setTimeout(function(){
1649            selected_text_element_clone.innerHTML = selected_text_element_HTML;
1650         }, 1000 + (50 * (newHTLArray.length -1)));
1651      }else{
1652         //console.log(elementID, selectedStep, elementDom, step, animType);
1653         if(!elementDom.classList.contains('brave_element-'+elementID+'_'+step+'_openAnim')){ elementDom.classList.add('brave_element-'+elementID+'_'+step+'_openAnim'); }
1654      }
1655   }
1656
1657   if(hasAnimation && openAnimData.length > 0){
1658      selectedStep.classList.add('brave_popup__step_wrap--show');
1659      openAnimData.forEach( function(element){
1660         if(element.animation && element.animation.load && element.animation.load.preset){
1661            var animType = element.animation.load.preset;
1662            var animDuration = element.animation.load.duration;
1663            var animDelay = element.animation.load.delay || 0;
1664            var elementID = element.id === 'popup' ? popupID : element.id;
1665            var elementDom = element.id === 'popup' ? selectedStep.querySelector('.brave_popup__step__'+currentDevice+' .brave_popupSections__wrap') : selectedStep.querySelector('.brave_popup__step__'+currentDevice+' #brave_element-'+element.id);
1666            elementDom.style.opacity = 0;
1667            selectedStep.classList.remove('brave_popup__step_wrap--show');
1668            if(animDelay){
1669               // setTimeout(function(){    brave_animateElement(elementID, selectedStep, elementDom, step, animType);  }, animDelay);
1670               brave_animateElement(elementID, selectedStep, elementDom, step, animType);
1671            }else{
1672               brave_animateElement(elementID, selectedStep, elementDom, step, animType);
1673            }
1674            if(element.id === 'popup'){  animDelay = 0; } //Disable Popup Animation Delay
1675            setTimeout(function() { elementDom.style.opacity = ''; }, animDelay+ animDuration - 100);
1676            setTimeout(function(){
1677               elementDom.classList.remove('brave_element-'+elementID+'_'+step+'_openAnim');
1678            }, animDelay+ animDuration + 500);
1679         }
1680      })
1681
1682   }else{
1683      selectedStep.classList.add('brave_popup__step_wrap--show');
1684   }
1685
1686}
1687
1688function brave_close_animation(popupID, step, currentDevice){
1689   //Close Animation
1690   var selectedStep = document.getElementById('brave_popup_'+popupID+'__step__'+step);
1691   var selectedStepDevice = selectedStep.querySelector('.brave_popup__step__'+currentDevice);
1692   var exitAnimation = selectedStepDevice.dataset.exitanimtype || '';
1693   var exitAnimationDuration = selectedStepDevice.dataset.exitanimlength ? parseFloat(selectedStepDevice.dataset.exitanimlength, 10) : 0.5;
1694   var hasAnimation = brave_popup_data[popupID].hasAnimation ?  brave_popup_data[popupID].hasAnimation : false;
1695   var advancedAnimation = brave_popup_data[popupID].advancedAnimation ?  brave_popup_data[popupID].advancedAnimation : false;
1696   var animationData = brave_popup_data[popupID].animationData ?  brave_popup_data[popupID].animationData : {};
1697   var hasCustomExitAnimation = animationData[step][currentDevice].totalDuration['exit'];
1698   //console.warn(currentDevice, exitAnimation, exitAnimationDuration, hasAnimation, selectedStepDevice);
1699
1700   if(selectedStep){
1701      if(exitAnimation){
1702         selectedStepDevice.querySelector('.brave_popupSections__wrap').classList.add('brave_element-'+popupID+'_'+step+'_exitAnim');
1703         setTimeout(function() { selectedStep.classList.remove('brave_popup__step_wrap--show');}, (exitAnimationDuration * 1000));
1704         setTimeout(function() { selectedStepDevice.querySelector('.brave_popupSections__wrap').classList.remove('brave_element-'+popupID+'_'+step+'_exitAnim'); }, (exitAnimationDuration * 1000)+500);
1705         if(selectedStep.querySelector('.brave_popup__step__'+currentDevice+' .brave_popup__step__overlay')){
1706            setTimeout(function() { 
1707               selectedStepDevice.querySelector('.brave_popup__step__overlay').classList.add('brave_popup__step__overlay--hide');
1708            }, (exitAnimationDuration > 0.3 ? ((exitAnimationDuration * 1000) - 200) : 200));
1709            setTimeout(function() { selectedStepDevice.querySelector('.brave_popup__step__overlay').classList.remove('brave_popup__step__overlay--hide'); }, (exitAnimationDuration * 1000)+500);
1710         }
1711      }else if(advancedAnimation && hasCustomExitAnimation){
1712         if(advancedAnimation && hasAnimation && animationData && brave_animate_popup){
1713            brave_animate_popup(animationData, popupID, step, 'exit');
1714         }
1715      }else{
1716         selectedStep.classList.add('brave_popup__step_wrap--hide');
1717         setTimeout(function() { selectedStep.classList.remove('brave_popup__step_wrap--show');}, 500);
1718         setTimeout(function() { selectedStep.classList.remove('brave_popup__step_wrap--hide');}, 800);
1719      }
1720   }
1721         
1722}
1723
1724function brave_close_popup(popupID, step=0, gotoStep=false, updateStat=true){
1725   var selectedStep = document.getElementById('brave_popup_'+popupID+'__step__'+step);
1726   var selectedPopupStep = selectedStep.querySelector('.brave_popup__step__'+brave_currentDevice);
1727   var noMobileContent = selectedPopupStep.dataset.nomobilecontent === 'true' ? true : false;
1728   var currentDevice = noMobileContent ? 'desktop' : brave_currentDevice;
1729   var hasLockScroll = selectedStep.querySelector('.brave_popup__step__'+currentDevice) && selectedStep.querySelector('.brave_popup__step__'+currentDevice).dataset.scrollock ?  true : false;
1730   var exitAnimation = selectedStep.querySelector('.brave_popup__step__'+currentDevice).dataset.exitanimtype || '';
1731   var exitAnimationDuration = selectedStep.dataset.exitanimlength ? parseFloat(selectedStep.dataset.exitanimlength, 10) : 0.5;
1732
1733   //Scroll Lock
1734   if(hasLockScroll){
1735      document.body.classList.remove('brave_scroll_lock')
1736   }
1737
1738   if(selectedStep){
1739
1740      if(updateStat){
1741         var currentPopupCloseStat = localStorage.getItem('brave_popup_'+popupID+'_closed') ? JSON.parse(localStorage.getItem('brave_popup_'+popupID+'_closed')) : {};
1742         var newCloseStat = {closed: currentPopupCloseStat.closed ? currentPopupCloseStat.closed + 1 : 1, closeTime: new Date().getTime()}
1743         localStorage.setItem('brave_popup_'+popupID+'_closed', JSON.stringify(newCloseStat));
1744      }
1745      
1746      //Set the Popup Open status to False 
1747      var selectedPopupStep = selectedStep.querySelector('.brave_popup__step__'+currentDevice);
1748      selectedPopupStep.dataset.popopen = 'false';
1749
1750      //Stop All Videos
1751      if(brave_popup_videos && Object.keys(brave_popup_videos).length > 0){
1752         Object.keys(brave_popup_videos).forEach(function(popupID){
1753            Object.keys(brave_popup_videos[popupID]).forEach(function(playerID){
1754               if(brave_popup_videos[popupID][playerID]){
1755                  if(playerID.includes('youtube') && brave_popup_videos[popupID][playerID] && brave_popup_videos[popupID][playerID].stopVideo){   brave_popup_videos[popupID][playerID].stopVideo();  }
1756                  if(playerID.includes('vimeo') && brave_popup_videos[popupID][playerID] && brave_popup_videos[popupID][playerID].pause){   brave_popup_videos[popupID][playerID].pause();  }
1757                  if(playerID.includes('custom') && brave_popup_videos[popupID][playerID] && brave_popup_videos[popupID][playerID].pause){   brave_popup_videos[popupID][playerID].pause();  }
1758               }
1759            });
1760         });
1761      }
1762
1763      brave_popup_data[popupID].userClosed = true;
1764      brave_popup_data[popupID].isOpen = false;
1765      var braveCloseEvent = new CustomEvent('brave_popup_close', { detail: {popupId: parseInt(popupID, 10), step: step} });
1766      document.dispatchEvent(braveCloseEvent);
1767
1768      //Play Exit Animation
1769      brave_close_animation(popupID, step, currentDevice);
1770
1771      //If has gotoStep Command, go there
1772      setTimeout(function() {
1773         if(gotoStep !== false && gotoStep >=0){
1774            //First set the Taget Step's Open status to false
1775            var targetStep = document.getElementById('brave_popup_'+popupID+'__step__'+gotoStep);
1776            targetStep.querySelector('.brave_popup__step__desktop').dataset.popopen = false;
1777            targetStep.querySelector('.brave_popup__step__mobile').dataset.popopen = false;
1778            
1779            //Then Open the Popup
1780            brave_open_popup(popupID, gotoStep);
1781         }
1782         var stickyBar = selectedPopupStep.dataset.layout === 'float' && selectedPopupStep.dataset.position === 'top_center' ? true : false;
1783         if(stickyBar){
1784            var newHeight = document.querySelector('body.admin-bar') ? '32px' : '0px';
1785            document.documentElement.style.setProperty('margin-top', newHeight, 'important');
1786         }
1787
1788         //Reset the zIndex that was set for click triggered Popups
1789         document.getElementById('brave_popup_'+popupID).style.zIndex = 9999999999;
1790         
1791      }, ( exitAnimation && exitAnimationDuration ? (exitAnimationDuration * 1000) : 10));
1792   }
1793
1794}
1795
1796function brave_send_ga_event(eventCategory, eventAction, eventLabel){
1797   //console.log('ga Event: ', eventCategory, eventAction, eventLabel);
1798   if ("gtag" in window && eventCategory && eventAction) {
1799      gtag("event", eventAction, {
1800         "event_category": eventCategory,
1801         "event_label": eventLabel
1802     });
1803   }
1804}
1805function brave_send_fbq_event(eventType, fbq_content_name, fbq_content_category, fbq_value, fbq_currency){
1806   //console.log('fbq Event: ', eventType, fbq_content_name, fbq_content_category, fbq_value, fbq_currency);
1807   if (window.fbq && eventType) {
1808      var fbqData = {};
1809      if(fbq_content_name){ fbqData.content_name = fbq_content_name }
1810      if(fbq_content_category){ fbqData.content_category = fbq_content_category }
1811      if(fbq_value){ fbqData.value = parseFloat(fbq_value, 10) }
1812      if(fbq_currency){ fbqData.currency = fbq_currency }
1813
1814      if(eventType === 'Contact'){
1815         fbq('track', 'Contact');
1816      }
1817      if(eventType === 'Lead'){
1818         fbq('track', 'Lead', fbqData);
1819         console.log(fbqData);
1820      }
1821  }
1822}
1823
1824
1825
1826function brave_load_video(videoType, videoURL, videoSettings, popupID){
1827   //console.log(videoType, videoURL, videoSettings, videoSettings.tracking);
1828
1829   var elmID = videoSettings.id.replace(/[^a-zA-Z0-9]+/g, '');
1830   if(!brave_popup_videos[popupID]){
1831      brave_popup_videos[popupID] = {}
1832   }
1833   if(videoType ==='custom'){
1834      brave_popup_videos[popupID]['video_'+videoType+elmID] = document.getElementById('brave_video_custom_'+videoSettings.id);
1835      if(videoSettings.autoplay){
1836         brave_play_video(popupID, videoSettings.id, 'custom', videoSettings.tracking);
1837      }
1838   }
1839
1840   if(videoType ==='youtube'){
1841      var youtube_regex = new RegExp(/^.*(youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\\&vi?=)([^#\\&\\?]*).*/);
1842      var parsed = videoURL.match(youtube_regex);
1843      var videoID = parsed && parsed[2] ? parsed[2]:null;
1844   
1845      if(!brave_popup_videos[popupID]['video_'+videoType+elmID]){
1846         setTimeout(function() {
1847            brave_popup_videos[popupID]['video_'+videoType+elmID] = new YT.Player('brave_video_iframe'+elmID, {
1848               videoId: videoID,
1849               playerVars: { 'autoplay': false, 'controls': videoSettings.controls ? 1 : 0, mute: videoSettings.mute ? videoSettings.mute : false  },
1850               events: {
1851                  'onReady': function(){
1852                     return videoSettings.autoplay && brave_play_video(popupID, videoSettings.id, 'youtube', videoSettings.tracking)
1853                  }
1854               }
1855            });
1856         }, 1000);
1857      }else{
1858         if(videoSettings.autoplay) { brave_play_video(popupID, videoSettings.id, 'youtube', videoSettings.tracking); }
1859      } 
1860   }
1861
1862   if(videoType ==='vimeo'){
1863      var vimeo_regex = new RegExp(/https?:\/\/(?:www\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/);
1864      var parsed = videoURL.match(vimeo_regex);
1865      var videoID = parsed && parsed[3] ? parsed[3] : null;
1866      
1867      if(!brave_popup_videos[popupID]['video_'+videoType+elmID]){
1868         setTimeout(function() {
1869            brave_popup_videos[popupID]['video_'+videoType+elmID] = new Vimeo.Player('brave_video_iframe'+elmID, {  id: videoID, background: videoSettings.controls ===false ? true : false });
1870            setTimeout(function() {
1871               if(videoSettings.mute){
1872                  brave_popup_videos[popupID]['video_'+videoType+elmID].setVolume(0);
1873               }
1874               if(videoSettings.autoplay){
1875                  brave_play_video(popupID, videoSettings.id, 'vimeo', videoSettings.tracking);
1876               }
1877            }, 2000);
1878         }, 1000);
1879      }else{
1880         if(videoSettings.autoplay) { brave_play_video(popupID, videoSettings.id, 'vimeo', videoSettings.tracking); }
1881      }
1882      
1883   }
1884
1885}
1886
1887function brave_play_video(popupID, elmentID, videoType, track=null, inline=false){
1888   console.log('brave_play_video', elmentID, videoType, track );
1889   var elmID = elmentID.replace(/[^a-zA-Z0-9]+/g, '');
1890   if(!brave_popup_videos[popupID]['video_'+videoType+elmID]){ return; }
1891
1892   if(document.getElementById("brave_element-"+elmentID)){
1893      document.getElementById("brave_element-"+elmentID).classList.add('brave_element--video-show');
1894   }
1895
1896   //Custom Video Playback
1897   if(videoType === 'custom' ){
1898      brave_popup_videos[popupID]['video_'+videoType+elmID].muted = true; //Video doesnt autoplay if not muted
1899      brave_popup_videos[popupID]['video_'+videoType+elmID].play();
1900      var videoMuted = brave_popup_videos[popupID]['video_'+videoType+elmID].classList.contains('brave_video_muted');
1901      if(!videoMuted){
1902         setTimeout(function() {
1903            brave_popup_videos[popupID]['video_'+videoType+elmID].muted=false;  brave_popup_videos[popupID]['video_'+videoType+elmID].volume=1; 
1904            brave_popup_videos[popupID]['video_'+videoType+elmID].play(); 
1905         }, 100);
1906      }
1907   }
1908   //Youtube and Vimeo Playback
1909   if(videoType === 'youtube' || videoType === 'vimeo'){
1910      if(videoType === 'youtube' && brave_popup_videos[popupID]['video_'+videoType+elmID]){   brave_popup_videos[popupID]['video_'+videoType+elmID].playVideo();   }
1911      if(videoType === 'vimeo' && brave_popup_videos[popupID]['video_'+videoType+elmID]){     brave_popup_videos[popupID]['video_'+videoType+elmID].play().then(); }
1912   }
1913
1914   //Track Video Playback
1915   if(inline && !track){
1916      var playButton = document.getElementById('brave_play_video-'+elmentID)
1917      if(playButton){
1918         var eventCategory = playButton.dataset.trackcategory || '';
1919         var eventAction = playButton.dataset.trackcategory || '';
1920         var eventLabel = playButton.dataset.tracklabel || '';
1921         track = {eventCategory: eventCategory, eventAction:eventAction, eventLabel: eventLabel}
1922      }
1923   }
1924   
1925   if(track && track.eventCategory && track.eventAction){
1926      brave_send_ga_event(track.eventCategory, track.eventAction, track.eventLabel || '');
1927   }
1928   
1929}
1930
1931function brave_complete_goal(popupID, goalType='view', auto=false){
1932   if(window.location.href.includes('brave_popup') === false && !brave_popup_data[popupID].goaled){ 
1933      var goalDate = new Date(); var goalYear = goalDate.getFullYear(); var goalMonth = brave_number_padding(goalDate.getMonth() + 1);  var goalDay = brave_number_padding(goalDate.getDate()); 
1934      var goalData = { 
1935         popupID: popupID, 
1936         pageURL: window.location, 
1937         security: bravepop_global.security, 
1938         goalType: goalType, 
1939         //viewTime: brave_popup_data[popupID].opened, 
1940         views: localStorage.getItem('brave_popup_'+popupID+'_viewed') || 1, 
1941         goalTime: new Date().getTime(), 
1942         goalDate: goalYear+'-'+goalMonth+'-'+goalDay,
1943         goalUTCTime: new Date().toUTCString(), 
1944         device: brave_currentDevice, 
1945         auto: auto,
1946         action: 'bravepop_ajax_popup_complete_goal' 
1947      };
1948
1949      brave_ajax_send(bravepop_global.ajaxURL, goalData, function(status, sentData){   brave_popup_data[popupID].goaled = true; console.log('Goal Complete!!!!!!', sentData);  });
1950      localStorage.setItem('brave_popup_'+popupID+'_goal_complete', goalData.goalTime);
1951      var braveGoalCompletEvent = new CustomEvent('brave_goal_complete', { detail: {popupId: parseInt(popupID, 10), goalType: goalType} });
1952      document.dispatchEvent(braveGoalCompletEvent);
1953      if(brave_popup_data[popupID].settings && brave_popup_data[popupID].settings.notification && brave_popup_data[popupID].settings.notification.analyticsGoal){
1954         setTimeout(function() {
1955            //console.log('##### Send Goal Event to GA!');
1956            brave_send_ga_event('popup', 'goal', brave_popup_data[popupID].title+' ('+popupID+')' || popupID);
1957         }, 2000);
1958      }
1959   }
1960}
1961
1962function brave_load_fonts(fontArray){
1963   var googleFonts  = []; var customFonts = [];
1964   fontArray.forEach(function(font){ 
1965      const inCustomFontList = bravepop_global && bravepop_global.customFonts.find((fnt)=> fnt.name === font);
1966      if(inCustomFontList){ customFonts.push(font); }else{ googleFonts.push(font); }
1967   })
1968    if(googleFonts.length > 0 && bravepop_global && bravepop_global.disableGoogleFonts === 'false'){
1969      WebFontConfig = {
1970         google: { families: googleFonts }
1971       };
1972       (function() {
1973          if(!document.getElementById('bravePopu_webfontLoader')){
1974               var wf = document.createElement('script');
1975               wf.setAttribute("id", "bravePopu_webfontLoader");
1976               wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +'://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js';
1977               wf.type = 'text/javascript';
1978               wf.async = 'true';
1979               var s = document.getElementsByTagName('script')[0];
1980               s.parentNode.insertBefore(wf, s);
1981          }
1982       })();
1983    }
1984   //  console.log(googleFonts, customFonts);
1985   //Load Custom Fonts
1986   if(bravepop_global.customFonts.length > 0 && customFonts.length > 0){
1987      customFonts.map((font)=> {
1988         var foundFont = bravepop_global.customFonts.find((fnt)=> font === fnt.name  );
1989         if(foundFont && foundFont.url && foundFont.url !=='UAF' && foundFont.name  && foundFont.name.includes('brave_custom-')){
1990            var custom_font = new FontFace(foundFont.name, 'url('+foundFont.url+')');
1991            custom_font.load().then(function(loaded_face) {
1992               document.fonts.add(loaded_face)
1993            }).catch(function(error) {
1994               console.error(error);
1995            });
1996         }
1997      })
1998   }
1999	//return fontArray;
2000};
2001
2002function brave_is_in_view(elem) {
2003   var rect = elem.getBoundingClientRect();
2004   return (rect.bottom >= 0 && rect.right >= 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth));
2005};
2006
2007
2008function brave_save_visitor_pageviews(){
2009   //Save Page View Data
2010   if(brave_popup_pageInfo.type === 'front' || brave_popup_pageInfo.pageID){
2011      var brave_page_visited = localStorage.getItem('brave_page_visited'); var currentPageType = 'page';
2012      if(brave_popup_pageInfo.type === 'front'){ currentPageType = 'front'; } 
2013      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() };
2014      if(brave_page_visited){
2015         var brave_page_visited_newData = JSON.parse(brave_page_visited);
2016         brave_page_visited_newData.push(brave_page_visited_new);
2017         localStorage.setItem('brave_page_visited', JSON.stringify(brave_page_visited_newData));
2018      }else{
2019         localStorage.setItem('brave_page_visited', JSON.stringify([brave_page_visited_new]));
2020      }
2021   }
2022}
2023
2024function brave_add_to_cart(elementID){
2025   brave_tooltip_open(elementID, 'Adding to Cart...', 'top');
2026   setTimeout(function() {   brave_tooltip_close();  }, 2000);
2027}
2028function brave_close_on_add_to_cart(popupID){
2029   setTimeout(function() { popupID &&  brave_close_popup(popupID);  }, 2000);
2030}
2031function brave_update_checkout_on_add_to_cart(){
2032   setTimeout(function() { if (typeof jQuery == 'function') { jQuery( document.body ).trigger( "update_checkout" ); }  }, 2000);
2033}
2034function brave_apply_woo_coupon(coupon, popupID, elementID, onCouponApply){
2035   if(elementID){ document.querySelector('#brave_button_loading_'+elementID).classList.add('brave_button_loading--show') }
2036   brave_ajax_send(location.href+'/?wc-ajax=apply_coupon', { coupon_code: coupon, security: bravepop_global.couponSecurity}, function(status, response){
2037      if(onCouponApply==='reload'){ location.reload(); }
2038      if(onCouponApply==='close' && popupID){ brave_close_popup(popupID); } 
2039      if(onCouponApply==='cart' && bravepop_global.cartURL){ location.href = bravepop_global.cartURL}
2040      if(onCouponApply==='checkout' && bravepop_global.checkoutURL){ location.href = bravepop_global.checkoutURL}
2041      if(elementID){ document.querySelector('#brave_button_loading_'+elementID).classList.remove('brave_button_loading--show') }
2042   })
2043}
2044function brave_copy_to_clipboard(elementID, tooltipData, position){
2045   var copyText = document.getElementById('bravepopup_text_copy-'+elementID);
2046   copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy");
2047   brave_tooltip_open(elementID, '✓ '+tooltipData, position);
2048   setTimeout(function() {   brave_tooltip_close();  }, 2000);
2049}
2050function brave_tooltip_open(elementID, tooltipData, position){
2051   var tooltipDiv = document.getElementById('bravepop_element_tooltip'); var tooltipElm = document.getElementById('brave_element-'+elementID); var elmPos = tooltipElm.getBoundingClientRect();
2052   if(tooltipDiv){
2053      tooltipDiv.innerHTML = tooltipData; tooltipDiv.className = 'bravepop_element_tooltip-show bravepop_element_tooltip-'+position; var tooltipWidth = tooltipDiv.offsetWidth;
2054      tooltipDiv.style.top = (elmPos.top + (elmPos.height/2) - 10)+'px'; tooltipDiv.style.left = (elmPos.left - (tooltipWidth) - 8)+'px';
2055      if(position === 'right'){ tooltipDiv.style.left = (elmPos.left + elmPos.width + 8)+'px';  }
2056      if(position === 'top'){ tooltipDiv.style.top = (elmPos.top - (tooltipDiv.offsetHeight) - 4 )+'px'; tooltipDiv.style.left = (elmPos.left - (tooltipWidth/2) + (elmPos.width/2) - 4)+'px';  }
2057      if(position === 'bottom'){ tooltipDiv.style.top = (elmPos.top + elmPos.height + 8)+'px'; tooltipDiv.style.left = (elmPos.left - (tooltipWidth/2) + (elmPos.width/2) + 8)+'px';  }
2058   }
2059}
2060function brave_tooltip_close(){
2061   var tooltipDiv = document.getElementById('bravepop_element_tooltip');
2062   if(tooltipDiv){   tooltipDiv.innerHTML = ''; tooltipDiv.className = '';  tooltipDiv.style.left = ''; tooltipDiv.style.top = ''; }
2063}
2064
2065function brave_lightbox_open(elementID, contentType, content){
2066   var bravelightbox = document.getElementById('bravepop_element_lightbox');  
2067   var bravelightboxContent = document.getElementById('bravepop_element_lightbox_content'); 
2068   if(!bravelightbox){return console.warn('Lightbox Html Div not found in the page.');}
2069   if(contentType === 'image' && bravelightboxContent){ bravelightboxContent.innerHTML = '<img src="'+content+'" />';bravelightbox.classList.add('bravepop_element_lightbox--open');}
2070   if(contentType === 'html' && content){ 
2071      bravelightboxContent.innerHTML = content;
2072      bravelightbox.classList.add('bravepop_element_lightbox--html');
2073      bravelightbox.classList.add('bravepop_element_lightbox--open');
2074   }
2075}
2076function brave_lightbox_close(){
2077   var bravelightbox = document.getElementById('bravepop_element_lightbox');  var bravelightboxContent = document.getElementById('bravepop_element_lightbox_content'); 
2078   if(bravelightbox && bravelightboxContent){ 
2079      bravelightbox.classList.remove('bravepop_element_lightbox--open');
2080      bravelightbox.classList.remove('bravepop_element_lightbox--html'); 
2081      bravelightboxContent.innerHTML = ''; 
2082   }
2083}
2084
2085function brave_responsiveness(event, popupID, popupData){
2086   if(window.location.href.includes('braveshot') === true && window.location.href.includes('brave_id') === true){ return; }
2087   //If a step has no Mobile Content is set, make the Desktop Content mobile friendly and display that instead
2088   var stepsWithNoMobile = document.querySelectorAll('.brave_popup__step--mobile-noContent');
2089   if(brave_isTab || (brave_currentDevice === 'mobile' && document.body.clientWidth < 350 )){ stepsWithNoMobile = document.querySelectorAll('.brave_popup__step_wrap'); }
2090   for (var i = 0; i < stepsWithNoMobile.length; i++) {
2091      var desktopStep =  stepsWithNoMobile[i].querySelector('.brave_popup__step__desktop');
2092      var mobileStep =  stepsWithNoMobile[i].querySelector('.brave_popup__step__mobile');
2093      var popupLayout = desktopStep.dataset.layout;
2094      var popupPosition = popupLayout === 'landing' ? 'top_center' :desktopStep.dataset.position;
2095      var popupWidth = parseInt(desktopStep.dataset.width, 10);
2096      var popupHeight = parseInt(desktopStep.dataset.height, 10);
2097      var windowWidth = document.body.clientWidth || window.innerWidth;  //window.innerWidth
2098      var windowHeight = window.innerHeight;
2099      
2100      if(brave_currentDevice === 'mobile' || brave_isTab){
2101         if(((windowWidth < popupWidth) && popupLayout == 'boxed')){
2102            var scale =  desktopStep ? windowWidth/ desktopStep.dataset.width : 0;
2103            var tansformOrigin = popupPosition.includes('top') ? 'top' : 'center';
2104            desktopStep.querySelector('.brave_popup__step__inner').style.transform = 'scale('+((scale*95)/100)+')';
2105            desktopStep.querySelector('.brave_popup__step__inner').style.transformOrigin = ((scale*95)/2)+'px '+tansformOrigin;
2106            if(windowWidth < popupWidth && windowHeight < popupHeight){
2107               desktopStep.querySelector('.brave_popup__step__inner').style.transformOrigin = 'left top';
2108               desktopStep.querySelector('.brave_popup__step__inner').style.marginTop = 0;
2109               desktopStep.querySelector('.brave_popup__step__inner').style.top = 0;
2110            }
2111            if(popupPosition.includes('center') ){
2112               var widthRemainder = windowWidth - (popupWidth * (scale*95)/100) ;
2113               var heightRemainder = windowHeight - (popupHeight * (scale*95)/100) ;
2114               desktopStep.querySelector('.brave_popup__step__inner').style.left = widthRemainder > 0 ? (widthRemainder/2)+'px' : '0';
2115               //if(popupPosition === 'center'){ desktopStep.querySelector('.brave_popup__step__inner').style.top = heightRemainder > 0 ? (heightRemainder/2)+'px' : '0'; }
2116            }
2117            // if(windowHeight < (popupHeight * (scale*95)/100) ){
2118            //    console.log('Window Height vs Popup Height', windowHeight < (popupHeight * (scale*95)/100), windowHeight , (popupHeight * (scale*95)/100) );
2119            // }
2120         }
2121
2122         if(brave_currentDevice === 'mobile'&& windowWidth < 321 && ((290 < popupWidth) || windowHeight < popupHeight) && (popupLayout == 'boxed' ) && (popupPosition === 'bottom_right') ){
2123            desktopStep.querySelector('.brave_popup__step__inner').style.transform = 'scale(0.8)';
2124            desktopStep.querySelector('.brave_popup__step__inner').style.transformOrigin = '100% bottom';
2125         }
2126         //Top/bottom bar on mobile phones, If no Mobile layout exists
2127         if(brave_currentDevice === 'mobile' && (popupLayout == 'float' ) && windowWidth < 750 ){
2128            desktopStep.querySelector('.brave_popup__step__elements').style.transform = 'scale('+(((windowWidth / 1024)*100)/100)+')';
2129            desktopStep.querySelector('.brave_popup__step__elements').style.transformOrigin = (((windowWidth / 1024)*100)/2)+'px center';
2130         }
2131         //Top/bottom bar ipad/iphone5 fix
2132         if(popupLayout == 'float' && ((brave_isTab && windowWidth < 1024 && windowWidth > 760) || (brave_currentDevice === 'mobile' && windowWidth < 360 && mobileStep))){
2133            if(brave_isTab && windowWidth < 1024 && windowWidth > 760){ popupWidth = 1024; }   var scale =  desktopStep ? windowWidth/ popupWidth : 0;
2134            if(!brave_isTab && windowWidth < 360 && mobileStep){ popupWidth = 360; scale =  windowWidth / popupWidth; desktopStep = mobileStep; } 
2135            desktopStep.querySelector('.brave_popup__step__elements').style.transform = 'scale('+((scale*100)/100)+')';
2136            desktopStep.querySelector('.brave_popup__step__elements').style.transformOrigin = ((scale*100)/2)+'px center';
2137         }
2138
2139      }
2140   }
2141   var allPopups = document.querySelectorAll('.brave_popup__step');
2142   for (var i = 0; i < allPopups.length; i++) {
2143      var aPopupHeight = allPopups[i].dataset.height ? parseInt(allPopups[i].dataset.height, 10) : 400;
2144      var aPopupPosition = allPopups[i].dataset.position; var aPopupLayout = allPopups[i].dataset.layout;
2145      if((window.innerHeight < aPopupHeight) && aPopupPosition.includes('center') && aPopupLayout === 'boxed' && !allPopups[i].classList.contains('brave_popup_show_scrollbar')){
2146         allPopups[i].classList.add('brave_popup_show_scrollbar', 'brave_popup_exceeds_windowHeight');
2147      }
2148   }
2149
2150   //Embedded Popup Resonsiveness
2151   var allEmbeddedPopups = document.querySelectorAll('.bravepopup_embedded');
2152   for (var x = 0; x < allEmbeddedPopups.length; x++) {
2153      var popupID = allEmbeddedPopups[x].dataset.popupid; var parentElm = allEmbeddedPopups[x].parentNode;  var popup_parent_width = parentElm.clientWidth;
2154      //Resize the embedded popup
2155      var allEmbeddedSteps = allEmbeddedPopups[x].querySelectorAll('.brave_popup__step_wrap');
2156      for (var i = 0; i < allEmbeddedSteps.length; i++) {
2157         var currentDevice = allEmbeddedSteps[i].classList.contains('brave_popup__step--mobile-noContent') ? 'desktop' : brave_currentDevice;
2158         var selectedStep =  allEmbeddedSteps[i].querySelector('.brave_popup__step__'+currentDevice+'.brave_popup__step--embedded');
2159         if(selectedStep){
2160            var stepWidth = parseInt(selectedStep.dataset.width, 10); var stepHeight = parseInt(selectedStep.dataset.height, 10);
2161            if(popup_parent_width && (popup_parent_width < stepWidth)){
2162               var scale =  Math.min( popup_parent_width / stepWidth);
2163               selectedStep.querySelector('.brave_popup__step__inner').style.transform = 'scale('+((scale*98)/100)+')';
2164               selectedStep.querySelector('.brave_popup__step__inner').style.transformOrigin = 'left top';
2165               selectedStep.querySelector('.brave_popup__step__inner').parentNode.classList.add('brave_popup__step__inner--scaled');
2166               selectedStep.style.height = ((stepHeight * (scale*98)/100 ))+'px';
2167            }
2168         }
2169      }
2170   }
2171
2172}
2173
2174
2175//Click Open Popup
2176function brave_click_open_popups(){
2177   var braveFoundOpenElems = document.querySelectorAll('a[href*="#brave_open_popup_"]');
2178   if(braveFoundOpenElems.length > 0){
2179      for (var i = 0; i < braveFoundOpenElems.length; i++) { 
2180         var rawOpenElmHref = braveFoundOpenElems[i].href; 
2181         var braveOpenPopupID = rawOpenElmHref && rawOpenElmHref.split('#brave_open_popup_')[1] ? parseInt(rawOpenElmHref.split('#brave_open_popup_')[1], 10) : false;
2182         //console.log(braveOpenPopupID);
2183         if(braveOpenPopupID && brave_popup_data[braveOpenPopupID] && document.getElementById('brave_popup_'+braveOpenPopupID)){
2184            braveFoundOpenElems[i].addEventListener( 'click', function(event){ event.preventDefault(); if(document.getElementById('brave_popup_'+braveOpenPopupID)) document.getElementById('brave_popup_'+braveOpenPopupID).style.zIndex = 9999999999;  });
2185            braveFoundOpenElems[i].setAttribute('onclick','brave_load_popup('+braveOpenPopupID+', brave_popup_data['+parseInt(braveOpenPopupID, 10)+'])');
2186         }
2187      }
2188   }
2189}
2190
2191//Replace Dynamic Text Cookie value
2192function brave_replace_dynamic_text_cookie(elmsWithCookie){
2193   if(elmsWithCookie.length > 0){
2194      for (var i = 0; i < elmsWithCookie.length; i++) { 
2195         var finalContent = elmsWithCookie[i].innerHTML;
2196         var allShortCodes =  finalContent.match(/({{cookie-)+([a-zA-Z0-9_]).+?}}
2196/gi);
2197         if(allShortCodes && allShortCodes.length > 0){
2198            allShortCodes.forEach(function(shortcode){
2199               var theShortcode = shortcode.replace('{{cookie-', '').replace('}}', '');
2200               var cookieVal = localStorage.getItem(theShortcode);
2201               finalContent = finalContent.replace(shortcode, cookieVal ? cookieVal : '');
2202            })
2203            elmsWithCookie[i].innerHTML = finalContent;
2204         }
2205      }
2206   }
2207}
2208
2209function brave_lazyLoad_content_images(emebeddedCampain){
2210   if(emebeddedCampain && !emebeddedCampain.classList.contains('bravepopup_embedded--lazyload_done') && brave_is_in_view(emebeddedCampain)){
2211      var allImages = emebeddedCampain.querySelectorAll('img');
2212      for (var i = 0; i < allImages.length; i++) { 
2213         if(allImages[i].dataset.lazy){
2214            allImages[i].src = allImages[i].dataset.lazy;
2215         }
2216      }
2217      emebeddedCampain.classList.add('bravepopup_embedded--lazyload_done');
2218   }
2219}
2220
2221function brave_after_page_load(){
2222   var allBraveFonts = []
2223   if(!brave_popup_data){ return; }
2224   Object.keys(brave_popup_data).forEach(function(popID) {
2225      brave_popup_data[popID].fonts.forEach(function(fontName) {
2226         if(!allBraveFonts.includes(fontName)){
2227               allBraveFonts.push(fontName);
2228         }
2229      })
2230   });
2231   brave_save_visitor_pageviews();
2232   brave_load_fonts(allBraveFonts);
2233   brave_click_open_popups();
2234   //brave_replace_dynamic_text_cookie();
2235   var emebddedContent = document.querySelectorAll('.bravepopup_embedded');
2236   if(emebddedContent && emebddedContent.length > 0){
2237      for (var i = 0; i < emebddedContent.length; i++) { 
2238         var emebeddedCampain = emebddedContent[i];
2239         if(emebeddedCampain){
2240            brave_lazyLoad_content_images(emebeddedCampain); //Load the images if they are in view on page load.
2241            document.addEventListener("scroll", function(){ brave_lazyLoad_content_images(emebeddedCampain) }, {passive: true});
2242         }
2243      }
2244   }
2245}
2246
2247window.addEventListener( 'DOMContentLoaded', brave_after_page_load );
2248window.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.