PageSourceSearch

https://alvasar.ru/wp-content/plugins/brave-popup-builder/assets/frontend/brave.js

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