<commit_before><!--
Select a culture from the Globalize culture list.

This can be used as a UI component, or an invisible component to load
language/culture settings. In that scenario, set the "name" attribute to the
desired language/culture, wait for the "basic-culture-changed" event to fire,
then read the "culture" attribute to get its settings.

@element basic-culture-selector
@demo http://basic-web-components.github.io/basic-web-components/src/basic-culture-selector/?dom=shadow
-->

<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">

<script src="../../bower_components/deepmerge/index.js"></script>

<!--
First, we load Globalize's dependencies (`cldrjs` and its supplemental
module).
-->
<script src="../../bower_components/cldrjs/dist/cldr.js"></script>
<script src="../../bower_components/cldrjs/dist/cldr/event.js"></script>
<script src="../../bower_components/cldrjs/dist/cldr/supplemental.js"></script>

<!--
Next, we load Globalize and its modules. Note they are already available on
this repository. If it's not, read Usage on Getting Started on the root's
README.md.
-->
<script src="../../bower_components/globalize/dist/globalize.js"></script>
<script src="../../bower_components/globalize/dist/globalize/message.js"></script>
<script src="../../bower_components/globalize/dist/globalize/number.js"></script>
<script src="../../bower_components/globalize/dist/globalize/plural.js"></script>

<!-- Load after globalize/number.js -->
<script src="../../bower_components/globalize/dist/globalize/date.js"></script>
<script src="../../bower_components/globalize/dist/globalize/currency.js"></script>

<!-- Load after globalize/number.js and globalize/plural.js-->
<script src="../../bower_components/globalize/dist/globalize/relative-time.js"></script>

<dom-module id="basic-culture-selector">
  <style>
    :host {
      display: inline-block;
    }

    select {
      max-width: 100%;
    }
  </style>

  <template>
    <content></content>
    <iron-ajax id="ajax"
               handle-as="json"
               on-response="_onAjaxComplete"></iron-ajax>
    <select id="culturePicker" value="{{name::input}}"></select>
  </template>
</dom-module>

<script>
// Stash the current file location so later we can load culture files relative
// to this path.
GlobalizeCulture = {
  _scriptPath: document.currentScript.baseURI
};

var BASE_PATH = GlobalizeCulture._scriptPath.substring(0, GlobalizeCulture._scriptPath.lastIndexOf('/'));

var DEFAULT_LOCALE = 'en';

Polymer({

  is: 'basic-culture-selector',

  // JSON to hand off to Globalize intializer
  _localeJson: {},

  // Expected and actual number of ajax responses
  _expectedResponseCount: 0,
  _actualResponseCount: 0,

  // Array of CLDR files to be loaded as part of initialization
  _cldrFiles: [
    '../../bower_components/cldr-data/supplemental/numberingSystems.json',
    '../../bower_components/cldr-data/supplemental/currencyData.json',
    '../../bower_components/cldr-data/supplemental/likelySubtags.json',
    '../../bower_components/cldr-data/supplemental/timeData.json',
    '../../bower_components/cldr-data/supplemental/weekData.json'
  ],

  // Array of files to be loaded per locale
  _localeFiles: [
    '../../bower_components/cldr-data/main/{{cultureString}}/ca-gregorian.json',
    '../../bower_components/cldr-data/main/{{cultureString}}/numbers.json',
    '../../bower_components/cldr-data/main/{{cultureString}}/currencies.json'
  ],

  // Have we initialized Globalize
  _globalizeInitialized: false,

  ready: function() {
    this._populatePicker();

    // Perform initial fetches for initialization of Globalize
    this._expectedResponseCount = this._cldrFiles.length + this._localeFiles.length;
    for (var i = 0; i < this._cldrFiles.length; i++) {
      this.$.ajax.url = new URL(this._cldrFiles[i], BASE_PATH);
      this.$.ajax.generateRequest();
    }

    this._loadLocaleFiles();
  },

  _populatePicker: function() {
    for (var key in LANGUAGE_BY_LOCALE) {
      var index = AVAILABLE_LOCALES.indexOf(key);
      if (LANGUAGE_BY_LOCALE.hasOwnProperty(key) && (key == DEFAULT_LOCALE || index >= 0)) {
        var elem = document.createElement('option');
        elem.value = key =='en-US' ? 'en-US-POSIX' : key;
        elem.innerHTML = LANGUAGE_BY_LOCALE[key];
        this.$.culturePicker.appendChild(elem);
      }
    }

    // Set the default selection option
    for (var i = 0; i < this.$.culturePicker.options.length; i++) {
      if (this.$.culturePicker.options[i].value === DEFAULT_LOCALE) {
        this.$.culturePicker.selectedIndex = i;
        break;
      }
    }
  },

  _loadLocaleFiles: function() {
    for (var i = 0; i < this._localeFiles.length; i++) {
      var url = this._localeFiles[i].replace('{{cultureString}}', this.name);
      this.$.ajax.url = new URL(url, BASE_PATH);
      this.$.ajax.generateRequest();
    }
  },

  _setGlobalizeLocale: function() {
    Globalize.load(this._localeJson);
    this._globalizeInitialized = true;
    this.culture = Globalize(this.name);
  },

  _onAjaxComplete: function(request) {
    this._localeJson = deepmerge(this._localeJson, request.detail.response);
    this._actualResponseCount++;

    if (this._actualResponseCount >= this._expectedResponseCount) {
      this._setGlobalizeLocale();
    }
  },

  /**
   * Fired when the culture attribute has been changed.
   *
   * @event basic-culture-changed
   * @param Object detail Event details; the "culture" property contains a
   *                      reference to the new Globalize culture.
   */
  cultureChanged: function() {
    this.dispatchEvent(new CustomEvent('basic-culture-changed', {
      detail: {
        culture: this.culture
      }
    }));
  },

  nameChanged: function() {
    if (this._globalizeInitialized) {
      // Need to reset _expectedResponseCount and _actualResponseCount prior to the
      // call to _loadLocaleFiles
      this._expectedResponseCount = this._localeFiles.length;
      this._actualResponseCount = 0;
      this._loadLocaleFiles();
    }
  },

  properties: {
    /**
     * The name of the Globalize culture/language assigned to this element.
     *<commit_msg>Add rudimentary error handling for failed asset loads in basic-culture-selector<commit_after><!--
Select a culture from the Globalize culture list.

This can be used as a UI component, or an invisible component to load
language/culture settings. In that scenario, set the "name" attribute to the
desired language/culture, wait for the "basic-culture-changed" event to fire,
then read the "culture" attribute to get its settings.

@element basic-culture-selector
@demo http://basic-web-components.github.io/basic-web-components/src/basic-culture-selector/?dom=shadow
-->

<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">

<script src="../../bower_components/deepmerge/index.js"></script>

<!--
First, we load Globalize's dependencies (`cldrjs` and its supplemental
module).
-->
<script src="../../bower_components/cldrjs/dist/cldr.js"></script>
<script src="../../bower_components/cldrjs/dist/cldr/event.js"></script>
<script src="../../bower_components/cldrjs/dist/cldr/supplemental.js"></script>

<!--
Next, we load Globalize and its modules. Note they are already available on
this repository. If it's not, read Usage on Getting Started on the root's
README.md.
-->
<script src="../../bower_components/globalize/dist/globalize.js"></script>
<script src="../../bower_components/globalize/dist/globalize/message.js"></script>
<script src="../../bower_components/globalize/dist/globalize/number.js"></script>
<script src="../../bower_components/globalize/dist/globalize/plural.js"></script>

<!-- Load after globalize/number.js -->
<script src="../../bower_components/globalize/dist/globalize/date.js"></script>
<script src="../../bower_components/globalize/dist/globalize/currency.js"></script>

<!-- Load after globalize/number.js and globalize/plural.js-->
<script src="../../bower_components/globalize/dist/globalize/relative-time.js"></script>

<dom-module id="basic-culture-selector">
  <style>
    :host {
      display: inline-block;
    }

    select {
      max-width: 100%;
    }
  </style>

  <template>
    <content></content>
    <iron-ajax id="ajax"
               handle-as="json"
               on-response="_onAjaxComplete"
               on-error="_onAjaxError"></iron-ajax>
    <select id="culturePicker" value="{{name::input}}"></select>
  </template>
</dom-module>

<script>
// Stash the current file location so later we can load culture files relative
// to this path.
GlobalizeCulture = {
  _scriptPath: document.currentScript.baseURI
};

var BASE_PATH = GlobalizeCulture._scriptPath.substring(0, GlobalizeCulture._scriptPath.lastIndexOf('/'));

var DEFAULT_LOCALE = 'en';

Polymer({

  is: 'basic-culture-selector',

  // JSON to hand off to Globalize intializer
  _localeJson: {},

  // Expected and actual number of ajax responses
  _expectedResponseCount: 0,
  _actualResponseCount: 0,

  // Was there an error during ajax operations?
  _ajaxError: false,

  // Array of CLDR files to be loaded as part of initialization
  _cldrFiles: [
    '../../bower_components/cldr-data/supplemental/numberingSystems.json',
    '../../bower_components/cldr-data/supplemental/currencyData.json',
    '../../bower_components/cldr-data/supplemental/likelySubtags.json',
    '../../bower_components/cldr-data/supplemental/timeData.json',
    '../../bower_components/cldr-data/supplemental/weekData.json'
  ],

  // Array of files to be loaded per locale
  _localeFiles: [
    '../../bower_components/cldr-data/main/{{cultureString}}/ca-gregorian.json',
    '../../bower_components/cldr-data/main/{{cultureString}}/numbers.json',
    '../../bower_components/cldr-data/main/{{cultureString}}/currencies.json'
  ],

  // Have we initialized Globalize
  _globalizeInitialized: false,

  ready: function() {
    this._populatePicker();

    // Perform initial fetches for initialization of Globalize
    this._expectedResponseCount = this._cldrFiles.length + this._localeFiles.length;
    for (var i = 0; i < this._cldrFiles.length; i++) {
      this.$.ajax.url = new URL(this._cldrFiles[i], BASE_PATH);
      this.$.ajax.generateRequest();
    }

    this._loadLocaleFiles();
  },

  _populatePicker: function() {
    for (var key in LANGUAGE_BY_LOCALE) {
      var index = AVAILABLE_LOCALES.indexOf(key);
      if (LANGUAGE_BY_LOCALE.hasOwnProperty(key) && (key == DEFAULT_LOCALE || index >= 0)) {
        var elem = document.createElement('option');
        elem.value = key =='en-US' ? 'en-US-POSIX' : key;
        elem.innerHTML = LANGUAGE_BY_LOCALE[key];
        this.$.culturePicker.appendChild(elem);
      }
    }

    // Set the default selection option
    for (var i = 0; i < this.$.culturePicker.options.length; i++) {
      if (this.$.culturePicker.options[i].value === DEFAULT_LOCALE) {
        this.$.culturePicker.selectedIndex = i;
        break;
      }
    }
  },

  _loadLocaleFiles: function() {
    for (var i = 0; i < this._localeFiles.length; i++) {
      var url = this._localeFiles[i].replace('{{cultureString}}', this.name);
      this.$.ajax.url = new URL(url, BASE_PATH);
      this.$.ajax.generateRequest();
    }
  },

  _setGlobalizeLocale: function() {
    Globalize.load(this._localeJson);
    this._globalizeInitialized = true;
    this.culture = Globalize(this.name);
  },

  _onAjaxComplete: function(request) {
    this._localeJson = deepmerge(this._localeJson, request.detail.response);
    this._actualResponseCount++;

    if (this._actualResponseCount >= this._expectedResponseCount) {
      this._setGlobalizeLocale();
    }
  },

  _onAjaxError: function(request, error) {
    this._actualResponseCount++;
    this._ajaxError = true;

    // Attempt to set the locale as best we can with what we have
    if (this._actualResponseCount >= this._expectedResponseCount) {
      this._setGlobalizeLocale();
    }
  },

  /**
   * Fired when the culture attribute has been changed.
   *
   * @event basic-culture-changed
   * @param Object detail Event details; the "culture" property contains a
   *                      reference to the new Globalize culture.
   */
  cultureChanged: function() {
    this.dispatchEvent(new CustomEvent('basic-culture-changed', {
      detail: {
        culture: this.culture
      }
    }));
  },

  nameChanged: function() {
    if (this._globalizeInitialized) {
      // Need to reset _expectedResponseCount and _actualResponseCount prior to the
      // call to _loadLocaleFiles
      this._expectedResponseCount = this._localeFiles.length;
      this._actualResponseCount = 0;
      this._ajaxError = false;
      this._loadLocaleFiles();
    }
  },

  properties: {
    /**
     * The name of the Globalize culture/language assigned to this element.
     *
{'fraction_non_alphanumeric': 0.14871834346855514, 'fraction_numerical': 0.001693480101608806, 'mean_word_length': 3.2863741339491916, 'pattern_counts': {'":': 0, '<': 93, '<?xml version=': 0, '>': 92, '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': '673101', 'n_tokens_mistral': 4044, 'n_tokens_neox': 3910, 'n_words': 854}