/*
@ Mask plugin for jQuery 1.2.1
@ 
@ author: Alexandre Quinto (kintobr[at]gmail.com)
@
@ how to use:
@ $('.object').masked('maskType');
@ mask types: 'currency'
*/

$.fn.masked = function(type){
	this.each(function(){
		new $.masked($(this), type);
	});
}

$.masked = function(obj, type){
	var ref = this;
	this.obj = obj;
	this.type = type;

	if (this.type == 'currency') this.obj.val('0,00');

	if ($.browser.mozilla) {
		this.obj.keypress(function(key){
			if (ref.type == 'currency') {
				key.charCode >= 48 && key.charCode <= 57 ? ref.currency(ref.obj, key) : ref.notChar(ref.obj, key);
			}
			if (ref.type == 'numeric') {
				if (key.charCode >= 48 && key.charCode <= 57) {
					return true;
				} else {
					return false;
				}
			}
		});
	}
	if ($.browser.msie) {
		this.obj.keydown(function(key){
			if (ref.type == 'currency') {
				(key.keyCode >= 96 && key.keyCode <= 105) || (key.keyCode >= 48 && key.keyCode <= 57) ? ref.currency(ref.obj, key) : ref.notChar(ref.obj, key);
			}
			if (ref.type == 'numeric') {
				if ((key.keyCode >= 96 && key.keyCode <= 105) || (key.keyCode >= 48 && key.keyCode <= 57)){
					return true;
				} else {
					return false;
				}
			}
		});
	}
}

$.masked.prototype = {
	currency: function(obj, key){
		var currentValue = obj.val();
		if (currentValue.indexOf('0,00') == 0) {
			return obj.val('0,0');
		} else {
			if (currentValue.indexOf('0,0') == 0) {
				return obj.val('0,' + currentValue.substr(currentValue.length - 1));
			} else {
				if (currentValue.indexOf('0,') == 0) {
					return obj.val(currentValue.substr(currentValue.length - 2, currentValue.length - 3) + ',' + currentValue.substr(currentValue.length - 1));
				} else {
					var valorAux = '';
					j=1;
					for (i = currentValue.replace(',','','gi').replace(/\./gi,'').length - 1; i >= 0; i--){
						if(j==2)
							valorAux = ',' + valorAux;
						if(j==5 || j==8 || j==11)
							valorAux = '.' + valorAux;
						j++
						valorAux = currentValue.replace(',','','gi').replace(/\./gi,'').charAt(i) + valorAux;
					}
					return obj.val(valorAux);
					//return obj.val(currentValue.replace(',','','gi').substr(0, currentValue.length - 2) + ',' + currentValue.substr(currentValue.length - 1));
				}
			}
		}
	},
	notChar: function(obj, key){
		var currentValue = obj.val();
		if(key.keyCode == 8){
			del = currentValue.replace(',','','gi').substr(0, currentValue.length - 4) + ',' + currentValue.replace(',','','gi').substr(currentValue.length - 4);
			if(del.indexOf(',') == 0){
				del = '0' + del;
			}
			return obj.val(del);
		}
	}
}
