
window.neoScripts = (window.neoScripts === undefined) ? [] : window.neoScripts;

(function() {

  var scriptId = "4g72k0o3";

  if (!window.neoScripts.includes(scriptId)) {
    window.neoScripts.push(scriptId);

    var $neo;
if (window.jQuery === undefined) {
  // jQuery not found
  var script_tag = document.createElement('script');
  script_tag.setAttribute("type","text/javascript");
  script_tag.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js");
  if (script_tag.readyState) {
    // For old versions of IE
    script_tag.onreadystatechange = function () {
      if (this.readyState == 'complete' || this.readyState == 'loaded') {scriptLoadHandler();}
    };
  } else {
    // For normal browsers
    script_tag.onload = scriptLoadHandler;
  }
  // Add jQuery to the head
  (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
  // jQuery was found
  $neo = window.jQuery;
  main();
}

function scriptLoadHandler() {
  $neo = window.jQuery.noConflict();
  main();
}

    

    function main() {
      /*!
 * Javascript Cookie v1.5.1
 * https://github.com/js-cookie/js-cookie
 *
 * Copyright 2006, 2014 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
  var jQuery;
  if (typeof exports === 'object') {
    // Node/CommonJS
    try {
      jQuery = require('jquery');
    } catch(e) {}
    module.exports = factory(jQuery);
  } else {
    // Browser globals
    var _OldCookies = window.Cookies;
    var api = window.Cookies = factory(window.jQuery);
    api.noConflict = function() {
      window.Cookies = _OldCookies;
      return api;
    };
  }
}(function ($) {

  var pluses = /\+/g;

  function encode(s) {
    return api.raw ? s : encodeURIComponent(s);
  }

  function decode(s) {
    return api.raw ? s : decodeURIComponent(s);
  }

  function stringifyCookieValue(value) {
    return encode(api.json ? JSON.stringify(value) : String(value));
  }

  function parseCookieValue(s) {
    if (s.indexOf('"') === 0) {
      // This is a quoted cookie as according to RFC2068, unescape...
      s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
    }

    try {
      // Replace server-side written pluses with spaces.
      // If we can't decode the cookie, ignore it, it's unusable.
      // If we can't parse the cookie, ignore it, it's unusable.
      s = decodeURIComponent(s.replace(pluses, ' '));
      return api.json ? JSON.parse(s) : s;
    } catch(e) {}
  }

  function read(s, converter) {
    var value = api.raw ? s : parseCookieValue(s);
    return isFunction(converter) ? converter(value) : value;
  }

  function extend() {
    var key, options;
    var i = 0;
    var result = {};
    for (; i < arguments.length; i++) {
      options = arguments[ i ];
      for (key in options) {
        result[key] = options[key];
      }
    }
    return result;
  }

  function isFunction(obj) {
    return Object.prototype.toString.call(obj) === '[object Function]';
  }

  var api = function (key, value, options) {

    // Write

    if (arguments.length > 1 && !isFunction(value)) {
      options = extend(api.defaults, options);

      if (typeof options.expires === 'number') {
        var days = options.expires, t = options.expires = new Date();
        t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
      }

      return (document.cookie = [
        encode(key), '=', stringifyCookieValue(value),
        options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
        options.path    ? '; path=' + options.path : '',
        options.domain  ? '; domain=' + options.domain : '',
        options.secure  ? '; secure' : ''
      ].join(''));
    }

    // Read

    var result = key ? undefined : {},
      // To prevent the for loop in the first place assign an empty array
      // in case there are no cookies at all. Also prevents odd result when
      // calling "get()".
      cookies = document.cookie ? document.cookie.split('; ') : [],
      i = 0,
      l = cookies.length;

    for (; i < l; i++) {
      var parts = cookies[i].split('='),
        name = decode(parts.shift()),
        cookie = parts.join('=');

      if (key === name) {
        // If second argument (value) is a function it's a converter...
        result = read(cookie, value);
        break;
      }

      // Prevent storing a cookie that we couldn't decode.
      if (!key && (cookie = read(cookie)) !== undefined) {
        result[name] = cookie;
      }
    }

    return result;
  };

  api.get = api.set = api;
  api.defaults = {};

  api.remove = function (key, options) {
    // Must not alter options, thus extending a fresh object...
    api(key, '', extend(options, { expires: -1 }));
    return !api(key);
  };

  if ( $ ) {
    $.cookie = api;
    $.removeCookie = api.remove;
  }

  return api;
}));

      /*! flip - v1.1.2 - 2016-10-20
* https://github.com/nnattawat/flip
* Copyright (c) 2016 Nattawat Nonsung; Licensed MIT */

!function(a){var b=function(){var a,b=document.createElement("fakeelement"),c={transition:"transitionend",OTransition:"oTransitionEnd",MozTransition:"transitionend",WebkitTransition:"webkitTransitionEnd"};for(a in c)if(void 0!==b.style[a])return c[a]},c=function(b,c,d){this.setting={axis:"y",reverse:!1,trigger:"click",speed:500,forceHeight:!1,forceWidth:!1,autoSize:!0,front:".front",back:".back"},this.setting=a.extend(this.setting,c),"string"!=typeof c.axis||"x"!==c.axis.toLowerCase()&&"y"!==c.axis.toLowerCase()||(this.setting.axis=c.axis.toLowerCase()),"boolean"==typeof c.reverse&&(this.setting.reverse=c.reverse),"string"==typeof c.trigger&&(this.setting.trigger=c.trigger.toLowerCase());var e=parseInt(c.speed);isNaN(e)||(this.setting.speed=e),"boolean"==typeof c.forceHeight&&(this.setting.forceHeight=c.forceHeight),"boolean"==typeof c.forceWidth&&(this.setting.forceWidth=c.forceWidth),"boolean"==typeof c.autoSize&&(this.setting.autoSize=c.autoSize),("string"==typeof c.front||c.front instanceof a)&&(this.setting.front=c.front),("string"==typeof c.back||c.back instanceof a)&&(this.setting.back=c.back),this.element=b,this.frontElement=this.getFrontElement(),this.backElement=this.getBackElement(),this.isFlipped=!1,this.init(d)};a.extend(c.prototype,{flipDone:function(a){var c=this;c.element.one(b(),function(){c.element.trigger("flip:done"),"function"==typeof a&&a.call(c.element)})},flip:function(a){if(!this.isFlipped){this.isFlipped=!0;var b="rotate"+this.setting.axis;this.frontElement.css({transform:b+(this.setting.reverse?"(-180deg)":"(180deg)"),"z-index":"0"}),this.backElement.css({transform:b+"(0deg)","z-index":"1"}),this.flipDone(a)}},unflip:function(a){if(this.isFlipped){this.isFlipped=!1;var b="rotate"+this.setting.axis;this.frontElement.css({transform:b+"(0deg)","z-index":"1"}),this.backElement.css({transform:b+(this.setting.reverse?"(180deg)":"(-180deg)"),"z-index":"0"}),this.flipDone(a)}},getFrontElement:function(){return this.setting.front instanceof a?this.setting.front:this.element.find(this.setting.front)},getBackElement:function(){return this.setting.back instanceof a?this.setting.back:this.element.find(this.setting.back)},init:function(a){var b=this,c=b.frontElement.add(b.backElement),d="rotate"+b.setting.axis,e=2*b.element["outer"+("rotatex"===d?"Height":"Width")](),f={perspective:e,position:"relative"},g={transform:d+"("+(b.setting.reverse?"180deg":"-180deg")+")","z-index":"0",position:"relative"},h={"backface-visibility":"hidden","transform-style":"preserve-3d",position:"absolute","z-index":"1"};b.setting.forceHeight?c.outerHeight(b.element.height()):b.setting.autoSize&&(h.height="100%"),b.setting.forceWidth?c.outerWidth(b.element.width()):b.setting.autoSize&&(h.width="100%"),(window.chrome||window.Intl&&Intl.v8BreakIterator)&&"CSS"in window&&(f["-webkit-transform-style"]="preserve-3d"),c.css(h).find("*").css({"backface-visibility":"hidden"}),b.element.css(f),b.backElement.css(g),setTimeout(function(){var d=b.setting.speed/1e3||.5;c.css({transition:"all "+d+"s ease-out"}),"function"==typeof a&&a.call(b.element)},20),b.attachEvents()},clickHandler:function(b){b||(b=window.event),this.element.find(a(b.target).closest('button, a, input[type="submit"]')).length||(this.isFlipped?this.unflip():this.flip())},hoverHandler:function(){var b=this;b.element.off("mouseleave.flip"),b.flip(),setTimeout(function(){b.element.on("mouseleave.flip",a.proxy(b.unflip,b)),b.element.is(":hover")||b.unflip()},b.setting.speed+150)},attachEvents:function(){var b=this;"click"===b.setting.trigger?b.element.on(a.fn.tap?"tap.flip":"click.flip",a.proxy(b.clickHandler,b)):"hover"===b.setting.trigger&&(b.element.on("mouseenter.flip",a.proxy(b.hoverHandler,b)),b.element.on("mouseleave.flip",a.proxy(b.unflip,b)))},flipChanged:function(a){this.element.trigger("flip:change"),"function"==typeof a&&a.call(this.element)},changeSettings:function(a,b){var c=this,d=!1;if(void 0!==a.axis&&c.setting.axis!==a.axis.toLowerCase()&&(c.setting.axis=a.axis.toLowerCase(),d=!0),void 0!==a.reverse&&c.setting.reverse!==a.reverse&&(c.setting.reverse=a.reverse,d=!0),d){var e=c.frontElement.add(c.backElement),f=e.css(["transition-property","transition-timing-function","transition-duration","transition-delay"]);e.css({transition:"none"});var g="rotate"+c.setting.axis;c.isFlipped?c.frontElement.css({transform:g+(c.setting.reverse?"(-180deg)":"(180deg)"),"z-index":"0"}):c.backElement.css({transform:g+(c.setting.reverse?"(180deg)":"(-180deg)"),"z-index":"0"}),setTimeout(function(){e.css(f),c.flipChanged(b)},0)}else c.flipChanged(b)}}),a.fn.flip=function(b,d){return"function"==typeof b&&(d=b),"string"==typeof b||"boolean"==typeof b?this.each(function(){var c=a(this).data("flip-model");"toggle"===b&&(b=!c.isFlipped),b?c.flip(d):c.unflip(d)}):this.each(function(){if(a(this).data("flip-model")){var e=a(this).data("flip-model");!b||void 0===b.axis&&void 0===b.reverse||e.changeSettings(b,d)}else a(this).data("flip-model",new c(a(this),b||{},d))}),this}}(jQuery);


      $neo(function($) {
        var stylesheetUrl = "https://app.neocamino.com/assets/pub/widget-d3f096ac57542772b1d8a9e069c6a2be587e9067cac3dfc97ffda73abf20439a.css";
renderStylesheet(stylesheetUrl);

function renderStylesheet(stylesheetUrl) {
  if (!$("link[href='" + stylesheetUrl + "']").length) {
    var cssLink = $("<link>", {rel: "stylesheet", type: "text/css", href: stylesheetUrl});
    cssLink.appendTo('head');
  };
}


        var CookiesNeo = Cookies.noConflict();

function cookieName(landingPageId) {
  return "neo_lp_" + landingPageId;
}

function getRejectedLandingPageIds() {
  var websiteCookies = CookiesNeo.get();
  return $.map(Object.keys(websiteCookies), function(val, i) {
    if (val.match(/^neo_lp_/) && websiteCookies[val]) {
      return val.replace('neo_lp_', '');
    }
  });
}

function cookieHideWidget(widget) {
  var cookieExpires = widget.data('cookie-expires');
  if (cookieExpires) { logHideWidgetsInCookies(widget.data('lp'), cookieExpires); }
}

function logHideWidgetsInCookies(landingPageId, cookieExpires) {
  CookiesNeo.set(cookieName(landingPageId), true, {
    expires: cookieExpires,
    path: '/',
    sameSite: 'None',
    secure: true
  });
}

function canShowWidget(landingPageId) {
  return !CookiesNeo.get(cookieName(landingPageId));
}

function isMobile() {
  return ('ontouchstart' in document.documentElement);
}

function hookRemoveEvents() {
  $('.neo-wg-close').click(function(e) {
    var widget = $(this).closest('.neo-widget');
    removeWidget(widget, 'logCookie');
  });
}

function hookHideEvents() {
  $(document).on('click', '.neo-wg-hide', function(e) {
    var closeBtn = $(e.target);
    var widget = closeBtn.closest('.neo-widget');
    hideWidget(widget);
  });
}

function removeWidget(widget, logCookie) {
  var logCookie = logCookie || false;
  widget.remove();
  enableScrollingWidgets();
  if (logCookie) { cookieHideWidget(widget) };
}


function hideWidget(widget) {
  enableScrollingWidgets();
  widget.hide();
}

function hideOrRemoveWidget(widget, logCookie) {
  var logCookie = logCookie || false;
  var hide = widget.hasClass('neo-wg-hideable');
  hide ? hideWidget(widget) : removeWidget(widget, logCookie);
}

// Show widget after scroll
enableScrollingWidgets();

function appearAfter(scrollingWidget) {
  var triggerDistance = scrollingWidget.data('scroll-top');
  if (triggerDistance == 'middle') { triggerDistance = middleOfPage(); }
  return triggerDistance;
}

function middleOfPage() {
  var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
  var documentHeight = document.body.clientHeight;
  return documentHeight/2 - viewportHeight/2;
}

function enableScrollingWidgets() {
  $(window).on('scroll', displayWidgetBasedOnScroll);
}

function disableScrollingWidgets() {
  $(window).off('scroll', displayWidgetBasedOnScroll);
}

function displayWidgetBasedOnScroll() {
  $('.neo-wg-scroll').each(function() {
    var scrollingWidget = $(this);
    var triggerDistance = appearAfter(scrollingWidget);

    if ($(window).scrollTop() > triggerDistance) {
      scrollingWidget.slideDown();
      logWidgetApperance(scrollingWidget);
    } else {
      scrollingWidget.slideUp();
    }
  });
}

function hideScrollingWidgets() {
  $('.neo-wg-scroll').each(function() {
    $(this).slideUp();
  });
}

function removeScrollingWidgets() {
  $('.neo-wg-scroll').each(function() {
    $(this).remove();
  });
}

function startTimer() {
  var popupWithTimer = $('.neo-wg-time');
  if (popupWithTimer.length == 0) { return false; }
  var timeToAppear = getTimerValue(popupWithTimer);

  setTimeout(function(){
      if (noPopupOpened()) {
        displayPopup(popupWithTimer);
        logWidgetApperance(popupWithTimer);
      };
    }, timeToAppear);
}

function getTimerValue(widget) {
  return 1000 * parseInt(widget.data('timer'), 10);
}

$(window).resize(function() {
  centerPopup();
});

$(document).on('click', '.neo-overlay', function() {
  var widget = $(this).closest('.neo-widget');
  hideOrRemoveWidget(widget);
});

function centerPopup(popup) {
  if (popup) {
    var popupContainer = popup.closest('.neo-popup');
  } else {
    var popupContainer = $('.neo-popup');
    popup = popupContainer.find('.neo-wg-popup:visible');
  }
  var topPadding = calculateProperPadding(popup);
  popupContainer.css('padding-top', topPadding);
}

function calculateProperPadding(popup) {
  var windowHeight = window.innerHeight || document.body.clientHeight;
  var top = (windowHeight - popup.outerHeight()) / 2;
  topPadding = (top > 0) ? top + 'px' : 0
  return topPadding;
}

function getClickPopupLpUuids() {
  var lpUuids = clickPopupLinks().map(function() {
    return getLandingPageUuid($(this));
  }).get().filter(function(n){ return n != undefined });
  return lpUuids;
}

function clickPopupLinks() { // Link that trigger click-popup display (can be 'raw' links or plain-widget links)
  return $("a[href*='uuid=']");
}

function clickPopupLinksFor(uuid) {
  return $("a[href*='uuid=" + uuid + "']");
}


function outOfWidgetClickPopupLinks() { // Only raw links
  var links = clickPopupLinks();
  var linksWithinWidget = $(".neo-widget a[href*='uuid=']");
  var outOfWidgetlinks = $.grep(links, function(el) { return $.inArray(el, linksWithinWidget) < 0 });
  return outOfWidgetlinks;
}

function hookClickOnClickPopupLinks() {
  $(document).on('click', "a[href*='uuid=']", function(e){
    e.preventDefault();
    var link = $(e.target).closest('a');
    displayClickPopup(link);
  });
}

function displayClickPopup(link) {
  var lpUuid = getLandingPageUuid(link);

  if (lpUuid) {
    var popup = $('#' + lpUuid);
    logPopupDisplayFromLink(popup, link);
    displayPopup(popup);
  }
}

function displayPopup(popup) {
  hideScrollingWidgets();
  disableScrollingWidgets();
  popup.show();

  var popupContent = popupVisibleContent(popup);
  centerPopup(popupContent);
  focusInPopup(popupContent);
}

function focusInPopup(popup) {
  var firstInput = popup.find('input:visible:first');
  firstInput.focus();
}

function displayThankPopup(form, successNotice) {
  var popup = findFormPopup(form);
  if (successNotice) {displaySuccessNotice(popup, successNotice);}
  removeScrollingWidgets();
  flipCard(popup);

  if (popup.is(':visible')) {
    centerPopup(popupVisibleContent(popup));
  } else {
    displayPopup(popup);
  }
}

function findFormPopup(form) {
  var formWidget = form.closest('.neo-widget');
  if (!formWidget.hasClass('neo-popup')) {
    var lpUuid = form.data('lpUuid');
    var popup = $('#' + lpUuid);
    return popup;
  } else {
    return formWidget;
  }
}

function removeAlert(form) {
  var alertContainer = form.find('.neo-alert-container');
  alertContainer.html('');
}

function noPopupOpened() {
  var openedPopups =
    $('.neo-popup, #contact-modal').filter(function () {
      return $(this).css('display') !== 'none';
    });
  return openedPopups.length === 0;
}

function logPopupDisplayFromLink(popup, link) {
  var neoMedium = getNeoMedium(link) || 'click_popup';
  setPopupNeoMedium(popup, neoMedium);
  logAnalyticsEventForWidget('widget-click', popup) // use popup original label, and category updated in setPopupNeoMedium
}

function setPopupNeoMedium(popup, neoMedium) {
  if (neoMedium) {
    popup.find('#lp_neo_medium').val(neoMedium);
    popup.attr('data-ga-category', neoMedium);
  }
}

function getNeoMedium(link) {
  return getParamValueFromLink('neo_medium', link);
}

function getLandingPageUuid(link) {
  return getParamValueFromLink('uuid', link);
}

function getParamValueFromLink(param, link) {
  var url = link.attr('href');
  return getParameterByName(param, url);
}

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
      results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function hookFlipEvents() {
  $('.neo-flip-card').flip({trigger: 'manual', front: '.neo-flip-front', back: '.neo-flip-back'});
}

function flipCard(popup) {
  var flipCard = popup.find('.neo-flip-card');

  flipCard.find('.neo-flip-back').show(0, function() {
    flipCard.find('.neo-flip-front').hide();
    flipCard.flip(true);
  });
}

function popupVisibleContent(popup) {
  var popupFront = popup.find('.neo-flip-front');
  var popupBack = popup.find('.neo-flip-back');

  var visibleSide = (popupFront.is(':visible')) ? popupFront : popupBack;

  return visibleSide.find('.neo-wg-popup');
}

function displaySuccessNotice(popup, successNotice) {
  popup.find('.neo-success-notice').removeClass('hidden').html(successNotice);
}

function getFormWidgetLpUuids() {
  var lpUuids = $(".neo-form-widget").map(function() {
    return ($(this).data('lp'));
  }).get().filter(function(n){ return n != undefined });
  return lpUuids;
}

// action: 'display', 'submit_error', 'submit_success' + 'widget-click' for click popup
// When a btn linked to a click_popup appears on page,
//   we log action: 'display', forceCategory: 'click_popup_link'
function logAnalyticsEventForWidget(action, widget, forceCategory) {
  var category = forceCategory || analyticsEventCategory(widget);
  var label = analyticsEventLabel(widget);
  var value = eventNeedsValue(action, category) ? analyticsEventValue(widget) : null;
  var nonInteraction = action == 'display';
  logAnalyticsEvent(action, category, label, value, nonInteraction);
  logDataLayerEvent(action, category, label);
}

// Arguments:
// - action: display, submit_error, submit_success, widget-click
// - category: click_popup, banner, scrollbox, show_popup_exit_intent, side_widget
// - label: name of the landing page
function logDataLayerEvent(action, category, label) {
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    event: 'neo.' + action,
    formLocation: category,
    formName: label,
  });
}

function logAnalyticsEvent(action, category, label, value, nonInteraction) {
  if (!(action && action.length && category && category.length && label && label.length)) {
    return;
  }
  if (gtagScriptLoaded()) {
    logGtagEvent(action, category, label, value, nonInteraction);
  } else if (gaScriptLoaded()) {
    logGaEvent(action, category, label, value, nonInteraction);
  }
  // fakeLogGaEvent(action, category, label, value, nonInteraction);
}

function logGaEvent(action, category, label, value, nonInteraction) {
  var doneAnalyticsIds = [];
  var tracker, trackingId;
  if (!gaTrackerLoaded()) return;

  for (var i = 0; i < ga.getAll().length; i++) {
    tracker = ga.getAll()[i];
    trackingId = tracker.get('trackingId');
    if (doneAnalyticsIds.indexOf(trackingId) == -1) {
      logGaEventFromTracker(tracker, action, category, label, value, nonInteraction);
      doneAnalyticsIds.push(trackingId);
    }
  }
}

function logGaEventFromTracker(tracker, action, category, label, value, nonInteraction) {
  tracker.send({
    hitType: 'event',
    eventCategory: category,
    eventAction: action,
    eventLabel: label,
    eventValue: value,
    nonInteraction: nonInteraction,
  });
}

function logGtagEvent(action, category, label, value, nonInteraction) {
  gtag('event', action, {
    event_category: category,
    event_label: label,
    value: value,
    non_interaction: nonInteraction,
  });
}

function fakeLogGaEvent(action, category, label, value, nonInteraction) {
  // Usefull to test GA event logging in development
  if (!(action && action.length && category && category.length && label && label.length)) {
    return;
  }
  console.log('sending GA event');
  console.log('----------');
  console.log('action : ' + action);
  console.log('category : ' + category);
  console.log('label : ' + label);
  console.log('value : ' + value);
  console.log('nonInteraction : ' + nonInteraction);
  console.log('----------');
}

function analyticsEventCategory(widget) {
  return $(widget).attr('data-ga-category');
}

function analyticsEventLabel(widget) {
  return $(widget).attr('data-ga-label');
}

function analyticsEventValue(widget) {
  var eventValue =
    $(widget).attr('data-ga-value') ||
    $(widget)
      .find('form')
      .attr('data-ga-value');
  return eventValue && Number(eventValue);
}

function gaScriptLoaded() {
  return typeof ga == 'function';
}

function gaTrackerLoaded() {
  return gaScriptLoaded() && typeof ga.getAll == 'function';
}

function getAnalyticsClientId() {
  if (!gaTrackerLoaded()) return;

  var tracker = getFirstGaTracker();
  if (tracker) {
    return tracker.get('clientId');
  }
}

function getFirstGaTracker() {
  var trackers = ga.getAll();
  if (trackers.length == 0) return;

  return trackers[0];
}

function gtagScriptLoaded() {
  return typeof gtag == 'function';
}

function eventNeedsValue(action, category) {
  if (action != 'display') {
    return true;
  }
  return ['popup', 'form_widget'].includes(category);
}

function getInPageWidgetLpIds() {
  var lpUuids = $("[class*='neo-wg-lp-side-preview-link']").map(function() {
    var classesString = $(this).attr('class');
    return getWidgetLpId(classesString);
  }).get().filter(function(n){ return n != undefined });
  return lpUuids;
}

function getWidgetLpId(classesString) {
  if (!classesString) { return; }
  classes = classesString || '';
  var regexp = /neo-wg-lp-side-preview-link-(\d*)(?:$|\s+)/;
  var match = classes.match(regexp);
  if (!match) { return; }
  return match[1];
}

function renderWidgets(widgets) {
  if (widgets && widgets.length > 0) {
    $.each(widgets, function(index, widget){
      appendWidget(widget.html, widget.container_class);
      updateClickPopupHref(widget);
      logInpageWidgetAppearance(widget);
    });
    hookWidgetsEvents();
    logClickPopupLinksAppearance();
  }
}

function updateClickPopupHref(widget) {
  if (widget.code == 'click_popup') {
    clickPopupLinksFor(widget.uuid).each(function() {
      url = $(this).attr('href');
      parser = new URL(url);
      widgetUrl = widget.url + parser.search;
      $(this).attr('href', widgetUrl);
    });
  }
}

function appendWidget(widget, containerClass) {
  var container = containerClass ? $('.' + containerClass) : $('body');
  if (widget) { container.append(widget); }
}

function hookWidgetsEvents() {
  startTimer();
  hookRemoveEvents();
  hookHideEvents();
  hookClickOnClickPopupLinks();
  hookSubmitWidgetForm();
  hookFlipEvents();
  hookExitIntentEvent();
  hookAnalyticsClientIDHelper();
}

function hookSubmitWidgetForm() {
  $(document).on('click', '.neo-widget input[type=submit]', hookSubmission);
}

function unhookSubmitWidgetForm() {
  $(document).on('click', '.neo-widget input[type=submit]', function (e) {
    e.preventDefault();
  });
  $(document).off('click', '.neo-widget input[type=submit]', hookSubmission);
}

function hookSubmission(event) {
  var submitBtn = $(event.target);
  var form = submitBtn.closest('form');
  var submitBtnText = submitBtn.val();
  var submitBtnDisableWith = submitBtn.data('disableWith');
  event.preventDefault();
  submitBtn.val(submitBtnDisableWith);
  submitWidgetForm(form, submitBtnText);
}

function hookAnalyticsClientIDHelper() {
  var clientID = getAnalyticsClientId();
  if (clientID) {
    $('.ga_client_id').val(clientID);
  }
}

function submitWidgetForm(form, submitBtnText) {
  var submitUrl = form.data('submit-url');
  var params = new FormData(form[0]);

  unhookSubmitWidgetForm();

  $.ajax({
    url: submitUrl,
    data: params,
    type: 'POST',
    dataType: 'json',
    processData: false,
    contentType: false,
    cache: false,
    success: function(data) { handleSubmitResponse(form, submitBtnText, data); }
  });
}

function handleSubmitResponse(form, submitBtnText, submitResponseData) {
  var widget = form.closest('.neo-widget');
  var data = submitResponseData;

  if (data.errors) {
    var alert = data.errors;
    displayAlertInForm(form, alert);
    activateSubmitBtn(form, submitBtnText);
    logAnalyticsEventForWidget('submit_error', widget);
  } else {
    var landingPageId = data.landing_page_id;
    var successNotice = data.success_notice;
    var redirectUrl = data.redirect_url;
    var facebookPixelCode = data.facebook_pixel_code;
    removeAlert(form);
    logLandingPageSubscription(landingPageId);
    logAnalyticsEventForWidget('submit_success', widget);
    if (redirectUrl) {
      window.location.href = redirectUrl;
    } else {
      displayThankPopup(form, successNotice);
      if (facebookPixelCode) pushFacebookConversionEvent();
    }
  }
  hookSubmitWidgetForm();
}

function pushFacebookConversionEvent() {
  if (typeof fbq !== 'undefined') {
    fbq('track', 'Lead');
  }
}

function displayAlertInForm(form, alert) {
  var alertContainer = form.closest('.neo-widget').find('.neo-alert-container');
  alertContainer.html(alert);
  centerPopup();
}

function activateSubmitBtn(form, submitBtnText) {
  var submitBtn = form.find('input[type=submit]');
  submitBtn.val(submitBtnText);
}

function logLandingPageSubscription(landingPageId) {
  logHideWidgetsInCookies(landingPageId, 365);
}

function logWidgetApperance(widget) {
  if (widget.attr('data-appeared')) { return };
  logAnalyticsEventForWidget('display', widget);
  widget.attr('data-appeared', true);
}

function logInpageWidgetAppearance(widgetData) {
  var widgetContainerClass = widgetData.container_class
  if (!widgetContainerClass) { return };
  var widget = $('.' + widgetContainerClass);
  logAnalyticsEventForWidget('display', widget);
}

function logClickPopupLinksAppearance() {
  $.each(outOfWidgetClickPopupLinks(), function(index, link){
    var clickPopupId = getLandingPageUuid($(link));
    var popup = $('#' + clickPopupId);
    logAnalyticsEventForWidget('display', popup, 'click_popup_link');
  });
}

function hookExitIntentEvent() {
  var timeBeforeExitIntentDetection = 3000;
  var popup = $('#neo-popup');

  if (popup.length > 0) {
    setTimeout(function() {
      hookExitIntentOnLeave(popup);
    }, timeBeforeExitIntentDetection);
  }
}

function hookExitIntentOnLeave(popup) {
  $(document).on('mouseout', function(event) {
    var noPointerTarget = (event.toElement === undefined || event.toElement === null) && event.relatedTarget === null;

    if(noPointerTarget && noPopupOpened()) {
      logPopupDisplayFromExitIntent(popup);
      displayPopup(popup);

      $(event.currentTarget).off('mouseout');
    }
  });
}

function logPopupDisplayFromExitIntent(popup) {
  var neoMedium = 'show_popup_exit_intent';

  setPopupNeoMedium(popup, neoMedium);
  logAnalyticsEventForWidget('display', popup);
}


// This will get executed after the helpers, since it's an additional request success callback


          var jsonp_url = "https://app.neocamino.com/api.json?id=4g72k0o3";

var inPageWidgetLpIds = getInPageWidgetLpIds();
var clickPopupLpUuids = getClickPopupLpUuids();
var formWidgetLpUuids = getFormWidgetLpUuids();
var rejectedLandingPageIds = getRejectedLandingPageIds();

var params = {
  url: document.URL,
  mobile: isMobile(),
  click_popup_lp_uuids: clickPopupLpUuids,
  form_widget_lp_uuids: formWidgetLpUuids,
  widget_lp_ids: inPageWidgetLpIds,
  rejected_lp_ids: rejectedLandingPageIds
};

// Send current URL to retrieve the widgets to show on that page
// NB: no error callback in cross-domain JSONP request, so the
// error handling is done in the success callback.

$.ajax({
  url: jsonp_url,
  data: params,
  dataType: "jsonp",
  success: function(data) {
    if (data.errors) {
      console.log(data.errors);
      hookWidgetsEvents();
    }
    else {
        renderWidgets(data.widgets);

    }
  }
});

      });
    }
  }
})();
