<commit_before>'use strict';

module.exports = function (aplazame) {

  var _ = aplazame._,
      api = require('../core/api'),
      isMobile = window.matchMedia('( max-width: 767px )'),
      widgetForbidden = false,
      watchInterval;

  function parsePrice (price) {
     var priceParts = ( '' + price ).match(/(\d+)([,.](\d+))?/);
     var amount = Number(priceParts[1])*100 + Number(priceParts[3]);
     return amount;
  }

  function getQty (qtySelector) {
    if( !_.isString(qtySelector) ) {
      console.warn('warning: data-qty should be an string. pe: form#article .final-price ');
      return 1;
    }
    var qtyElement;
    try {
      qtyElement = document.querySelector(qtySelector);
    } catch(err) {
      console.warn(err.message + '\ndata-qty should be an string. pe: form#article .final-price ');
      return 1;
    }

    switch( qtyElement.nodeName.toLowerCase() ) {
      case 'input':
        return Number( qtyElement.value );
      case 'select':
        return Number( qtyElement.querySelector('option[selected]').value );
      default:
        return Number( qtyElement.textContent.trim() );
    }
  }

  var cmsPriceSelector = [
        'form#product_addtocart_form .special-price .price', // magento
        'form#product_addtocart_form .regular-price .price', // magento
        '#product-info .special-price .price', // magento
        '#product-info .regular-price .price', // magento
        'form#buy_block #our_price_display', // prestashop
        '#main [itemtype="http://schema.org/Product"] [itemtype="http://schema.org/Offer"] .price .amount' // woocommerce
      ],
      cmsQtySelector = [
        'form#product_addtocart_form input[name="qty"]', // magento
        'form#buy_block input[name="qty"]', // prestashop
        'form#product-options-form button[data-id=qty]', // custom
        '#main [itemtype="http://schema.org/Product"] form.cart input[name="quantity"]' // woocommerce
      ];

  function matchSelector (selector) {
    return document.querySelector(selector);
  }

  function readPrice (element) {
    var price = element.textContent.replace(/[^0-9,.]/g,''), addDot;

    if( /[.,]/.test(price) ) {
      return price;
    }

    return element.firstElementChild ? [].reduce.call(element.querySelectorAll('*'), function (prev, elem) {
      var value = elem.textContent.replace(/[^0-9,.]/g,'');
      if( addDot === undefined && prev && !/\./.test(prev) ) {
        addDot = true;
      }
      return prev + ( addDot ? '.' : '' ) + value;
    }, '') : element.textContent.replace(/[^0-9,.]/g,'');
  }

  function amountGetter (widgetElement) {
    var priceSelector = widgetElement.getAttribute('data-price'),
        qtySelector = widgetElement.getAttribute('data-qty');

    if( priceSelector ) {
      try{
        document.querySelector(priceSelector);
      } catch(err) {
        priceSelector = null;
        console.warn(err.message);
      }
      if( qtySelector ) {
        try{
          document.querySelector(qtySelector);
        } catch(err) {
          qtySelector = null;
          console.warn(err.message);
        }
      }
    } else {
      priceSelector = cmsPriceSelector.find(matchSelector);

      if( priceSelector ) {
        qtySelector = cmsQtySelector.find(matchSelector);
      }
    }

    var getter = priceSelector ? function () {
      var qty = qtySelector ? getQty( qtySelector ) : 1,
          priceElement = document.querySelector( priceSelector );

      return qty * parsePrice( priceElement.value !== undefined ? priceElement.value : readPrice(priceElement) );
    } : function () {
      return Number( widgetElement.getAttribute('data-amount') );
    };

    getter.priceSelector = priceSelector;
    getter.qtySelector = qtySelector;

    return getter;
  }

  function widgetsLookup (element) {
    if( !element.querySelectorAll ) {
      return;
    }

    var simulators = element.querySelectorAll('[data-aplazame-simulator]');

    if( simulators.length ) {

      var iframes = [],
          choices = [],
          currentAmount;

      _.listen(window, 'message', function (e) {
        var message = e.data;

        if( !e.used && message.aplazame === 'simulator' ) {
          e.used = true;

          switch (message.event) {
            case 'resize':
              iframes.forEach(function (iframe) {
                if( iframe.contentWindow === e.source ) {
                  iframe.style.height = message.data.height + 'px';
                }
              });
              break;
            case 'require:choices':
              e.source.postMessage({
                aplazame: 'simulator',
                event: 'choices',
                choices: choices,
                amount: currentAmount,
                mobile: isMobile.matches
              }, '*');
              break;
          }
        }
      });

      _.listen(window, 'resize', function (e) {

        iframes.forEach(function (iframe) {

          iframe.contentWindow.postMessage({
            aplazame: 'simulator',
            event: 'mobile',
            mobile: isMobile.matches
          }, '*');

        });

      });

      [].forEach.call(simulators, function (simulator) {

        if( _.elementData(simulator, 'checked') ) {
          return;
        }

        _.elementData(simulator, 'checked', true);

        var getAmount = amountGetter(simulator);
        currentAmount = Number( simulator.getAttribute('data-amount') ) || getAmount();

        var simulatorParams = {
              simulator: '[data-aplazame-simulator]',
              amount: currentAmount,
              publicKey: simulator.getAttribute('data-public-key')
            },
            iframe,
            choicesCache = {};

        simulator.innerHTML = '<div style="padding: 10px; text-align: center;">comprobando financiación...</div>';

        aplazame.simulator(simulatorParams.amount, function (_choices) {
          var child = simulator.firstChild,
              now = new Date().getTime();

          choices = _choices;
          _choices.$amount = simulatorParams.amount;
          choicesCache[simulatorParams.amount] = _choices;

          while( child ) {
            simulator.removeChild(child);
            child = simulator.firstChild;
          }

          _.http( api.baseUrl + 'widgets/simulator/simulator.html?' + now ).then(function (response) {
            iframe = _.getIFrame({
              width: '100%'
            });

            iframes.push(iframe);
            iframe.src = api.baseUrl + 'widgets/simulator/simulator.html?' + now;
            simulator.appendChild(iframe);
          }, function () {
            simulator.innerHTML = '';
          });
        }, function () {
          simulator.innerHTML = '';
        }, function (response) {
          widgetForbidden = true;
          if( watchInterval ) {
            clearInterval(watchInterval);
          }
        });

        if( getAmount.priceSelector ) {
          var updateWidgetChoices = function (choices) {
                iframe.contentWindow.postMessage({
                  aplazame: 'simulator',
                  event: 'choices',
                  choices: choices,
                  amount: currentAmount,
                  mobile: isMobile.matches
                }, '*');
              },
              onPriceChange = function (amount) {
                currentAmount = amount;<commit_msg>showning in console when widget is disabled<commit_after>'use strict';

module.exports = function (aplazame) {

  var _ = aplazame._,
      api = require('../core/api'),
      isMobile = window.matchMedia('( max-width: 767px )'),
      widgetForbidden = false,
      watchInterval;

  function parsePrice (price) {
     var priceParts = ( '' + price ).match(/(\d+)([,.](\d+))?/);
     var amount = Number(priceParts[1])*100 + Number(priceParts[3]);
     return amount;
  }

  function getQty (qtySelector) {
    if( !_.isString(qtySelector) ) {
      console.warn('warning: data-qty should be an string. pe: form#article .final-price ');
      return 1;
    }
    var qtyElement;
    try {
      qtyElement = document.querySelector(qtySelector);
    } catch(err) {
      console.warn(err.message + '\ndata-qty should be an string. pe: form#article .final-price ');
      return 1;
    }

    switch( qtyElement.nodeName.toLowerCase() ) {
      case 'input':
        return Number( qtyElement.value );
      case 'select':
        return Number( qtyElement.querySelector('option[selected]').value );
      default:
        return Number( qtyElement.textContent.trim() );
    }
  }

  var cmsPriceSelector = [
        'form#product_addtocart_form .special-price .price', // magento
        'form#product_addtocart_form .regular-price .price', // magento
        '#product-info .special-price .price', // magento
        '#product-info .regular-price .price', // magento
        'form#buy_block #our_price_display', // prestashop
        '#main [itemtype="http://schema.org/Product"] [itemtype="http://schema.org/Offer"] .price .amount' // woocommerce
      ],
      cmsQtySelector = [
        'form#product_addtocart_form input[name="qty"]', // magento
        'form#buy_block input[name="qty"]', // prestashop
        'form#product-options-form button[data-id=qty]', // custom
        '#main [itemtype="http://schema.org/Product"] form.cart input[name="quantity"]' // woocommerce
      ];

  function matchSelector (selector) {
    return document.querySelector(selector);
  }

  function readPrice (element) {
    var price = element.textContent.replace(/[^0-9,.]/g,''), addDot;

    if( /[.,]/.test(price) ) {
      return price;
    }

    return element.firstElementChild ? [].reduce.call(element.querySelectorAll('*'), function (prev, elem) {
      var value = elem.textContent.replace(/[^0-9,.]/g,'');
      if( addDot === undefined && prev && !/\./.test(prev) ) {
        addDot = true;
      }
      return prev + ( addDot ? '.' : '' ) + value;
    }, '') : element.textContent.replace(/[^0-9,.]/g,'');
  }

  function amountGetter (widgetElement) {
    var priceSelector = widgetElement.getAttribute('data-price'),
        qtySelector = widgetElement.getAttribute('data-qty');

    if( priceSelector ) {
      try{
        document.querySelector(priceSelector);
      } catch(err) {
        priceSelector = null;
        console.warn(err.message);
      }
      if( qtySelector ) {
        try{
          document.querySelector(qtySelector);
        } catch(err) {
          qtySelector = null;
          console.warn(err.message);
        }
      }
    } else {
      priceSelector = cmsPriceSelector.find(matchSelector);

      if( priceSelector ) {
        qtySelector = cmsQtySelector.find(matchSelector);
      }
    }

    var getter = priceSelector ? function () {
      var qty = qtySelector ? getQty( qtySelector ) : 1,
          priceElement = document.querySelector( priceSelector );

      return qty * parsePrice( priceElement.value !== undefined ? priceElement.value : readPrice(priceElement) );
    } : function () {
      return Number( widgetElement.getAttribute('data-amount') );
    };

    getter.priceSelector = priceSelector;
    getter.qtySelector = qtySelector;

    return getter;
  }

  function widgetsLookup (element) {
    if( !element.querySelectorAll ) {
      return;
    }

    var simulators = element.querySelectorAll('[data-aplazame-simulator]');

    if( simulators.length ) {

      var iframes = [],
          choices = [],
          currentAmount;

      _.listen(window, 'message', function (e) {
        var message = e.data;

        if( !e.used && message.aplazame === 'simulator' ) {
          e.used = true;

          switch (message.event) {
            case 'resize':
              iframes.forEach(function (iframe) {
                if( iframe.contentWindow === e.source ) {
                  iframe.style.height = message.data.height + 'px';
                }
              });
              break;
            case 'require:choices':
              e.source.postMessage({
                aplazame: 'simulator',
                event: 'choices',
                choices: choices,
                amount: currentAmount,
                mobile: isMobile.matches
              }, '*');
              break;
          }
        }
      });

      _.listen(window, 'resize', function (e) {

        iframes.forEach(function (iframe) {

          iframe.contentWindow.postMessage({
            aplazame: 'simulator',
            event: 'mobile',
            mobile: isMobile.matches
          }, '*');

        });

      });

      [].forEach.call(simulators, function (simulator) {

        if( _.elementData(simulator, 'checked') ) {
          return;
        }

        _.elementData(simulator, 'checked', true);

        var getAmount = amountGetter(simulator);
        currentAmount = Number( simulator.getAttribute('data-amount') ) || getAmount();

        var simulatorParams = {
              simulator: '[data-aplazame-simulator]',
              amount: currentAmount,
              publicKey: simulator.getAttribute('data-public-key')
            },
            iframe,
            choicesCache = {};

        simulator.innerHTML = '<div style="padding: 10px; text-align: center;">comprobando financiación...</div>';

        aplazame.simulator(simulatorParams.amount, function (_choices) {
          var child = simulator.firstChild,
              now = new Date().getTime();

          choices = _choices;
          _choices.$amount = simulatorParams.amount;
          choicesCache[simulatorParams.amount] = _choices;

          while( child ) {
            simulator.removeChild(child);
            child = simulator.firstChild;
          }

          _.http( api.baseUrl + 'widgets/simulator/simulator.html?' + now ).then(function (response) {
            iframe = _.getIFrame({
              width: '100%'
            });

            iframes.push(iframe);
            iframe.src = api.baseUrl + 'widgets/simulator/simulator.html?' + now;
            simulator.appendChild(iframe);
          }, function () {
            simulator.innerHTML = '';
          });
        }, function () {
          simulator.innerHTML = '';
        }, function (response) {
          console.log('widget disabled');
          widgetForbidden = true;
          if( watchInterval ) {
            clearInterval(watchInterval);
          }
        });

        if( getAmount.priceSelector ) {
          var updateWidgetChoices = function (choices) {
                iframe.contentWindow.postMessage({
                  aplazame: 'simulator',
                  event: 'choices',
                  choices: choices,
                  amount: currentAmount,
                  mobile: isMobile.matches
                }, '*');
              },
              onPriceChange = function (amount) {
                currentAmount = amount;
{'fraction_non_alphanumeric': 0.13578919064264589, 'fraction_numerical': 0.0029577843506318905, 'mean_word_length': 1.9957712444623439, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '98445', 'n_tokens_mistral': 4322, 'n_tokens_neox': 4167, 'n_words': 785}