// Javascript modules
var IdeupMath = {
  /**
   * Sums fields automatically and shows total in another field
   */
  observeAndSum: function(fieldsSelector, totalFieldSelector) {
    // Initialize total
    if($(totalFieldSelector).html() == '') {
      IdeupMath.sumUp(fieldsSelector, totalFieldSelector);
    }
    // Set observer
    $(fieldsSelector).change(function() {
      IdeupMath.sumUp(fieldsSelector, totalFieldSelector);
    });
  },
  /**
   * Sums fields and shows total in another field
   */
  sumUp: function(fieldsSelector, totalFieldSelector) {
    var total = 0;
    $(fieldsSelector).each(function(index, element) {
      // 2,456.77 --> 2456.77   2,456 --> 2456
      if (/\d+,\d{3}\.\d{2,3}$/.test(element.value) || /\d+,\d{3}$/.test(element.value)) {
        element.value = element.value.replace(',', '');
      }

      // 2.456,77 --> 2456.77
      if (/\d+\.\d{3},\d{2,3}$/.test(element.value)) {
        element.value = element.value.replace('.', '');
        element.value = element.value.replace(',', '.');
      }

      if(!isNaN(element.value)) {
        total += Number(element.value);
      } 
    });
    total =  IdeupMath.numberFormat(total, {});
    $(totalFieldSelector).html(total);
  },

  /**
   * Da formato especificado a cadena numerica (por defecto, notacion española)
   *
   * Salio de: http://plugins.jquery.com/project/currencynumberformatter
   */
  numberFormat: function(numero, params)
  {
    //parametros default
    var sDefaults =
    {
      numberOfDecimals: 2,
      decimalSeparator: ',',
      thousandSeparator: '.',
      symbol: ''
    }

    //Sustituye parametros por defecto por los que lleguen
    var options = jQuery.extend(sDefaults, params);

    //Mojo
    var number = numero;
    var decimals = options.numberOfDecimals;
    var dec_point = options.decimalSeparator;
    var thousands_sep = options.thousandSeparator;
    var currencySymbol = options.symbol;

    var exponent = "";
    var numberstr = number.toString ();
    var eindex = numberstr.indexOf ("e");
    if (eindex > -1)
    {
      exponent = numberstr.substring (eindex);
      number = parseFloat (numberstr.substring (0, eindex));
    }

    if (decimals != null)
    {
      var temp = Math.pow (10, decimals);
      number = Math.round (number * temp) / temp;
    }
    var sign = number < 0 ? "-" : "";
    var integer = (number > 0 ?
      Math.floor (number) : Math.abs (Math.ceil (number))).toString ();

    var fractional = number.toString ().substring (integer.length + sign.length);
    dec_point = dec_point != null ? dec_point : ".";
    fractional = decimals != null && decimals > 0 || fractional.length > 1 ?
    (dec_point + fractional.substring (1)) : "";
    if (decimals != null && decimals > 0)
    {
      for (i = fractional.length - 1, z = decimals; i < z; ++i)
        fractional += "0";
    }

    thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ?
    thousands_sep : null;
    if (thousands_sep != null && thousands_sep != "")
    {
      for (i = integer.length - 3; i > 0; i -= 3)
        integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
    }

    if (options.symbol == '')
    {
      return sign + integer + fractional + exponent;
    }
    else
    {
      return currencySymbol + ' ' + sign + integer + fractional + exponent;
    }
  }
}

