<commit_before>/*
 * Chartkick.js
 * Create beautiful Javascript charts with minimal code
 * https://github.com/ankane/chartkick.js
 * v1.0.2
 * MIT License
 */

/*jslint browser: true, indent: 2, plusplus: true */
/*global google, $*/

(function() {
  'use strict';

  // helpers

  function isArray(variable) {
    return Object.prototype.toString.call(variable) === "[object Array]";
  }

  function isPlainObject(variable) {
    return variable instanceof Object;
  }

  // https://github.com/madrobby/zepto/blob/master/src/zepto.js
  function extend(target, source) {
    var key;
    for (key in source) {
      if (isPlainObject(source[key]) || isArray(source[key])) {
        if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
          target[key] = {};
        }
        if (isArray(source[key]) && !isArray(target[key])) {
          target[key] = [];
        }
        extend(target[key], source[key]);
      }
      else if (source[key] !== undefined) {
        target[key] = source[key];
      }
    }
  }

  function merge(obj1, obj2) {
    var target = {};
    extend(target, obj1);
    extend(target, obj2);
    return target;
  }

  // https://github.com/Do/iso8601.js
  var ISO8601_PATTERN = /(\d\d\d\d)(\-)?(\d\d)(\-)?(\d\d)(T)?(\d\d)(:)?(\d\d)?(:)?(\d\d)?([\.,]\d+)?($|Z|([\+\-])(\d\d)(:)?(\d\d)?)/i;
  var DECIMAL_SEPARATOR = String(1.5).charAt(1);

  function parseISO8601(input) {
    var day, hour, matches, milliseconds, minutes, month, offset, result, seconds, type, year;
    type = Object.prototype.toString.call(input);
    if (type === '[object Date]') {
      return input;
    }
    if (type !== '[object String]') {
      return;
    }
    if (matches = input.match(ISO8601_PATTERN)) {
      year = parseInt(matches[1], 10);
      month = parseInt(matches[3], 10) - 1;
      day = parseInt(matches[5], 10);
      hour = parseInt(matches[7], 10);
      minutes = matches[9] ? parseInt(matches[9], 10) : 0;
      seconds = matches[11] ? parseInt(matches[11], 10) : 0;
      milliseconds = matches[12] ? parseFloat(DECIMAL_SEPARATOR + matches[12].slice(1)) * 1000 : 0;
      result = Date.UTC(year, month, day, hour, minutes, seconds, milliseconds);
      if (matches[13] && matches[14]) {
        offset = matches[15] * 60;
        if (matches[17]) {
          offset += parseInt(matches[17], 10);
        }
        offset *= matches[14] === '-' ? -1 : 1;
        result -= offset * 60 * 1000;
      }
      return new Date(result);
    }
  }
  // end iso8601.js

  function negativeValues(series) {
    var i, j, data;
    for (i = 0; i < series.length; i++) {
      data = series[i].data;
      for (j = 0; j < data.length; j++) {
        if (data[j][1] < 0) {
          return true;
        }
      }
    }
    return false;
  }

  function jsOptionsFunc(defaultOptions, hideLegend, setMin, setMax) {
    return function(series, opts) {
      var options = merge({}, defaultOptions);

      // hide legend
      // this is *not* an external option!
      if (opts.hideLegend) {
        hideLegend(options);
      }

      // min
      if ("min" in opts) {
        setMin(options, opts.min);
      }
      else if (!negativeValues(series)) {
        setMin(options, 0);
      }

      // max
      if ("max" in opts) {
        setMax(options, opts.max);
      }

      // merge library last
      options = merge(options, opts.library || {});

      return options;
    };
  }

  // only functions that need defined specific to charting library
  var renderLineChart, renderPieChart, renderColumnChart;

  if ("Highcharts" in window) {

    var defaultOptions = {
      chart: {},
      xAxis: {
        labels: {
          style: {
            fontSize: "12px"
          }
        }
      },
      yAxis: {
        title: {
          text: null
        },
        labels: {
          style: {
            fontSize: "12px"
          }
        }
      },
      title: {
        text: null
      },
      credits: {
        enabled: false
      },
      legend: {
        borderWidth: 0
      },
      tooltip: {
        style: {
          fontSize: "12px"
        }
      }
    };

    var hideLegend = function(options) {
      options.legend.enabled = false;
    };

    var setMin = function(options, min) {
      options.yAxis.min = min;
    };

    var setMax = function(options, max) {
      options.yAxis.max = max;
    };

    var jsOptions = jsOptionsFunc(defaultOptions, hideLegend, setMin, setMax);

    renderLineChart = function(element, series, opts) {
      var options = jsOptions(series, opts), data, i, j;
      options.xAxis.type = "datetime";
      options.chart.type = "spline";
      options.chart.renderTo = element.id;

      for (i = 0; i < series.length; i++) {
        data = series[i].data;
        for (j = 0; j < data.length; j++) {
          data[j][0] = data[j][0].getTime();
        }
        series[i].marker = {symbol: "circle"};
      }
      options.series = series;
      new Highcharts.Chart(options);
    };

    renderPieChart = function(element, series, opts) {
      var options = merge(defaultOptions, opts.library || {});
      options.chart.renderTo = element.id;
      options.series = [{
        type: "pie",
        name: "Value",
        data: series
      }];
      new Highcharts.Chart(options);
    };

    renderColumnChart = function(element, series, opts) {
      var options = jsOptions(series, opts), i, j, s, d, rows = [];
      options.chart.type = "column";
      options.chart.renderTo = element.id;

      for (i = 0; i < series.length; i++) {
        s = series[i];

        for (j = 0; j < s.data.length; j++) {
          d = s.data[j];
          if (!rows[d[0]]) {
            rows[d[0]] = new Array(series.length);
          }
          rows[d[0]][i] = d[1];
        }
      }

      var categories = [];
      for (i in rows) {
        if (rows.hasOwnProperty(i)) {
          categories.push(i);
        }
      }
      options.xAxis.categories = categories;

      var newSeries = [];
      for (i = 0; i < series.length; i++) {
        d = [];
        for (j = 0; j < categories.length; j++) {
          d.push(rows[categories[j]][i] || 0);
        }

        newSeries.push({
          name: series[i].name,
          data: d
        });
      }
      options.series = newSeries;

      new Highcharts.Chart(options);
    };
  } else if ("google" in window) { // Google charts
    // load from google
    var loaded = false;
    google.setOnLoadCallback(function() {
      loaded = true;
    });
    google.load("visualization", "1.0", {"packages": ["corechart"]});

    var waitForLoaded = function(callback) {
      google.setOnLoadCallback(callback); // always do this to prevent race conditions (watch out for other issues due to this)
      if (loaded) {
        callback();
      }
    };

    // Set chart options
    var defaultOptions = {
      chartArea: {},
      fontName: "'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif",
      pointSize: 6,
      legend: {
        textStyle: {
          fontSize: 12,
          color: "#444"
        },
        alignment: "center",
        position: "right"
      },
      curveType: "function",
      hAxis: {
        textStyle: {
          color: "#666",
          fontSize: 12
        },
        gridlines: {
          color: "transparent"
        },
        baselineColor: "#ccc"
      },
      vAxis: {
        textStyle: {
          color: "#666",
          fontSize: 12
        },
        baselineColor: "#ccc",
        viewWindow: {}
      },
      tooltip: {
        textStyle: {
          color: "#666",
          fontSize: 12
        }
      }
    };

    var hideLegend = function(options) {
      options.legend.position = "none";
    };

    var setMin = function(options, min) {
      options.vAxis.viewWindow.min = min;
    };

    var setMax = function(options, max) {
      options.vAxis.viewWindow.max = max;
    };

    var jsOptions = jsOptionsFunc(defaultOptions, hideLegend, setMin, setMax);

    // cant use object as key
    var createDataTable = function(series, columnType) {
      var data = new google.visualization.DataTable();
      data.addColumn(columnType, "");

      var i, j, s, d, key, rows = [];
      for (i = 0; i < series.length; i++) {
        s = series[i];
        data.addColumn("number", s.name);

        for (j = 0; j < s.data.length; j++) {
          d = s.data[j];
          key = (columnType === "datetime") ? d[0].getTime() : d[0];
          if (!rows[key]) {
            rows[key] = new Array(series.length);
          }
          rows[key][i] = toFloat(d[1]);
        }
      }

      var rows2 = [];
      for (i in rows) {
        if (rows.hasOwnProperty(i)) {
          rows2.push([(columnType === "datetime") ? new Date(toFloat(i)) : i].concat(rows[i]));
        }
      }
      if (columnType === "datetime") {
        rows2.sort(sortByTime);
      }
      data.addRows(rows2);

      return data;
    };

    renderLineChart = function(element, series, opts) {
      waitForLoaded(function() {
        var options = jsOptions(series, opts);
        var data = createDataTable(series, "datetime");
        var chart = new google.visualization.LineChart(element);
        chart.draw(data, options);
      });
    };

    renderPieChart = function(element, series, opts) {
      waitForLoaded(function() {
        var chartOptions = {
          chartArea: {
            top: "10%",
            height: "80%"
          }
        };
        var options = merge(merge(defaultOptions, chartOptions), opts.library || {});

        var data = new google.visualization.DataTable();
        data.addColumn("string", "");
        data.addColumn("number", "Value");
        data.addRows(series);

        var chart = new google.visualization.PieChart(element);
        chart.draw(data, options);
      });
    };

    renderColumnChart = function(element, series, opts) {
      waitForLoaded(function() {
        var options = jsOptions(series, opts);
        var data = createDataTable(series, "string");
        var chart = new google.visualization.ColumnChart(element);
        chart.draw(data, options);
      });
    };
  } else { // no chart library installed
    renderLineChart = renderPieChart = renderColumnChart = function() {
      throw new Error("Please install Google Charts or Highcharts");
    };
  }

  function setText(element, text) {
    if (document.body.innerText) {
      element.innerText = text;
    } else {
      element.textContent = text;
    }
  }

  function chartError(element, message) {
    setText(element, "Error Loading Chart: " + message);
    element.style.color = "#ff0000";
  }

  function getJSON(element, url, success) {
    $.ajax({
      dataType: "json",
      url: url,
      success: success,
      error: function(jqXHR, textStatus, errorThrown) {
        var message = (typeof errorThrown === "string") ? errorThrown : errorThrown.message;
        chartError(element, message);
      }
    });
  }

  function errorCatcher(element, data, opts, callback) {
    try {
      callback(element, data, opts);
    } catch (err) {
      chartError(element, err.message);
      throw err;
    }
  }

  function fetchDataSource(element, dataSource, opts, callback) {
    if (typeof dataSource === "string") {
      getJSON(element, dataSource, function(data, textStatus, jqXHR) {
        errorCatcher(element, data, opts, callback);
      });
    } else {
      errorCatcher(element, dataSource, opts, callback);
    }
  }

  // type conversions

  function toStr(n) {
    return "" + n;
  }

  function toFloat(n) {
    return parseFloat(n);
  }

  function toDate(n) {
    if (typeof n !== "object") {
      if (typeof n === "number") {
        n = new Date(n * 1000); // ms
      } else { // str
        // try our best to get the str into iso8601
        // TODO be smarter about this
        var str = n.replace(/ /, "T").replace(" ", "").replace("UTC", "Z");
        n = parseISO8601(str) || new Date(n);
      }
    }
    return n;
  }

  function toArr(n) {
    if (!isArray(n)) {
      var arr = [], i;
      for (i in n) {
        if (n.hasOwnProperty(i)) {
          arr.push([i, n[i]]);
        }
      }
      n = arr;
    }
    return n;
  }

  // process data

  function sortByTime(a, b) {
    return a[0].getTime() - b[0].getTime();
  }

  function processSeries(series, opts, time) {
    var i, j, data, r, key;

    // see if one series or multiple
    if (!isArray(series) || typeof series[0] !== "object" || isArray(series[0])) {
      series = [{name: "Value", data: series}];
      opts.hideLegend = true;
    } else {
      opts.hideLegend = false;
    }

    // right format
    for (i = 0; i < series.length; i++) {
      data = toArr(series[i].data);
      r = [];
      for (j = 0; j < data.length; j++) {
        key = data[j][0];
        key = time ? toDate(key) : toStr(key);
        r.push([key, toFloat(data[j][1])]);
      }
      if (time) {
        r.sort(sortByTime);
      }
      series[i].data = r;
    }

    return series;
  }

  function processLineData(element, data, opts) {
    renderLineChart(element, processSeries(data, opts, true), opts);
  }

  function processColumnData(element, data, opts) {
    renderColumnChart(element, processSeries(data, opts, false), opts);
  }

  function processPieData(element, data, opts) {
    var perfectData = toArr(data), i;
    for (i = 0; i < perfectData.length; i++) {
      perfectData[i] = [toStr(perfectData[i][0]), toFloat(perfectData[i][1])];
    }
    renderPieChart(element, perfectData, opts);
  }

  function setElement(element, data, opts, callback) {
    if (typeof element === "string") {
      element = document.getElementById(element);
    }
    fetchDataSource(element, data, opts || {}, callback);
  }

  // define classes

  var Chartkick = {
    LineChart: function(element, dataSource, opts) {
      setElement(element, dataSource, opts, processLineData);
    },
    ColumnChart: function(element, dataSource, opts) {
      setElement(element, dataSource, opts, processColumnData);
    },
    PieChart: function(element, dataSource, opts) {
      setElement(element, dataSource, opts, processPieData);
    }
  };

  window.Chartkick = Chartkick;
})();
<commit_msg>Redraw charts on resize<commit_after>/*
 * Chartkick.js
 * Create beautiful Javascript charts with minimal code
 * https://github.com/ankane/chartkick.js
 * v1.0.2
 * MIT License
 */

/*jslint browser: true, indent: 2, plusplus: true */
/*global google, $*/

(function() {
  'use strict';

  // helpers

  function isArray(variable) {
    return Object.prototype.toString.call(variable) === "[object Array]";
  }

  function isPlainObject(variable) {
    return variable instanceof Object;
  }

  // https://github.com/madrobby/zepto/blob/master/src/zepto.js
  function extend(target, source) {
    var key;
    for (key in source) {
      if (isPlainObject(source[key]) || isArray(source[key])) {
        if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
          target[key] = {};
        }
        if (isArray(source[key]) && !isArray(target[key])) {
          target[key] = [];
        }
        extend(target[key], source[key]);
      }
      else if (source[key] !== undefined) {
        target[key] = source[key];
      }
    }
  }

  function merge(obj1, obj2) {
    var target = {};
    extend(target, obj1);
    extend(target, obj2);
    return target;
  }

  // https://github.com/Do/iso8601.js
  var ISO8601_PATTERN = /(\d\d\d\d)(\-)?(\d\d)(\-)?(\d\d)(T)?(\d\d)(:)?(\d\d)?(:)?(\d\d)?([\.,]\d+)?($|Z|([\+\-])(\d\d)(:)?(\d\d)?)/i;
  var DECIMAL_SEPARATOR = String(1.5).charAt(1);

  function parseISO8601(input) {
    var day, hour, matches, milliseconds, minutes, month, offset, result, seconds, type, year;
    type = Object.prototype.toString.call(input);
    if (type === '[object Date]') {
      return input;
    }
    if (type !== '[object String]') {
      return;
    }
    if (matches = input.match(ISO8601_PATTERN)) {
      year = parseInt(matches[1], 10);
      month = parseInt(matches[3], 10) - 1;
      day = parseInt(matches[5], 10);
      hour = parseInt(matches[7], 10);
      minutes = matches[9] ? parseInt(matches[9], 10) : 0;
      seconds = matches[11] ? parseInt(matches[11], 10) : 0;
      milliseconds = matches[12] ? parseFloat(DECIMAL_SEPARATOR + matches[12].slice(1)) * 1000 : 0;
      result = Date.UTC(year, month, day, hour, minutes, seconds, milliseconds);
      if (matches[13] && matches[14]) {
        offset = matches[15] * 60;
        if (matches[17]) {
          offset += parseInt(matches[17], 10);
        }
        offset *= matches[14] === '-' ? -1 : 1;
        result -= offset * 60 * 1000;
      }
      return new Date(result);
    }
  }
  // end iso8601.js

  function negativeValues(series) {
    var i, j, data;
    for (i = 0; i < series.length; i++) {
      data = series[i].data;
      for (j = 0; j < data.length; j++) {
        if (data[j][1] < 0) {
          return true;
        }
      }
    }
    return false;
  }

  function jsOptionsFunc(defaultOptions, hideLegend, setMin, setMax) {
    return function(series, opts) {
      var options = merge({}, defaultOptions);

      // hide legend
      // this is *not* an external option!
      if (opts.hideLegend) {
        hideLegend(options);
      }

      // min
      if ("min" in opts) {
        setMin(options, opts.min);
      }
      else if (!negativeValues(series)) {
        setMin(options, 0);
      }

      // max
      if ("max" in opts) {
        setMax(options, opts.max);
      }

      // merge library last
      options = merge(options, opts.library || {});

      return options;
    };
  }

  // only functions that need defined specific to charting library
  var renderLineChart, renderPieChart, renderColumnChart;

  if ("Highcharts" in window) {

    var defaultOptions = {
      chart: {},
      xAxis: {
        labels: {
          style: {
            fontSize: "12px"
          }
        }
      },
      yAxis: {
        title: {
          text: null
        },
        labels: {
          style: {
            fontSize: "12px"
          }
        }
      },
      title: {
        text: null
      },
      credits: {
        enabled: false
      },
      legend: {
        borderWidth: 0
      },
      tooltip: {
        style: {
          fontSize: "12px"
        }
      }
    };

    var hideLegend = function(options) {
      options.legend.enabled = false;
    };

    var setMin = function(options, min) {
      options.yAxis.min = min;
    };

    var setMax = function(options, max) {
      options.yAxis.max = max;
    };

    var jsOptions = jsOptionsFunc(defaultOptions, hideLegend, setMin, setMax);

    renderLineChart = function(element, series, opts) {
      var options = jsOptions(series, opts), data, i, j;
      options.xAxis.type = "datetime";
      options.chart.type = "spline";
      options.chart.renderTo = element.id;

      for (i = 0; i < series.length; i++) {
        data = series[i].data;
        for (j = 0; j < data.length; j++) {
          data[j][0] = data[j][0].getTime();
        }
        series[i].marker = {symbol: "circle"};
      }
      options.series = series;
      new Highcharts.Chart(options);
    };

    renderPieChart = function(element, series, opts) {
      var options = merge(defaultOptions, opts.library || {});
      options.chart.renderTo = element.id;
      options.series = [{
        type: "pie",
        name: "Value",
        data: series
      }];
      new Highcharts.Chart(options);
    };

    renderColumnChart = function(element, series, opts) {
      var options = jsOptions(series, opts), i, j, s, d, rows = [];
      options.chart.type = "column";
      options.chart.renderTo = element.id;

      for (i = 0; i < series.length; i++) {
        s = series[i];

        for (j = 0; j < s.data.length; j++) {
          d = s.data[j];
          if (!rows[d[0]]) {
            rows[d[0]] = new Array(series.length);
          }
          rows[d[0]][i] = d[1];
        }
      }

      var categories = [];
      for (i in rows) {
        if (rows.hasOwnProperty(i)) {
          categories.push(i);
        }
      }
      options.xAxis.categories = categories;

      var newSeries = [];
      for (i = 0; i < series.length; i++) {
        d = [];
        for (j = 0; j < categories.length; j++) {
          d.push(rows[categories[j]][i] || 0);
        }

        newSeries.push({
          name: series[i].name,
          data: d
        });
      }
      options.series = newSeries;

      new Highcharts.Chart(options);
    };
  } else if ("google" in window) { // Google charts
    // load from google
    var loaded = false;
    google.setOnLoadCallback(function() {
      loaded = true;
    });
    google.load("visualization", "1.0", {"packages": ["corechart"]});

    var waitForLoaded = function(callback) {
      google.setOnLoadCallback(callback); // always do this to prevent race conditions (watch out for other issues due to this)
      if (loaded) {
        callback();
      }
    };

    // Set chart options
    var defaultOptions = {
      chartArea: {},
      fontName: "'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif",
      pointSize: 6,
      legend: {
        textStyle: {
          fontSize: 12,
          color: "#444"
        },
        alignment: "center",
        position: "right"
      },
      curveType: "function",
      hAxis: {
        textStyle: {
          color: "#666",
          fontSize: 12
        },
        gridlines: {
          color: "transparent"
        },
        baselineColor: "#ccc"
      },
      vAxis: {
        textStyle: {
          color: "#666",
          fontSize: 12
        },
        baselineColor: "#ccc",
        viewWindow: {}
      },
      tooltip: {
        textStyle: {
          color: "#666",
          fontSize: 12
        }
      }
    };

    var hideLegend = function(options) {
      options.legend.position = "none";
    };

    var setMin = function(options, min) {
      options.vAxis.viewWindow.min = min;
    };

    var setMax = function(options, max) {
      options.vAxis.viewWindow.max = max;
    };

    var jsOptions = jsOptionsFunc(defaultOptions, hideLegend, setMin, setMax);

    // cant use object as key
    var createDataTable = function(series, columnType) {
      var data = new google.visualization.DataTable();
      data.addColumn(columnType, "");

      var i, j, s, d, key, rows = [];
      for (i = 0; i < series.length; i++) {
        s = series[i];
        data.addColumn("number", s.name);

        for (j = 0; j < s.data.length; j++) {
          d = s.data[j];
          key = (columnType === "datetime") ? d[0].getTime() : d[0];
          if (!rows[key]) {
            rows[key] = new Array(series.length);
          }
          rows[key][i] = toFloat(d[1]);
        }
      }

      var rows2 = [];
      for (i in rows) {
        if (rows.hasOwnProperty(i)) {
          rows2.push([(columnType === "datetime") ? new Date(toFloat(i)) : i].concat(rows[i]));
        }
      }
      if (columnType === "datetime") {
        rows2.sort(sortByTime);
      }
      data.addRows(rows2);

      return data;
    };

    var resize = function(callback) {
      if (window.attachEvent) {
        window.attachEvent("onresize", callback);
      }
      else if (window.addEventListener) {
        window.addEventListener("resize", callback, true);
      }
      callback();
    };

    renderLineChart = function(element, series, opts) {
      waitForLoaded(function() {
        var options = jsOptions(series, opts);
        var data = createDataTable(series, "datetime");
        var chart = new google.visualization.LineChart(element);
        resize( function() {
          chart.draw(data, options);
        });
      });
    };

    renderPieChart = function(element, series, opts) {
      waitForLoaded(function() {
        var chartOptions = {
          chartArea: {
            top: "10%",
            height: "80%"
          }
        };
        var options = merge(merge(defaultOptions, chartOptions), opts.library || {});

        var data = new google.visualization.DataTable();
        data.addColumn("string", "");
        data.addColumn("number", "Value");
        data.addRows(series);

        var chart = new google.visualization.PieChart(element);
        resize( function() {
          chart.draw(data, options);
        });
      });
    };

    renderColumnChart = function(element, series, opts) {
      waitForLoaded(function() {
        var options = jsOptions(series, opts);
        var data = createDataTable(series, "string");
        var chart = new google.visualization.ColumnChart(element);
        resize( function() {
          chart.draw(data, options);
        });
      });
    };
  } else { // no chart library installed
    renderLineChart = renderPieChart = renderColumnChart = function() {
      throw new Error("Please install Google Charts or Highcharts");
    };
  }

  function setText(element, text) {
    if (document.body.innerText) {
      element.innerText = text;
    } else {
      element.textContent = text;
    }
  }

  function chartError(element, message) {
    setText(element, "Error Loading Chart: " + message);
    element.style.color = "#ff0000";
  }

  function getJSON(element, url, success) {
    $.ajax({
      dataType: "json",
      url: url,
      success: success,
      error: function(jqXHR, textStatus, errorThrown) {
        var message = (typeof errorThrown === "string") ? errorThrown : errorThrown.message;
        chartError(element, message);
      }
    });
  }

  function errorCatcher(element, data, opts, callback) {
    try {
      callback(element, data, opts);
    } catch (err) {
      chartError(element, err.message);
      throw err;
    }
  }

  function fetchDataSource(element, dataSource, opts, callback) {
    if (typeof dataSource === "string") {
      getJSON(element, dataSource, function(data, textStatus, jqXHR) {
        errorCatcher(element, data, opts, callback);
      });
    } else {
      errorCatcher(element, dataSource, opts, callback);
    }
  }

  // type conversions

  function toStr(n) {
    return "" + n;
  }

  function toFloat(n) {
    return parseFloat(n);
  }

  function toDate(n) {
    if (typeof n !== "object") {
      if (typeof n === "number") {
        n = new Date(n * 1000); // ms
      } else { // str
        // try our best to get the str into iso8601
        // TODO be smarter about this
        var str = n.replace(/ /, "T").replace(" ", "").replace("UTC", "Z");
        n = parseISO8601(str) || new Date(n);
      }
    }
    return n;
  }

  function toArr(n) {
    if (!isArray(n)) {
      var arr = [], i;
      for (i in n) {
        if (n.hasOwnProperty(i)) {
          arr.push([i, n[i]]);
        }
      }
      n = arr;
    }
    return n;
  }

  // process data

  function sortByTime(a, b) {
    return a[0].getTime() - b[0].getTime();
  }

  function processSeries(series, opts, time) {
    var i, j, data, r, key;

    // see if one series or multiple
    if (!isArray(series) || typeof series[0] !== "object" || isArray(series[0])) {
      series = [{name: "Value", data: series}];
      opts.hideLegend = true;
    } else {
      opts.hideLegend = false;
    }

    // right format
    for (i = 0; i < series.length; i++) {
      data = toArr(series[i].data);
      r = [];
      for (j = 0; j < data.length; j++) {
        key = data[j][0];
        key = time ? toDate(key) : toStr(key);
        r.push([key, toFloat(data[j][1])]);
      }
      if (time) {
        r.sort(sortByTime);
      }
      series[i].data = r;
    }

    return series;
  }

  function processLineData(element, data, opts) {
    renderLineChart(element, processSeries(data, opts, true), opts);
  }

  function processColumnData(element, data, opts) {
    renderColumnChart(element, processSeries(data, opts, false), opts);
  }

  function processPieData(element, data, opts) {
    var perfectData = toArr(data), i;
    for (i = 0; i < perfectData.length; i++) {
      perfectData[i] = [toStr(perfectData[i][0]), toFloat(perfectData[i][1])];
    }
    renderPieChart(element, perfectData, opts);
  }

  function setElement(element, data, opts, callback) {
    if (typeof element === "string") {
      element = document.getElementById(element);
    }
    fetchDataSource(element, data, opts || {}, callback);
  }

  // define classes

  var Chartkick = {
    LineChart: function(element, dataSource, opts) {
      setElement(element, dataSource, opts, processLineData);
    },
    ColumnChart: function(element, dataSource, opts) {
      setElement(element, dataSource, opts, processColumnData);
    },
    PieChart: function(element, dataSource, opts) {
      setElement(element, dataSource, opts, processPieData);
    }
  };

  window.Chartkick = Chartkick;
})();
<|endoftext|>


<commit_before>/*

jQuery.Freefocus 0.7.0

Copyright (c) 2013-2014 Ilia Ablamonov. Licensed under the MIT license.

*/

(function ($) {
  'use strict';

  /*

  ### $.freefocus({options...}, {moveOptions...})

  Set up keyboard navigation.

  Options:

  - `focusedSelector` - selector for currently focused (or active) element. default: `':focus'`
  - `hoverFocus` - focus target elements on mouse enter. default: `false`
  - `throttle` - throttle key input for specified time (in milliseconds).
    You'll need underscore.js included to use this feature. default: `false`

  Move options are passed to `$.fn.freefocus`

  Usage:
  ```
  $.freefocus({hoverFocus: true})
  ```

  ### $.freefocus('remove')

  Remove previously set keyboard navigation.

  ### $.freefocus('cache', options)

  Compute and cache dimension information for focusable elements. Options: `focusablesSelector`, `focusablesFilter`

  */

  $.freefocus = function (setupOptions, moveOptions) {
    if (setupOptions === 'remove') {
      removeHandlers();
      return;
    }

    if (setupOptions === 'cache') {
      cacheFocusables(moveOptions);
      return;
    }

    setupOptions = $.extend({}, $.freefocus.setupOptions, setupOptions);

    var keyHandler = function (move) {
      var options = $.extend({}, moveOptions, { move: move });

      $(setupOptions.focusedSelector).freefocus(options);
    };

    if (typeof setupOptions.throttle === 'number') {
      keyHandler = _.throttle(keyHandler, setupOptions.throttle);
    }

    addHandler('keydown', function (event) {
      var move = $.freefocus.keys[event.which];

      if (!move)
        return;

      event.preventDefault();

      keyHandler(move);
    });

    if (setupOptions.hoverFocus) {
      if (!moveOptions.focusablesSelector)
        throw new Error('focusablesSelector is required for hoverFocus');
      addHandler('mouseenter', moveOptions.focusablesSelector, function () {
        var trigger = (moveOptions || {}).trigger || $.freefocus.moveOptions.trigger;
        var target = $(this);
        if (setupOptions.focusablesFilter)
          target = target.filter(setupOptions.focusablesFilter);
        return target.trigger(trigger);
      });
    }
  };

  /*

  ### .freefocus({moveOptions...})

  Move 'focus' from active element to one of the targets by triggering specified event.

  Options:

  - `move` - move direction: `left` | `right` | `up` | `down`. no default
  - `focusablesSelector` - selector for navigation targets. default: a long selector describing all focusable options in web browsers.
    You may want to provide something shorter to improve performance or use `:focusable` from jQuery UI.
  - `focusablesFilter` — selector that filters targets after they were selected using `focusablesSelector`.
    Separated for performance reasons. default: `':visible'`
  - `focusablesContext` — element or selector, conext for navigation targets search. default: `undefined`
  - `targets` - jQuery object containing 'focusable' elements. no default
    You should supply either focusablesSelector/Filter (preferred if you use nav-*) or explicit targets.
  - `debug` - print weighting information over targets. default: `false`
  - `trigger` - event to trigger on selected target. default: `'focus'`
  - `preTrigger` - event to trigger on selected target before the `trigger` one. default: `false` (don't trigger)
    Useful if `trigger` is `focus` to move the next focused element into view to avoid native behavior.
  - `useNavProps` - respect `nav-*` directional focus navigation style properties. default: `true`
  - `maxDistance` - maximum distance to element to still consider moving to it. default: `Infinity`
  - `cache` - cache dimension information for element. default: `false`.
    You'll need to manually reset cache for moved elements by using `$(element).freefocus('moved')`

  Usage:
  ```
  $(':focus').freefocus({move: 'right', targets: $('[tabindex]')})
  ```

  ### .freefocus('dimensions')

  Get element dimensions `{top, left, width, height}`. Uses cache, if it's enabled.

  ### .freefocus('moved')

  Clears cache for element.

  */

  $.fn.freefocus = function (options) {
    if (options === 'dimensions') {
      var box = getElementBox(this, true, false);
      return {
        left: box.x1,
        top: box.y1,
        width: box.x2 - box.x1,
        height: box.y2 - box.y1
      };
    }

    if (options === 'moved') {
      this.data('freefocus-dimensions', null);
      return;
    }

    options = $.extend({}, $.freefocus.moveOptions, options);

    if ($.freefocus.moves[options.move] === null)
      throw new Error('Unknown move direction "' + options.move + '"');
    if (!options.targets && !options.focusablesSelector)
      throw new Error('Options should contain either focusablesSelector or targets');
    if (options.targets && !(options.targets instanceof $))
      throw new Error('Argument targets should be a jQuery object');
    if (this.size() > 1)
      throw new Error('Can\'t move from multiple elements');
    if (!this.size())
      return this; // It's useful to be silent here

    if (options.debug) {
      clearDots();
    }

    updateFocusPoint(this, options.move, options.cache);

    var to = targetFromNavProps(this, options) || targetWithMinDistance(this, options);

    if (!to || !to.length)
      return this; // It's useful to be silent here

    moveFocusPoint(to, options.move, options.debug, options.cache);

    if (options.preTrigger) {
      to.trigger(options.preTrigger);
    }
    to.trigger(options.trigger);

    return this;
  };

  /*

  Defaults:

  */

  $.freefocus.moveOptions = {
    focusablesSelector: [
                          'a[href]',
                          'area[href]',
                          'input:enabled',
                          'select:enabled',
                          'textarea:enabled',
                          'button:enabled',
                          'iframe',
                          'object',
                          'embed',
                          '*[tabindex]',
                          '*[contenteditable]'
                        ].join(', '),
    focusablesFilter: ':visible',
    focusablesContext: undefined,
    trigger: 'focus',
    preTrigger: false,
    debug: false,
    useNavProps: true,
    maxDistance: Infinity
  };

  $.freefocus.setupOptions = {
    focusedSelector: ':focus',
    hoverFocus: false,
    throttle: false
  };

  $.freefocus.keys = {
    37: 'left',
    38: 'up',
    39: 'right',
    40: 'down'
  };

  $.freefocus.moves = {
    left: {},
    right: {},
    up: {},
    down: {}
  };

  /*

  Private:

  */

  $.freefocus.focusPoint = {};

  function targetFromNavProps($el, options) {
    var to = $el.get(0).style['nav' + (options.move.charAt(0).toUpperCase()) + (options.move.slice(1))];

    if (to && to.length) {
      // Toshiba adds garbage to the end
      to = to.split(' ')[0];
    } else {
      to = parseStyleString($el.attr('style') || '')['nav-' + options.move];
    }

    if (!to || !to.length)
      return;

    if (to === 'none')
      return $();

    if (to.indexOf('#') !== 0)
      to = '#' + to;

    var target = $(to);

    if (options.focusablesFilter && !target.is(options.focusablesFilter))
      return;

    return target;
  }

  function parseStyleString(style) {
    var result = {};
    style.split(';').forEach(function (rule) {
      var kv = rule.split(':');
      if (kv[1])
        result[kv[0].trim()] = kv[1].trim();
    });
    return result;
  }

  function updateFocusPoint($el, direction, cache) {
    var box = getElementBox($el, cache, cache);
    var fp = $.freefocus.focusPoint;

    // If the element was focused by freefocus,
    // thus we have valid current focus point
    if (!$el.is(fp.$el)) {
      fp.$el = $el;
      fp.box = {
        x: (box.x2 - box.x1) / 2,
        y: (box.y2 - box.y1) / 2
      };
    }
    fp.updatedInDirection = coordsInDirection(boxCoordsToClient(fp.box, box), direction);
    fp.updatedInDirection.fwd = boxInDirection(box, direction).fwd2;
  }

  function moveFocusPoint($el, direction, debug, cache) {
    var box = getElementBox($el, cache, cache);
    var fp = $.freefocus.focusPoint;

    fp.$el = $el;

    var boxInDir = boxInDirection(box, direction);
    var movedInDirection = {
      fwd: boxInDir.fwd1,
      ort: bound(fp.updatedInDirection.ort, boxInDir.ort1, boxInDir.ort2)
    };
    fp.box = clientCoordsToBox(coordsFromDirection(movedInDirection, direction), box);

    if (debug) {
      putDot(coordsFromDirection(movedInDirection, direction), '#00f', 'entry focus point for ' + $el.html());
    }
  }

  function targetWithMinDistance($fromEl, options) {
    var fromBox = boxInDirection(getElementBox($fromEl, options.cache, options.cache), options.move);

    if (options.debug) {
      putDot(coordsFromDirection($.freefocus.focusPoint.updatedInDirection, options.move), '#0f0', 'exit focus point for ' + $fromEl.html());
    }

    var minDistance = Infinity;
    var $resultEl = null;

    var targets;
    if (options.targets) {
      targets = options.targets;
    } else {
      targets = $(options.focusablesSelector, options.focusablesContext);
      if (options.focusablesFilter)
        targets = targets.filter(options.focusablesFilter);
    }

    targets.each(function () {
      var $toEl = $(this);

      // Skip currently focused element
      if ($toEl.is($fromEl))
        return;

      var toBox = boxInDirection(getElementBox($toEl, options.cache, options.cache), options.move);

      // Skip elements that are not in the direction of movement
      if (toBox.fwd2 <= fromBox.fwd2)
        return;

      var dist = distance(fromBox, toBox);

      if (dist < options.maxDistance && dist < minDistance) {
        $resultEl = $toEl;
        minDistance = dist;
      }
    });

    if (options.debug && $resultEl) {
      console.log('Distance from', $fromEl.get(0), 'to', $resultEl.get(0), 'is', minDistance);
    }

    return $resultEl;
  }

  function distance(fromBox, toBox) {
    var fromPoint = $.freefocus.focusPoint.updatedInDirection;

    var toPoint = {
      fwd: toBox.fwd1,
      ort: bound(fromPoint.ort, toBox.ort1, toBox.ort2)
    };

    var fwdDist = Math.abs(toPoint.fwd - fromPoint.fwd);
    var ortDist = Math.abs(toPoint.ort - fromPoint.ort);

    // The Euclidian distance between the current focus point position and
    // its potential position in the candidate.
    // If the two positions have the same coordinate on the axis orthogonal
    // to the navigation direction, dotDist is forced to 0 in order to favor
    // elements in direction of navigation
    var dotDist;
    if (toPoint.ort === fromPoint.ort) {
      dotDist = 0;
    } else {
      dotDist = Math.sqrt(fwdDist * fwdDist + ortDist * ortDist);
    }

    // The overlap between the opposing edges of currently focused element and the candidate.
    // Elements are rewarded for having high overlap with the currently focused element.
    var overlap = boxOverlap(fromBox, toBox);

    return dotDist + fwdDist + 2 * ortDist - Math.sqrt(overlap);
  }

  function boxOverlap(box1, box2) {
    var orts = {
      ort1: box1.ort1,
      ort2: box1.ort2
    };

    if (box2.ort1 > orts.ort1)
      orts.ort1 = box2.ort1;
    if (box2.ort2 < orts.ort2)
      orts.ort2 = box2.ort2;

    var result = orts.ort2 - orts.ort1;
    if (result < 0)
      result = 0;

    return result;
  }

  function computeElementBox($el) {
    var offset = $el.offset();
    return {
      x1: offset.left,
      y1: offset.top,
      x2: offset.left + $el.outerWidth(),
      y2: offset.top + $el.outerHeight()
    };
  }

  function getElementBox($el, readCache, writeCache) {
    var box;

    if (readCache)
      box = $el.data('freefocus-dimensions');
    if (!box)
      box = computeElementBox($el);
    if (writeCache)
      $el.data('freefocus-dimensions', box);

    return box;
  }

  function boxInDirection(box, direction) {
    var p1 = coordsInDirection({ x: box.x1, y: box.y1 }, direction);
    var p2 = coordsInDirection({ x: box.x2, y: box.y2 }, direction);
    return {
      fwd1: Math.min(p1.fwd, p2.fwd),
      ort1: Math.min(p1.ort, p2.ort),
      fwd2: Math.max(p1.fwd, p2.fwd),
      ort2: Math.max(p1.ort, p2.ort)
    };
  }

  function coordsInDirection(coords, direction) {
    switch (direction) {
      case 'left':
        return { fwd: -coords.x, ort: -coords.y };
      case 'right':
        return { fwd:  coords.x, ort:  coords.y };
      case 'down':
        return { fwd:  coords.y, ort: -coords.x };
      case 'up':
        return { fwd: -coords.y, ort:  coords.x };
    }
  }

  function coordsFromDirection(coords, direction) {
    switch (direction) {
      case 'left':
        return { x: -coords.fwd, y: -coords.ort };
      case 'right':
        return { x:  coords.fwd, y:  coords.ort };
      case 'down':
        return { x: -coords.ort, y:  coords.fwd };
      case 'up':
        return { x:  coords.ort, y: -coords.fwd };
    }
  }

  function boxCoordsToClient(coords, box) {
    return {
      x: coords.x + box.x1,
      y: coords.y + box.y1
    };
  }

  function clientCoordsToBox(coords, box) {
    return {
      x: coords.x - box.x1,
      y: coords.y - box.y1
    };
  }

  function bound(val, min, max) {
    return Math.min(Math.max(val, min), max);
  }

  function cacheFocusables(options) {
    var targets = $(options.focusablesSelector, options.focusablesContext);
    if (options.focusablesFilter)
      targets = targets.filter(options.focusablesFilter);
    targets.each(function () {
      getElementBox($(this), true, true);
    });
  }

  /*

  Debug:

  */

  function clearDots() {
    $('.freefocus-debug').remove();
  }

  function putDot(coords, color, title) {
    $('

').appendTo($('body')).css({
      position: 'absolute',
      left: coords.x - 3,
      top: coords.y - 3,
      width: 6,
      height: 6,
      background: color,
      'border-radius': 3
    }).attr('title', title);
  }

  /*

  Event handlers:

  */

  var eventHandlers = [];
  var $document = $(document);

  function addHandler() {
    $document.on.apply($document, arguments);
    eventHandlers.push(arguments);
  }

  function removeHandlers() {
    eventHandlers.forEach(function (args) {
      $document.off.apply($document, args);
    });
    eventHandlers = [];
  }
})(jQuery);
<commit_msg>Changed the meaning of "elements in the direction" to a more strict one.<commit_after>/*

jQuery.Freefocus 0.7.0

Copyright (c) 2013-2014 Ilia Ablamonov. Licensed under the MIT license.

*/

(function ($) {
  'use strict';

  /*

  ### $.freefocus({options...}, {moveOptions...})

  Set up keyboard navigation.

  Options:

  - `focusedSelector` - selector for currently focused (or active) element. default: `':focus'`
  - `hoverFocus` - focus target elements on mouse enter. default: `false`
  - `throttle` - throttle key input for specified time (in milliseconds).
    You'll need underscore.js included to use this feature. default: `false`

  Move options are passed to `$.fn.freefocus`

  Usage:
  ```
  $.freefocus({hoverFocus: true})
  ```

  ### $.freefocus('remove')

  Remove previously set keyboard navigation.

  ### $.freefocus('cache', options)

  Compute and cache dimension information for focusable elements. Options: `focusablesSelector`, `focusablesFilter`

  */

  $.freefocus = function (setupOptions, moveOptions) {
    if (setupOptions === 'remove') {
      removeHandlers();
      return;
    }

    if (setupOptions === 'cache') {
      cacheFocusables(moveOptions);
      return;
    }

    setupOptions = $.extend({}, $.freefocus.setupOptions, setupOptions);

    var keyHandler = function (move) {
      var options = $.extend({}, moveOptions, { move: move });

      $(setupOptions.focusedSelector).freefocus(options);
    };

    if (typeof setupOptions.throttle === 'number') {
      keyHandler = _.throttle(keyHandler, setupOptions.throttle);
    }

    addHandler('keydown', function (event) {
      var move = $.freefocus.keys[event.which];

      if (!move)
        return;

      event.preventDefault();

      keyHandler(move);
    });

    if (setupOptions.hoverFocus) {
      if (!moveOptions.focusablesSelector)
        throw new Error('focusablesSelector is required for hoverFocus');
      addHandler('mouseenter', moveOptions.focusablesSelector, function () {
        var trigger = (moveOptions || {}).trigger || $.freefocus.moveOptions.trigger;
        var target = $(this);
        if (setupOptions.focusablesFilter)
          target = target.filter(setupOptions.focusablesFilter);
        return target.trigger(trigger);
      });
    }
  };

  /*

  ### .freefocus({moveOptions...})

  Move 'focus' from active element to one of the targets by triggering specified event.

  Options:

  - `move` - move direction: `left` | `right` | `up` | `down`. no default
  - `focusablesSelector` - selector for navigation targets. default: a long selector describing all focusable options in web browsers.
    You may want to provide something shorter to improve performance or use `:focusable` from jQuery UI.
  - `focusablesFilter` — selector that filters targets after they were selected using `focusablesSelector`.
    Separated for performance reasons. default: `':visible'`
  - `focusablesContext` — element or selector, conext for navigation targets search. default: `undefined`
  - `targets` - jQuery object containing 'focusable' elements. no default
    You should supply either focusablesSelector/Filter (preferred if you use nav-*) or explicit targets.
  - `debug` - print weighting information over targets. default: `false`
  - `trigger` - event to trigger on selected target. default: `'focus'`
  - `preTrigger` - event to trigger on selected target before the `trigger` one. default: `false` (don't trigger)
    Useful if `trigger` is `focus` to move the next focused element into view to avoid native behavior.
  - `useNavProps` - respect `nav-*` directional focus navigation style properties. default: `true`
  - `maxDistance` - maximum distance to element to still consider moving to it. default: `Infinity`
  - `cache` - cache dimension information for element. default: `false`.
    You'll need to manually reset cache for moved elements by using `$(element).freefocus('moved')`

  Usage:
  ```
  $(':focus').freefocus({move: 'right', targets: $('[tabindex]')})
  ```

  ### .freefocus('dimensions')

  Get element dimensions `{top, left, width, height}`. Uses cache, if it's enabled.

  ### .freefocus('moved')

  Clears cache for element.

  */

  $.fn.freefocus = function (options) {
    if (options === 'dimensions') {
      var box = getElementBox(this, true, false);
      return {
        left: box.x1,
        top: box.y1,
        width: box.x2 - box.x1,
        height: box.y2 - box.y1
      };
    }

    if (options === 'moved') {
      this.data('freefocus-dimensions', null);
      return;
    }

    options = $.extend({}, $.freefocus.moveOptions, options);

    if ($.freefocus.moves[options.move] === null)
      throw new Error('Unknown move direction "' + options.move + '"');
    if (!options.targets && !options.focusablesSelector)
      throw new Error('Options should contain either focusablesSelector or targets');
    if (options.targets && !(options.targets instanceof $))
      throw new Error('Argument targets should be a jQuery object');
    if (this.size() > 1)
      throw new Error('Can\'t move from multiple elements');
    if (!this.size())
      return this; // It's useful to be silent here

    if (options.debug) {
      clearDots();
    }

    updateFocusPoint(this, options.move, options.cache);

    var to = targetFromNavProps(this, options) || targetWithMinDistance(this, options);

    if (!to || !to.length)
      return this; // It's useful to be silent here

    moveFocusPoint(to, options.move, options.debug, options.cache);

    if (options.preTrigger) {
      to.trigger(options.preTrigger);
    }
    to.trigger(options.trigger);

    return this;
  };

  /*

  Defaults:

  */

  $.freefocus.moveOptions = {
    focusablesSelector: [
                          'a[href]',
                          'area[href]',
                          'input:enabled',
                          'select:enabled',
                          'textarea:enabled',
                          'button:enabled',
                          'iframe',
                          'object',
                          'embed',
                          '*[tabindex]',
                          '*[contenteditable]'
                        ].join(', '),
    focusablesFilter: ':visible',
    focusablesContext: undefined,
    trigger: 'focus',
    preTrigger: false,
    debug: false,
    useNavProps: true,
    maxDistance: Infinity
  };

  $.freefocus.setupOptions = {
    focusedSelector: ':focus',
    hoverFocus: false,
    throttle: false
  };

  $.freefocus.keys = {
    37: 'left',
    38: 'up',
    39: 'right',
    40: 'down'
  };

  $.freefocus.moves = {
    left: {},
    right: {},
    up: {},
    down: {}
  };

  /*

  Private:

  */

  $.freefocus.focusPoint = {};

  function targetFromNavProps($el, options) {
    var to = $el.get(0).style['nav' + (options.move.charAt(0).toUpperCase()) + (options.move.slice(1))];

    if (to && to.length) {
      // Toshiba adds garbage to the end
      to = to.split(' ')[0];
    } else {
      to = parseStyleString($el.attr('style') || '')['nav-' + options.move];
    }

    if (!to || !to.length)
      return;

    if (to === 'none')
      return $();

    if (to.indexOf('#') !== 0)
      to = '#' + to;

    var target = $(to);

    if (options.focusablesFilter && !target.is(options.focusablesFilter))
      return;

    return target;
  }

  function parseStyleString(style) {
    var result = {};
    style.split(';').forEach(function (rule) {
      var kv = rule.split(':');
      if (kv[1])
        result[kv[0].trim()] = kv[1].trim();
    });
    return result;
  }

  function updateFocusPoint($el, direction, cache) {
    var box = getElementBox($el, cache, cache);
    var fp = $.freefocus.focusPoint;

    // If the element was focused by freefocus,
    // thus we have valid current focus point
    if (!$el.is(fp.$el)) {
      fp.$el = $el;
      fp.box = {
        x: (box.x2 - box.x1) / 2,
        y: (box.y2 - box.y1) / 2
      };
    }
    fp.updatedInDirection = coordsInDirection(boxCoordsToClient(fp.box, box), direction);
    fp.updatedInDirection.fwd = boxInDirection(box, direction).fwd2;
  }

  function moveFocusPoint($el, direction, debug, cache) {
    var box = getElementBox($el, cache, cache);
    var fp = $.freefocus.focusPoint;

    fp.$el = $el;

    var boxInDir = boxInDirection(box, direction);
    var movedInDirection = {
      fwd: boxInDir.fwd1,
      ort: bound(fp.updatedInDirection.ort, boxInDir.ort1, boxInDir.ort2)
    };
    fp.box = clientCoordsToBox(coordsFromDirection(movedInDirection, direction), box);

    if (debug) {
      putDot(coordsFromDirection(movedInDirection, direction), '#00f', 'entry focus point for ' + $el.html());
    }
  }

  function targetWithMinDistance($fromEl, options) {
    var fromBox = boxInDirection(getElementBox($fromEl, options.cache, options.cache), options.move);

    if (options.debug) {
      putDot(coordsFromDirection($.freefocus.focusPoint.updatedInDirection, options.move), '#0f0', 'exit focus point for ' + $fromEl.html());
    }

    var minDistance = Infinity;
    var $resultEl = null;

    var targets;
    if (options.targets) {
      targets = options.targets;
    } else {
      targets = $(options.focusablesSelector, options.focusablesContext);
      if (options.focusablesFilter)
        targets = targets.filter(options.focusablesFilter);
    }

    targets.each(function () {
      var $toEl = $(this);

      // Skip currently focused element
      if ($toEl.is($fromEl))
        return;

      var toBox = boxInDirection(getElementBox($toEl, options.cache, options.cache), options.move);

      // Skip elements that are not in the direction of movement
      if (toBox.fwd1 <= fromBox.fwd2)
        return;

      var dist = distance(fromBox, toBox);

      if (dist < options.maxDistance && dist < minDistance) {
        $resultEl = $toEl;
        minDistance = dist;
      }
    });

    if (options.debug && $resultEl) {
      console.log('Distance from', $fromEl.get(0), 'to', $resultEl.get(0), 'is', minDistance);
    }

    return $resultEl;
  }

  function distance(fromBox, toBox) {
    var fromPoint = $.freefocus.focusPoint.updatedInDirection;

    var toPoint = {
      fwd: toBox.fwd1,
      ort: bound(fromPoint.ort, toBox.ort1, toBox.ort2)
    };

    var fwdDist = Math.abs(toPoint.fwd - fromPoint.fwd);
    var ortDist = Math.abs(toPoint.ort - fromPoint.ort);

    // The Euclidian distance between the current focus point position and
    // its potential position in the candidate.
    // If the two positions have the same coordinate on the axis orthogonal
    // to the navigation direction, dotDist is forced to 0 in order to favor
    // elements in direction of navigation
    var dotDist;
    if (toPoint.ort === fromPoint.ort) {
      dotDist = 0;
    } else {
      dotDist = Math.sqrt(fwdDist * fwdDist + ortDist * ortDist);
    }

    // The overlap between the opposing edges of currently focused element and the candidate.
    // Elements are rewarded for having high overlap with the currently focused element.
    var overlap = boxOverlap(fromBox, toBox);

    return dotDist + fwdDist + 2 * ortDist - Math.sqrt(overlap);
  }

  function boxOverlap(box1, box2) {
    var orts = {
      ort1: box1.ort1,
      ort2: box1.ort2
    };

    if (box2.ort1 > orts.ort1)
      orts.ort1 = box2.ort1;
    if (box2.ort2 < orts.ort2)
      orts.ort2 = box2.ort2;

    var result = orts.ort2 - orts.ort1;
    if (result < 0)
      result = 0;

    return result;
  }

  function computeElementBox($el) {
    var offset = $el.offset();
    return {
      x1: offset.left,
      y1: offset.top,
      x2: offset.left + $el.outerWidth(),
      y2: offset.top + $el.outerHeight()
    };
  }

  function getElementBox($el, readCache, writeCache) {
    var box;

    if (readCache)
      box = $el.data('freefocus-dimensions');
    if (!box)
      box = computeElementBox($el);
    if (writeCache)
      $el.data('freefocus-dimensions', box);

    return box;
  }

  function boxInDirection(box, direction) {
    var p1 = coordsInDirection({ x: box.x1, y: box.y1 }, direction);
    var p2 = coordsInDirection({ x: box.x2, y: box.y2 }, direction);
    return {
      fwd1: Math.min(p1.fwd, p2.fwd),
      ort1: Math.min(p1.ort, p2.ort),
      fwd2: Math.max(p1.fwd, p2.fwd),
      ort2: Math.max(p1.ort, p2.ort)
    };
  }

  function coordsInDirection(coords, direction) {
    switch (direction) {
      case 'left':
        return { fwd: -coords.x, ort: -coords.y };
      case 'right':
        return { fwd:  coords.x, ort:  coords.y };
      case 'down':
        return { fwd:  coords.y, ort: -coords.x };
      case 'up':
        return { fwd: -coords.y, ort:  coords.x };
    }
  }

  function coordsFromDirection(coords, direction) {
    switch (direction) {
      case 'left':
        return { x: -coords.fwd, y: -coords.ort };
      case 'right':
        return { x:  coords.fwd, y:  coords.ort };
      case 'down':
        return { x: -coords.ort, y:  coords.fwd };
      case 'up':
        return { x:  coords.ort, y: -coords.fwd };
    }
  }

  function boxCoordsToClient(coords, box) {
    return {
      x: coords.x + box.x1,
      y: coords.y + box.y1
    };
  }

  function clientCoordsToBox(coords, box) {
    return {
      x: coords.x - box.x1,
      y: coords.y - box.y1
    };
  }

  function bound(val, min, max) {
    return Math.min(Math.max(val, min), max);
  }

  function cacheFocusables(options) {
    var targets = $(options.focusablesSelector, options.focusablesContext);
    if (options.focusablesFilter)
      targets = targets.filter(options.focusablesFilter);
    targets.each(function () {
      getElementBox($(this), true, true);
    });
  }

  /*

  Debug:

  */

  function clearDots() {
    $('.freefocus-debug').remove();
  }

  function putDot(coords, color, title) {
    $('

').appendTo($('body')).css({
      position: 'absolute',
      left: coords.x - 3,
      top: coords.y - 3,
      width: 6,
      height: 6,
      background: color,
      'border-radius': 3
    }).attr('title', title);
  }

  /*

  Event handlers:

  */

  var eventHandlers = [];
  var $document = $(document);

  function addHandler() {
    $document.on.apply($document, arguments);
    eventHandlers.push(arguments);
  }

  function removeHandlers() {
    eventHandlers.forEach(function (args) {
      $document.off.apply($document, args);
    });
    eventHandlers = [];
  }
})(jQuery);
<|endoftext|>


<commit_before>/*
Options
-----------------
data: object
start: date
end: date
cellWidth: number
*/

(function (jQuery) {
    jQuery.fn.ganttView = function (options) {

		var els = this;
		var defaults = { cellWidth: 21, vHeaderWidth: 100 };
		var opts = $.extend(defaults, options);
		var months = Gantt.getMonths(opts.start, opts.end);

		els.each(function () {

			var container = $(this);
			var div = $("
", { "class": "ganttview" });

			Gantt.addHzHeader(div, months, opts.cellWidth);
			Gantt.addVtHeader(div, opts.data);
			Gantt.addGrid(div, opts.data, months, opts.cellWidth);
			Gantt.addBlocks(div, opts.data, opts.cellWidth, opts.start);

			container.append(div);
		});
	};

	var Gantt = {

		monthNames: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],

		getMonths: function (start, end) {
			var months = []; months[start.getMonth()] = [start];
			var last = start;
			while (last.compareTo(end) == -1) {
				var next = last.clone().addDays(1);
				if (!months[next.getMonth()]) { months[next.getMonth()] = []; }
				months[next.getMonth()].push(next);
				last = next;
			}
			return months;
		},

		addHzHeader: function (div, months, cellWidth) {
			var headerDiv = $("
", { "class": "ganttview-hzheader" });
			var monthsDiv = $("
", { "class": "ganttview-hzheader-months" });
			var daysDiv = $("
", { "class": "ganttview-hzheader-days" });
			for (var i = 0; i < 12; i++) {
				if (months[i]) {
					monthsDiv.append($("
", {
						"class": "ganttview-hzheader-month",
						"css": { "width": ((months[i].length * cellWidth) - 1) + "px" }
					}).append(Gantt.monthNames[i]));
					for (var j = 0; j < months[i].length; j++) {
						daysDiv.append($("
", { "class": "ganttview-hzheader-day" }).append(months[i][j].getDate()));
					}
				}
			}
			headerDiv.append(monthsDiv).append(daysDiv);
			div.append(headerDiv);
		},

		addVtHeader: function (div, data) {
			var headerDiv = $("
", { "class": "ganttview-vtheader" });
			for (var i = 0; i < data.length; i++) {
				var itemDiv = $("
", { "class": "ganttview-vtheader-item" });
				itemDiv.append($("
", { "class": "ganttview-vtheader-item-name" }).append(data[i].name));
				var seriesDiv = $("
", { "class": "ganttview-vtheader-series" });
				for (var j = 0; j < data[i].series.length; j++) {
					seriesDiv.append($("
", { "class": "ganttview-vtheader-series-name" }).append(data[i].series[j].name));
				}
				itemDiv.append(seriesDiv);
				headerDiv.append(itemDiv)
			}
			div.append(headerDiv);
		},

		addGrid: function (div, data, months, cellWidth) {
			var gridDiv = $("
", { "class": "ganttview-grid" });
			var rowDiv = $("
", { "class": "ganttview-grid-row" });
			for (var i = 0; i < 12; i++) {
				if (months[i]) {
					for (var j = 0; j < months[i].length; j++) {
						rowDiv.append($("
", { "class": "ganttview-grid-row-cell " }));
					}
				}
			}
			rowDiv.css("width", ($("div.ganttview-grid-row-cell", rowDiv).length * cellWidth) + "px");
			for (var i = 0; i < data.length; i++) {
				for (var j = 0; j < data[i].series.length; j++) {
					gridDiv.append(rowDiv.clone());
				}
			}
			div.append(gridDiv);
		},

		addBlocks: function (div, data, cellWidth, start) {
			var rows = $("div.ganttview-grid div.ganttview-grid-row", div);
			var rowIdx = 0;
			for (var i = 0; i < data.length; i++) {
				for (var j = 0; j < data[i].series.length; j++) {
					var size = DateUtils.daysBetween(data[i].series[j].start, data[i].series[j].end);
					var offset = DateUtils.daysBetween(start, data[i].series[j].start);
					var blockDiv = $("
", {
						"class": "ganttview-block",
						"css": {
							"width": (size * cellWidth) + "px",
							"margin-left": (offset * cellWidth) + "px"
						}
					});
					$(rows[rowIdx]).append(blockDiv);
					rowIdx = rowIdx + 1;
				}
			}
		}

	};

})(jQuery);

var ArrayUtils = {
	contains: function (arr, obj) {
		var has = false;
		for (var i = 0; i < arr.length; i++) { if (arr[i] == obj) { has = true; } }
		return has;
	}
};

var DateUtils = {
	daysBetween: function (start, end) {
		var count = 0;
		while (start.compareTo(end) == -1) { count = count + 1; start.addDays(1); }
		return count;
	}
};

/* SAMPLE GENERATED MARKUP

Feature 1

Planned

Actual

Feature 2

Planned

Actual

Jan

Feb

Mar

1

2

3

1

2

3

1

2

3

*/

/*

createTable: function (months) {
	var tbl = $("
", { "class": "ganttview" });
	var w = 200;
	for (var i = 0; i < months.length; i++) {
		if (months[i]) { w = w + months[i].length * 28; }
	}
	tbl.css("width", w + "px");
	return tbl;
},
addHeaderToTable: function (tbl, months) {
	var thead = $("

");
	var monthTr = $("

");
	var emptyHdr = " 	";
	monthTr.append(emptyHdr).append(emptyHdr);
	var dateTr = $("

");
	for (var i = 0; i < 12; i++) {
		if (months[i]) {
			monthTr.append("" + Gantt.monthNames[i] + "	");
			for (var j = 0; j < months[i].length; j++) {
				dateTr.append("" + months[i][j].getDate() + "	");
			}
		}
	}
	thead.append(monthTr).append(dateTr);
	tbl.append(thead);
},
addGridToTable: function (tbl, data, months) {

	var tbody = $("

");

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

		var tr = $("

");
		var itemTd = $("" + data[i].name + "	");
		tr.append(itemTd);

		var seriesTd = $("" + data[i].series[0].name + "	");
		tr.append(seriesTd);
		Gantt.addCellsToSeriesRow(tr, months);
		tbody.append(tr);

		for (var j = 1; j < data[i].series.length; j++) {
			tr = $("

");
			var seriesTd = $("" + data[i].series[j].name + "	");
			tr.append(seriesTd);
			Gantt.addCellsToSeriesRow(tr, months);
			tbody.append(tr);
		}
	}

	tbl.append(tbody);
},
addCellsToSeriesRow: function (tr, months) {
	for (var i = 0; i < 12; i++) {
		if (months[i]) {
			for (var j = 0; j < months[i].length; j++) {
				tr.append("	");
			}
		}
	}
}
*/<commit_msg>chris pirillo sucks...and so do reference bugs<commit_after>/*
Options
-----------------
data: object
start: date
end: date
cellWidth: number
*/

(function (jQuery) {
    jQuery.fn.ganttView = function (options) {

		var els = this;
		var defaults = { cellWidth: 21, vHeaderWidth: 100 };
		var opts = $.extend(defaults, options);
		var months = Gantt.getMonths(opts.start, opts.end);

		els.each(function () {

			var container = $(this);
			var div = $("
", { "class": "ganttview" });

			Gantt.addHzHeader(div, months, opts.cellWidth);
			Gantt.addVtHeader(div, opts.data);
			Gantt.addGrid(div, opts.data, months, opts.cellWidth);
			Gantt.addBlocks(div, opts.data, opts.cellWidth, opts.start);

			container.append(div);
		});
	};

	var Gantt = {

		monthNames: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],

		getMonths: function (start, end) {
			var months = []; months[start.getMonth()] = [start];
			var last = start;
			while (last.compareTo(end) == -1) {
				var next = last.clone().addDays(1);
				if (!months[next.getMonth()]) { months[next.getMonth()] = []; }
				months[next.getMonth()].push(next);
				last = next;
			}
			return months;
		},

		addHzHeader: function (div, months, cellWidth) {
			var headerDiv = $("
", { "class": "ganttview-hzheader" });
			var monthsDiv = $("
", { "class": "ganttview-hzheader-months" });
			var daysDiv = $("
", { "class": "ganttview-hzheader-days" });
			for (var i = 0; i < 12; i++) {
				if (months[i]) {
					monthsDiv.append($("
", {
						"class": "ganttview-hzheader-month",
						"css": { "width": ((months[i].length * cellWidth) - 1) + "px" }
					}).append(Gantt.monthNames[i]));
					for (var j = 0; j < months[i].length; j++) {
						daysDiv.append($("
", { "class": "ganttview-hzheader-day" }).append(months[i][j].getDate()));
					}
				}
			}
			headerDiv.append(monthsDiv).append(daysDiv);
			div.append(headerDiv);
		},

		addVtHeader: function (div, data) {
			var headerDiv = $("
", { "class": "ganttview-vtheader" });
			for (var i = 0; i < data.length; i++) {
				var itemDiv = $("
", { "class": "ganttview-vtheader-item" });
				itemDiv.append($("
", { "class": "ganttview-vtheader-item-name" }).append(data[i].name));
				var seriesDiv = $("
", { "class": "ganttview-vtheader-series" });
				for (var j = 0; j < data[i].series.length; j++) {
					seriesDiv.append($("
", { "class": "ganttview-vtheader-series-name" }).append(data[i].series[j].name));
				}
				itemDiv.append(seriesDiv);
				headerDiv.append(itemDiv)
			}
			div.append(headerDiv);
		},

		addGrid: function (div, data, months, cellWidth) {
			var gridDiv = $("
", { "class": "ganttview-grid" });
			var rowDiv = $("
", { "class": "ganttview-grid-row" });
			for (var i = 0; i < 12; i++) {
				if (months[i]) {
					for (var j = 0; j < months[i].length; j++) {
						rowDiv.append($("
", { "class": "ganttview-grid-row-cell " }));
					}
				}
			}
			rowDiv.css("width", ($("div.ganttview-grid-row-cell", rowDiv).length * cellWidth) + "px");
			for (var i = 0; i < data.length; i++) {
				for (var j = 0; j < data[i].series.length; j++) {
					gridDiv.append(rowDiv.clone());
				}
			}
			div.append(gridDiv);
		},

		addBlocks: function (div, data, cellWidth, start) {
			var rows = $("div.ganttview-grid div.ganttview-grid-row", div);
			var rowIdx = 0;
			for (var i = 0; i < data.length; i++) {
				for (var j = 0; j < data[i].series.length; j++) {
					var size = DateUtils.daysBetween(data[i].series[j].start, data[i].series[j].end);
					var offset = DateUtils.daysBetween(start, data[i].series[j].start);
					var blockDiv = $("
", {
						"class": "ganttview-block",
						"css": {
							"width": (size * cellWidth) + "px",
							"margin-left": (offset * cellWidth) + "px"
						}
					});
					$(rows[rowIdx]).append(blockDiv);
					rowIdx = rowIdx + 1;
				}
			}
		}

	};

})(jQuery);

var ArrayUtils = {
	contains: function (arr, obj) {
		var has = false;
		for (var i = 0; i < arr.length; i++) { if (arr[i] == obj) { has = true; } }
		return has;
	}
};

var DateUtils = {
	daysBetween: function (start, end) {
		var count = 0, date = start.clone();
		while (date.compareTo(end) == -1) { count = count + 1; date.addDays(1); }
		return count;
	}
};

/* SAMPLE GENERATED MARKUP

Feature 1

Planned

Actual

Feature 2

Planned

Actual

Jan

Feb

Mar

1

2

3

1

2

3

1

2

3

*/

/*

createTable: function (months) {
	var tbl = $("
", { "class": "ganttview" });
	var w = 200;
	for (var i = 0; i < months.length; i++) {
		if (months[i]) { w = w + months[i].length * 28; }
	}
	tbl.css("width", w + "px");
	return tbl;
},
addHeaderToTable: function (tbl, months) {
	var thead = $("

");
	var monthTr = $("

");
	var emptyHdr = " 	";
	monthTr.append(emptyHdr).append(emptyHdr);
	var dateTr = $("

");
	for (var i = 0; i < 12; i++) {
		if (months[i]) {
			monthTr.append("" + Gantt.monthNames[i] + "	");
			for (var j = 0; j < months[i].length; j++) {
				dateTr.append("" + months[i][j].getDate() + "	");
			}
		}
	}
	thead.append(monthTr).append(dateTr);
	tbl.append(thead);
},
addGridToTable: function (tbl, data, months) {

	var tbody = $("

");

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

		var tr = $("

");
		var itemTd = $("" + data[i].name + "	");
		tr.append(itemTd);

		var seriesTd = $("" + data[i].series[0].name + "	");
		tr.append(seriesTd);
		Gantt.addCellsToSeriesRow(tr, months);
		tbody.append(tr);

		for (var j = 1; j < data[i].series.length; j++) {
			tr = $("

");
			var seriesTd = $("" + data[i].series[j].name + "	");
			tr.append(seriesTd);
			Gantt.addCellsToSeriesRow(tr, months);
			tbody.append(tr);
		}
	}

	tbl.append(tbody);
},
addCellsToSeriesRow: function (tr, months) {
	for (var i = 0; i < 12; i++) {
		if (months[i]) {
			for (var j = 0; j < months[i].length; j++) {
				tr.append("	");
			}
		}
	}
}
*/<|endoftext|>


<commit_before>/*
* @Copyright (c) 2010 Aurélio Saraiva, Diego Plentz
* @Page http://github.com/plentz/jquery-maskmoney
* try at http://inoveideia.com.br/maskInputMoney/

* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/

/*
* @Version: 0.5
* @Release: 2010-10-19
*/
(function($) {
	$.fn.maskMoney = function(settings) {
		settings = $.extend({
			symbol:'US$',
			decimal:'.',
			precision:2,
			thousands:',',
			allowZero:false,
			allowNegative:false,
			showSymbol:false,
			symbolStay:false
		}, settings);

		return this.each(function() {
			var input = $(this);

			function keypressEvent(e) {
				e = e||window.event;
				var k = e.charCode||e.keyCode||e.which;
				if (k == undefined) return; //needed to handle an IE "special" event

				if (k==8) { // backspace key
					preventDefault(e);
					var x = input.val().substring(0,input.val().length-1);
					input.val(maskValue(x));
					return false;
				} else if (k==9) { // tab key
					return true;
				}
				if (k<48||k>57) {
					if (k==45) { // -(minus) key
						input.val(changeSign(input));
						return false;
					}
					if (k==43) { // +(plus) key
						input.val(input.val().replace('-',''));
						return false;
					} else	{
						preventDefault(e);
						return true;
					}
				} else if (input.val().length==input.attr('maxlength')) {
					return false;
				}

				var key = String.fromCharCode(k);
				preventDefault(e);
				input.val(maskValue(input.val()+key));
			}

			function focusEvent(e) {
				if (input.val()=='') {
					input.val(setSymbol(getDefaultMask()));
				} else {
					input.val(setSymbol(input.val()));
				}
                if (this.createTextRange) {
                    var textRange = this.createTextRange();
                    textRange.collapse(false); // set the cursor at the end of the input
                    textRange.select();
                }
			}

			function blurEvent(e) {
                if ($.browser.msie) {
                    keypressEvent(e);
                }

				if (input.val()==setSymbol(getDefaultMask())) {
					if(!settings.allowZero) input.val('');
				} else {
					if (!settings.symbolStay) input.val(input.val().replace(settings.symbol,''));
				}
			}

			function preventDefault(e) {
				if (e.preventDefault) { //standart browsers
					e.preventDefault();
				} else { // internet explorer
					e.returnValue = false
				}
			}

			function maskValue(v) {
				v = v.replace(settings.symbol,'');

				var strCheck = '0123456789';
				var len = v.length;
				var a = '', t = '', neg='';

				if(len!=0 && v.charAt(0)=='-'){
					v = v.replace('-','');
					if(settings.allowNegative){
						neg = '-';
					}
				}

				if (len==0) {
					t = '0.00';
				}

				for (var i = 0; i<len; i++) {
					if ((v.charAt(i)!='0') && (v.charAt(i)!=settings.decimal)) break;
                }

				for (; i<len; i++) {
					if (strCheck.indexOf(v.charAt(i))!=-1) a+= v.charAt(i);
				}

				var n = parseFloat(a);
				n = isNaN(n) ? 0 : n/Math.pow(10,settings.precision);
				t = n.toFixed(settings.precision);

                i = settings.precision == 0 ? 0 : 1;
				var p, d = (t=t.split('.'))[i].substr(0,settings.precision);
				for (p = (t=t[0]).length; (p-=3)>=1;) {
					t = t.substr(0,p)+settings.thousands+t.substr(p);
				}

				return (settings.precision>0)
                    ? setSymbol(neg+t+settings.decimal+d+Array((settings.precision+1)-d.length).join(0))
                    : setSymbol(neg+t);
			}

			function getDefaultMask() {
				var n = parseFloat('0')/Math.pow(10,settings.precision);
				return (n.toFixed(settings.precision)).replace(new RegExp('\\.','g'),settings.decimal);
			}

			function setSymbol(v) {
				if (settings.showSymbol) {
					return settings.symbol+v;
				}
				return v;
			}

			function changeSign(i){
				if (settings.allowNegative) {
					var vic = i.val();
					if (i.val()!='' && i.val().charAt(0)=='-'){
						return i.val().replace('-','');
					} else{
						return '-'+i.val();
					}
				} else {
					return i.val();
				}
			}

			input.bind('keypress',keypressEvent);
			input.bind('blur',blurEvent);
			input.bind('focus',focusEvent);

			input.one('unmaskMoney',function() {
				input.unbind('focus',focusEvent);
				input.unbind('blur',blurEvent);
				input.unbind('keypress',keypressEvent);

				if ($.browser.msie) {
                    this.onpaste= null;
				} else if ($.browser.mozilla) {
                    this.removeEventListener('input',blurEvent,false);
                }
			});
		});
	}

	$.fn.unmaskMoney=function() {
		return this.trigger('unmaskMoney');
	};
})(jQuery);<commit_msg>fixing typo (standart -> standard)<commit_after>/*
* @Copyright (c) 2010 Aurélio Saraiva, Diego Plentz
* @Page http://github.com/plentz/jquery-maskmoney
* try at http://inoveideia.com.br/maskInputMoney/

* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/

/*
* @Version: 0.5
* @Release: 2010-10-19
*/
(function($) {
	$.fn.maskMoney = function(settings) {
		settings = $.extend({
			symbol:'US$',
			decimal:'.',
			precision:2,
			thousands:',',
			allowZero:false,
			allowNegative:false,
			showSymbol:false,
			symbolStay:false
		}, settings);

		return this.each(function() {
			var input = $(this);

			function keypressEvent(e) {
				e = e||window.event;
				var k = e.charCode||e.keyCode||e.which;
				if (k == undefined) return; //needed to handle an IE "special" event

				if (k==8) { // backspace key
					preventDefault(e);
					var x = input.val().substring(0,input.val().length-1);
					input.val(maskValue(x));
					return false;
				} else if (k==9) { // tab key
					return true;
				}
				if (k<48||k>57) {
					if (k==45) { // -(minus) key
						input.val(changeSign(input));
						return false;
					}
					if (k==43) { // +(plus) key
						input.val(input.val().replace('-',''));
						return false;
					} else	{
						preventDefault(e);
						return true;
					}
				} else if (input.val().length==input.attr('maxlength')) {
					return false;
				}

				var key = String.fromCharCode(k);
				preventDefault(e);
				input.val(maskValue(input.val()+key));
			}

			function focusEvent(e) {
				if (input.val()=='') {
					input.val(setSymbol(getDefaultMask()));
				} else {
					input.val(setSymbol(input.val()));
				}
                if (this.createTextRange) {
                    var textRange = this.createTextRange();
                    textRange.collapse(false); // set the cursor at the end of the input
                    textRange.select();
                }
			}

			function blurEvent(e) {
                if ($.browser.msie) {
                    keypressEvent(e);
                }

				if (input.val()==setSymbol(getDefaultMask())) {
					if(!settings.allowZero) input.val('');
				} else {
					if (!settings.symbolStay) input.val(input.val().replace(settings.symbol,''));
				}
			}

			function preventDefault(e) {
				if (e.preventDefault) { //standard browsers
					e.preventDefault();
				} else { // internet explorer
					e.returnValue = false
				}
			}

			function maskValue(v) {
				v = v.replace(settings.symbol,'');

				var strCheck = '0123456789';
				var len = v.length;
				var a = '', t = '', neg='';

				if(len!=0 && v.charAt(0)=='-'){
					v = v.replace('-','');
					if(settings.allowNegative){
						neg = '-';
					}
				}

				if (len==0) {
					t = '0.00';
				}

				for (var i = 0; i<len; i++) {
					if ((v.charAt(i)!='0') && (v.charAt(i)!=settings.decimal)) break;
                }

				for (; i<len; i++) {
					if (strCheck.indexOf(v.charAt(i))!=-1) a+= v.charAt(i);
				}

				var n = parseFloat(a);
				n = isNaN(n) ? 0 : n/Math.pow(10,settings.precision);
				t = n.toFixed(settings.precision);

                i = settings.precision == 0 ? 0 : 1;
				var p, d = (t=t.split('.'))[i].substr(0,settings.precision);
				for (p = (t=t[0]).length; (p-=3)>=1;) {
					t = t.substr(0,p)+settings.thousands+t.substr(p);
				}

				return (settings.precision>0)
                    ? setSymbol(neg+t+settings.decimal+d+Array((settings.precision+1)-d.length).join(0))
                    : setSymbol(neg+t);
			}

			function getDefaultMask() {
				var n = parseFloat('0')/Math.pow(10,settings.precision);
				return (n.toFixed(settings.precision)).replace(new RegExp('\\.','g'),settings.decimal);
			}

			function setSymbol(v) {
				if (settings.showSymbol) {
					return settings.symbol+v;
				}
				return v;
			}

			function changeSign(i){
				if (settings.allowNegative) {
					var vic = i.val();
					if (i.val()!='' && i.val().charAt(0)=='-'){
						return i.val().replace('-','');
					} else{
						return '-'+i.val();
					}
				} else {
					return i.val();
				}
			}

			input.bind('keypress',keypressEvent);
			input.bind('blur',blurEvent);
			input.bind('focus',focusEvent);

			input.one('unmaskMoney',function() {
				input.unbind('focus',focusEvent);
				input.unbind('blur',blurEvent);
				input.unbind('keypress',keypressEvent);

				if ($.browser.msie) {
                    this.onpaste= null;
				} else if ($.browser.mozilla) {
                    this.removeEventListener('input',blurEvent,false);
                }
			});
		});
	}

	$.fn.unmaskMoney=function() {
		return this.trigger('unmaskMoney');
	};
})(jQuery);<|endoftext|>