<commit_before>/**
 * The Feed view.
 */
define([
  'jquery',
  'backbone',
  'underscore',
  'd3',
  'mps',
  'views/SourceWindowView',
  'views/ShareView',
  'countries/views/CountryHeaderView',
  'countries/helpers/CountryHelper'

], function($, Backbone, _, d3, mps, SourceWindowView, ShareView, CountryHeaderView, CountryHelper) {

  'use strict';

  var CountryOverviewModel = Backbone.Model.extend({
    defaults: {
      graph: 'total_loss',
      years: true,
      class: null
    }
  });



  var CountryOverviewView = Backbone.View.extend({

    el: '#countryOverviewView',

    events: {
      'click .graph_tab': '_updateGraph',
      'click .show-more-countries': '_drawList',
      'click .trigger-mode span': '_toggle_total_percent',
      'click .share-link': '_openShareModal'
    },

    initialize: function() {
      if (!this.$el.length) {
        return
      }

      this.helper = CountryHelper;
      this.model = new CountryOverviewModel();
      this.headerView = new CountryHeaderView();

      this.setListeners();

      this.$graph = $('.overview_graph__area');
      this.$years = $('.overview_graph__years');
      this.$big_figures   = $('.overview_graph__figure_only')
      var m = this.m = 40,
          w = this.w = this.$graph.width(),
          h = this.h = this.$graph.height(),
          vertical_m = this.vertical_m = 20;

      this.x_scale = d3.scale.linear()
        .range([m, w-m])
        .domain([2001, 2013]);

      this.grid_scale = d3.scale.linear()
        .range([vertical_m, h-vertical_m])
        .domain([0, 1]);

      this.model.bind('change:graph', this._redrawGraph, this);
      this.model.bind('change:years', this._toggleYears, this);
      this.model.bind('change:class', this._toggleClass, this);

      this._initViews();
    },

    _initViews: function() {
      this.sourceWindow = new SourceWindowView();

      this.tooltip = d3.select('body')
        .append('div')
        .attr('class', 'tooltip2');

      this._drawYears();
      this._drawGraph();
      this._drawList();
    },

    setListeners: function(){
      mps.subscribe('Threshold:change', _.bind(function(threshold){
        this.helper.config.canopy_choice = threshold;
        this._updateGraphOverview();
      }, this ));

    },

    _openShareModal: function(event) {
      var shareView = new ShareView().share(event);
      this.$el.append(shareView.el);
    },

    _toggleYears: function() {
      var that = this;

      if (this.model.get('years') === false) {
        this.$years.slideUp(250, function() {
          $('.overview_graph__axis').slideDown();
        });
      } else {
        $('.overview_graph__axis').slideUp(250, function() {
          that.$years.slideDown();
        });
      }
    },

    _showYears: function() {
      if (!this.model.get('years')) {
        this.model.set('years', true);
      }
    },

    _hideYears: function() {
      if (this.model.get('years')) {
        this.model.set('years', false);
      }
    },

    _updateGraph: function(e) {
      e.preventDefault();

      var $target = $(e.target).closest('.graph_tab'),
          graph = $target.attr('data-slug');

      if (graph === this.model.get('graph')) {
        return;
      } else {
        $('.graph_tab').removeClass('selected');
        $target.addClass('selected');

        this.model.set('graph', graph);
      }
      ga('send', 'event', 'Country overview', 'Click', 'Overview graph: ' + graph);
    },

    _redrawGraph: function() {
      var graph = this.model.get('graph');
      var $legend = $('.overview_graph__legend');
      $('.overview_graph__title').html(this.helper.config.GRAPHS[graph].title);
      $legend.find('p').html(this.helper.config.GRAPHS[graph].subtitle);
      $legend.find('.info').data('source', graph);

      this.$graph.removeClass('is-hidden');
      this.$years.removeClass('is-hidden');
      $legend.removeClass('is-hidden');

      this.$graph.find('.'+graph);

      this.$graph.find('.chart').hide();
      this.$graph.find('.'+graph).fadeIn();

      this._drawGraph();
      this._drawList();

      this.$el.find('.overview_button_group .settings').removeClass('disable')
      if (graph === 'total_extent' || graph === 'percent_loss') {
        this.$big_figures.show();
        this.$graph.addClass('is-hidden');
        this.$years.addClass('is-hidden');
        if (graph == 'percent_loss') this.$el.find('.overview_button_group .settings').addClass('disable')
      } else {
        this.$big_figures.hide();
      }
    },
    _updateGraphOverview: function(e) {
      if (typeof ga !== "undefined") ga('send', 'event', 'Country Overview', 'Change', 'Threshold');
      var $cnp_op = this.$el.find('.overview_button_group .settings')
      if (this.helper.config.canopy_choice != 30) $cnp_op.addClass('no_def');
      else $cnp_op.removeClass('no_def');

      this._drawYears();
      this._drawGraph();
      this._drawList();
    },

    _reorderRanking: function(e) {
      var $ul = $('.countries_list ul'),
      $ul_li = $ul.children('li');

      $ul_li.sort(function(a,b){
        var an = parseFloat($(a).find('.loss').data('orig')),
            bn = parseFloat($(b).find('.loss').data('orig'));
        if(an > bn) {
          return -1;
        }
        if(an < bn) {
          return 1;
        }
        return 0;
      });

      $ul_li.detach().appendTo($ul);
      $ul_li.find('.countries_list__num').each(function(i, ele){ $(ele).empty().text(i+1) })
    },

    _toggle_total_percent: function(e) {
      if (!sessionStorage.getItem('OVERVIEWMODE')) {
        var mode = JSON.stringify(
        {
          'mode': 'percent'
        });
        sessionStorage.setItem('OVERVIEWMODE', mode);
      } else {
        var mode = JSON.parse(sessionStorage.getItem('OVERVIEWMODE'));
        mode = (!!mode & mode.mode == 'total') ? 'percent' : 'total';
        sessionStorage.setItem('OVERVIEWMODE', JSON.stringify({'mode':mode}))
      }
      this._drawList();
      this._drawGraph();
    },

    _drawList: function(e) {
      var that = this;

      e && e.preventDefault();

      if (this.model.get('graph') === 'total_loss') {
        var sql = 'SELECT umd.iso, c.name, c.enabled, Sum(umd.loss) loss FROM umd_nat_final_1 umd, gfw2_countries c WHERE thresh = '+ (this.helper.config.canopy_choice || 30) +' AND umd.iso = c.iso AND NOT loss = 0 AND umd.year > 2000 GROUP BY umd.iso, c.name, c.enabled ORDER BY loss DESC ';
        var mode = JSON.parse(sessionStorage.getItem('OVERVIEWMODE'));
        if (!!mode && mode.mode == 'percent') {
          sql = 'SELECT umd.iso, c.name, c.enabled, Sum(umd.loss) / umd.extent_2000 loss_perc FROM umd_nat_final_1 umd, gfw2_countries c WHERE thresh = '+ (this.helper.config.canopy_choice || 30) +' AND umd.iso = c.iso AND NOT loss_perc = 0 AND umd.year > 2000 AND extent_2000 > 10 GROUP BY umd.extent_2000, umd.iso, c.name, c.enabled ORDER BY loss_perc DESC '
        }

        if (e) {
          sql += 'OFFSET 10';
          $('.show-more-countries').fadeOut();
        } else {
          sql += 'LIMIT 10';
          $('.countries_list ul').html('');
          $('.show-more-countries').show();
        }
        d3.json('http://wri-01.cartodb.com/api/v2/sql/?q='+encodeURIComponent(sql), _.bind(function(json) {
          var self = that,
              markup_list = '';

          var data = json.rows;

          _.each(data, _.bind(function(val, key) {
            var ord = e ? (key+11) : (key+1),
                enabled = val.enabled ? '<a href="/country/'+val.iso+'">'+val.name+'</a>' : val.name;

            var max_trigger = data.length -1;
            $.ajax({
              url: window.gfw.config.GFW_API_HOST + '/forest-change/umd-loss-gain/admin/' + val.iso+'?thresh=' + (this.helper.config.canopy_choice || 30),
              dataType: 'json',
              success: _.bind(function(data) {
                var loss = Math.round(val.loss) || (val.loss_perc*100).toFixed(3);
                var orig = loss;
                var g_mha, l_mha = '%';

                if (! !!val.loss_perc){
                  g_mha = l_mha = 'Mha';
                  if (loss.toString().length >= 7) {
                    loss = ((loss /1000)/1000).toFixed(2)
                  } else if (loss.toString().length >= 4) {
                    l_mha = 'KHa';
                    loss = (loss /1000);
                  if (loss % 1 != 0) loss = loss.toFixed(2)
                  } else {
                    l_mha = 'Ha';
                  }
                }

                $('#umd_'+val.iso+'').empty().append('<span class="loss line" data-orig="' + orig + '"><span>'+ parseFloat(loss).toLocaleString() +' </span>'+ l_mha +'</span>');

                if (key == max_trigger){
                  that._reorderRanking();
                }
              }, this),
            });
            markup_list += '<li>\
                              <div class="countries_list__minioverview countries_list__minioverview_'+val.iso+'"></div>\
                              <div class="countries_list__num">'+ord+'</div>\
                              <div class="countries_list__title">'+enabled+'</div>\
                              <div class="countries_list__data">\
                                <div id="umd_'+val.iso+'"></div>\
                              </div>\
                            </li>';
          }, this ));

          if (e) {
            $('.show-more-countries').fadeOut();
          } else {
            $('.countries_list ul').html('');
            $('.show-more-countries').show();

            if (!!mode && mode.mode == 'percent') {
              $('.overview_graph__legend').find('.trigger-mode').html('<span>GROSS LOSS</span> <strong>PERCENT LOSS</strong>').show();
              $('.overview_graph__title').html('Countries with greatest percent loss (2001-2013) relative to tree cover in 2000');

            } else {
              $('.overview_graph__legend').find('.trigger-mode').html('<strong>GROSS LOSS</strong> <span>PERCENT LOSS</span>').show();
              $('.overview_graph__title').html('Countries with greatest tree cover loss (2001-2013)');
            }
          }

          $('.countries_list ul').append(markup_list);

          that.model.set('class', null);
          if (!!mode && mode.mode == 'percent') {
            $('.countries_list__data').addClass('no-graph');
          } else {
            _.each(data, function(val, key) {
              self._drawMiniOverview(val.iso);
            });
          }
        }, this ));
      } else if (this.model.get('graph') === 'percent_loss') {
        $('.countries_list__header__minioverview').hide();
        var mode = JSON.parse(sessionStorage.getItem('OVERVIEWMODE'));

        var sql = 'SELECT umd.iso, c.name, c.enabled, Sum(umd.gain) gain FROM umd_nat_final_1 umd, gfw2_countries c WHERE umd.iso = c.iso AND NOT loss = 0 AND umd.year > 2000 GROUP BY umd.iso, c.name, c.enabled ORDER BY gain DESC ';
        if (!!mode && mode.mode == 'percent')
            sql = 'SELECT (gain*12/extent_2000)*100 as ratio, country as name, c.iso as iso, c.enabled, u.iso as iso2 from umd_nat_final_1 u, gfw2_countries c  WHERE thresh = 50 AND c.iso = u.iso AND extent_2000 > 10  group by ratio, country, u.iso, c.iso, c.enabled order by ratio desc ';
        if (e) {
          sql += 'OFFSET 10';
        } else {
          sql += 'LIMIT 10';
        }

        d3.json('http://wri-01.cartodb.com/api/v2/sql/?q='+encodeURIComponent(sql), function(json) {
          var self = that,
              markup_list = '';

          var data = json.rows;
          var max_trigger = data.length -1;
          _.each(data, function(val, key) {
            var ord = e ? (key+11) : (key+1),
                enabled = val.enabled ? '<a href="/country/'+val.iso+'">'+val.name+'</a>' : val.name;
            if (! !!mode || (mode.mode != 'percent')) {
              $.ajax({
                url: window.gfw.config.GFW_API_HOST + '/forest-change/umd-loss-gain/admin/' + val.iso+'?thresh=30',
                dataType: 'json',
                success: _.bind(function(data) {
                  var g_mha, l_mha;
                  g_mha = l_mha = 'Mha';
                  data.years[1].gain = Math.round(data.years[1].gain);
                  if (data.years[1].gain.toString().length >= 7) {
                    data.years[1].gain = ((data.years[1].gain /1000)/1000).toFixed(2)
                  } else if (data.years[1].gain.toString().length >= 4) {
                    l_mha = 'KHa';
                    data.years[1].gain = (data.years[1].gain /1000);
                  if (data.years[1].gain % 1 != 0) data.years[1].gain = data.years[1].gain.toFixed(2)
                  } else {
                    l_mha = 'Ha';
                  }
                  $('#perc_'+val.iso+'').empty().append('<span class="loss line"><span>'+ parseFloat(data.years[1].gain).toLocaleString() +' '+ l_mha +' </span></span>');
                }
                , this),
              });
            }
            if (!!mode && mode.mode == 'percent') {
              markup_list += '<li>\
                              <div class="countries_list__num">'+ord+'</div>\
                              <div class="countries_list__title">'+enabled+'</div>\
                              <div class="countries_list__data">\
                                <div id="perc_'+val.iso+'" class="perct"><span class="loss line"><span>'+ val.ratio.toLocaleString() + '%</span></span></div>\
                              </div>\
                            </li>';
            } else {<commit_msg>Tree cover gain list is now calculated correctly<commit_after>/**
 * The Feed view.
 */
define([
  'jquery',
  'backbone',
  'underscore',
  'd3',
  'mps',
  'views/SourceWindowView',
  'views/ShareView',
  'countries/views/CountryHeaderView',
  'countries/helpers/CountryHelper'

], function($, Backbone, _, d3, mps, SourceWindowView, ShareView, CountryHeaderView, CountryHelper) {

  'use strict';

  var CountryOverviewModel = Backbone.Model.extend({
    defaults: {
      graph: 'total_loss',
      years: true,
      class: null
    }
  });



  var CountryOverviewView = Backbone.View.extend({

    el: '#countryOverviewView',

    events: {
      'click .graph_tab': '_updateGraph',
      'click .show-more-countries': '_drawList',
      'click .trigger-mode span': '_toggle_total_percent',
      'click .share-link': '_openShareModal'
    },

    initialize: function() {
      if (!this.$el.length) {
        return
      }

      this.helper = CountryHelper;
      this.model = new CountryOverviewModel();
      this.headerView = new CountryHeaderView();

      this.setListeners();

      this.$graph = $('.overview_graph__area');
      this.$years = $('.overview_graph__years');
      this.$big_figures   = $('.overview_graph__figure_only')
      var m = this.m = 40,
          w = this.w = this.$graph.width(),
          h = this.h = this.$graph.height(),
          vertical_m = this.vertical_m = 20;

      this.x_scale = d3.scale.linear()
        .range([m, w-m])
        .domain([2001, 2013]);

      this.grid_scale = d3.scale.linear()
        .range([vertical_m, h-vertical_m])
        .domain([0, 1]);

      this.model.bind('change:graph', this._redrawGraph, this);
      this.model.bind('change:years', this._toggleYears, this);
      this.model.bind('change:class', this._toggleClass, this);

      this._initViews();
    },

    _initViews: function() {
      this.sourceWindow = new SourceWindowView();

      this.tooltip = d3.select('body')
        .append('div')
        .attr('class', 'tooltip2');

      this._drawYears();
      this._drawGraph();
      this._drawList();
    },

    setListeners: function(){
      mps.subscribe('Threshold:change', _.bind(function(threshold){
        this.helper.config.canopy_choice = threshold;
        this._updateGraphOverview();
      }, this ));

    },

    _openShareModal: function(event) {
      var shareView = new ShareView().share(event);
      this.$el.append(shareView.el);
    },

    _toggleYears: function() {
      var that = this;

      if (this.model.get('years') === false) {
        this.$years.slideUp(250, function() {
          $('.overview_graph__axis').slideDown();
        });
      } else {
        $('.overview_graph__axis').slideUp(250, function() {
          that.$years.slideDown();
        });
      }
    },

    _showYears: function() {
      if (!this.model.get('years')) {
        this.model.set('years', true);
      }
    },

    _hideYears: function() {
      if (this.model.get('years')) {
        this.model.set('years', false);
      }
    },

    _updateGraph: function(e) {
      e.preventDefault();

      var $target = $(e.target).closest('.graph_tab'),
          graph = $target.attr('data-slug');

      if (graph === this.model.get('graph')) {
        return;
      } else {
        $('.graph_tab').removeClass('selected');
        $target.addClass('selected');

        this.model.set('graph', graph);
      }
      ga('send', 'event', 'Country overview', 'Click', 'Overview graph: ' + graph);
    },

    _redrawGraph: function() {
      var graph = this.model.get('graph');
      var $legend = $('.overview_graph__legend');
      $('.overview_graph__title').html(this.helper.config.GRAPHS[graph].title);
      $legend.find('p').html(this.helper.config.GRAPHS[graph].subtitle);
      $legend.find('.info').data('source', graph);

      this.$graph.removeClass('is-hidden');
      this.$years.removeClass('is-hidden');
      $legend.removeClass('is-hidden');

      this.$graph.find('.'+graph);

      this.$graph.find('.chart').hide();
      this.$graph.find('.'+graph).fadeIn();

      this._drawGraph();
      this._drawList();

      this.$el.find('.overview_button_group .settings').removeClass('disable')
      if (graph === 'total_extent' || graph === 'percent_loss') {
        this.$big_figures.show();
        this.$graph.addClass('is-hidden');
        this.$years.addClass('is-hidden');
        if (graph == 'percent_loss') this.$el.find('.overview_button_group .settings').addClass('disable')
      } else {
        this.$big_figures.hide();
      }
    },
    _updateGraphOverview: function(e) {
      if (typeof ga !== "undefined") ga('send', 'event', 'Country Overview', 'Change', 'Threshold');
      var $cnp_op = this.$el.find('.overview_button_group .settings')
      if (this.helper.config.canopy_choice != 30) $cnp_op.addClass('no_def');
      else $cnp_op.removeClass('no_def');

      this._drawYears();
      this._drawGraph();
      this._drawList();
    },

    _reorderRanking: function(e) {
      var $ul = $('.countries_list ul'),
      $ul_li = $ul.children('li');

      $ul_li.sort(function(a,b){
        var an = parseFloat($(a).find('.loss').data('orig')),
            bn = parseFloat($(b).find('.loss').data('orig'));
        if(an > bn) {
          return -1;
        }
        if(an < bn) {
          return 1;
        }
        return 0;
      });

      $ul_li.detach().appendTo($ul);
      $ul_li.find('.countries_list__num').each(function(i, ele){ $(ele).empty().text(i+1) })
    },

    _toggle_total_percent: function(e) {
      if (!sessionStorage.getItem('OVERVIEWMODE')) {
        var mode = JSON.stringify(
        {
          'mode': 'percent'
        });
        sessionStorage.setItem('OVERVIEWMODE', mode);
      } else {
        var mode = JSON.parse(sessionStorage.getItem('OVERVIEWMODE'));
        mode = (!!mode & mode.mode == 'total') ? 'percent' : 'total';
        sessionStorage.setItem('OVERVIEWMODE', JSON.stringify({'mode':mode}))
      }
      this._drawList();
      this._drawGraph();
    },

    _drawList: function(e) {
      var that = this;

      e && e.preventDefault();

      if (this.model.get('graph') === 'total_loss') {
        var sql = 'SELECT umd.iso, c.name, c.enabled, Sum(umd.loss) loss FROM umd_nat_final_1 umd, gfw2_countries c WHERE thresh = '+ (this.helper.config.canopy_choice || 30) +' AND umd.iso = c.iso AND NOT loss = 0 AND umd.year > 2000 GROUP BY umd.iso, c.name, c.enabled ORDER BY loss DESC ';
        var mode = JSON.parse(sessionStorage.getItem('OVERVIEWMODE'));
        if (!!mode && mode.mode == 'percent') {
          sql = 'SELECT umd.iso, c.name, c.enabled, Sum(umd.loss) / umd.extent_2000 loss_perc FROM umd_nat_final_1 umd, gfw2_countries c WHERE thresh = '+ (this.helper.config.canopy_choice || 30) +' AND umd.iso = c.iso AND NOT loss_perc = 0 AND umd.year > 2000 AND extent_2000 > 10 GROUP BY umd.extent_2000, umd.iso, c.name, c.enabled ORDER BY loss_perc DESC '
        }

        if (e) {
          sql += 'OFFSET 10';
          $('.show-more-countries').fadeOut();
        } else {
          sql += 'LIMIT 10';
          $('.countries_list ul').html('');
          $('.show-more-countries').show();
        }
        d3.json('http://wri-01.cartodb.com/api/v2/sql/?q='+encodeURIComponent(sql), _.bind(function(json) {
          var self = that,
              markup_list = '';

          var data = json.rows;

          _.each(data, _.bind(function(val, key) {
            var ord = e ? (key+11) : (key+1),
                enabled = val.enabled ? '<a href="/country/'+val.iso+'">'+val.name+'</a>' : val.name;

            var max_trigger = data.length -1;
            $.ajax({
              url: window.gfw.config.GFW_API_HOST + '/forest-change/umd-loss-gain/admin/' + val.iso+'?thresh=' + (this.helper.config.canopy_choice || 30),
              dataType: 'json',
              success: _.bind(function(data) {
                var loss = Math.round(val.loss) || (val.loss_perc*100).toFixed(3);
                var orig = loss;
                var g_mha, l_mha = '%';

                if (! !!val.loss_perc){
                  g_mha = l_mha = 'Mha';
                  if (loss.toString().length >= 7) {
                    loss = ((loss /1000)/1000).toFixed(2)
                  } else if (loss.toString().length >= 4) {
                    l_mha = 'KHa';
                    loss = (loss /1000);
                  if (loss % 1 != 0) loss = loss.toFixed(2)
                  } else {
                    l_mha = 'Ha';
                  }
                }

                $('#umd_'+val.iso+'').empty().append('<span class="loss line" data-orig="' + orig + '"><span>'+ parseFloat(loss).toLocaleString() +' </span>'+ l_mha +'</span>');

                if (key == max_trigger){
                  that._reorderRanking();
                }
              }, this),
            });
            markup_list += '<li>\
                              <div class="countries_list__minioverview countries_list__minioverview_'+val.iso+'"></div>\
                              <div class="countries_list__num">'+ord+'</div>\
                              <div class="countries_list__title">'+enabled+'</div>\
                              <div class="countries_list__data">\
                                <div id="umd_'+val.iso+'"></div>\
                              </div>\
                            </li>';
          }, this ));

          if (e) {
            $('.show-more-countries').fadeOut();
          } else {
            $('.countries_list ul').html('');
            $('.show-more-countries').show();

            if (!!mode && mode.mode == 'percent') {
              $('.overview_graph__legend').find('.trigger-mode').html('<span>GROSS LOSS</span> <strong>PERCENT LOSS</strong>').show();
              $('.overview_graph__title').html('Countries with greatest percent loss (2001-2013) relative to tree cover in 2000');

            } else {
              $('.overview_graph__legend').find('.trigger-mode').html('<strong>GROSS LOSS</strong> <span>PERCENT LOSS</span>').show();
              $('.overview_graph__title').html('Countries with greatest tree cover loss (2001-2013)');
            }
          }

          $('.countries_list ul').append(markup_list);

          that.model.set('class', null);
          if (!!mode && mode.mode == 'percent') {
            $('.countries_list__data').addClass('no-graph');
          } else {
            _.each(data, function(val, key) {
              self._drawMiniOverview(val.iso);
            });
          }
        }, this ));
      } else if (this.model.get('graph') === 'percent_loss') {
        $('.countries_list__header__minioverview').hide();
        var mode = JSON.parse(sessionStorage.getItem('OVERVIEWMODE'));

        var sql = 'SELECT umd.iso, c.name, c.enabled, Sum(umd.gain) gain FROM umd_nat_final_1 umd, gfw2_countries c WHERE umd.iso = c.iso AND NOT loss = 0 AND umd.year > 2000 GROUP BY umd.iso, c.name, c.enabled ORDER BY gain DESC ';
        if (!!mode && mode.mode == 'percent')
            sql = 'SELECT (gain*12/extent_2000)*100 as ratio, country as name, c.iso as iso, c.enabled, u.iso as iso2 from umd_nat_final_1 u, gfw2_countries c  WHERE thresh = 50 AND c.iso = u.iso AND extent_2000 > 10  group by ratio, country, u.iso, c.iso, c.enabled order by ratio desc ';
        if (e) {
          sql += 'OFFSET 10';
        } else {
          sql += 'LIMIT 10';
        }

        d3.json('http://wri-01.cartodb.com/api/v2/sql/?q='+encodeURIComponent(sql), function(json) {
          var self = that,
              markup_list = '';

          var data = json.rows;
          var max_trigger = data.length -1;
          _.each(data, function(val, key) {
            var ord = e ? (key+11) : (key+1),
                enabled = val.enabled ? '<a href="/country/'+val.iso+'">'+val.name+'</a>' : val.name;
            if (! !!mode || (mode.mode != 'percent')) {
              $.ajax({
                url: window.gfw.config.GFW_API_HOST + '/forest-change/umd-loss-gain/admin/' + val.iso+'?thresh=30',
                dataType: 'json',
                success: _.bind(function(data) {
                  var g_mha, l_mha;
                  g_mha = l_mha = 'Mha';
                  data.years[1].gain = Math.round(data.years[1].total_gain);
                  if (data.years[1].gain.toString().length >= 7) {
                    data.years[1].gain = ((data.years[1].gain /1000)/1000).toFixed(2)
                  } else if (data.years[1].gain.toString().length >= 4) {
                    l_mha = 'KHa';
                    data.years[1].gain = (data.years[1].gain /1000);
                  if (data.years[1].gain % 1 != 0) data.years[1].gain = data.years[1].gain.toFixed(2)
                  } else {
                    l_mha = 'Ha';
                  }
                  $('#perc_'+val.iso+'').empty().append('<span class="loss line"><span>'+ parseFloat(data.years[1].gain).toLocaleString() +' '+ l_mha +' </span></span>');
                }
                , this),
              });
            }
            if (!!mode && mode.mode == 'percent') {
              markup_list += '<li>\
                              <div class="countries_list__num">'+ord+'</div>\
                              <div class="countries_list__title">'+enabled+'</div>\
                              <div class="countries_list__data">\
                                <div id="perc_'+val.iso+'" class="perct"><span class="loss line"><span>'+ val.ratio.toLocaleString() + '%</span></span></div>\
                              </div>\
                            </li>';
            } else {
{'fraction_non_alphanumeric': 0.17387159461738716, 'fraction_numerical': 0.014006526601400653, 'mean_word_length': 1.9840262582056893, 'pattern_counts': {'":': 0, '<': 97, '<?xml version=': 0, '>': 115, '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': '676524', 'n_tokens_mistral': 8936, 'n_tokens_neox': 8371, 'n_words': 1533}