MaskInput = function(f, m){
	function mask(e){
		var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[\xC0-\xFF]/i, "8": /./ },
			rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
		function accept(c, rule){
			for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
				if(r & i && patterns[i].test(c))
					break;
				return i <= r || c == rule;
		}
		var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
		(!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
			r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
			: (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
			r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
	}
	for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
		addEvent(f, i, mask);
};

addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

function remote_sum(elements){
  var size = elements.size();
  var count = 0;                   
  var parameters_str = elements.inject('', function(txt, element){
    if(!txt.empty){
      txt = txt + '&'
    }
    txt = txt + 'element' + count + '=' + element;                                          
    count++;
    return txt;
  });
  parameters_str = parameters_str + '&size=' + size;
  var result = 0;
  new Ajax.Request('/financeiro/lancamento_notas_entrada/remote_sum', {asynchronous:false, parameters:parameters_str, evalScripts:true, onComplete:function(request){result = eval('(' + request.responseText + ')')}});
  return result;
}


function function_soma(targets, show_field, after_function){
  var soma = 0;
  var vetor_itens = $$('[' + targets + ']');
  var vetor_soma = vetor_itens.collect(function(item){
      return parseFloat(item.value.gsub('[.]','').gsub(',','.'))
    });
  soma = remote_sum(vetor_soma);
  if (show_field==null) {
    return soma;
  } else {                              
      if (isNaN(soma)) {
        $(show_field).value = "Algum valor inválido";
      } else {
        $(show_field).value = 'R$ ' + soma;
      }
  }

  if (after_function != null){
    after_function(soma);
  }

}

function display_valid(id, value) {
  if (value) {
    $(id + '_true').show()
    $(id + '_false').hide()
  }else {
    $(id + '_true').hide()
    $(id + '_false').show()
  }
}


// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

//Funcoes para a utilizacao do jscalendar http://www.dynarch.com/demos/jscalendar/ 
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked) //&& (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
    cal.callCloseHandler();
}

function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}

function showCalendar(id, format, showsTime) {
  var el = document.getElementById(id); 
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = true;
    }
    
    cal.showsOtherMonths = true;
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  //_dynarch_popupCalendar.showAtElement(el,"BR");        // show the calendar
  _dynarch_popupCalendar.showAtElement(document.getElementById("button_"+id),"t");        // show the calendar

  return false;
}
