function formatMoney(value, revert) {
  if (value == '') {
    return '0';
  }

  re = /\s/gi;
  if (revert) {
    return value.replace(re, '');
  }

  value = value.replace(re, '');
  var returnvalue = '';
  var counter = 0;
  for(i=value.length-1; i>=0; i--) {
    returnvalue = value.charAt(i) + returnvalue;
    counter++;
    if (counter == 3) {
      returnvalue = ' ' + returnvalue;
      counter = 0;
    }
  }
  return returnvalue;
}

function focusNextDateControl(e, control) {
  var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
  if (((key >= 48) && (key <= 57)) || ((key >= 96) && (key <= 105))) {
     if ($(control).attr("maxlength") == $(control).val().length) {
      var nameparts = $(control).attr("id").split('_');
      if (nameparts[nameparts.length-1] == "year") {
        nameparts[nameparts.length-1] = "month";
      } else {
        nameparts[nameparts.length-1] = "day";
      }
      var nextcontrolname = nameparts.join('_');
      $("#" + nextcontrolname).select();
      $("#" + nextcontrolname).focus();
    }
  }
}

function checkIntegerMinMax(value, min, max) {
  var intvalue = parseInt(value, 10);
  if (isNaN(intvalue)) {
    intvalue = 0;
  }

  if (intvalue < min) {
    return min;
  } else if (intvalue > max) {
    return max;
  } else {
    return intvalue;
  }
}

$(document).ready(function(){
  $("#l_username").focus();

  $("input.integerinput").numeric();

  $("input.moneyinput").blur(function(e) {
    $(this).val(formatMoney($(this).val(), false));
  });
  $("input.moneyinput").focus(function(e) {
    $(this).val(formatMoney($(this).val(), true));
  });

  $("input.datetimepicker_yearpart").keyup(function(e) {
    focusNextDateControl(e, this)
  });
  $("input.datetimepicker_monthpart").keyup(function(e) {
    focusNextDateControl(e, this)
  });
  $("input.datetimepicker_yearpart").blur(function(e) {
    $(this).val(checkIntegerMinMax($(this).val(), 1900, 3000));
  });
  $("input.datetimepicker_monthpart").blur(function(e) {
    $(this).val(checkIntegerMinMax($(this).val(), 1, 12));
  });
  $("input.datetimepicker_daypart").blur(function(e) {
    $(this).val(checkIntegerMinMax($(this).val(), 1, 31));
  });

  $("input.moneyinput").each(function(i){
    this.value = formatMoney(this.value);
  });

  $("form").submit(function(){
    $("input.moneyinput").each(function(i){
      this.value = formatMoney(this.value, true);
    });
  });
});
