<commit_before>var small_chart_height = 250;
var medium_chart_height = 500;
var large_chart_height = 650;
var small_width = 480; //544
var medium_width = 720; //768
var result_chart_width = 768;
var valueAccessor = function (d) {return d.Value < 1 ? 0 : d.Value};
var our_colors = ["#9df5e7","#b2bfdb","#a1eda1","#fc9898", "#afedf0","#afede1", "#fc6565"];
var team_default = d3.scale.ordinal().range(["#015B64"]);
var year_default = d3.scale.ordinal().range(["#1C293B"]);
var default_colors = d3.scale.ordinal().range(our_colors);
//For pie chart
var donut_inner = 40
var donut_outer = 80
var donut_height = 100
var perc_view = false;

grey_undefined = function(chart) {
  chart.selectAll("text.row").classed("grey",function(d) {return d.value.not_real || d.value.count == 0});
}

//---------------------CLEANUP functions-------------------------

var yearDom = [];

function cleanup(d) {

  d.Year = d.Date.slice(-2);
  d.Year = d.Year > 16 ? 1900+parseInt(d.Year) : 2000+parseInt(d.Year);
  d.Value = 1;
	d.properDate = new Date(d.Date.split('-')[1] + " " + d.Date.split('-')[0] + ", " + d.Year);
  d.matchAgainst = d.Team + '/' + d.Opposition;
  if (d.Result != "tied") d.resultStatus = d.Team + '@' + d.Result;

  return d;
}

function isOdd(num) {
	return num % 2;
}

function capitalizeFirst(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

function change_result_view() {
  result_year_chart = dc.barChart('#result_year')
      .group(result_year_group, "won")
      .valueAccessor(function(d){return d.value["won"]})
      .stack(result_year_group, "lost", function(d) { return d.value["lost"] })
      .stack(result_year_group, "tied", function(d) { return d.value["tied"] })
      .dimension(result_year)
      .centerBar(true)
      .height(medium_chart_height/2)
      .width(result_chart_width)
      .colors(d3.scale.ordinal().domain(["won", "lost", "tied"]).range(["#45936E","#92332F", "#3E70A1"]))
      .x(d3.scale.linear().domain([1995, 2016]))
      .elasticX(false)
      .elasticY(true)
      .transitionDuration(200)
      .mouseZoomable(false)
      .yAxisLabel("Games")
      .renderHorizontalGridLines(true)
      .renderVerticalGridLines(true)
      .brushOn(true)
      .margins({top: 10, right: 50, bottom: 30, left: 50})
      .on("renderlet.result_year", function (chart) {
          //Check if labels exist
          var gLabels = chart.select(".labels");
          if (gLabels.empty()){
            gLabels = chart.select(".chart-body").append('g').classed('labels', true);
          }

          var gLabelsData = gLabels.selectAll("text").data(chart.selectAll(".bar")[0]);

          gLabelsData.exit().remove(); //Remove unused elements

          gLabelsData.enter().append("text") //Add new elements

          gLabelsData
            .attr('text-anchor', 'middle  ')
            .attr('fill', 'white')
            .attr("font-size", "11px")
            .text(function(d){
              return d3.select(d).data()[0].y
            })
            .attr('x', function(d){
              return +d.getAttribute('x') + (d.getAttribute('width')/2);
            })
            .attr('y', function(d){ return +d.getAttribute('y') + 15; })
            .attr('style', function(d){
              if (+d.getAttribute('height') < 18) return "display:none";
            });
        })
        .on("preRedraw", function (chart) {
            chart.rescale();
        })
        .on("preRender", function (chart) {
            chart.rescale();
        })
        .on("pretransition", function (chart) {
            chart.rescale();
        });

    result_year_chart.xAxis().ticks(10).tickFormat(d3.format("d"));

  if (perc_view == false) {
    $('.result_year_title').text("Overall Team Performance by Games");
    result_year_chart
      .label(function(d) { return d; })
      .title(function(d) {
        d3.selectAll("rect.bar")
          .on('mouseover', function(d){
          });
          return d.key+": "+d3.format(',')(d.value[this.layer])+" ("+this.layer+")";
      });

  }
  else {
    $('.result_year_title').text("Overall Team Performance by Percentage");
    result_year_chart
      .group(result_year_group, "won")
      .valueAccessor(function(d){
        var v = parseFloat(d.value["won"]/(d.value["won"]+d.value["lost"]+d.value["tied"]));
        if (isNaN(v)) return 0;
        return parseFloat((v*100).toFixed(1));
      })
      .stack(result_year_group, "lost", function(d) {
        var v = parseFloat(d.value["lost"]/(d.value["won"]+d.value["lost"]+d.value["tied"]));
        if (isNaN(v)) return 0;
        return parseFloat((v*100).toFixed(1));
      })
      .stack(result_year_group, "tied", function(d) {
      if (d.value["tied"] == 0) return 0
      else
        var v = parseFloat(d.value["tied"] /(d.value["won"]+d.value["lost"]+d.value["tied"]))
        if (isNaN(v)) return 0;
        return parseFloat((v*100).toFixed(1));
      })
      .label(function(d) { return d; })
      .title(function(d) {
        d3.selectAll("rect.bar")
          .on('mouseover', function(d){
          });
          return d.key+": "+d3.format(',')(d.value[this.layer])+" ("+this.layer+")";
      });

  }

  result_year_chart.yAxis().ticks(5).tickFormat(d3.format("g"));
  grey_undefined(result_year_chart);

  //Need to reset the filter when the view changes or else, filter lingers
  result_year_chart.filterAll();
  dc.renderAll();
  perc_view = !perc_view;

}

//Queueing defer ensures that all our datasets get loaded before any work is done

queue()
    .defer(d3.csv, "data/cricket-odi.csv")
    // .defer(d3.csv, "import-data.csv") //change name here to load more than 1 file
    .await(showCharts);

function showCharts(err, data) {
  _data = [];

  for (i in data) {
		data[i] = cleanup(data[i]);
  }
  _data = data;
//	console.log(data);

  function configureableReduce(field, value, init) {
    return {
      add: function(v,d){
        v[d[field]] = (v[d[field]] || 0) + d[value];
        return v
      },
      remove: function(v,d){
        v[d[field]] -= d[value];
        return v
      },
      init: function() {
        return init ? JSON.parse(JSON.stringify(init)) : {}
      }
    }
  }

	resultByYear = configureableReduce("Result", "Value", {
		"won":0,
		"lost":0,
		"tied":0
	});

	//---------------------------------FILTERS-----------------------------------------
  ndx = crossfilter(_data);
  //---------------------------ORDINARY CHARTS --------------------------------------
	year = ndx.dimension(function(d){return d.Year});

  year_group = year.group().reduceSum(function(d){return d.Value});

	year_chart = dc.rowChart('#year')
    .dimension(year)
    .group(year_group)
    .colors(year_default)
    .transitionDuration(200)
    .height(large_chart_height/1.5)
		.width(small_width)
    .ordering(function(d){ return -d.key })
//		.x(d3.scale.linear().domain([-25, 25]))
    .elasticX(true);

	year_chart.xAxis().ticks(10).tickFormat(d3.format("g"));
	grey_undefined(year_chart);

  year_bar = ndx.dimension(function(d){return d.Year});

  year_bar_group = year_bar.group().reduceSum(function(d){return d.Value});

	year_bar_chart = dc.barChart('#year-bar')
      .dimension(year_bar)
      .group(year_bar_group)
      .colors(default_colors)
      .transitionDuration(200)
      .height(medium_chart_height)
      .width(small_width)
      .ordering(function(d){ return -d.key })
      .x(d3.scale.linear().domain([-25, 25]))
      .brushOn(true)
      .elasticY(true)
      .elasticX(true);

	year_bar_chart.xAxis().ticks(5).tickFormat(d3.format("g"));
	grey_undefined(year_bar_chart);

	opposition = ndx.dimension(function(d){return d.Opposition});

  opposition_group = opposition.group().reduceSum(function(d){return d.Value});

	opposition_chart = dc.rowChart('#opposition')
    .dimension(opposition)
    .group(opposition_group)
    .colors(team_default)
    .transitionDuration(200)
    .height(small_chart_height)
		.width(small_width-50)
    .ordering(function(d){ return -d.key })
//		.xAxisLabel('Total Games')
//		.xAxisPadding(500)
    .elasticX(true);

	opposition_chart.xAxis().ticks(5).tickFormat(d3.format("d"));
	grey_undefined(opposition_chart);

	team = ndx.dimension(function(d){return d.Team});
  team_group = team.group().reduceSum(function(d){return d.Value});

  team_chart = dc.rowChart('#team')
    .dimension(team)
    .group(team_group)
    .colors(team_default)
    .transitionDuration(200)
    .height(small_chart_height)
    .width(small_width-50)
    .ordering(function(d){ return -d.key })
    .elasticX(true);

  team_chart.xAxis().ticks(5).tickFormat(d3.format("d"));
  grey_undefined(team_chart);

	result = ndx.dimension(function(d){return d.Result});

  result_group = result.group().reduceSum(function(d){return d.Value});

	result_chart = dc.pieChart('#result')
    .dimension(result)
    .group(result_group)
    .transitionDuration(200)
    .legend(dc.legend().x(0).y(25).itemHeight(18).gap(5))
    .height(small_chart_height-50)
    .title(function(d) {
      var title = capitalizeFirst(d.key) + ": " + d.value;
      if (d.key == "won"){
        return "Team A \n" + title;
      }
      else if (d.key == "lost"){
        return "Team B \n" + title;
      }
      return title;
    })
    .label(function(d) {
      if (d.key == "won") return "Team A: " + d.value;
      else if (d.key == "lost") return "Team B: " + d.value;
      return capitalizeFirst(d.key) + ": " + d.value;
    })
    .radius(donut_outer)
    .colors(d3.scale.ordinal().domain(["won", "lost", "tied"])
                              .range(["#45936E","#92332F", "#3E70A1"]))
    .colorAccessor(function(d) {
			if (d.key == "won") return "won";
			else if (d.key == "lost") return "lost";
			return "tied";
		});

	result_year = ndx.dimension(function(d){return d.Year});
	result_year_group = result_year.group().reduce(resultByYear.add, resultByYear.remove, resultByYear.init);

  change_result_view();

  var all = ndx.groupAll();
  data_count_chart = dc.dataCount('#data_count')
    .dimension(ndx)
    .group(all)
    .html({
        some: '%filter-count selected out of %total-count records' +
            ' | Reset All',
        all: 'All records selected. Please click on the graph to apply filters.'
    });

  //pyramid chart
  resultStatus = ndx.dimension(function(d) {return d.resultStatus});
  result_group = resultStatus.group().reduceSum(function(d){return d.Value})

  team_opp_chart = dc.pyramidChart('#team_opp')
    .dimension(resultStatus)
    .group(result_group)
    .colors(d3.scale.ordinal().domain(["won", "lost"])
                              .range(["#45936E","#92332F"]))
    .colorAccessor(function(d) {
      if (d.key.split('@')[1] == "won") return "won";
      else if (d.key.split('@')[1] == "lost") return "lost";
    })
    .height(small_chart_height)
    .width(medium_width-50)
    .leftColumn(function (d){ return d.key.split('@')[1] == "won"})
    .rowAccessor(function(d){ return d.key.split('@')[0]})
    .label(function(d){return d.key.split('@')[0]})
    .title(function(d){
      if (d.key.split('@')[1] == "won") return "Won: " + d.value;
      else if (d.key.split('@')[1] == "lost") return "Lost: " + d.value;
      else return NaN;
    })
    .elasticX(false)
    .twoLabels(false)
    .rowOrdering(d3.ascending)
    .columnLabels(['Won','Lost'])
    .columnLabelPosition([150,0])
    .transitionDuration(200);

  team_opp_chart.xAxis().ticks(7).tickFormat(function(x) {return d3.format('s')(Math.abs(x))})

	dc.renderAll();

  initialize();
};

function initialize(){
  //odd are wins, even are losses
  var a = $('#team_opp g .row text:eq(7)');
//  var b = $('#team_opp g .row rect:eq(6)');

  a.simulate('click');
//  b.simulate('click');

};

function hideshow(id){
  var a = $(id);
  a.toggle('show');
};

function showAll() {
  var idList = ["#result_year", "#team_opp", "#result", "#team", "#opposition"]

  for (x in idList) {
    var a = $(idList[x]);
    if (a.css('display') == "none"){
      a.toggle('show');
    }
  }
  $('[type=checkbox]').prop('checked', true);
};<commit_msg>change win loss colors for all charts<commit_after>var small_chart_height = 250;
var medium_chart_height = 500;
var large_chart_height = 650;
var small_width = 480; //544
var medium_width = 720; //768
var result_chart_width = 768;
var valueAccessor = function (d) {return d.Value < 1 ? 0 : d.Value};
var our_colors = ["#9df5e7","#b2bfdb","#a1eda1","#fc9898", "#afedf0","#afede1", "#fc6565"];
var team_default = d3.scale.ordinal().range(["#015B64"]);
var won_default = d3.scale.ordinal().range(["#45936E"]);
var lost_default = d3.scale.ordinal().range(["#92332F"]);
var year_default = d3.scale.ordinal().range(["#1C293B"]);
var default_colors = d3.scale.ordinal().range(our_colors);
//For pie chart
var donut_inner = 40
var donut_outer = 80
var donut_height = 100
var perc_view = false;

grey_undefined = function(chart) {
  chart.selectAll("text.row").classed("grey",function(d) {return d.value.not_real || d.value.count == 0});
}

//---------------------CLEANUP functions-------------------------

var yearDom = [];

function cleanup(d) {

  d.Year = d.Date.slice(-2);
  d.Year = d.Year > 16 ? 1900+parseInt(d.Year) : 2000+parseInt(d.Year);
  d.Value = 1;
	d.properDate = new Date(d.Date.split('-')[1] + " " + d.Date.split('-')[0] + ", " + d.Year);
  d.matchAgainst = d.Team + '/' + d.Opposition;
  if (d.Result != "tied") d.resultStatus = d.Team + '@' + d.Result;

  return d;
}

function isOdd(num) {
	return num % 2;
}

function capitalizeFirst(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

function change_result_view() {
  result_year_chart = dc.barChart('#result_year')
      .group(result_year_group, "won")
      .valueAccessor(function(d){return d.value["won"]})
      .stack(result_year_group, "lost", function(d) { return d.value["lost"] })
      .stack(result_year_group, "tied", function(d) { return d.value["tied"] })
      .dimension(result_year)
      .centerBar(true)
      .height(medium_chart_height/2)
      .width(result_chart_width)
      .colors(d3.scale.ordinal().domain(["won", "lost", "tied"]).range(["#45936E","#92332F", "#3E70A1"]))
      .x(d3.scale.linear().domain([1995, 2016]))
      .elasticX(false)
      .elasticY(true)
      .transitionDuration(200)
      .mouseZoomable(false)
      .yAxisLabel("Games")
      .renderHorizontalGridLines(true)
      .renderVerticalGridLines(true)
      .brushOn(true)
      .margins({top: 10, right: 50, bottom: 30, left: 50})
      .on("renderlet.result_year", function (chart) {
          //Check if labels exist
          var gLabels = chart.select(".labels");
          if (gLabels.empty()){
            gLabels = chart.select(".chart-body").append('g').classed('labels', true);
          }

          var gLabelsData = gLabels.selectAll("text").data(chart.selectAll(".bar")[0]);

          gLabelsData.exit().remove(); //Remove unused elements

          gLabelsData.enter().append("text") //Add new elements

          gLabelsData
            .attr('text-anchor', 'middle  ')
            .attr('fill', 'white')
            .attr("font-size", "11px")
            .text(function(d){
              return d3.select(d).data()[0].y
            })
            .attr('x', function(d){
              return +d.getAttribute('x') + (d.getAttribute('width')/2);
            })
            .attr('y', function(d){ return +d.getAttribute('y') + 15; })
            .attr('style', function(d){
              if (+d.getAttribute('height') < 18) return "display:none";
            });
        })
        .on("preRedraw", function (chart) {
            chart.rescale();
        })
        .on("preRender", function (chart) {
            chart.rescale();
        })
        .on("pretransition", function (chart) {
            chart.rescale();
        });

    result_year_chart.xAxis().ticks(10).tickFormat(d3.format("d"));

  if (perc_view == false) {
    $('.result_year_title').text("Overall Team Performance by Games");
    result_year_chart
      .label(function(d) { return d; })
      .title(function(d) {
        d3.selectAll("rect.bar")
          .on('mouseover', function(d){
          });
          return d.key+": "+d3.format(',')(d.value[this.layer])+" ("+this.layer+")";
      });

  }
  else {
    $('.result_year_title').text("Overall Team Performance by Percentage");
    result_year_chart
      .group(result_year_group, "won")
      .valueAccessor(function(d){
        var v = parseFloat(d.value["won"]/(d.value["won"]+d.value["lost"]+d.value["tied"]));
        if (isNaN(v)) return 0;
        return parseFloat((v*100).toFixed(1));
      })
      .stack(result_year_group, "lost", function(d) {
        var v = parseFloat(d.value["lost"]/(d.value["won"]+d.value["lost"]+d.value["tied"]));
        if (isNaN(v)) return 0;
        return parseFloat((v*100).toFixed(1));
      })
      .stack(result_year_group, "tied", function(d) {
      if (d.value["tied"] == 0) return 0
      else
        var v = parseFloat(d.value["tied"] /(d.value["won"]+d.value["lost"]+d.value["tied"]))
        if (isNaN(v)) return 0;
        return parseFloat((v*100).toFixed(1));
      })
      .label(function(d) { return d; })
      .title(function(d) {
        d3.selectAll("rect.bar")
          .on('mouseover', function(d){
          });
          return d.key+": "+d3.format(',')(d.value[this.layer])+" ("+this.layer+")";
      });

  }

  result_year_chart.yAxis().ticks(5).tickFormat(d3.format("g"));
  grey_undefined(result_year_chart);

  //Need to reset the filter when the view changes or else, filter lingers
  result_year_chart.filterAll();
  dc.renderAll();
  perc_view = !perc_view;

}

//Queueing defer ensures that all our datasets get loaded before any work is done

queue()
    .defer(d3.csv, "data/cricket-odi.csv")
    // .defer(d3.csv, "import-data.csv") //change name here to load more than 1 file
    .await(showCharts);

function showCharts(err, data) {
  _data = [];

  for (i in data) {
		data[i] = cleanup(data[i]);
  }
  _data = data;
//	console.log(data);

  function configureableReduce(field, value, init) {
    return {
      add: function(v,d){
        v[d[field]] = (v[d[field]] || 0) + d[value];
        return v
      },
      remove: function(v,d){
        v[d[field]] -= d[value];
        return v
      },
      init: function() {
        return init ? JSON.parse(JSON.stringify(init)) : {}
      }
    }
  }

	resultByYear = configureableReduce("Result", "Value", {
		"won":0,
		"lost":0,
		"tied":0
	});

	//---------------------------------FILTERS-----------------------------------------
  ndx = crossfilter(_data);
  //---------------------------ORDINARY CHARTS --------------------------------------
	year = ndx.dimension(function(d){return d.Year});

  year_group = year.group().reduceSum(function(d){return d.Value});

	year_chart = dc.rowChart('#year')
    .dimension(year)
    .group(year_group)
    .colors(year_default)
    .transitionDuration(200)
    .height(large_chart_height/1.5)
		.width(small_width)
    .ordering(function(d){ return -d.key })
//		.x(d3.scale.linear().domain([-25, 25]))
    .elasticX(true);

	year_chart.xAxis().ticks(10).tickFormat(d3.format("g"));
	grey_undefined(year_chart);

  year_bar = ndx.dimension(function(d){return d.Year});

  year_bar_group = year_bar.group().reduceSum(function(d){return d.Value});

	year_bar_chart = dc.barChart('#year-bar')
      .dimension(year_bar)
      .group(year_bar_group)
      .colors(default_colors)
      .transitionDuration(200)
      .height(medium_chart_height)
      .width(small_width)
      .ordering(function(d){ return -d.key })
      .x(d3.scale.linear().domain([-25, 25]))
      .brushOn(true)
      .elasticY(true)
      .elasticX(true);

	year_bar_chart.xAxis().ticks(5).tickFormat(d3.format("g"));
	grey_undefined(year_bar_chart);

	opposition = ndx.dimension(function(d){return d.Opposition});

  opposition_group = opposition.group().reduceSum(function(d){return d.Value});

	opposition_chart = dc.rowChart('#opposition')
    .dimension(opposition)
    .group(opposition_group)
    .colors(lost_default)
    .transitionDuration(200)
    .height(small_chart_height)
		.width(small_width-50)
    .ordering(function(d){ return -d.key })
//		.xAxisLabel('Total Games')
//		.xAxisPadding(500)
    .elasticX(true);

	opposition_chart.xAxis().ticks(5).tickFormat(d3.format("d"));
	grey_undefined(opposition_chart);

	team = ndx.dimension(function(d){return d.Team});
  team_group = team.group().reduceSum(function(d){return d.Value});

  team_chart = dc.rowChart('#team')
    .dimension(team)
    .group(team_group)
    .colors(won_default)
    .transitionDuration(200)
    .height(small_chart_height)
    .width(small_width-50)
    .ordering(function(d){ return -d.key })
    .elasticX(true);

  team_chart.xAxis().ticks(5).tickFormat(d3.format("d"));
  grey_undefined(team_chart);

	result = ndx.dimension(function(d){return d.Result});

  result_group = result.group().reduceSum(function(d){return d.Value});

	result_chart = dc.pieChart('#result')
    .dimension(result)
    .group(result_group)
    .transitionDuration(200)
    .legend(dc.legend().x(0).y(25).itemHeight(18).gap(5))
    .height(small_chart_height-50)
    .title(function(d) {
      var title = capitalizeFirst(d.key) + ": " + d.value;
      if (d.key == "won"){
        return "Team A \n" + title;
      }
      else if (d.key == "lost"){
        return "Team B \n" + title;
      }
      return title;
    })
    .label(function(d) {
      if (d.key == "won") return "Team A: " + d.value;
      else if (d.key == "lost") return "Team B: " + d.value;
      return capitalizeFirst(d.key) + ": " + d.value;
    })
    .radius(donut_outer)
    .colors(d3.scale.ordinal().domain(["won", "lost", "tied"])
                              .range(["#45936E","#92332F", "#3E70A1"]))
    .colorAccessor(function(d) {
			if (d.key == "won") return "won";
			else if (d.key == "lost") return "lost";
			return "tied";
		});

	result_year = ndx.dimension(function(d){return d.Year});
	result_year_group = result_year.group().reduce(resultByYear.add, resultByYear.remove, resultByYear.init);

  change_result_view();

  var all = ndx.groupAll();
  data_count_chart = dc.dataCount('#data_count')
    .dimension(ndx)
    .group(all)
    .html({
        some: '%filter-count selected out of %total-count records' +
            ' | Reset All',
        all: 'All records selected. Please click on the graph to apply filters.'
    });

  //pyramid chart
  resultStatus = ndx.dimension(function(d) {return d.resultStatus});
  result_group = resultStatus.group().reduceSum(function(d){return d.Value})

  team_opp_chart = dc.pyramidChart('#team_opp')
    .dimension(resultStatus)
    .group(result_group)
    .colors(d3.scale.ordinal().domain(["won", "lost"])
                              .range(["#45936E","#92332F"]))
    .colorAccessor(function(d) {
      if (d.key.split('@')[1] == "won") return "won";
      else if (d.key.split('@')[1] == "lost") return "lost";
    })
    .height(small_chart_height)
    .width(medium_width-50)
    .leftColumn(function (d){ return d.key.split('@')[1] == "won"})
    .rowAccessor(function(d){ return d.key.split('@')[0]})
    .label(function(d){return d.key.split('@')[0]})
    .title(function(d){
      if (d.key.split('@')[1] == "won") return "Won: " + d.value;
      else if (d.key.split('@')[1] == "lost") return "Lost: " + d.value;
      else return NaN;
    })
    .elasticX(false)
    .twoLabels(false)
    .rowOrdering(d3.ascending)
    .columnLabels(['Won','Lost'])
    .columnLabelPosition([150,0])
    .transitionDuration(200);

  team_opp_chart.xAxis().ticks(7).tickFormat(function(x) {return d3.format('s')(Math.abs(x))})

	dc.renderAll();

  initialize();
};

function initialize(){
  //odd are wins, even are losses
  var a = $('#team_opp g .row text:eq(7)');
//  var b = $('#team_opp g .row rect:eq(6)');

  a.simulate('click');
//  b.simulate('click');

};

function hideshow(id){
  var a = $(id);
  a.toggle('show');
};

function showAll() {
  var idList = ["#result_year", "#team_opp", "#result", "#team", "#opposition"]

  for (x in idList) {
    var a = $(idList[x]);
    if (a.css('display') == "none"){
      a.toggle('show');
    }
  }
  $('[type=checkbox]').prop('checked', true);
};<|endoftext|>


<commit_before>var Backbone = require('backbone'),
    AppView = require('views/app_view'),
    AdminView = require('views/admin_view'),
<<<<<<< HEAD
    DetailView = require('views/detail_view');
=======
    ListView = require('views/list_view');
>>>>>>> 342628d9de2c8ef7b9f7550a0872bf1c92c7662a

var Router = Backbone.Router.extend({
  routes: {
    '': 'query',
    'list': 'list',
    'admin': 'admin',
    'detail': 'detail'
  },

  query: function() {
    console.log('entering query route');

    var appView = new AppView();
    appView.render();
  },

  list: function() {
    console.log('entering list route');

    var listView = new ListView();
    listView.render();
  },

  admin: function() {
    console.log('entering admin route');

    var adminView = new AdminView();
    adminView.render();
  },
  detail: function() {
    var detailView = new DetailView();
    detailView.render();
  }
});

module.exports = Router;
<commit_msg>remove merge vestige<commit_after>var Backbone = require('backbone'),
    AppView = require('views/app_view'),
    AdminView = require('views/admin_view'),
    DetailView = require('views/detail_view'),
    ListView = require('views/list_view');

var Router = Backbone.Router.extend({
  routes: {
    '': 'query',
    'list': 'list',
    'admin': 'admin',
    'detail': 'detail'
  },

  query: function() {
    console.log('entering query route');

    var appView = new AppView();
    appView.render();
  },

  list: function() {
    console.log('entering list route');

    var listView = new ListView();
    listView.render();
  },

  admin: function() {
    console.log('entering admin route');

    var adminView = new AdminView();
    adminView.render();
  },
  detail: function() {
    var detailView = new DetailView();
    detailView.render();
  }
});

module.exports = Router;
<|endoftext|>


<commit_before>var Profile = {

    MapColorSquares:{
        init:function () {
            $("#map-colors > .selectable").selectable({
                filter:"div",
                selected:Profile.MapColorSquares.selectedListener
            });

            // Farben aus der DB
            $.post("/getmapcolors", function (mapColors) {
                console.log(mapColors);

                $.each(mapColors, function (index, value) {
                    $("#preview" + index).css("background-color", "#" + value);
                })
            });

            // hover-effect for Squares
            $(".ui-selectee").mouseenter(
                function () {
                    $(this).addClass("map-colors-hover");
                }).mouseleave(function () {
                    $(this).removeClass("map-colors-hover");
                });
        },

        selectedListener:function (event, ui) {
            var bgColor = $("#" + ui.selected.id).css("background-color");

            var values = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(bgColor);
            var red = parseInt(values[2]);
            var green = parseInt(values[3]);
            var blue = parseInt(values[4]);

            Profile.MapColorPicker.updateSlider(red, green, blue);
        }
    },

    MapColorPicker:{
        init:function () {
            $("#red, #green, #blue").slider({
                orientation:"horizontal",
                range:"min",
                max:255,
                value:127,
                slide:Profile.MapColorPicker.updatePreview,
                change:Profile.MapColorPicker.updatePreview
            });
            $("#red > .ui-slider-handle",
                "#green > .ui-slider-handle",
                "#blue > .ui-slider-handle").bind("touchmove", Profile.MapColorPicker.updateSliderHandle);
        },

        updateSlider:function (red, green, blue) {
            $("#red").slider("value", red);
            $("#green").slider("value", green);
            $("#blue").slider("value", blue);
        },

        updatePreview:function (event, ui) {
            var red = $("#red").slider("value"),
                green = $("#green").slider("value"),
                blue = $("#blue").slider("value"),
                hex = Profile.MapColorPicker.toHex(red, green, blue);
            $(".ui-selected").css("background-color", "#" + hex);
        },

        /* iPad-Optimierung
         * @author Lars Ebert
         * http://www.advitum.de/blog/2011/09/nutzeroberflachen-furs-ipad-jquery-ui-slider/ [Stand 21.05.2012]
         * TODO: Testen!!
         */
        updateSliderHandle:function (event, ui) {
            // x- und y-Position des Fingers, jQuery unterstützt diese Eigenschaft noch nicht, deshalb brauchen wir das Original-Event
            var e = event.originalEvent;

            // Position des Sliders
            var left = $(ui).parent().offset().left;
            var right = left + $(ui).parent().width();

            // Minimaler und maximaler Wert des Sliders
            var min = $(ui).parent().slider('option', 'min');
            var max = $(ui).parent().slider('option', 'max');

            // Mithilfe von einfachem Dreisatz können wir berechnen, welchen Wert die neue Position ergibt
            var newvalue = min + (e.touches.item(0).clientX - left) / (right - left) * (max - min);

            // Jetzt setzen wir den neuen Wert
            $(ui).parent().slider('value', newvalue);
        },

        toHex:function (red, green, blue) {
            var hex = [red.toString(16), green.toString(16), blue.toString(16)];
            $.each(hex, function (index, value) {
                if (value.length === 1) {
                    hex[index] = "0" + value;
                }
            });
            return hex.join("").toUpperCase();
        }
    },

    setMapColors:function () {
        var mapColors = new Array();

        //TODO: hart?
        for (var i = 0; i < 6; i++) {
            var bgColor = $("#preview" + i).css("background-color");

            var values = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(bgColor);
            var red = parseInt(values[2]);
            var green = parseInt(values[3]);
            var blue = parseInt(values[4]);

            mapColors.push(Profile.MapColorPicker.toHex(red, green, blue));
        }

        $.post("/updatemapcolors", {mapcolors:mapColors}, function (data) {
            console.log(data);
        });
    }
}

$(document).ready(function () {
    Profile.MapColorSquares.init();
    Profile.MapColorPicker.init();
});
<commit_msg>profile.js aufgeräumt<commit_after>var Profile = {

    MapColorSquares:{
        init:function () {
            $("#map-colors > .selectable").selectable({
                filter:"div",
                selected:Profile.MapColorSquares.selectedListener
            });

            // Farben aus der DB
            $.post("/getmapcolors", function (mapColors) {
                $.each(mapColors, function (index, value) {
                    $("#preview" + index).css("background-color", "#" + value);
                })
            });

            // hover-effect for Squares
            $(".ui-selectee").mouseenter(
                function () {
                    $(this).addClass("map-colors-hover");
                }).mouseleave(function () {
                    $(this).removeClass("map-colors-hover");
                });
        },

        selectedListener:function (event, ui) {
            var bgColor = $("#" + ui.selected.id).css("background-color");
            var values = Profile.MapColorPicker.parseRGBAString(bgColor);

            Profile.MapColorPicker.updateSlider(values["red"], values["green"], values["blue"]);
        }
    },

    MapColorPicker:{
        init:function () {
            $("#red, #green, #blue").slider({
                orientation:"horizontal",
                range:"min",
                max:255,
                value:127,
                slide:Profile.MapColorPicker.updatePreview,
                change:Profile.MapColorPicker.updatePreview
            });
            $("#red > .ui-slider-handle",
                "#green > .ui-slider-handle",
                "#blue > .ui-slider-handle").bind("touchmove", Profile.MapColorPicker.updateSliderHandle);
        },

        updateSlider:function (red, green, blue) {
            $("#red").slider("value", red);
            $("#green").slider("value", green);
            $("#blue").slider("value", blue);
        },

        updatePreview:function (event, ui) {
            var red = $("#red").slider("value"),
                green = $("#green").slider("value"),
                blue = $("#blue").slider("value"),
                hex = Profile.MapColorPicker.toHex(red, green, blue);
            $(".ui-selected").css("background-color", "#" + hex);
        },

        /* iPad-Optimierung
         * @author Lars Ebert
         * http://www.advitum.de/blog/2011/09/nutzeroberflachen-furs-ipad-jquery-ui-slider/ [Stand 21.05.2012]
         * TODO: Testen!!
         */
        updateSliderHandle:function (event, ui) {
            // x- und y-Position des Fingers, jQuery unterstützt diese Eigenschaft noch nicht, deshalb brauchen wir das Original-Event
            var e = event.originalEvent;

            // Position des Sliders
            var left = $(ui).parent().offset().left;
            var right = left + $(ui).parent().width();

            // Minimaler und maximaler Wert des Sliders
            var min = $(ui).parent().slider('option', 'min');
            var max = $(ui).parent().slider('option', 'max');

            // Mithilfe von einfachem Dreisatz können wir berechnen, welchen Wert die neue Position ergibt
            var newvalue = min + (e.touches.item(0).clientX - left) / (right - left) * (max - min);

            // Jetzt setzen wir den neuen Wert
            $(ui).parent().slider('value', newvalue);
        },

        toHex:function (red, green, blue) {
            var hex = [red.toString(16), green.toString(16), blue.toString(16)];
            $.each(hex, function (index, value) {
                if (value.length === 1) {
                    hex[index] = "0" + value;
                }
            });
            return hex.join("").toUpperCase();
        },

        parseRGBAString:function (rgba) {
            var res = new Array();

            var values = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(rgba);

            res["red"] = parseInt(values[2]);
            res["green"] = parseInt(values[3]);
            res["blue"] = parseInt(values[4]);

            return res;
        }
    },

    setMapColors:function () {
        var mapColors = new Array();

        //TODO: hart?
        for (var i = 0; i < 6; i++) {
            var bgColor = $("#preview" + i).css("background-color");
            var values = Profile.MapColorPicker.parseRGBAString(bgColor);

            mapColors.push(Profile.MapColorPicker.toHex(values["red"], values["green"], values["blue"]));
        }

        $.post("/updatemapcolors", {mapcolors:mapColors}, function (data) {
            console.log(data);
        });
    }
}

$(document).ready(function () {
    Profile.MapColorSquares.init();
    Profile.MapColorPicker.init();
});
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var exampleChoiceList = document.getElementById('example-choice-list');
    var liveEditorContainer = document.getElementById('live');
    var liveEditor = document.getElementById('editor');

    /**
     * Binds an event to the `window` object and listens for the onload event.
     * When the event is fired, the iframe load time is calculated, and the result
     * passed on to `trackFrameLoadTime` for performance analytics.
     * @param {String} exampleType - One of js or css
     */
    function sendPerformanceMetric(exampleType) {
        window.onload = function sendLoadTime() {
            mceAnalytics.trackFrameLoadTime(
                exampleType,
                mceUtils.calculateFrameLoadTime()
            );
        };
    }

    // only bind events if the container exist
    if (exampleChoiceList) {
        sendPerformanceMetric('css');

        exampleChoiceList.addEventListener('keyup', function(event) {
            var parentElement = event.target.parentElement;
            var resetButton = parentElement.querySelector('.reset');
            // only toggle the reset button on keyup if it is currently hidden
            if (resetButton.classList.contains('hidden')) {
                window.mceUtils.toggleReset(parentElement);
            }

            if (!localStorage.getItem('firstCSSEditRecorded')) {
                mceAnalytics.trackFirstEdit('css');
            }
        });
    }

    if (liveEditor) {
        sendPerformanceMetric('js');

        liveEditorContainer.addEventListener('click', function(event) {
            switch (event.target.id) {
            case 'execute':
                mceAnalytics.trackRunClicks();
                break;
            }
        });

        liveEditor.addEventListener('keyup', function() {
            var resetButton = liveEditor.querySelector('.reset');
            // only toggle the reset button on keyup if it is currently hidden
            if (resetButton.classList.contains('hidden')) {
                window.mceUtils.toggleReset(liveEditor);
            }

            if (!localStorage.getItem('firstJSEditRecorded')) {
                mceAnalytics.trackFirstEdit('js');
            }
        });
    }
})();
<commit_msg>Fix issue #55, add JS error logging to analytics<commit_after>(function() {
    'use strict';

    var exampleChoiceList = document.getElementById('example-choice-list');
    var liveEditorContainer = document.getElementById('live');
    var liveEditor = document.getElementById('editor');

    /**
     * Binds an event to the `window` object and listens for the onload event.
     * When the event is fired, the iframe load time is calculated, and the result
     * passed on to `trackFrameLoadTime` for performance analytics.
     * @param {String} exampleType - One of js or css
     */
    function sendPerformanceMetric(exampleType) {
        window.onload = function sendLoadTime() {
            mceAnalytics.trackFrameLoadTime(
                exampleType,
                mceUtils.calculateFrameLoadTime()
            );
        };
    }

    // only bind events if the container exist
    if (exampleChoiceList) {
        sendPerformanceMetric('css');

        exampleChoiceList.addEventListener('keyup', function(event) {
            var parentElement = event.target.parentElement;
            var resetButton = parentElement.querySelector('.reset');
            // only toggle the reset button on keyup if it is currently hidden
            if (resetButton.classList.contains('hidden')) {
                window.mceUtils.toggleReset(parentElement);
            }

            if (!localStorage.getItem('firstCSSEditRecorded')) {
                mceAnalytics.trackFirstEdit('css');
            }
        });
    }

    if (liveEditor) {
        sendPerformanceMetric('js');

        liveEditorContainer.addEventListener('click', function(event) {
            switch (event.target.id) {
            case 'execute':
                mceAnalytics.trackRunClicks();
                break;
            }
        });

        liveEditor.addEventListener('keyup', function() {
            var resetButton = liveEditor.querySelector('.reset');
            // only toggle the reset button on keyup if it is currently hidden
            if (resetButton.classList.contains('hidden')) {
                window.mceUtils.toggleReset(liveEditor);
            }

            if (!localStorage.getItem('firstJSEditRecorded')) {
                mceAnalytics.trackFirstEdit('js');
            }
        });
    }

    /**
     * Catches JavaScript errors from the editor that bubble up to the
     * window and passes them on to GA
     */
    window.onerror = function(msg, url, lineNo, columnNo, error) {
        var errorDetails = [
            'URL: ' + url,
            'Line: ' + lineNo,
            'Column: ' + columnNo,
            'Error object: ' + JSON.stringify(error)
        ].join(' - ');

        mceAnalytics.trackEvent({
            category: 'JavaScript Errors',
            action: errorDetails,
            label: msg
        });
    };
})();
<|endoftext|>


<commit_before>define(['handlebars'], function(Handlebars){

  Handlebars.registerHelper('link', function(text, url) {
    text = Handlebars.Utils.escapeExpression(text);
    url  = Handlebars.Utils.escapeExpression(url);

    // Exemplo: {{name}}
    var result = '' + text + '';

    return new Handlebars.SafeString(result);
  });

  Handlebars.registerHelper('list_proposal', function(proposals, options) {

    var ret = "";
    for(var i=0, j=proposals.length; i<j; i++) {
      var proposal = proposals[i];

      element = '
' +
        '' +
          '
' +
            '' + proposal.title;
      category = "
";

      for(var x=0, y=proposal.categories.length; x<y; x++) {
        if((options.hash['category'] != null) && (options.hash['category'] != proposal.categories[x].slug)){
          element = '';
          continue;
        }
        category = category + '
' + proposal.categories[x].name + '
';
      }
      if(element == ''){
        continue;
      }
      category =  category + '
';
      // element = element + options.fn(proposal);
      element = element + (proposal.abstract ? proposal.abstract : '');

      element = element + category;
      ret = ret + element + '

';
    }
    return ret;
  });

  Handlebars.registerHelper('proposal_detail', function(proposals, options) {
    var ret = "";
    for(var i=0, j=proposals.length; i<j; i++) {
      ret = ret + "
";
      ret = ret + "
" + proposals[i].title + "
";
      ret = ret + "" + proposals[i].body + "";
      ret = ret + '
';
    }
    return ret;
  });

  Handlebars.registerHelper('replace', function(string, to_replace, replacement) {
    return (string || '').replace(new RegExp(to_replace, 'g'), replacement);
  });

  Handlebars.registerHelper('score', function(article) {
    return article.votes_for - article.votes_against;
  });

  Handlebars.registerHelper('select_proposal', function(proposals, category_slug, selected_id) {
    var ret = 'Selecione o programa'
    ret =  ret + '<select id="proposal-selection" name="proposal-selection" title="Selecione o programa" class="proposal-selection">';

    for(var i=0; i<proposals.length; i++) {
      if(!proposal_has_category(proposals[i], category_slug)) continue;
      var selected = proposals[i].id===selected_id ? "selected" : "";
      ret += '<option value="'+proposals[i].id+'" '+selected+'>'+proposals[i].title+'</option>';
    }
    ret += '</select>';
    return ret;
  });

  Handlebars.registerHelper('trimString', function(passedString, endstring) {
    var theString = passedString.substring(0, endstring);
    return new Handlebars.SafeString(theString)
  });

  Handlebars.registerHelper('proposal_action', function(discussion, target) {
    if(discussion.setting && discussion.setting.moderate_proposals) {
      return '/api/v1/articles/'+target.id+'/children/suggest';
    } else {
      return '/api/v1/articles/'+target.id+'/children';
    }
  });

  function proposal_has_category(proposal, category_slug) {
    for(var i=0; i<proposal.categories.length; i++) {
      if(proposal.categories[i].slug == category_slug)
        return true;
    }
    return false;
  }

});
<commit_msg>List programs in alphabetical order<commit_after>define(['handlebars'], function(Handlebars){

  Handlebars.registerHelper('link', function(text, url) {
    text = Handlebars.Utils.escapeExpression(text);
    url  = Handlebars.Utils.escapeExpression(url);

    // Exemplo: {{name}}
    var result = '' + text + '';

    return new Handlebars.SafeString(result);
  });

  Handlebars.registerHelper('list_proposal', function(proposals, options) {

    proposals = proposals.sort(function(p1, p2) {
      var v1 = p1.title.toLowerCase();
      var v2 = p2.title.toLowerCase();
      return v1 < v2 ? -1 : (v1 > v2 ? 1 : 0);
    });
    var ret = "";
    for(var i=0, j=proposals.length; i<j; i++) {
      var proposal = proposals[i];

      element = '
' +
        '' +
          '
' +
            '' + proposal.title;
      category = "
";

      for(var x=0, y=proposal.categories.length; x<y; x++) {
        if((options.hash['category'] != null) && (options.hash['category'] != proposal.categories[x].slug)){
          element = '';
          continue;
        }
        category = category + '
' + proposal.categories[x].name + '
';
      }
      if(element == ''){
        continue;
      }
      category =  category + '
';
      // element = element + options.fn(proposal);
      element = element + (proposal.abstract ? proposal.abstract : '');

      element = element + category;
      ret = ret + element + '

';
    }
    return ret;
  });

  Handlebars.registerHelper('proposal_detail', function(proposals, options) {
    var ret = "";
    for(var i=0, j=proposals.length; i<j; i++) {
      ret = ret + "
";
      ret = ret + "
" + proposals[i].title + "
";
      ret = ret + "" + proposals[i].body + "";
      ret = ret + '
';
    }
    return ret;
  });

  Handlebars.registerHelper('replace', function(string, to_replace, replacement) {
    return (string || '').replace(new RegExp(to_replace, 'g'), replacement);
  });

  Handlebars.registerHelper('score', function(article) {
    return article.votes_for - article.votes_against;
  });

  Handlebars.registerHelper('select_proposal', function(proposals, category_slug, selected_id) {
    var ret = 'Selecione o programa'
    ret =  ret + '<select id="proposal-selection" name="proposal-selection" title="Selecione o programa" class="proposal-selection">';

    for(var i=0; i<proposals.length; i++) {
      if(!proposal_has_category(proposals[i], category_slug)) continue;
      var selected = proposals[i].id===selected_id ? "selected" : "";
      ret += '<option value="'+proposals[i].id+'" '+selected+'>'+proposals[i].title+'</option>';
    }
    ret += '</select>';
    return ret;
  });

  Handlebars.registerHelper('trimString', function(passedString, endstring) {
    var theString = passedString.substring(0, endstring);
    return new Handlebars.SafeString(theString)
  });

  Handlebars.registerHelper('proposal_action', function(discussion, target) {
    if(discussion.setting && discussion.setting.moderate_proposals) {
      return '/api/v1/articles/'+target.id+'/children/suggest';
    } else {
      return '/api/v1/articles/'+target.id+'/children';
    }
  });

  function proposal_has_category(proposal, category_slug) {
    for(var i=0; i<proposal.categories.length; i++) {
      if(proposal.categories[i].slug == category_slug)
        return true;
    }
    return false;
  }

});
<|endoftext|>


<commit_before>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
            $('#container').removeClass('container');
            $('#container').css('margin', '20px');
            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);

                            });
                        },
                    });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).attr('checked'));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).attr('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).attr('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).attr('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).attr('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).attr('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).attr('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).attr('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).attr('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).attr('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).attr('checked'));
        });
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });

        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked == 'checked')
            totalChecked++;
        else
            totalChecked--;

        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                selfObj.initDataTable();
                selfObj.bindEvents();
				$('.dropdown-toggle-custom').bind('click',function(){
					$(this).next().slideToggle();
				});
            }

        });
    }
    var customFieldName = 'All';
    var customColumnName = 'all';
    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {
        $('#addKeyword').click(function () {
            if ($('#keywordSearch').val() != '') {
                if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                    Filters = JSON.parse($('#facet_keyword_search').val());
                }
                else {
                    Filters = new Array();
                }
                for (x in Filters) {
                    if (Filters[x].value == $('#keywordSearch').val()) {
                        alert($('#keywordSearch').val() + " filter is already applied.");
                        return false;
                    }
                }
                var temp = {};
                temp.value = $('#keywordSearch').val();
                temp.type = customColumnName;
                Filters.push(temp);

                $('#facet_keyword_search').val(JSON.stringify(Filters));

                filterRecords();
            }
        });
    }
}

<commit_msg>worked on the facet<commit_after>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
            $('#container').removeClass('container');
            $('#container').css('margin', '20px');
            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);

                            });
                        },
                    });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).attr('checked'));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).attr('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).attr('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).attr('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).attr('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).attr('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).attr('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).attr('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).attr('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).attr('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).attr('checked'));
        });
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });

        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked == 'checked')
            totalChecked++;
        else
            totalChecked--;

        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                selfObj.initDataTable();
                selfObj.bindEvents();
				$('.dropdown-toggle,.button-dropdown').bind('click',function(){
					$(this).next().slideToggle();
				});
            }

        });
    }
    var customFieldName = 'All';
    var customColumnName = 'all';
    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {
        $('#addKeyword').click(function () {
            if ($('#keywordSearch').val() != '') {
                if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                    Filters = JSON.parse($('#facet_keyword_search').val());
                }
                else {
                    Filters = new Array();
                }
                for (x in Filters) {
                    if (Filters[x].value == $('#keywordSearch').val()) {
                        alert($('#keywordSearch').val() + " filter is already applied.");
                        return false;
                    }
                }
                var temp = {};
                temp.value = $('#keywordSearch').val();
                temp.type = customColumnName;
                Filters.push(temp);

                $('#facet_keyword_search').val(JSON.stringify(Filters));

                filterRecords();
            }
        });
    }
}

<|endoftext|>


<commit_before>"use strict";

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');

//  ---------------------------------------------------------------------------

module.exports = class independentreserve extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'independentreserve',
            'name': 'Independent Reserve',
            'countries': [ 'AU', 'NZ' ], // Australia, New Zealand
            'rateLimit': 1000,
            'has': {
                'CORS': false,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/30521662-cf3f477c-9bcb-11e7-89bc-d1ac85012eda.jpg',
                'api': {
                    'public': 'https://api.independentreserve.com/Public',
                    'private': 'https://api.independentreserve.com/Private',
                },
                'www': 'https://www.independentreserve.com',
                'doc': 'https://www.independentreserve.com/API',
            },
            'api': {
                'public': {
                    'get': [
                        'GetValidPrimaryCurrencyCodes',
                        'GetValidSecondaryCurrencyCodes',
                        'GetValidLimitOrderTypes',
                        'GetValidMarketOrderTypes',
                        'GetValidOrderTypes',
                        'GetValidTransactionTypes',
                        'GetMarketSummary',
                        'GetOrderBook',
                        'GetTradeHistorySummary',
                        'GetRecentTrades',
                        'GetFxRates',
                    ],
                },
                'private': {
                    'post': [
                        'PlaceLimitOrder',
                        'PlaceMarketOrder',
                        'CancelOrder',
                        'GetOpenOrders',
                        'GetClosedOrders',
                        'GetClosedFilledOrders',
                        'GetOrderDetails',
                        'GetAccounts',
                        'GetTransactions',
                        'GetDigitalCurrencyDepositAddress',
                        'GetDigitalCurrencyDepositAddresses',
                        'SynchDigitalCurrencyDepositAddressWithBlockchain',
                        'WithdrawDigitalCurrency',
                        'RequestFiatWithdrawal',
                        'GetTrades',
                    ],
                },
            },
        });
    }

    async fetchMarkets () {
        let baseCurrencies = await this.publicGetValidPrimaryCurrencyCodes ();
        let quoteCurrencies = await this.publicGetValidSecondaryCurrencyCodes ();
        let result = [];
        for (let i = 0; i < baseCurrencies.length; i++) {
            let baseId = baseCurrencies[i];
            let baseIdUppercase = baseId.toUpperCase ();
            let base = this.commonCurrencyCode (baseIdUppercase);
            for (let j = 0; j < quoteCurrencies.length; j++) {
                let quoteId = quoteCurrencies[j];
                let quoteIdUppercase = quoteId.toUpperCase ();
                let quote = this.commonCurrencyCode (quoteIdUppercase);
                let id = baseId + '/' + quoteId;
                let symbol = base + '/' + quote;
                let taker = 0.5 / 100;
                let maker = 0.5 / 100;
                result.push ({
                    'id': id,
                    'symbol': symbol,
                    'base': base,
                    'quote': quote,
                    'baseId': baseId,
                    'quoteId': quoteId,
                    'taker': taker,
                    'maker': maker,
                    'info': id,
                });
            }
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let balances = await this.privatePostGetAccounts ();
        let result = { 'info': balances };
        for (let i = 0; i < balances.length; i++) {
            let balance = balances[i];
            let currencyCode = balance['CurrencyCode'];
            let uppercase = currencyCode.toUpperCase ();
            let currency = this.commonCurrencyCode (uppercase);
            let account = this.account ();
            account['free'] = balance['AvailableBalance'];
            account['total'] = balance['TotalBalance'];
            account['used'] = account['total'] - account['free'];
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetOrderBook (this.extend ({
            'primaryCurrencyCode': market['baseId'],
            'secondaryCurrencyCode': market['quoteId'],
        }, params));
        let timestamp = this.parse8601 (response['CreatedTimestampUtc']);
        return this.parseOrderBook (response, timestamp, 'BuyOrders', 'SellOrders', 'Price', 'Volume');
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = this.parse8601 (ticker['CreatedTimestampUtc']);
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': ticker['DayHighestPrice'],
            'low': ticker['DayLowestPrice'],
            'bid': ticker['CurrentHighestBidPrice'],
            'ask': ticker['CurrentLowestOfferPrice'],
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': ticker['LastPrice'],
            'change': undefined,
            'percentage': undefined,
            'average': ticker['DayAvgPrice'],
            'baseVolume': ticker['DayVolumeXbtInSecondaryCurrrency'],
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetMarketSummary (this.extend ({
            'primaryCurrencyCode': market['baseId'],
            'secondaryCurrencyCode': market['quoteId'],
        }, params));
        return this.parseTicker (response, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.parse8601 (trade['TradeTimestampUtc']);
        return {
            'id': undefined,
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'order': undefined,
            'type': undefined,
            'side': undefined,
            'price': trade['SecondaryCurrencyTradePrice'],
            'amount': trade['PrimaryCurrencyAmount'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetRecentTrades (this.extend ({
            'primaryCurrencyCode': market['baseId'],
            'secondaryCurrencyCode': market['quoteId'],
            'numberOfRecentTradesToRetrieve': 50, // max = 50
        }, params));
        return this.parseTrades (response['Trades'], market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let capitalizedOrderType = this.capitalize (type);
        let method = 'privatePostPlace' + capitalizedOrderType + 'Order';
        let orderType = capitalizedOrderType;
        orderType += (side == 'sell') ?  'Offer' : 'Bid';
        let order = this.ordered ({
            'primaryCurrencyCode': market['baseId'],
            'secondaryCurrencyCode': market['quoteId'],
            'orderType': orderType,
        });
        if (type == 'limit')
            order['price'] = price;
        order['volume'] = amount;
        let response = await this[method] (this.extend (order, params));
        return {
            'info': response,
            'id': response['OrderGuid'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        return await this.privatePostCancelOrder ({ 'orderGuid': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api] + '/' + path;
        if (api == 'public') {
            if (Object.keys (params).length)
                url += '?' + this.urlencode (params);
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ();
            let auth = [
                url,
                'apiKey=' + this.apiKey,
                'nonce=' + nonce.toString (),
            ];
            let keysorted = this.keysort (params);
            let keys = Object.keys (keysorted);
            for (let i = 0; i < keys.length; i++) {
                let key = keys[i];
                auth.push (key + '=' + params[key]);
            }
            let message = auth.join (',');
            let signature = this.hmac (this.encode (message), this.encode (this.secret));
            let query = this.keysort (this.extend ({
                'apiKey': this.apiKey,
                'nonce': nonce,
                'signature': signature,
            }, params));
            body = this.json (query);
            headers = { 'Content-Type': 'application/json' };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        // todo error handling
        return response;
    }
}
<commit_msg>independentreserve new naming schema for implicit methods, linting<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');

//  ---------------------------------------------------------------------------

module.exports = class independentreserve extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'independentreserve',
            'name': 'Independent Reserve',
            'countries': [ 'AU', 'NZ' ], // Australia, New Zealand
            'rateLimit': 1000,
            'has': {
                'CORS': false,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/30521662-cf3f477c-9bcb-11e7-89bc-d1ac85012eda.jpg',
                'api': {
                    'public': 'https://api.independentreserve.com/Public',
                    'private': 'https://api.independentreserve.com/Private',
                },
                'www': 'https://www.independentreserve.com',
                'doc': 'https://www.independentreserve.com/API',
            },
            'api': {
                'public': {
                    'get': [
                        'GetValidPrimaryCurrencyCodes',
                        'GetValidSecondaryCurrencyCodes',
                        'GetValidLimitOrderTypes',
                        'GetValidMarketOrderTypes',
                        'GetValidOrderTypes',
                        'GetValidTransactionTypes',
                        'GetMarketSummary',
                        'GetOrderBook',
                        'GetTradeHistorySummary',
                        'GetRecentTrades',
                        'GetFxRates',
                    ],
                },
                'private': {
                    'post': [
                        'PlaceLimitOrder',
                        'PlaceMarketOrder',
                        'CancelOrder',
                        'GetOpenOrders',
                        'GetClosedOrders',
                        'GetClosedFilledOrders',
                        'GetOrderDetails',
                        'GetAccounts',
                        'GetTransactions',
                        'GetDigitalCurrencyDepositAddress',
                        'GetDigitalCurrencyDepositAddresses',
                        'SynchDigitalCurrencyDepositAddressWithBlockchain',
                        'WithdrawDigitalCurrency',
                        'RequestFiatWithdrawal',
                        'GetTrades',
                    ],
                },
            },
        });
    }

    async fetchMarkets () {
        let baseCurrencies = await this.publicGetGetValidPrimaryCurrencyCodes ();
        let quoteCurrencies = await this.publicGetGetValidSecondaryCurrencyCodes ();
        let result = [];
        for (let i = 0; i < baseCurrencies.length; i++) {
            let baseId = baseCurrencies[i];
            let baseIdUppercase = baseId.toUpperCase ();
            let base = this.commonCurrencyCode (baseIdUppercase);
            for (let j = 0; j < quoteCurrencies.length; j++) {
                let quoteId = quoteCurrencies[j];
                let quoteIdUppercase = quoteId.toUpperCase ();
                let quote = this.commonCurrencyCode (quoteIdUppercase);
                let id = baseId + '/' + quoteId;
                let symbol = base + '/' + quote;
                let taker = 0.5 / 100;
                let maker = 0.5 / 100;
                result.push ({
                    'id': id,
                    'symbol': symbol,
                    'base': base,
                    'quote': quote,
                    'baseId': baseId,
                    'quoteId': quoteId,
                    'taker': taker,
                    'maker': maker,
                    'info': id,
                });
            }
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let balances = await this.privatePostGetAccounts ();
        let result = { 'info': balances };
        for (let i = 0; i < balances.length; i++) {
            let balance = balances[i];
            let currencyCode = balance['CurrencyCode'];
            let uppercase = currencyCode.toUpperCase ();
            let currency = this.commonCurrencyCode (uppercase);
            let account = this.account ();
            account['free'] = balance['AvailableBalance'];
            account['total'] = balance['TotalBalance'];
            account['used'] = account['total'] - account['free'];
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetGetOrderBook (this.extend ({
            'primaryCurrencyCode': market['baseId'],
            'secondaryCurrencyCode': market['quoteId'],
        }, params));
        let timestamp = this.parse8601 (response['CreatedTimestampUtc']);
        return this.parseOrderBook (response, timestamp, 'BuyOrders', 'SellOrders', 'Price', 'Volume');
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = this.parse8601 (ticker['CreatedTimestampUtc']);
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': ticker['DayHighestPrice'],
            'low': ticker['DayLowestPrice'],
            'bid': ticker['CurrentHighestBidPrice'],
            'ask': ticker['CurrentLowestOfferPrice'],
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': ticker['LastPrice'],
            'change': undefined,
            'percentage': undefined,
            'average': ticker['DayAvgPrice'],
            'baseVolume': ticker['DayVolumeXbtInSecondaryCurrrency'],
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetGetMarketSummary (this.extend ({
            'primaryCurrencyCode': market['baseId'],
            'secondaryCurrencyCode': market['quoteId'],
        }, params));
        return this.parseTicker (response, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.parse8601 (trade['TradeTimestampUtc']);
        return {
            'id': undefined,
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'order': undefined,
            'type': undefined,
            'side': undefined,
            'price': trade['SecondaryCurrencyTradePrice'],
            'amount': trade['PrimaryCurrencyAmount'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetGetRecentTrades (this.extend ({
            'primaryCurrencyCode': market['baseId'],
            'secondaryCurrencyCode': market['quoteId'],
            'numberOfRecentTradesToRetrieve': 50, // max = 50
        }, params));
        return this.parseTrades (response['Trades'], market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let capitalizedOrderType = this.capitalize (type);
        let method = 'privatePostPlace' + capitalizedOrderType + 'Order';
        let orderType = capitalizedOrderType;
        orderType += (side === 'sell') ?  'Offer' : 'Bid';
        let order = this.ordered ({
            'primaryCurrencyCode': market['baseId'],
            'secondaryCurrencyCode': market['quoteId'],
            'orderType': orderType,
        });
        if (type === 'limit')
            order['price'] = price;
        order['volume'] = amount;
        let response = await this[method] (this.extend (order, params));
        return {
            'info': response,
            'id': response['OrderGuid'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        return await this.privatePostCancelOrder ({ 'orderGuid': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api] + '/' + path;
        if (api === 'public') {
            if (Object.keys (params).length)
                url += '?' + this.urlencode (params);
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ();
            let auth = [
                url,
                'apiKey=' + this.apiKey,
                'nonce=' + nonce.toString (),
            ];
            let keysorted = this.keysort (params);
            let keys = Object.keys (keysorted);
            for (let i = 0; i < keys.length; i++) {
                let key = keys[i];
                auth.push (key + '=' + params[key]);
            }
            let message = auth.join (',');
            let signature = this.hmac (this.encode (message), this.encode (this.secret));
            let query = this.keysort (this.extend ({
                'apiKey': this.apiKey,
                'nonce': nonce,
                'signature': signature,
            }, params));
            body = this.json (query);
            headers = { 'Content-Type': 'application/json' };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        // todo error handling
        return response;
    }
};
<|endoftext|>


<commit_before>//  Copyright 2002-2015, University of Colorado Boulder

/**
 * A tool is any node that can be dragged from a toolbox, carousel, panel, etc.
 *
 * TODO: This file is highly volatile an not ready for public consumption.  It is being actively developed
 * as part of https://github.com/phetsims/scenery-phet/issues/186 for work in Bending Light.  If it cannot be generalized
 * for usage in other simulations, it will be moved to Bending Light.  The API and implementation are subject to
 * change, and this disclaimer will be removed when the code is ready for review or usage.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Property = require( 'AXON/Property' );
  var SimpleDragHandler = require( 'SCENERY/input/SimpleDragHandler' );

  /**
   * Move a node from one parent to another but keeping it in exactly the same position/scale/orientation on the screen.
   * @param node
   * @param oldParent
   * @param newParent
   */
  var reparent = function( node, oldParent, newParent ) {
    var g1 = node.getLocalToGlobalMatrix();

    oldParent.removeChild( node );
    newParent.addChild( node );

    var p2 = newParent.getGlobalToLocalMatrix();

    var m2 = p2.timesMatrix( g1 );
    node.setMatrix( m2 );
  };

  /**
   * When the tool is dragged to/from the toolbox it shrinks/grows with animation.
   * @param node
   * @param scale
   * @returns {*}
   */
  var animateScale = function( node, scale ) {
    var parameters = { scale: node.getScaleVector().x }; // initial state, modified as the animation proceeds
    return new TWEEN.Tween( parameters )
      .easing( TWEEN.Easing.Cubic.InOut )
      .to( { scale: scale }, 200 )
      .onUpdate( function() {
        node.setScaleMagnitude( parameters.scale );
      } )
      .onComplete( function() {
      } )
      .start();
  };

  /**
   *
   * @constructor
   */
  function ToolListener( node, toolboxNode, playAreaNode, playAreaBoundsProperty, inToolbox, toolboxScale, playAreaScale ) {
    var inToolboxProperty = new Property( inToolbox );
    node.setScaleMagnitude( inToolbox ? toolboxScale : playAreaScale );

    var startOffset = null;

    var options = {
      allowTouchSnag: true,
      start: function( event ) {
        inToolboxProperty.value = false;

        // Note the options.startDrag can change the locationProperty, so read it again above, see https://github.com/phetsims/scenery-phet/issues/157
        var location = node.getCenter();
        startOffset = node.globalToParentPoint( event.pointer.point ).minus( location );
      },
      drag: function( event ) {
        var parentPoint = node.globalToParentPoint( event.pointer.point ).minus( startOffset );
        parentPoint = playAreaBoundsProperty.value.closestPointTo( parentPoint );
        //self.events.trigger1( 'startedCallbacksForDragged', location );

        //locationProperty.set( location );
        node.setCenter( parentPoint );

        //options.onDrag( event );

        //self.events.trigger0( 'endedCallbacksForDragged' );
      },
      end: function( event ) {

        // Drop into the toolbox.  But when there is no toolbox (when playAreaNode===toolboxNode) then do nothing.
        if ( toolboxNode !== playAreaNode && node.getGlobalBounds().intersectsBounds( toolboxNode.getGlobalBounds() ) ) {
          inToolboxProperty.value = true;
        }
      }
    };

    SimpleDragHandler.call( this, options );

    inToolboxProperty.lazyLink( function( inToolbox ) {
      if ( !inToolbox ) {
        animateScale( node, playAreaScale );
        reparent( node, toolboxNode, playAreaNode );
      }
      else {
        reparent( node, playAreaNode, toolboxNode );
        animateScale( node, toolboxScale );
      }
    } );

    // If the drag bounds changes, make sure the protractor didn't go out of bounds
    playAreaBoundsProperty.link( function( playAreaBounds ) {
      node.center = playAreaBounds.getClosestPoint( node.centerX, node.centerY );
    } );

    /**
     *
     * @param {Bounds2} parentBounds -
     * @param {Bounds2} childBounds -
     * @return {Vector2} - a translation vector that moves the childBounds to fit within the parentBounds, null
     *                   - if it cannot fit or ZERO if it is already within bounds.
     */
    //var getTranslationVectorToMoveInBounds = function( parentBounds, childBounds ) {
    //  if ( parentBounds.containsBounds( childBounds ) ) {
    //    return Vector2.ZERO;
    //  }
    //  else if ( childBounds.width > parentBounds.width || childBounds.height > parentBounds.height ) {
    //    return null;
    //  }
    //  else {
    //    var dx = 0;
    //    var dy = 0;
    //    if ( childBounds.minX < parentBounds.minX ) {
    //      dx = parentBounds.minX - childBounds.minX;
    //    }else if (childBounds.)
    //  }
    //};
  }

  return inherit( SimpleDragHandler, ToolListener );
} );<commit_msg>Animate nodes to the appropriate location in the toolbox, see https://github.com/phetsims/scenery-phet/issues/186<commit_after>//  Copyright 2002-2015, University of Colorado Boulder

/**
 * A tool is any node that can be dragged from a toolbox, carousel, panel, etc.
 *
 * TODO: This file is highly volatile an not ready for public consumption.  It is being actively developed
 * as part of https://github.com/phetsims/scenery-phet/issues/186 for work in Bending Light.  If it cannot be generalized
 * for usage in other simulations, it will be moved to Bending Light.  The API and implementation are subject to
 * change, and this disclaimer will be removed when the code is ready for review or usage.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Property = require( 'AXON/Property' );
  var SimpleDragHandler = require( 'SCENERY/input/SimpleDragHandler' );
  var Vector2 = require( 'DOT/Vector2' );

  /**
   * Move a node from one parent to another but keeping it in exactly the same position/scale/orientation on the screen.
   * @param node
   * @param oldParent
   * @param newParent
   */
  var reparent = function( node, oldParent, newParent ) {
    var g1 = node.getLocalToGlobalMatrix();

    oldParent.removeChild( node );
    newParent.addChild( node );

    var p2 = newParent.getGlobalToLocalMatrix();

    var m2 = p2.timesMatrix( g1 );
    node.setMatrix( m2 );
  };

  /**
   * When the tool is dragged to/from the toolbox it shrinks/grows with animation.
   * @param node
   * @param scale
   * @param centerX
   * @param centerY
   * @returns {*}
   */
  var animateScale = function( node, scale, centerX, centerY ) {
    var parameters = {
      scale: node.getScaleVector().x,
      centerX: node.centerX,
      centerY: node.centerY
    }; // initial state, modified as the animation proceeds
    return new TWEEN.Tween( parameters )
      .easing( TWEEN.Easing.Cubic.InOut )
      .to( {
        scale: scale,
        centerX: centerX,
        centerY: centerY
      }, 200 )
      .onUpdate( function() {
        node.setScaleMagnitude( parameters.scale );
        node.center = new Vector2( parameters.centerX, parameters.centerY )
      } )
      .onComplete( function() {
      } )
      .start();
  };

  /**
   *
   * @constructor
   */
  function ToolListener( node, toolboxNode, playAreaNode, playAreaBoundsProperty, inToolbox, toolboxScale, playAreaScale,
                         //
                         // Function that determines where the object should animate to in the toolbox, when dropped back
                         // in the toolbox.  This must be a function since sometimes the place things go back to in the
                         // toolbox is different than where they came from, for instance in the Fractions sims stacks of
                         // cards
                         getToolboxPosition ) {
    var inToolboxProperty = new Property( inToolbox );
    node.setScaleMagnitude( inToolbox ? toolboxScale : playAreaScale );
    node.center = inToolbox ? getToolboxPosition() : node.center;

    var startOffset = null;

    var options = {
      allowTouchSnag: true,
      start: function( event ) {
        var wasInToolbox = inToolboxProperty.value;
        inToolboxProperty.value = false;

        // Note the options.startDrag can change the locationProperty, so read it again above, see https://github.com/phetsims/scenery-phet/issues/157
        var location = node.getCenter();

        if ( wasInToolbox ) {
          startOffset = new Vector2( 0, 0 );
        }
        else {
          startOffset = node.globalToParentPoint( event.pointer.point ).minus( location );
        }

        if ( wasInToolbox && !inToolboxProperty.value ) {

          reparent( node, toolboxNode, playAreaNode );

          var parentPoint = node.globalToParentPoint( event.pointer.point ).minus( startOffset );
          parentPoint = playAreaBoundsProperty.value.closestPointTo( parentPoint );

          animateScale( node, playAreaScale, parentPoint.x, parentPoint.y );
        }
      },
      drag: function( event ) {
        var parentPoint = node.globalToParentPoint( event.pointer.point ).minus( startOffset );
        parentPoint = playAreaBoundsProperty.value.closestPointTo( parentPoint );
        //self.events.trigger1( 'startedCallbacksForDragged', location );

        //locationProperty.set( location );
        node.setCenter( parentPoint );

        //options.onDrag( event );

        //self.events.trigger0( 'endedCallbacksForDragged' );
      },
      end: function( event ) {

        // Drop into the toolbox.  But when there is no toolbox (when playAreaNode===toolboxNode) then do nothing.
        if ( toolboxNode !== playAreaNode && node.getGlobalBounds().intersectsBounds( toolboxNode.getGlobalBounds() ) ) {
          reparent( node, playAreaNode, toolboxNode );
          inToolboxProperty.value = true;
          var toolboxPosition = getToolboxPosition();
          animateScale( node, toolboxScale, toolboxPosition.x, toolboxPosition.y );
        }
      }
    };

    SimpleDragHandler.call( this, options );

    // If the drag bounds changes, make sure the protractor didn't go out of bounds
    playAreaBoundsProperty.link( function( playAreaBounds ) {
      node.center = playAreaBounds.getClosestPoint( node.centerX, node.centerY );
    } );

    /**
     *
     * @param {Bounds2} parentBounds -
     * @param {Bounds2} childBounds -
     * @return {Vector2} - a translation vector that moves the childBounds to fit within the parentBounds, null
     *                   - if it cannot fit or ZERO if it is already within bounds.
     */
    //var getTranslationVectorToMoveInBounds = function( parentBounds, childBounds ) {
    //  if ( parentBounds.containsBounds( childBounds ) ) {
    //    return Vector2.ZERO;
    //  }
    //  else if ( childBounds.width > parentBounds.width || childBounds.height > parentBounds.height ) {
    //    return null;
    //  }
    //  else {
    //    var dx = 0;
    //    var dy = 0;
    //    if ( childBounds.minX < parentBounds.minX ) {
    //      dx = parentBounds.minX - childBounds.minX;
    //    }else if (childBounds.)
    //  }
    //};
  }

  return inherit( SimpleDragHandler, ToolListener );
} );<|endoftext|>