var CooperativaMask = new Class({
	
	initialize: function() {
		this.keypress = this.keypress.bind(this);
		this.keyup = this.keyup.bind(this);
		this.focus = this.focus.bind(this);
		this.bluer = this.blur.bind(this);
	},

    isValid: function(value) {
        return value.isNumeric()
        	&& value.length <= 4
        	&& value.toInt() != 0;
    },
    
    mask: function(value) {
    	value = value.onlyNumeric();
    	return value.length > 4 ? value.substr(0 , 4) : value;
    },    

    keypress: function(event) {
        var key = event.key;
        var value = event.target.value;
        if (key.isNumeric() || Event.Keys.has(key)) {
            return true;
        } else {
           event.stop();
           return false;
        }
    },

    keyup: function(event) {
        if (!this.isValid(event.target.value)) {
            event.target.value = this.mask(event.target.value);
        }
    	return true;
    },

    focus: function(event) {
    	event.target.maxLength = 4;
    	event.target.select();
    },

    blur: function(event) {
    	var value = this.mask(event.target.value);
    	var len = event.target.maxLength;
        if (this.isValid(event.target.value)) {
        	event.target.value = value.leftPad(len, '0');
        } else {
        	event.target.value = "";
        }
    	return true;
    }
    
});