// functions just like Rails helper
var Helpers = {
  number_to_currency: function (num, opts) {
    if (!isDefined(opts)) {
      opts = {};
    }

    if (opts.precision === null) {
      opts.precision = 0;
    }

    // remove any other formatting
    str = ('' + num).replace(/[^0-9\.]/g, '');

    // remove decimals for now
    arr = str.split('.');
    str = arr[0];
    decimals = arr[1];

    // apply precision
    if (decimals && opts.precision > 0) {
      if (decimals.length >= opts.precision) {
        str += '.' + decimals.substr(0, opts.precision);
      }
      else {
        str += '.' + decimals;
        for (var i = 0; i < opts.precision - decimals.length; i++) {
          str += '0';
        }
      }
    }

    return '$' + Helpers.number_with_delimiter(str);
  },

  number_with_delimiter: function (num, delim) {
    if (!isDefined(delim)) {
      delim = ',';
    }

    arr = ('' + num).split('.');
    str = arr[0];
    decimals = arr[1];

    index = str.length % 3;
    if (index === 0) {
      index = 3;
    }
    out = str.substr(0, index);
    while (index + 3 <= str.length) {
      out += delim + str.substr(index, 3);
      index += 3;
    }

    if (decimals) {
      out += '.' + decimals;
    }

    return out;
  },

  strip_number_formatting: function (str) {
    return parseInt(('' + str).replace(/[^0-9\.]/g, ''), 10);
  }
};

$(document).ready(function () {
  // All inputs with class 'clear_on_focus' should be cleared when clicked 
  // and should revert if blurred and still blank.
  $('input.clear_on_focus').livequery('focus', function () {
    t = $(this);
    t.attr('clear_restore', t.val());
    t.val('');
  });

  $('input.clear_on_focus').livequery('blur', function () {
    t = $(this);
    if ((t.val() == '') && (a = t.attr('clear_restore'))) {
      t.val(a);
    }
    t.attr('clear_restore', null);
  });

  // All inputs with class 'price' should automatically format its value
  // on blur.
  $('input.price').livequery('blur', function () {
    $(this).val(Helpers.number_to_currency($(this).val()));
  });
});
