/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Mario Costa |  */
function formataMoeda(fld, e) {
  var milSep = '.';
  var decSep = ',';
  var sep = 0;
  var key = '';
  var i = j = 0;
  var len = len2 = 0;
  var strCheck = '0123456789';
  var aux = aux2 = '';
  var whichCode = (window.Event) ? e.which : e.keyCode;

  if (whichCode == 13) return true;  // Enter
  if (whichCode == 8) return true;  // Delete
  key = String.fromCharCode(whichCode);  // Get key value from key code
  if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
  len = fld.value.length;
  for(i = 0; i < len; i++)
  if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
  aux = '';
  for(; i < len; i++)
  if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
  aux += key;
  len = aux.length;
  if (len == 0) fld.value = '';
  if (len == 1) fld.value = '0'+ decSep + '0' + aux;
  if (len == 2) fld.value = '0'+ decSep + aux;
  if (len > 2) {
    aux2 = '';
    for (j = 0, i = len - 3; i >= 0; i--) {
      if (j == 3) {
        aux2 += milSep;
        j = 0;
      }
      aux2 += aux.charAt(i);
      j++;
    }
    fld.value = '';
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
    fld.value += aux2.charAt(i);
    fld.value += decSep + aux.substr(len - 2, len);
  }
  return false;
}

function toMoney(fld) {
	if(typeof(fld) == 'undefined') return('0,00');
	var vl = new Array();
	var cents = '00';
	
	
	fld = fld.toString();
	
	if(fld.indexOf(".") > -1)
	{
		vl = fld.split(".");
		if(vl[1].length != 2)
		{
			if(vl[1].length > 2) 
			{
				cents = vl[1].substring(0,2);
			}
			else 
			{
				if(vl[1].length == 0)
					cents = vl[1] + '00';
				else
					cents = vl[1] + '0';
			}
		}
		else
		{
			cents = vl[1];
		}
		var valBru = vl[0] + "." + cents;
	}
	else
	{
		valBru = fld + ".00";
	}
	
	
	//fld = fld.toString();
	//var valBru = fld;

	valBru = valBru.replace(',', '');
	valBru = valBru.replace('.', '');
	var qtd = String(valBru).length;
	var valCont = String(valBru).length - 2;
	var resto = valCont%3;
	var result = Math.floor((valCont)/3);
	var valFin = String(valBru);
	var voltas = 1;
	if (resto==0){result=result-1;}
	if (result<0)
	{
		if(qtd==1){
			valFin = valFin+",00";
		}
		else if(qtd==2)
		{
			valFin = valFin.substring(0,1)+","+valFin.substring(1,2)+"0";
		}
		else
		{
			valFin = "0,00";
		}
	}
  
	for (var i=0; i<=result; i++)
	{
		if(i==result)
		{
			if (qtd==5){
				resto=3;
			}  
			valFin = valFin.substring(0,resto)+","+valFin.substring(resto,qtd+voltas);
		}
		else
		{
			if (resto==0){
				resto=3;
			}
			valFin = valFin.substring(0,resto)+"."+valFin.substring(resto,qtd+voltas);          
		}
		voltas++;
		resto = resto+4;  
	}
	return valFin;
}


