/*!
 * jQuery Plugin for making masks in their text entries in forms
 * http://plugins.jquery.com/project/jmask
 *
 * Copyright 2010, Pablo Diego - pablodc@gmail.com
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Date: Wed Feb 03 23:37:55 2010 -0300
 */

jQuery.JMask = function(identify, mask) {

	var element = $(identify);

	element.keypress(function(e) {

		var code = e.keyCode||e.which;
		var value = $(this).val();
		var begin = value.length;
		var end = begin + 1;
		var maskpart = mask.substring(begin, end);
		var nextmaskpart = mask.substring((begin+1), (end+1));
		var keychar = String.fromCharCode(code);

		if(e.shiftKey || e.ctrlKey || e.metaKey || code == 8 || code == 9 || code == 13 ||  code == 37 ||  code == 38 ||  code == 39 ||  code == 40 || code == 46) {
			return true;
		}

		if(begin < mask.length) {

			if(maskpart == 9) {

				return /[0-9]+/.test(keychar);

			}else if(maskpart == '@') {

				return /[A-Za-z]+/.test(keychar);

			}else if(maskpart == '#') {

				return /[A-Za-z0-9]+/.test(keychar);

			}else{

				if(nextmaskpart == 9) {
					if(/[0-9]+/.test(keychar)) {
						$(this).val(value + maskpart + keychar).focus();
					}
					return false;
				}else if(nextmaskpart == '@') {
					if(/[A-Za-z]+/.test(keychar)) {
						$(this).val(value + maskpart + keychar).focus();
					}
					return false;
				}else if(nextmaskpart == '#') {
					if(/[A-Za-z0-9]+/.test(keychar)) {
						$(this).val(value + maskpart + keychar).focus();
					}
					return false;
				}else{
					$(this).val(value + maskpart + nextmaskpart + keychar).focus();
					return false;
				}

			}

		}else{

			return false;

		}

	});

}
