PageSourceSearch

https://www.italiaslowtour.it/wp-content/plugins/brave-popup-builder/assets/frontend/brave.js

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