<commit_before>$(document).ready(function(){

  $(".sk-folding-cube").hide();

  // show spinner on AJAX start
  $(document).ajaxStart(function(){
    $(".sk-folding-cube").show();
  });

  // hide spinner on AJAX stop
  $(document).ajaxStop(function(){
    $(".sk-folding-cube").hide();
  });

  var utcdate = function(data){

    var year = data[0];
    var month = data[1];
    var day = data[2];

    return Date.UTC(year, month, day)
  };

  var portfolio_id = $( '.hidden_portfolio_id' ).text();

  var link = "/portfolios/" + portfolio_id + "/fetch";

  console.log(link);

  var request = $.ajax({
    url: link,
    type: "GET"
  });

  request.done(function(response){

    // prepare data for pie chart
    var data_for_pie = [];

    for (var i=0; i < response["holdings"].length; i++){
    data_for_pie.push({name: response["holdings"][i]["symbol"],
        y: response["holdings"][i]["allocation"]})
    }

    for (var i=0; i < response["stocks"].length; i++){
      response["stocks"][i][0] = utcdate(response["stocks"][i][0]);
    }
    for (var i=0; i < response["nasdaq"].length; i++){
      response["nasdaq"][i][0] = utcdate(response["nasdaq"][i][0]);
    }
    for (var i=0; i < response["snp"].length; i++){
      response["snp"][i][0] = utcdate(response["snp"][i][0]);
    }
    for (var i=0; i < response["dji"].length; i++){
      response["dji"][i][0] = utcdate(response["dji"][i][0]);
    }
    for (var i = 0; i < response["articles"].length; i++){
      response["articles"][i][1] = jQuery.parseJSON(response["articles"][i][1])
    }

    // construct both charts
    startChart(response["stocks"],response["nasdaq"],response["snp"],response["dji"],response["articles"],response["title"]);
    startPieChart(data_for_pie)

  });

  request.fail(function(){
    console.log("request failed");

  });

});

var startPieChart = function(data_for_pie){
  $(function () {
  $('#pie-chart').highcharts({
    chart: {
      plotBackgroundColor: null,
      plotBorderWidth: null,
      plotShadow: false,
      type: 'pie'
    },
    title: {
      text: 'Look I am a Pie chart for your portfolio'
    },
    credits: {
      enabled: false
  },
    tooltip: {
      pointFormat: '{series.name}: {point.percentage:.1f}%'
    },
    plotOptions: {
      pie: {
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: {
          enabled: true,
          format: '{point.name}: {point.percentage:.1f} %',
          style: {
            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
          }
        }
      }
    },
    series: [{
      name: 'Brands',
      colorByPoint: true,
      data: data_for_pie

      // }, {
      //     name: 'Chrome',
      //     y: 24.03,
      //     sliced: true,
      //     selected: true
      // }, {
      //     name: 'Firefox',
      //     y: 10.38
      // }, {
      //     name: 'Safari',
      //     y: 4.77
      // }, {
      //     name: 'Opera',
      //     y: 0.91
      // }, {
      //     name: 'Proprietary or Undetectable',
      //     y: 0.2

    }]
  });
  });
};

var startChart = function(stocks,nasdaq,snp,dji,articles,title){
  $(function () {
      var seriesOptions = [],
          seriesCounter = 0,
          names = ['Portfolio','NASDAQ', 'SNP', 'DJI'],
          data = [stocks,nasdaq,snp,dji];
      /**
       * Create the chart when all data is loaded
       * @returns {undefined}
       */
      function createChart() {
        $('#chart').highcharts('StockChart', {
            rangeSelector: {
                selected: 4
          },
          yAxis: {
              labels: {
                  formatter: function () {
                      return (this.value > 0 ? ' + ' : '') + this.value + '%';
                  }
              },
              plotLines: [{
                  value: 0,
                  width: 2,
                  color: 'silver'
              }]
          },
          plotOptions: {
              series: {
                  compare: 'percent'

              }
          },
          tooltip: {
              pointFormat: '{series.name}: {point.y} ({point.change}%)
',
              valueDecimals: 2
          },
          title : {
            text : title
          },
          credits: {
           enabled: true
          },
          plotOptions:{
                flags:{
                    point:{
                    events:{
                        click:function(e){
                            e.preventDefault();
                            var url = this.url;
                            window.open(url,'_blank');
                        }

                      }
                    }
                }
            },
            series: seriesOptions
        }

      );
    }
    $.each(names, function (i, name) {
        seriesOptions[i] = {
            name: name,
            data: data[i],
            id: i + 1
        // As we're loading the data asynchronously, we don't know what order it will arrive. So
        // we keep a counter and create the chart when all the data is loaded.
        // seriesCounter += 1;
        // if (seriesCounter === names.length) {
        //     createChart();
        // }
      }
    });
    for (var i = 0; i < articles.length; i++){
      for (var j =0; j <articles[i][1].response.docs.length; j++){
        seriesOptions.push({
                type: 'flags',
                data: [{
                  x : Date.parse(articles[i][1].response.docs[j].pub_date),
                  title: articles[i][0],
                  url: articles[i][1].response.docs[j].web_url
                }],
                onSeries: 1
                })
      }
    }
    createChart();
  });

};
<commit_msg>Remove console.log<commit_after>$(document).ready(function(){

  $(".sk-folding-cube").hide();

  // show spinner on AJAX start
  $(document).ajaxStart(function(){
    $(".sk-folding-cube").show();
  });

  // hide spinner on AJAX stop
  $(document).ajaxStop(function(){
    $(".sk-folding-cube").hide();
  });

  var utcdate = function(data){

    var year = data[0];
    var month = data[1];
    var day = data[2];

    return Date.UTC(year, month, day)
  };

  var portfolio_id = $( '.hidden_portfolio_id' ).text();

  var link = "/portfolios/" + portfolio_id + "/fetch";

  var request = $.ajax({
    url: link,
    type: "GET"
  });

  request.done(function(response){

    // prepare data for pie chart
    var data_for_pie = [];

    for (var i=0; i < response["holdings"].length; i++){
    data_for_pie.push({name: response["holdings"][i]["symbol"],
        y: response["holdings"][i]["allocation"]})
    }

    for (var i=0; i < response["stocks"].length; i++){
      response["stocks"][i][0] = utcdate(response["stocks"][i][0]);
    }
    for (var i=0; i < response["nasdaq"].length; i++){
      response["nasdaq"][i][0] = utcdate(response["nasdaq"][i][0]);
    }
    for (var i=0; i < response["snp"].length; i++){
      response["snp"][i][0] = utcdate(response["snp"][i][0]);
    }
    for (var i=0; i < response["dji"].length; i++){
      response["dji"][i][0] = utcdate(response["dji"][i][0]);
    }
    for (var i = 0; i < response["articles"].length; i++){
      response["articles"][i][1] = jQuery.parseJSON(response["articles"][i][1])
    }

    // construct both charts
    startChart(response["stocks"],response["nasdaq"],response["snp"],response["dji"],response["articles"],response["title"]);
    startPieChart(data_for_pie)

  });

  request.fail(function(){
    console.log("request failed");

  });

});

var startPieChart = function(data_for_pie){
  $(function () {
  $('#pie-chart').highcharts({
    chart: {
      plotBackgroundColor: null,
      plotBorderWidth: null,
      plotShadow: false,
      type: 'pie'
    },
    title: {
      text: 'Look I am a Pie chart for your portfolio'
    },
    credits: {
      enabled: false
  },
    tooltip: {
      pointFormat: '{series.name}: {point.percentage:.1f}%'
    },
    plotOptions: {
      pie: {
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: {
          enabled: true,
          format: '{point.name}: {point.percentage:.1f} %',
          style: {
            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
          }
        }
      }
    },
    series: [{
      name: 'Brands',
      colorByPoint: true,
      data: data_for_pie

      // }, {
      //     name: 'Chrome',
      //     y: 24.03,
      //     sliced: true,
      //     selected: true
      // }, {
      //     name: 'Firefox',
      //     y: 10.38
      // }, {
      //     name: 'Safari',
      //     y: 4.77
      // }, {
      //     name: 'Opera',
      //     y: 0.91
      // }, {
      //     name: 'Proprietary or Undetectable',
      //     y: 0.2

    }]
  });
  });
};

var startChart = function(stocks,nasdaq,snp,dji,articles,title){
  $(function () {
      var seriesOptions = [],
          seriesCounter = 0,
          names = ['Portfolio','NASDAQ', 'SNP', 'DJI'],
          data = [stocks,nasdaq,snp,dji];
      /**
       * Create the chart when all data is loaded
       * @returns {undefined}
       */
      function createChart() {
        $('#chart').highcharts('StockChart', {
            rangeSelector: {
                selected: 4
          },
          yAxis: {
              labels: {
                  formatter: function () {
                      return (this.value > 0 ? ' + ' : '') + this.value + '%';
                  }
              },
              plotLines: [{
                  value: 0,
                  width: 2,
                  color: 'silver'
              }]
          },
          plotOptions: {
              series: {
                  compare: 'percent'

              }
          },
          tooltip: {
              pointFormat: '{series.name}: {point.y} ({point.change}%)
',
              valueDecimals: 2
          },
          title : {
            text : title
          },
          credits: {
           enabled: true
          },
          plotOptions:{
                flags:{
                    point:{
                    events:{
                        click:function(e){
                            e.preventDefault();
                            var url = this.url;
                            window.open(url,'_blank');
                        }

                      }
                    }
                }
            },
            series: seriesOptions
        }

      );
    }
    $.each(names, function (i, name) {
        seriesOptions[i] = {
            name: name,
            data: data[i],
            id: i + 1
        // As we're loading the data asynchronously, we don't know what order it will arrive. So
        // we keep a counter and create the chart when all the data is loaded.
        // seriesCounter += 1;
        // if (seriesCounter === names.length) {
        //     createChart();
        // }
      }
    });
    for (var i = 0; i < articles.length; i++){
      for (var j =0; j <articles[i][1].response.docs.length; j++){
        seriesOptions.push({
                type: 'flags',
                data: [{
                  x : Date.parse(articles[i][1].response.docs[j].pub_date),
                  title: articles[i][0],
                  url: articles[i][1].response.docs[j].web_url
                }],
                onSeries: 1
                })
      }
    }
    createChart();
  });

};
<|endoftext|>


<commit_before>/*-----------------------------------------------------------------------*/

function get_names() {

  return get_json('/poet/names/').names;
}
/*-----------------------------------------------------------------------*/

function post_create_or_get(name) {

  var xmlhttp = get_xmlhttp();
  var AUTH_TOKEN = $('meta[name=csrf-token]').attr('content');

  var name = encodeURIComponent(name);
  var authenticity = encodeURIComponent(AUTH_TOKEN);

  var data = "authenticity_token="+authenticity+"&name="+name

  xmlhttp.open("POST", "/poet/post_create_or_get", false);
  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  xmlhttp.send(data);

  return jQuery.parseJSON(xmlhttp.responseText);
}

/*-----------------------------------------------------------------------*/

function post_suggestions(name, xmlhttp) {

  var limit = 50;

  var AUTH_TOKEN = $('meta[name=csrf-token]').attr('content');

  var name = encodeURIComponent(name);
  var authenticity = encodeURIComponent(AUTH_TOKEN);

  var data = "authenticity_token="+authenticity+"&name="+name+"&limit="+limit;

  xmlhttp.open("POST", "/poet/post_suggestions", true);
  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  xmlhttp.send(data);
}

/*-----------------------------------------------------------------------*/

function suggest_onclick(cell) {

  var input_id = $(cell).parents('table').attr('id') + '_input';
  var input = document.getElementById(input_id);

  input.value = cell.innerHTML;
  remove_suggestions(document.getElementById($(cell).parents('table').attr('id')));
}

/*-----------------------------------------------------------------------*/

function handle_onmouseover_cell(cell) {

  var table_id = $(cell).parents('table').attr('id');
  var table = document.getElementById(table_id);

  cell.original_color = cell.style.backgroundColor;
  cell.style.backgroundColor = '#D8D8D8';

  if (table.index != -1 && cell.index != table.index && table.index < table.cells.length)
    handle_onmouseout_cell(table.cells[table.index]);

  table.index = cell.index;
}

/*-----------------------------------------------------------------------*/

function handle_onmouseout_cell(cell) {

  cell.style.backgroundColor = cell.original_color;
}

/*-----------------------------------------------------------------------*/

function clear_suggestions_data(table) {

  table.is_poet_in_database = false;
  table.index = -1;
  table.cells = [];
}

/*-----------------------------------------------------------------------*/

function add_suggestions(table, names, name) {

  clear_suggestions_data(table);

  for (var i=0; i<names.length; i++) {

    var row = table.insertRow(-1);

    var cell = row.insertCell(0);
    table.cells.push(cell);
    cell.index = i;
    cell.setAttribute("border", "none");
    cell.style.border = "none";
    cell.innerHTML = names[i]; //Sanitizing it sometime?

    row.className = "suggestion";
    cell.onmouseover = function() {handle_onmouseover_cell(this);};
    cell.onmouseout = function() {handle_onmouseout_cell(this);};
    cell.onclick = function() {suggest_onclick(this);};

    if (name.replace(/\s+/g, ' ').trim().toLowerCase() == names[i].toLowerCase()) {
      cell.style.backgroundColor = "#C6AEC7";
      table.is_poet_in_database = true;
    }

  }

  var num_suggestions = parseInt(table.getAttribute("data-num_suggestions"));
  num_suggestions += names.length;
  table.setAttribute("data-num_suggestions", num_suggestions);

}
/*-----------------------------------------------------------------------*/

function remove_suggestions(table) {

  var num_suggestions = parseInt(table.getAttribute("data-num_suggestions"));

  for (var i=0; i<num_suggestions; i++)
    table.deleteRow(-1)

  table.setAttribute("data-num_suggestions", 0);
}
/*-----------------------------------------------------------------------*/

// Get suggestions from the server and display the suggestions.
function get_suggestions_from_server(table, data) {

  data.state = "pending";
  var name = data.name;

  if((/^\s*$/).test(name)) {
    remove_suggestions(table);
    data.state = "done";
    return true;
  }

  var xmlhttp = get_xmlhttp();

  xmlhttp.onreadystatechange = function()
      {
       if (xmlhttp.readyState==4 && xmlhttp.status==200) {
	remove_suggestions(table);

        var names =  jQuery.parseJSON(xmlhttp.responseText).names;
        console.log(names);
	add_suggestions(table, names, name);

	data.state = "done";
       }
      };

  post_suggestions(name, xmlhttp);
  return true;
}
/*-----------------------------------------------------------------------*/

function init_suggestions(table) {

  if (table.queue === undefined) {
    table.queue = [];
    var interval = 10;
    setInterval(process_queue, interval, table);
  }
}

/*-----------------------------------------------------------------------*/
function process_queue(table) {

  if (table.queue.length >0 && table.queue[0].state == "pending")
    return;

  if (table.queue.length > 0 && table.queue[0].state == "done")
    table.queue.splice(0,1);

  if (table.queue.length > 0 && table.queue[0].state == "start") {

    if (table.queue.length > 1)
      table.queue.splice(0, table.queue.length - 1); // We can ignore all but the last item on the queue

    get_suggestions_from_server(table, table.queue[0]);
  }
}

/*-----------------------------------------------------------------------*/
function display_suggestions_for_name(table, name) {

  if (window.event.keyCode == 38 || window.event.keyCode == 40 || window.event.keyCode == 13)
    return;

  // data.state is on one three: "start", "pending", "done"
  init_suggestions(table);

  var data = {};
  data.state = "start";
  data.name = name;

  table.queue.push(data);

  console.log(window.event.keyCode);
}

/*-----------------------------------------------------------------------*/

function handle_onfocus(input) {

  window.suggestion_table = document.getElementById($(input).parents('table').attr('id'));
  window.original_onkeydown = document.onkeydown;

  document.onkeydown = function() {

    if (window.original_onkeydown != null)
      window.original_onkeydown();

    onkeydown();
  };
}

/*-----------------------------------------------------------------------*/
function handle_onblur(input) {

  document.onkeydown = window.original_onkeydown;
  window.suggestion_table = null;

}
/*-----------------------------------------------------------------------*/

function onkeydown() {

  var table = window.suggestion_table;

  switch (window.event.keyCode) {

    case 38: // Up Arrow

      if (table.index > 0) {
	var cell = table.cells[table.index -1];
	handle_onmouseover_cell(cell);
      }
      break;
    case 40: // Down Arrow

      if (table.index < table.cells.length -1) {
	var cell = table.cells[table.index + 1];
	handle_onmouseover_cell(cell);
      }
      break;
    case 13: //Enter
      var cell = table.cells[table.index];
      suggest_onclick(cell);
      break;
  }
}
/*-----------------------------------------------------------------------*/
<commit_msg>fixed (I believe) bugs related to keyboard support for poet names suggestions<commit_after>/*-----------------------------------------------------------------------*/

function get_names() {

  return get_json('/poet/names/').names;
}
/*-----------------------------------------------------------------------*/

function post_create_or_get(name) {

  var xmlhttp = get_xmlhttp();
  var AUTH_TOKEN = $('meta[name=csrf-token]').attr('content');

  var name = encodeURIComponent(name);
  var authenticity = encodeURIComponent(AUTH_TOKEN);

  var data = "authenticity_token="+authenticity+"&name="+name

  xmlhttp.open("POST", "/poet/post_create_or_get", false);
  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  xmlhttp.send(data);

  return jQuery.parseJSON(xmlhttp.responseText);
}

/*-----------------------------------------------------------------------*/

function post_suggestions(name, xmlhttp) {

  var limit = 50;

  var AUTH_TOKEN = $('meta[name=csrf-token]').attr('content');

  var name = encodeURIComponent(name);
  var authenticity = encodeURIComponent(AUTH_TOKEN);

  var data = "authenticity_token="+authenticity+"&name="+name+"&limit="+limit;

  xmlhttp.open("POST", "/poet/post_suggestions", true);
  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  xmlhttp.send(data);
}

/*-----------------------------------------------------------------------*/

function suggest_onclick(cell) {

  var input_id = $(cell).parents('table').attr('id') + '_input';
  var input = document.getElementById(input_id);

  input.value = cell.innerHTML;
  remove_suggestions(document.getElementById($(cell).parents('table').attr('id')));
}

/*-----------------------------------------------------------------------*/

function handle_onmouseover_cell(cell) {

  var table_id = $(cell).parents('table').attr('id');
  var table = document.getElementById(table_id);
  if (cell.index == table.index)
    return;

  for (var i=0; i<table.cells.length; i++)
    handle_onmouseout_cell(table.cells[i]);

  cell.original_color = cell.style.backgroundColor;
  cell.style.backgroundColor = '#D8D8D8';

  table.index = cell.index;
}

/*-----------------------------------------------------------------------*/

function handle_onmouseout_cell(cell) {

  var table_id = $(cell).parents('table').attr('id');
  var table = document.getElementById(table_id);
  table.index = -1;

  cell.style.backgroundColor = cell.original_color;
}

/*-----------------------------------------------------------------------*/

function clear_suggestions_data(table) {

  table.is_poet_in_database = false;
  table.index = -1;
  table.cells = [];
}

/*-----------------------------------------------------------------------*/

function add_suggestions(table, names, name) {

  clear_suggestions_data(table);

  for (var i=0; i<names.length; i++) {

    var row = table.insertRow(-1);

    var cell = row.insertCell(0);
    table.cells.push(cell);
    cell.index = i;
    cell.setAttribute("border", "none");
    cell.style.border = "none";
    cell.innerHTML = names[i]; //Sanitizing it sometime?

    row.className = "suggestion";
    cell.onmouseover = function() {handle_onmouseover_cell(this);};
    cell.onmouseout = function() {handle_onmouseout_cell(this);};
    cell.onclick = function() {suggest_onclick(this);};

    if (name.replace(/\s+/g, ' ').trim().toLowerCase() == names[i].toLowerCase()) {
      cell.style.backgroundColor = "#C6AEC7";
      table.is_poet_in_database = true;
    }

  }

  var num_suggestions = parseInt(table.getAttribute("data-num_suggestions"));
  num_suggestions += names.length;
  table.setAttribute("data-num_suggestions", num_suggestions);

}
/*-----------------------------------------------------------------------*/

function remove_suggestions(table) {

  var num_suggestions = parseInt(table.getAttribute("data-num_suggestions"));

  for (var i=0; i<num_suggestions; i++)
    table.deleteRow(-1)

      table.setAttribute("data-num_suggestions", 0);
}
/*-----------------------------------------------------------------------*/

// Get suggestions from the server and display the suggestions.
function get_suggestions_from_server(table, data) {

  data.state = "pending";
  var name = data.name;

  if((/^\s*$/).test(name)) {
    remove_suggestions(table);
    data.state = "done";
    return true;
  }

  var xmlhttp = get_xmlhttp();

  xmlhttp.onreadystatechange = function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      remove_suggestions(table);

      var names =  jQuery.parseJSON(xmlhttp.responseText).names;
      console.log(names);
      add_suggestions(table, names, name);

      data.state = "done";
    }
  };

  post_suggestions(name, xmlhttp);
  return true;
}
/*-----------------------------------------------------------------------*/

function init_suggestions(table) {

  if (table.queue === undefined) {
    table.queue = [];
    var interval = 10;
    setInterval(process_queue, interval, table);
  }
}

/*-----------------------------------------------------------------------*/
function process_queue(table) {

  if (table.queue.length >0 && table.queue[0].state == "pending")
    return;

  if (table.queue.length > 0 && table.queue[0].state == "done")
    table.queue.splice(0,1);

  if (table.queue.length > 0 && table.queue[0].state == "start") {

    if (table.queue.length > 1)
      table.queue.splice(0, table.queue.length - 1); // We can ignore all but the last item on the queue

    get_suggestions_from_server(table, table.queue[0]);
  }
}

/*-----------------------------------------------------------------------*/
function display_suggestions_for_name(table, name) {

  if (window.event.keyCode == 38 || window.event.keyCode == 40 || window.event.keyCode == 13)
    return;

  // data.state is on one three: "start", "pending", "done"
  init_suggestions(table);

  var data = {};
  data.state = "start";
  data.name = name;

  table.queue.push(data);

  console.log(window.event.keyCode);
}

/*-----------------------------------------------------------------------*/

function handle_onfocus(input) {

  window.suggestion_table = document.getElementById($(input).parents('table').attr('id'));
  window.original_onkeydown = document.onkeydown;

  document.onkeydown = function() {

    if (window.original_onkeydown != null)
      window.original_onkeydown();

    onkeydown();
  };
}

/*-----------------------------------------------------------------------*/
function handle_onblur(input) {

  document.onkeydown = window.original_onkeydown;
  window.suggestion_table = null;

}
/*-----------------------------------------------------------------------*/

function onkeydown() {

  var table = window.suggestion_table;

  switch (window.event.keyCode) {

    case 38: // Up Arrow

      if (table.index > 0) {
	var cell = table.cells[table.index -1];
	handle_onmouseover_cell(cell);
      }
      break;
    case 40: // Down Arrow

      if (table.index < table.cells.length -1) {
	var cell = table.cells[table.index + 1];
	handle_onmouseover_cell(cell);
      }
      break;
    case 13: //Enter
      var cell = table.cells[table.index];
      suggest_onclick(cell);
      break;
  }
}
/*-----------------------------------------------------------------------*/
<|endoftext|>


<commit_before>$(function () {
  totalApproved()

  if (document.getElementById('additional-info-reject').value = 'Other') {
    document.getElementById('additional-info-reject-manual').disabled = false
    document.getElementById('additional-info-reject-manual').visible = true
  }

  $('.claim-expense-status').change(function () {
    var id = $(this).attr('data-id')
    var value = $(this).val()
    if (value === 'APPROVED-DIFF-AMOUNT') {
      $(`#claim-expense-${id}-approvedcost`).removeClass('visibility-hidden').addClass('visibility-visible')
      $(this).next('input').on('input').addClass('approved-amount')
      $(this).parent().parent().find('td.cost').removeClass('approved-amount')
      $('input.approved-amount').on('input', function () {
        totalApproved()
      })
    } else if (value === 'APPROVED') {
      $(`#claim-expense-${id}-approvedcost`).removeClass('visibility-visible').addClass('visibility-hidden')
      $(this).parent().parent().find('td.cost').addClass('approved-amount')
      $(this).next('input').on('input').removeClass('approved-amount')
    } else {
      $(`#claim-expense-${id}-approvedcost`).removeClass('visibility-visible').addClass('visibility-hidden')
      $(this).parent().parent().find('td.cost').removeClass('approved-amount')
      $(this).next('input').on('input').removeClass('approved-amount')
    } totalApproved()
  })

  $('input[value="Remove"]').parent().parent().find('td.deduction').addClass('approved-amount')
  $('input.approved-amount').on('input', function () {
    totalApproved()
  })

  $('.claim-expense-status').each(function () {
    var value = this[this.selectedIndex].value
    if (value === 'APPROVED') {
      $(this).parent().parent().find('td.cost').addClass('approved-amount')
      $(this).next('input').removeClass('approved-amount')
    } else if (value === 'APPROVED-DIFF-AMOUNT') {
      $(this).next('input').addClass('approved-amount')
      $(this).parent().parent().find('td.cost').removeClass('approved-amount')
    } else {
      $(this).parent().parent().find('td.cost').removeClass('approved-amount')
    }
  })

  $('.approved-amount').each(function () {
    totalApproved()
  })

  $('#overpayment-toggle').change(function () {
    showClosedClaimActionSection('#overpayment-input')
  })

  $('#close-toggle').change(function () {
    showClosedClaimActionSection('#close-advanced-claim-input')
  })

  $('#request-new-payment-details-toggle').change(function () {
    showClosedClaimActionSection('#request-new-payment-details-input')
  })

  $('#additional-info-reject').change(function () {
    if (this[this.selectedIndex].value === 'Other') {
      document.getElementById('additional-info-reject-manual').disabled = false
      document.getElementById('additional-info-reject-manual').visible = true

    } else {
      document.getElementById('additional-info-reject-manual').disabled = true
      document.getElementById('additional-info-reject-manual').visible = false
      document.getElementById('additional-info-reject-manual').value = ''
    }
  })
})

function totalApproved () {
  var approvedCost = 0
  var manuallyProcessed = 0

  if ($('#unassign').length) {
    $('input.approved-amount').each(function () {
      if (!isNaN(this.value) && this.value.length !== 0 && this.value.indexOf('e') === -1 && this.value.indexOf('E') === -1) {
        manuallyProcessed += parseFloat(this.value)
      }
    })

    $('td.approved-amount').each(function () {
      approvedCost += +$(this).text().replace('£', '')
    })
  } else { // use hidden approved cost for unassigned claims
    $('input.approved-cost').each(function () {
      if (!isNaN(this.value) && this.value.length !== 0) {
        approvedCost += parseFloat(this.value)
      }
    })
    $('td.deduction').each(function () {
      approvedCost += +$(this).text().replace('£', '')
    })
  }

  $('.claim-expense-approvedCostText').text('£' + (approvedCost + manuallyProcessed).toFixed(2))
}

function showClosedClaimActionSection (id) {
  $('#overpayment-input').addClass('js-hidden')
  $('#close-advanced-claim-input').addClass('js-hidden')
  $('#request-new-payment-details-input').addClass('js-hidden')
  $(id).removeClass('js-hidden')
}
<commit_msg>APVS0142: Fixng an issue with jQuery that automatically selected the 'other' rejection reason when the page loaded<commit_after>$(function () {
  totalApproved()

  if (document.getElementById('additional-info-reject').value === 'Other') {
    document.getElementById('additional-info-reject-manual').disabled = false
    document.getElementById('additional-info-reject-manual').visible = true
  }

  $('.claim-expense-status').change(function () {
    var id = $(this).attr('data-id')
    var value = $(this).val()
    if (value === 'APPROVED-DIFF-AMOUNT') {
      $(`#claim-expense-${id}-approvedcost`).removeClass('visibility-hidden').addClass('visibility-visible')
      $(this).next('input').on('input').addClass('approved-amount')
      $(this).parent().parent().find('td.cost').removeClass('approved-amount')
      $('input.approved-amount').on('input', function () {
        totalApproved()
      })
    } else if (value === 'APPROVED') {
      $(`#claim-expense-${id}-approvedcost`).removeClass('visibility-visible').addClass('visibility-hidden')
      $(this).parent().parent().find('td.cost').addClass('approved-amount')
      $(this).next('input').on('input').removeClass('approved-amount')
    } else {
      $(`#claim-expense-${id}-approvedcost`).removeClass('visibility-visible').addClass('visibility-hidden')
      $(this).parent().parent().find('td.cost').removeClass('approved-amount')
      $(this).next('input').on('input').removeClass('approved-amount')
    } totalApproved()
  })

  $('input[value="Remove"]').parent().parent().find('td.deduction').addClass('approved-amount')
  $('input.approved-amount').on('input', function () {
    totalApproved()
  })

  $('.claim-expense-status').each(function () {
    var value = this[this.selectedIndex].value
    if (value === 'APPROVED') {
      $(this).parent().parent().find('td.cost').addClass('approved-amount')
      $(this).next('input').removeClass('approved-amount')
    } else if (value === 'APPROVED-DIFF-AMOUNT') {
      $(this).next('input').addClass('approved-amount')
      $(this).parent().parent().find('td.cost').removeClass('approved-amount')
    } else {
      $(this).parent().parent().find('td.cost').removeClass('approved-amount')
    }
  })

  $('.approved-amount').each(function () {
    totalApproved()
  })

  $('#overpayment-toggle').change(function () {
    showClosedClaimActionSection('#overpayment-input')
  })

  $('#close-toggle').change(function () {
    showClosedClaimActionSection('#close-advanced-claim-input')
  })

  $('#request-new-payment-details-toggle').change(function () {
    showClosedClaimActionSection('#request-new-payment-details-input')
  })

  $('#additional-info-reject').change(function () {
    if (this[this.selectedIndex].value === 'Other') {
      document.getElementById('additional-info-reject-manual').disabled = false
      document.getElementById('additional-info-reject-manual').visible = true

    } else {
      document.getElementById('additional-info-reject-manual').disabled = true
      document.getElementById('additional-info-reject-manual').visible = false
      document.getElementById('additional-info-reject-manual').value = ''
    }
  })
})

function totalApproved () {
  var approvedCost = 0
  var manuallyProcessed = 0

  if ($('#unassign').length) {
    $('input.approved-amount').each(function () {
      if (!isNaN(this.value) && this.value.length !== 0 && this.value.indexOf('e') === -1 && this.value.indexOf('E') === -1) {
        manuallyProcessed += parseFloat(this.value)
      }
    })

    $('td.approved-amount').each(function () {
      approvedCost += +$(this).text().replace('£', '')
    })
  } else { // use hidden approved cost for unassigned claims
    $('input.approved-cost').each(function () {
      if (!isNaN(this.value) && this.value.length !== 0) {
        approvedCost += parseFloat(this.value)
      }
    })
    $('td.deduction').each(function () {
      approvedCost += +$(this).text().replace('£', '')
    })
  }

  $('.claim-expense-approvedCostText').text('£' + (approvedCost + manuallyProcessed).toFixed(2))
}

function showClosedClaimActionSection (id) {
  $('#overpayment-input').addClass('js-hidden')
  $('#close-advanced-claim-input').addClass('js-hidden')
  $('#request-new-payment-details-input').addClass('js-hidden')
  $(id).removeClass('js-hidden')
}
<|endoftext|>


<commit_before>'use strict';
import React, { PropTypes as T } from 'react';
import * as d3 from 'd3';
import * as topojson from 'topojson';
import _ from 'lodash';

var Map = React.createClass({
  propTypes: {
    className: T.string,
    geometries: T.object,
    data: T.array
  },

  chart: null,

  onWindowResize: function () {
    console.log('resize');
    this.chart.checkSize();
  },

  componentDidMount: function () {
    // console.log('LineChart componentDidMount');
    // Debounce event.
    this.onWindowResize = _.debounce(this.onWindowResize, 200);

    window.addEventListener('resize', this.onWindowResize);
    this.chart = Chart();

    d3.select(this.refs.container).call(this.chart
      .geometries(this.props.geometries)
      .data(this.props.data)
    );
  },

  componentWillUnmount: function () {
    window.removeEventListener('resize', this.onWindowResize);
    this.chart.destroy();
  },

  componentDidUpdate: function (prevProps/* prevState */) {
    this.chart.pauseUpdate();
    if (prevProps.geometries !== this.props.geometries) {
      this.chart.geometries(this.props.geometries);
    }
    if (prevProps.data !== this.props.data) {
      this.chart.data(this.props.data);
    }
    this.chart.continueUpdate();
  },

  render: function () {
    return (

    );
  }
});

module.exports = Map;

var Chart = function (options) {
  // Data related variables for which we have getters and setters.
  var _data = null;
  var _geometries = null;

  // Islands.
  var _islandsPortugal = null;
  // Continental Portugal.
  var _portugal = null;

  // Pause
  var _pauseUpdate = false;

  // Containters
  var $el, $svg;
  // Var declaration.
  var margin = {top: 0, right: 0, bottom: 0, left: 0};
  // width and height refer to the data canvas. To know the svg size the margins
  // must be added.
  var _width, _height;

  // Update functions.
  var updateData, upateSize;

  function _calcSize () {
    _width = parseInt($el.style('width'), 10) - margin.left - margin.right;
    _height = parseInt($el.style('height'), 10) - margin.top - margin.bottom;
  }

  /**
   * Checks whether the id is in a list of ids.
   * @param  {String} id  Id to check
   * @param  {Array} ids List of numeric ids
   * @return {boolean}
   */
  const isIn = (id, ids) => ids.indexOf(parseInt(id)) !== -1;

  /**
   * Returns the topojson with only the features with the given ids.
   * @param  {Array} ids  ids of the features to find
   * @return {Object}    Topojson
   */
  const getIsland = (ids) => {
    var island = _.cloneDeep(_islandsPortugal);
    island.geometries = island.geometries.filter(o => {
      let id = id = o.properties.id;
      if (id.length === 4) {
        id = id.substring(0, 2);
      }
      return isIn(id, ids);
    });
    return topojson.feature(_geometries, island);
  };

  /**
   * Returns the path for drawing the islands taking into account their
   * new projection.
   * @param  {array} center    New center
   * @param  {array} translate Offset from the new center.
   * @return {Function}        Path drawing function
   */
  const getPathFn = (center, translate) => {
    const scaleValue = s(6000);
    let projection = d3.geoMercator()
      .scale(scaleValue)
      .center(center)
      .translate(translate);

    return d3.geoPath().projection(projection);
  };

  // Make charts reusable!
  // Helper function to draw a group of features. Originally used to draw the
  // different archipelagos, but extended to include the main land.
  // Usage: .call(drawFeatureGroup('name'))
  // opts = {
  //   name: // Name for the feature group
  //   type: // What this refers to (island|main)
  // }
  function drawFeatureGroup (opts) {
    let {name, type} = opts;
    let aaLevel = type === 'island' ? 'distrito' : 'nut3';
    // Return a function to handle each individual island.
    // Wrapped in a closure to include path variables.
    function drawFeature (data) {
      let h = type === 'island' ? s(_height * 0.85) : s(_height / 2);
      let path = getPathFn(data.center, [s(_width / 2) + s(data.offset[0]), h + s(data.offset[1])]);

      return function (sel) {
        return sel.attr('d', path)
          .attr('class', d => `aa--${d.properties.type}`)
          .style('stroke', d => d.properties.type === aaLevel ? '#fff' : '#fff')
          .style('stroke-width', d => d.properties.type === aaLevel ? '1.5px' : '0.5px')
          .style('fill', d => d.properties.type === aaLevel ? '#fff' : 'none')
          .style('fill-opacity', d => d.properties.type === aaLevel ? 0.32 : 1)
          .style('pointer-events', d => d.properties.type === aaLevel ? 'all' : 'none')
          .on('mouseover', function (d, i) {
            d3.select(this).style('cursor', 'pointer');
            let el = type === 'island' ? $svg.selectAll(`.${name} .aa--distrito`) : d3.select(this);
            el.transition()
              .style('fill-opacity', 0);
          })
          .on('mouseout', function (d, i) {
            d3.select(this).style('cursor', 'default');
            let el = type === 'island' ? $svg.selectAll(`.${name} .aa--distrito`) : d3.select(this);
            el.transition()
              .style('fill-opacity', 0.32);
          });
      };
    }

    // Returns a function to draw the archipelago.
    return function (selection) {
      selection.enter().each(function (d, i) {
        let el = d3.select(this);

        el.append('g')
          .attr('class', d => `feature feature--${d.id}`)
          .selectAll('path')
          .data(d.feature.features)
          .enter()
          .append('path')
          .call(drawFeature(d));
      });

      selection.each(function (d, i) {
        let el = d3.select(this);

        el.selectAll('path')
          .data(d.feature.features)
          .call(drawFeature(d));
      });
    };
  }

  // Scale function based on a predefined size.
  const baseSize = 374;
  const s = (v) => _width * v / baseSize;

  function chartFn (selection) {
    $el = selection;

    var layers = {
      baseGeometries: function () {
        // Açores and their coordinates to allow for reprojetion.
        let acores = [
          {
            id: 41,
            center: [-25.1312, 36.9762],
            feature: getIsland([41]),
            offset: [111, 72]
          },
          {
            id: 42,
            center: [-25.4883, 37.7751],
            feature: getIsland([42]),
            offset: [101, 55]
          },
          {
            id: 43,
            center: [-27.2131, 38.7069],
            feature: getIsland([43]),
            offset: [65, 20]
          },
          {
            id: 44,
            center: [-28.0151, 39.0533],
            feature: getIsland([44]),
            offset: [28, 1]
          },
          {
            id: 45,
            center: [-28.0261, 38.6340],
            feature: getIsland([45]),
            offset: [34, 24]
          },
          {
            id: 4647,
            center: [-28.5370, 38.5138],
            feature: getIsland([46, 47]),
            offset: [9, 37]
          },
          {
            id: 48,
            center: [-31.2067, 39.4320],
            feature: getIsland([48]),
            offset: [-23, 7]
          },
          {
            id: 49,
            center: [-31.1188, 39.7030],
            feature: getIsland([49]),
            offset: [-8, -13]
          }
        ];

        // MAdeira and their coordinates to allow for reprojetion.
        let madeira = [
          {
            id: 31,
            center: [-16.7473, 32.6220],
            feature: getIsland([31]),
            offset: [-101, 34]
          },
          {
            id: 32,
            center: [-16.3435, 33.0754],
            feature: getIsland([32]),
            offset: [-95, -3]
          }
        ];

        // Add group for Açores if it doesn't exist.
        let $acoresG = $svg.select('g.acores');
        if ($acoresG.empty()) {
          $acoresG = $svg
            .append('g')
            .attr('class', 'acores');
        }

        // Draw Açores.
        $acoresG
            .selectAll('g.feature')
            .data(acores)
            .call(drawFeatureGroup({name: 'acores', type: 'island'}));

        // Add group for Madeira if it doesn't exist.
        let $madeiraG = $svg.select('g.madeira');
        if ($madeiraG.empty()) {
          $madeiraG = $svg
            .append('g')
            .attr('class', 'madeira');
        }

        // Draw Madeira
        $madeiraG
            .selectAll('g.feature')
            .data(madeira)
            .call(drawFeatureGroup({name: 'madeira', type: 'island'}));

        // Add group for Portugal if it doesn't exist.
        let $portugalG = $svg.select('g.continente');
        if ($portugalG.empty()) {
          $portugalG = $svg
            .append('g')
            .attr('class', 'continente');
        }

        // Draw continental Portugal.
        $portugalG
            .selectAll('g.feature')
            .data([{
              id: 1,
              center: [-8, 38],
              feature: topojson.feature(_geometries, _portugal),
              offset: [-10, 130]
            }])
            .call(drawFeatureGroup({name: 'continente', type: 'main'}));
      },

      municipioColors: function () {
        d3.selectAll('.aa--concelho').each(function () {
          let el = d3.select(this);
          let d = el.datum();
          let bucket = _data.find(o => o.id === parseInt(d.properties.id));
          el.style('fill', bucket ? bucket.color : 'none');
        });
      }
    };

    upateSize = function () {
      $svg
        .attr('width', _width + margin.left + margin.right)
        .attr('height', _height + margin.top + margin.bottom);

      // Redraw.
      layers.baseGeometries();
      layers.municipioColors();
    };

    updateData = function () {
      if (!_data || _pauseUpdate) {
        return;
      }

      // Redraw.
      layers.municipioColors();
    };

    // -----------------------------------------------------------------
    // INIT.
    $svg = $el.append('svg')
      .attr('class', 'chart')
      .style('display', 'block');

    _calcSize();
    upateSize();
    updateData();
    console.log('_width', _width);
    console.log('_height', _height);
  }

  chartFn.checkSize = function () {
    _calcSize();
    upateSize();
    return chartFn;
  };

  chartFn.destroy = function () {
    // Cleanup.
  };

  // --------------------------------------------
  // Getters and setters.
  chartFn.data = function (d) {
    if (!arguments.length) return _data;
    _data = _.cloneDeep(d);
    if (typeof updateData === 'function') updateData();
    return chartFn;
  };

  chartFn.geometries = function (d) {
    if (!arguments.length) return _geometries;
    _geometries = _.cloneDeep(d);
    _islandsPortugal = _.cloneDeep(_geometries.objects.all_areas);
    _islandsPortugal.geometries = _islandsPortugal.geometries.filter(o => {
      if (o.properties.type === 'concelho') {
        if (o.properties.id.length !== 4) {
          return false;
        }
        return parseInt(o.properties.id.substring(0, 2)) > 30;
      }
      return o.properties.type === 'distrito' && parseInt(o.properties.id) > 30;
    });

    _portugal = _.cloneDeep(_geometries.objects.all_areas);
    _portugal.geometries = _portugal.geometries.filter(o => {
      if (o.properties.type === 'concelho') {
        let id = o.properties.id.substring(0, o.properties.id.length === 3 ? 1 : 2);
        return id < 30;
      }
      if (o.properties.type === 'nut3') {
        return ['PT200', 'PT300'].indexOf(o.properties.id) === -1;
      }
    });

    return chartFn;
  };

  chartFn.pauseUpdate = function () {
    _pauseUpdate = true;
    return chartFn;
  };

  chartFn.continueUpdate = function () {
    _pauseUpdate = false;
    if (typeof updateData === 'function') updateData();
    return chartFn;
  };

  return chartFn;
};
<commit_msg>Make map fully responsive<commit_after>'use strict';
import React, { PropTypes as T } from 'react';
import * as d3 from 'd3';
import * as topojson from 'topojson';
import _ from 'lodash';

var Map = React.createClass({
  propTypes: {
    className: T.string,
    geometries: T.object,
    data: T.array
  },

  chart: null,

  onWindowResize: function () {
    console.log('resize');
    this.chart.checkSize();
  },

  componentDidMount: function () {
    // console.log('LineChart componentDidMount');
    // Debounce event.
    this.onWindowResize = _.debounce(this.onWindowResize, 200);

    window.addEventListener('resize', this.onWindowResize);
    this.chart = Chart();

    d3.select(this.refs.container).call(this.chart
      .geometries(this.props.geometries)
      .data(this.props.data)
    );
  },

  componentWillUnmount: function () {
    window.removeEventListener('resize', this.onWindowResize);
    this.chart.destroy();
  },

  componentDidUpdate: function (prevProps/* prevState */) {
    this.chart.pauseUpdate();
    if (prevProps.geometries !== this.props.geometries) {
      this.chart.geometries(this.props.geometries);
    }
    if (prevProps.data !== this.props.data) {
      this.chart.data(this.props.data);
    }
    this.chart.continueUpdate();
  },

  render: function () {
    return (

    );
  }
});

module.exports = Map;

var Chart = function (options) {
  // Data related variables for which we have getters and setters.
  var _data = null;
  var _geometries = null;

  // Islands.
  var _islandsPortugal = null;
  // Continental Portugal.
  var _portugal = null;

  // Pause
  var _pauseUpdate = false;

  // Containers
  var $el, $svg;
  // Var declaration.
  var margin = {top: 0, right: 0, bottom: 0, left: 0};
  // width and height refer to the data canvas. To know the svg size the margins
  // must be added.
  var _width, _height;
  // Geo scale.
  var _projectionScaleValue;

  // Update functions.
  var updateData, upateSize;

  function _calcSize () {
    _width = parseInt($el.style('width'), 10) - margin.left - margin.right;
    _height = parseInt($el.style('height'), 10) - margin.top - margin.bottom;
  }

  /**
   * Checks whether the id is in a list of ids.
   * @param  {String} id  Id to check
   * @param  {Array} ids List of numeric ids
   * @return {boolean}
   */
  const isIn = (id, ids) => ids.indexOf(parseInt(id)) !== -1;

  /**
   * Returns the topojson with only the features with the given ids.
   * @param  {Array} ids  ids of the features to find
   * @return {Object}    Topojson
   */
  const getIsland = (ids) => {
    var island = _.cloneDeep(_islandsPortugal);
    island.geometries = island.geometries.filter(o => {
      let id = id = o.properties.id;
      if (id.length === 4) {
        id = id.substring(0, 2);
      }
      return isIn(id, ids);
    });
    return topojson.feature(_geometries, island);
  };

  /**
   * Returns the path for drawing the islands taking into account their
   * new projection.
   * @param  {array} center    New center
   * @param  {array} translate Offset from the new center.
   * @return {Function}        Path drawing function
   */
  const getPathFn = (center, translate) => {
    const tw = _width / 2;
    // The vertical value for the translate is computed from the width.
    const th = 125 / 114 * _width;
    // The offset values must be scaled according the the projection
    // scale value.
    const scalar = (v) => _projectionScaleValue * v / 6439.143067978895;

    const projection = d3.geoMercator()
      .scale(_projectionScaleValue)
      .center(center)
      .translate([tw + scalar(translate[0]), th + scalar(translate[1])]);

    return d3.geoPath().projection(projection);
  };

  // Make charts reusable!
  // Helper function to draw a group of features. Originally used to draw the
  // different archipelagos, but extended to include the main land.
  // Usage: .call(drawFeatureGroup('name'))
  // opts = {
  //   name: // Name for the feature group
  //   type: // What this refers to (island|main)
  // }
  function drawFeatureGroup (opts) {
    let {name, type} = opts;
    let aaLevel = type === 'island' ? 'distrito' : 'nut3';
    // Return a function to handle each individual island.
    // Wrapped in a closure to include path variables.
    function drawFeature (data) {
      let additionalHOffset = type === 'island' ? 385 : 0;
      let path = getPathFn(data.center, [data.offset[0], data.offset[1] + additionalHOffset]);

      return function (sel) {
        return sel.attr('d', path)
          .attr('class', d => `aa--${d.properties.type}`)
          .style('stroke', d => d.properties.type === aaLevel ? '#fff' : '#fff')
          .style('stroke-width', d => d.properties.type === aaLevel ? '1.5px' : '0.5px')
          .style('fill', d => d.properties.type === aaLevel ? '#fff' : 'none')
          .style('fill-opacity', d => d.properties.type === aaLevel ? 0.32 : 1)
          .style('pointer-events', d => d.properties.type === aaLevel ? 'all' : 'none')
          .on('mouseover', function (d, i) {
            d3.select(this).style('cursor', 'pointer');
            let el = type === 'island' ? $svg.selectAll(`.${name} .aa--distrito`) : d3.select(this);
            el.transition()
              .style('fill-opacity', 0);
          })
          .on('mouseout', function (d, i) {
            d3.select(this).style('cursor', 'default');
            let el = type === 'island' ? $svg.selectAll(`.${name} .aa--distrito`) : d3.select(this);
            el.transition()
              .style('fill-opacity', 0.32);
          });
      };
    }

    // Returns a function to draw the archipelago.
    return function (selection) {
      selection.enter().each(function (d, i) {
        let el = d3.select(this);

        el.append('g')
          .attr('class', d => `feature feature--${d.id}`)
          .selectAll('path')
          .data(d.feature.features)
          .enter()
          .append('path')
          .call(drawFeature(d));
      });

      selection.each(function (d, i) {
        let el = d3.select(this);

        el.selectAll('path')
          .data(d.feature.features)
          .call(drawFeature(d));
      });
    };
  }

  function chartFn (selection) {
    $el = selection;

    var layers = {
      baseGeometries: function () {
        // Açores and their coordinates to allow for reprojetion.
        let acores = [
          {
            id: 41,
            center: [-25.1312, 36.9762],
            feature: getIsland([41]),
            offset: [111, 72]
          },
          {
            id: 42,
            center: [-25.4883, 37.7751],
            feature: getIsland([42]),
            offset: [101, 55]
          },
          {
            id: 43,
            center: [-27.2131, 38.7069],
            feature: getIsland([43]),
            offset: [65, 20]
          },
          {
            id: 44,
            center: [-28.0151, 39.0533],
            feature: getIsland([44]),
            offset: [28, 1]
          },
          {
            id: 45,
            center: [-28.0261, 38.6340],
            feature: getIsland([45]),
            offset: [34, 24]
          },
          {
            id: 4647,
            center: [-28.5370, 38.5138],
            feature: getIsland([46, 47]),
            offset: [9, 37]
          },
          {
            id: 48,
            center: [-31.2067, 39.4320],
            feature: getIsland([48]),
            offset: [-23, 7]
          },
          {
            id: 49,
            center: [-31.1188, 39.7030],
            feature: getIsland([49]),
            offset: [-8, -13]
          }
        ];

        // MAdeira and their coordinates to allow for reprojetion.
        let madeira = [
          {
            id: 31,
            center: [-16.7473, 32.6220],
            feature: getIsland([31]),
            offset: [-101, 34]
          },
          {
            id: 32,
            center: [-16.3435, 33.0754],
            feature: getIsland([32]),
            offset: [-95, -3]
          }
        ];

        // Add group for Açores if it doesn't exist.
        let $acoresG = $svg.select('g.acores');
        if ($acoresG.empty()) {
          $acoresG = $svg
            .append('g')
            .attr('class', 'acores');
        }

        // Draw Açores.
        $acoresG
            .selectAll('g.feature')
            .data(acores)
            .call(drawFeatureGroup({name: 'acores', type: 'island'}));

        // Add group for Madeira if it doesn't exist.
        let $madeiraG = $svg.select('g.madeira');
        if ($madeiraG.empty()) {
          $madeiraG = $svg
            .append('g')
            .attr('class', 'madeira');
        }

        // Draw Madeira
        $madeiraG
            .selectAll('g.feature')
            .data(madeira)
            .call(drawFeatureGroup({name: 'madeira', type: 'island'}));

        // Add group for Portugal if it doesn't exist.
        let $portugalG = $svg.select('g.continente');
        if ($portugalG.empty()) {
          $portugalG = $svg
            .append('g')
            .attr('class', 'continente');
        }

        // Draw continental Portugal.
        $portugalG
            .selectAll('g.feature')
            .data([{
              id: 1,
              center: [-8.2245, 39.3999],
              feature: topojson.feature(_geometries, _portugal),
              offset: [-42, 0]
            }])
            .call(drawFeatureGroup({name: 'continente', type: 'main'}));
      },

      municipioColors: function () {
        d3.selectAll('.aa--concelho').each(function () {
          let el = d3.select(this);
          let d = el.datum();
          let bucket = _data.find(o => o.id === parseInt(d.properties.id));
          el.style('fill', bucket ? bucket.color : 'none');
        });
      }
    };

    upateSize = function () {
      $svg
        .attr('width', _width + margin.left + margin.right)
        .attr('height', _height + margin.top + margin.bottom);

      // Compute the scale value by using fitSize on the country.
      _projectionScaleValue = d3.geoMercator()
        .fitSize([_width, _height], topojson.feature(_geometries, _portugal))
        .scale();

      console.log('_width', _width);
      console.log('_height', _height);
      console.log('_projectionScaleValue', _projectionScaleValue);
      // Redraw.
      layers.baseGeometries();
      layers.municipioColors();
    };

    updateData = function () {
      if (!_data || _pauseUpdate) {
        return;
      }

      // Redraw.
      layers.municipioColors();
    };

    // -----------------------------------------------------------------
    // INIT.
    $svg = $el.append('svg')
      .attr('class', 'chart')
      .style('display', 'block');

    _calcSize();
    upateSize();
    updateData();
  }

  chartFn.checkSize = function () {
    _calcSize();
    upateSize();
    return chartFn;
  };

  chartFn.destroy = function () {
    // Cleanup.
  };

  // --------------------------------------------
  // Getters and setters.
  chartFn.data = function (d) {
    if (!arguments.length) return _data;
    _data = _.cloneDeep(d);
    if (typeof updateData === 'function') updateData();
    return chartFn;
  };

  chartFn.geometries = function (d) {
    if (!arguments.length) return _geometries;
    _geometries = _.cloneDeep(d);
    _islandsPortugal = _.cloneDeep(_geometries.objects.all_areas);
    _islandsPortugal.geometries = _islandsPortugal.geometries.filter(o => {
      if (o.properties.type === 'concelho') {
        if (o.properties.id.length !== 4) {
          return false;
        }
        return parseInt(o.properties.id.substring(0, 2)) > 30;
      }
      return o.properties.type === 'distrito' && parseInt(o.properties.id) > 30;
    });

    _portugal = _.cloneDeep(_geometries.objects.all_areas);
    _portugal.geometries = _portugal.geometries.filter(o => {
      if (o.properties.type === 'concelho') {
        let id = o.properties.id.substring(0, o.properties.id.length === 3 ? 1 : 2);
        return id < 30;
      }
      if (o.properties.type === 'nut3') {
        return ['PT200', 'PT300'].indexOf(o.properties.id) === -1;
      }
    });

    return chartFn;
  };

  chartFn.pauseUpdate = function () {
    _pauseUpdate = true;
    return chartFn;
  };

  chartFn.continueUpdate = function () {
    _pauseUpdate = false;
    if (typeof updateData === 'function') updateData();
    return chartFn;
  };

  return chartFn;
};
<|endoftext|>


<commit_before>import autosize from "autosize"

const script = String.raw`<iframe id="forecast_embed" type="text/html" frameborder="0" height="245" width="100%" src="//forecast.io/embed/#lat=42.3583&lon=-71.0603&name=Downtown Boston">
</iframe>`

export default function runDemo(app) {
  const {embedCodeInput, locationSelect, pluginDetailsForm} = app.refs

  embedCodeInput.autofocus = false
  embedCodeInput.value = script
  autosize.update(embedCodeInput)
  app.parseInput()

  locationSelect.value = "body"

  const {option_7, option_8, option_9} = app.entities

  option_7.title = "Latitude"
  option_8.title = "Longitude"
  option_9.title = "Location Name"

  app.toggleEntityTracking(option_7.element)
  app.toggleEntityTracking(option_8.element)
  app.toggleEntityTracking(option_9.element)

  const fields = {
    "[name='app[title]']": "Forecast.io",
    "[name='app[description]']": "Display local weather information on your website.",
    "[name='email']": "demo@instantwordpressplugin.com"
  }

  Object
    .keys(fields)
    .forEach(name => pluginDetailsForm.querySelector(name).value = fields[name])

  app.imageUploader.imageURL = `${ASSET_BASE}/forecast.png`
}
<commit_msg>Touch up names.<commit_after>import autosize from "autosize"

const script = String.raw`<iframe id="forecast_embed" type="text/html" frameborder="0" height="245" width="100%" src="//forecast.io/embed/#lat=42.3583&lon=-71.0603&name=Downtown Boston">
</iframe>`

export default function runDemo(app) {
  const {embedCodeInput, locationSelect, pluginDetailsForm} = app.refs

  embedCodeInput.autofocus = false
  embedCodeInput.value = script
  autosize.update(embedCodeInput)
  app.parseInput()

  locationSelect.value = "body"

  const {option_7, option_8, option_9} = app.entities

  option_7.title = "Latitude"
  option_8.title = "Longitude"
  option_9.title = "Description"

  app.toggleEntityTracking(option_7.element)
  app.toggleEntityTracking(option_8.element)
  app.toggleEntityTracking(option_9.element)

  const fields = {
    "[name='app[title]']": "Forecast.io",
    "[name='app[description]']": "Display local weather information on your website.",
    "[name='email']": "demo@instantwordpressplugin.com"
  }

  Object
    .keys(fields)
    .forEach(name => pluginDetailsForm.querySelector(name).value = fields[name])

  app.imageUploader.imageURL = `${ASSET_BASE}/forecast.png`
}
<|endoftext|>


<commit_before>// @flow
import React, { Component, PropTypes } from 'react';
import { observer, inject, PropTypes as MobxPropTypes } from 'mobx-react';
import { defineMessages, intlShape } from 'react-intl';
import WalletTransactionsList from '../../components/wallet/home/WalletTransactionsList';
import WalletTransactionsSearch from '../../components/wallet/home/WalletTransactionsSearch';
import WalletNoTransactions from '../../components/wallet/home/WalletNoTransactions';
import CachedRequest from '../../stores/lib/CachedRequest';

const messages = defineMessages({
  noTransactions: {
    id: 'wallet.transactions.no.transactions',
    defaultMessage: '!!!No transactions',
    description: 'Message shown when wallet has no transactions yet.'
  },
  noTransactionsFound: {
    id: 'wallet.transactions.no.transactions.found',
    defaultMessage: '!!!No transactions found',
    description: 'Message shown when wallet transaction search returns zero results.'
  }
});

@inject('stores', 'actions') @observer
export default class WalletTransactionsPage extends Component {

  static propTypes = {
    stores: PropTypes.shape({
      transactions: PropTypes.shape({
        searchOptions: PropTypes.shape({
          searchTerm: PropTypes.string.isRequired,
          searchLimit: PropTypes.number.isRequired,
        }),
        allTransactionsRequest: PropTypes.instanceOf(CachedRequest),
        filtered: MobxPropTypes.arrayOrObservableArray.isRequired,
        hasAnyFiltered: PropTypes.bool.isRequired,
        totalFilteredAvailable: PropTypes.number.isRequired,
      })
    }).isRequired,
    actions: PropTypes.shape({
      filterTransactions: PropTypes.func.isRequired
    }).isRequired
  };

  static contextTypes = {
    intl: intlShape.isRequired,
  };

  _handleSearchInputChange = (value: string, event: Object) => {
    this.props.actions.filterTransactions({ searchTerm: event.target.value });
  };

  render() {
    const { intl } = this.context;
    const actions = this.props.actions;
    const { transactions } = this.props.stores;
    const {
      searchOptions,
      searchRequest,
      hasAny,
      totalAvailable,
      filtered,
    } = transactions;
    const { searchLimit, searchTerm } = searchOptions;
    const wasSearched = searchTerm !== '';
    let walletTransactions = null;
    let transactionSearch = null;
    const noTransactionsLabel = intl.formatMessage(messages.noTransactions);
    const noTransactionsFoundLabel = intl.formatMessage(messages.noTransactionsFound);

    if (wasSearched || hasAny) {
      transactionSearch = (

          <WalletTransactionsSearch
            searchTerm={searchTerm}
            onChange={this._handleSearchInputChange}
          />

      );
    }

    if (searchRequest.isExecutingFirstTime || hasAny) {
      walletTransactions = (
        <WalletTransactionsList
          transactions={filtered}
          isLoadingTransactions={searchRequest.isExecutingFirstTime}
          hasMoreToLoad={totalAvailable > searchLimit}
          onLoadMore={actions.loadMoreTransactions}
        />
      );
    } else if (wasSearched && !hasAny) {
      walletTransactions = <WalletNoTransactions label={noTransactionsFoundLabel} />;
    } else if (!hasAny) {
      walletTransactions = <WalletNoTransactions label={noTransactionsLabel} />;
    }

    return (

        {transactionSearch}
        {walletTransactions}

    );
  }

}
<commit_msg>hide transactions search bar<commit_after>// @flow
import React, { Component, PropTypes } from 'react';
import { observer, inject, PropTypes as MobxPropTypes } from 'mobx-react';
import { defineMessages, intlShape } from 'react-intl';
import WalletTransactionsList from '../../components/wallet/home/WalletTransactionsList';
import WalletTransactionsSearch from '../../components/wallet/home/WalletTransactionsSearch';
import WalletNoTransactions from '../../components/wallet/home/WalletNoTransactions';
import CachedRequest from '../../stores/lib/CachedRequest';

const messages = defineMessages({
  noTransactions: {
    id: 'wallet.transactions.no.transactions',
    defaultMessage: '!!!No transactions',
    description: 'Message shown when wallet has no transactions yet.'
  },
  noTransactionsFound: {
    id: 'wallet.transactions.no.transactions.found',
    defaultMessage: '!!!No transactions found',
    description: 'Message shown when wallet transaction search returns zero results.'
  }
});

@inject('stores', 'actions') @observer
export default class WalletTransactionsPage extends Component {

  static propTypes = {
    stores: PropTypes.shape({
      transactions: PropTypes.shape({
        searchOptions: PropTypes.shape({
          searchTerm: PropTypes.string.isRequired,
          searchLimit: PropTypes.number.isRequired,
        }),
        allTransactionsRequest: PropTypes.instanceOf(CachedRequest),
        filtered: MobxPropTypes.arrayOrObservableArray.isRequired,
        hasAnyFiltered: PropTypes.bool.isRequired,
        totalFilteredAvailable: PropTypes.number.isRequired,
      })
    }).isRequired,
    actions: PropTypes.shape({
      filterTransactions: PropTypes.func.isRequired
    }).isRequired
  };

  static contextTypes = {
    intl: intlShape.isRequired,
  };

  _handleSearchInputChange = (value: string, event: Object) => {
    this.props.actions.filterTransactions({ searchTerm: event.target.value });
  };

  render() {
    const { intl } = this.context;
    const actions = this.props.actions;
    const { transactions } = this.props.stores;
    const {
      searchOptions,
      searchRequest,
      hasAny,
      totalAvailable,
      filtered,
    } = transactions;
    const { searchLimit, searchTerm } = searchOptions;
    const wasSearched = searchTerm !== '';
    let walletTransactions = null;
    let transactionSearch = null;
    const noTransactionsLabel = intl.formatMessage(messages.noTransactions);
    const noTransactionsFoundLabel = intl.formatMessage(messages.noTransactionsFound);

    // if (wasSearched || hasAny) {
    //   transactionSearch = (
    //

    //       <WalletTransactionsSearch
    //         searchTerm={searchTerm}
    //         onChange={this._handleSearchInputChange}
    //       />
    //

    //   );
    // }

    if (searchRequest.isExecutingFirstTime || hasAny) {
      walletTransactions = (
        <WalletTransactionsList
          transactions={filtered}
          isLoadingTransactions={searchRequest.isExecutingFirstTime}
          hasMoreToLoad={totalAvailable > searchLimit}
          onLoadMore={actions.loadMoreTransactions}
        />
      );
    } else if (wasSearched && !hasAny) {
      walletTransactions = <WalletNoTransactions label={noTransactionsFoundLabel} />;
    } else if (!hasAny) {
      walletTransactions = <WalletNoTransactions label={noTransactionsLabel} />;
    }

    return (

        {transactionSearch}
        {walletTransactions}

    );
  }

}
<|endoftext|>


<commit_before>/**
 * @fileoverview Tests for the highlightSeriesBackgroundAlpha and
 * highlightSeriesBackgroundColor options.
 * @author sergeyslepian@gmail.com
 */

import Dygraph from '../../src/dygraph';
import * as utils from '../../src/dygraph-utils';
import Util from './Util';

describe("highlight-series-background", function() {

  cleanupAfterEach();

  function setupGraph(highlightSeriesBackgroundAlpha,
                      highlightSeriesBackgroundColor) {
    var opts = {
      width: 480,
      height: 320,
      labels: ['x', 'y'],
      legend: 'always',
      highlightSeriesOpts: {
        strokeWidth: 1,
        strokeBorderWidth: 1,
        highlightCircleSize: 1
      }
    };

    if (highlightSeriesBackgroundAlpha) utils.update(opts, {highlightSeriesBackgroundAlpha});
    if (highlightSeriesBackgroundColor) utils.update(opts, {highlightSeriesBackgroundColor});

    var data = [];
    for (var j = 0; j < 10; j++) {
      data.push([j, 0]);
    }

    return new Dygraph('graph', data, opts);
  }

  it('testDefaultHighlight', function(done) {
    var graph = setupGraph();

    assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,0,0,0]);

    graph.setSelection(0, 'y', true);

    // handle background color fade-in time
    setTimeout(function() {
      assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [255,255,255,127]);
      done();
    }, 1000);
  });

  it('testNoHighlight', function(done) {
    var graph = setupGraph(1);

    assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,0,0,0]);

    graph.setSelection(0, 'y', true);

    // handle background color fade-in time
    setTimeout(function() {
      assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,0,0,0]);
      done();
    }, 1000);
  });

  it('testCustomHighlightColor', function(done) {
    var graph = setupGraph(null, 'rgb(0,255,255)');

    assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,0,0,0]);

    graph.setSelection(0, 'y', true);

    // handle background color fade-in time
    setTimeout(function() {
      assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,255,255,127]);
      done();
    }, 1000);
  });

  it('testCustomHighlightAlpha', function(done) {
    var graph = setupGraph(0.3);

    assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,0,0,0]);

    graph.setSelection(0, 'y', true);

    // handle background color fade-in time
    setTimeout(function() {
      assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [255,255,255,179]);
      done();
    }, 1000);
  });

  it('testCustomHighlightColorAndAlpha', function(done) {
    var graph = setupGraph(0.7,'rgb(255,0,0)');

    assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,0,0,0]);

    graph.setSelection(0, 'y', true);

    // handle background color fade-in time
    setTimeout(function() {
      assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [255,0,0,76]);
      done();
    }, 1000);
  });
});
<commit_msg>Attempt to make async tests run faster<commit_after>/**
 * @fileoverview Tests for the highlightSeriesBackgroundAlpha and
 * highlightSeriesBackgroundColor options.
 * @author sergeyslepian@gmail.com
 */

import Dygraph from '../../src/dygraph';
import * as utils from '../../src/dygraph-utils';
import Util from './Util';

describe("highlight-series-background", function() {

  cleanupAfterEach();

  var origRepeatAndCleanup;

  beforeEach(function() {
    // A "fast" version of repeatAndCleanup
    origRepeatAndCleanup = utils.repeatAndCleanup;
    // utils.repeatAndCleanup = function(repeatFn, maxFrames, framePeriodInMillis, cleanupFn) {
    //   repeatFn(0);
    //   if (maxFrames > 1) repeatFn(maxFrames - 1);
    //   cleanupFn();
    // };
  });

  afterEach(function() {
    utils.repeatAndCleanup = origRepeatAndCleanup;
  });

  function setupGraph(highlightSeriesBackgroundAlpha,
                      highlightSeriesBackgroundColor) {
    var opts = {
      width: 480,
      height: 320,
      labels: ['x', 'y'],
      legend: 'always',
      highlightSeriesOpts: {
        strokeWidth: 1,
        strokeBorderWidth: 1,
        highlightCircleSize: 1
      }
    };

    if (highlightSeriesBackgroundAlpha) utils.update(opts, {highlightSeriesBackgroundAlpha});
    if (highlightSeriesBackgroundColor) utils.update(opts, {highlightSeriesBackgroundColor});

    var data = [];
    for (var j = 0; j < 10; j++) {
      data.push([j, 0]);
    }

    return new Dygraph('graph', data, opts);
  }

  it('testDefaultHighlight', function(done) {
    var graph = setupGraph();

    assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,0,0,0]);

    graph.setSelection(0, 'y', true);

    // handle background color fade-in time
    window.setTimeout(() => {
      assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [255,255,255,127]);
      done();
    }, 500);
  });

  it('testNoHighlight', function(done) {
    var graph = setupGraph(1);

    assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,0,0,0]);

    graph.setSelection(0, 'y', true);

    // handle background color fade-in time
    window.setTimeout(() => {
      assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,0,0,0]);
      done();
    }, 500);
  });

  it('testCustomHighlightColor', function(done) {
    var graph = setupGraph(null, 'rgb(0,255,255)');

    assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,0,0,0]);

    graph.setSelection(0, 'y', true);

    // handle background color fade-in time
    window.setTimeout(() => {
      assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,255,255,127]);
      done();
    }, 500);
  });

  it('testCustomHighlightAlpha', function(done) {
    var graph = setupGraph(0.3);

    assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,0,0,0]);

    graph.setSelection(0, 'y', true);

    // handle background color fade-in time
    window.setTimeout(() => {
      assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [255,255,255,179]);
      done();
    }, 500);
  });

  it('testCustomHighlightColorAndAlpha', function(done) {
    var graph = setupGraph(0.7,'rgb(255,0,0)');

    assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [0,0,0,0]);

    graph.setSelection(0, 'y', true);

    // handle background color fade-in time
    window.setTimeout(() => {
      assert.deepEqual(Util.samplePixel(graph.canvas_, 100, 100), [255,0,0,76]);
      done();
    }, 500);
  });
});
<|endoftext|>