/*
 *
 * Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Version 1.0
 * Demo: http://www.texotela.co.uk/code/jquery/numeric/
 *
 * $LastChangedDate: 2007-05-29 11:31:36 +0100 (Tue, 29 May 2007) $
 * $Rev: 2005 $
 */
 
/*
 * Allows only valid characters to be entered into input boxes.
 * Note: does not validate that the final text is a valid number
 * (that could be done by another script, or server-side)
 *
 * @name     numeric
 * @param    decimal      Decimal separator (e.g. '.' or ',' - default is '.')
 * @param    negative     Indica si se permiten numeros negativos
 * @param    callback     A function that runs if the number is not valid (fires onblur)
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @mod      Manuel Morales 
 * 
 * @example  $(".numeric").numeric(); //sin separador
 * @example  $(".numeric").numeric(",");
 * @example  $(".numeric").numeric(",",true);
 * @example  $(".numeric").numeric(",",false);
 * @example  $(".numeric").numeric(null, true,callback);
 * @example  $(".numeric").numeric(null, callback);
 *
 */
jQuery.fn.numeric = function(decimal,negative, callback)
{
	decimal = decimal || "";// || ".";
	callback = typeof callback == "function" ? callback : function(){};
        negative = negative || false;
        
	this.keypress(
		function(e)
		{
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			// allow enter/return key (only when in an input box)
			if(key == 13 && this.nodeName.toLowerCase() == "input")
			{
				return true;
			}
			else if(key == 13)
			{
				return false;
			}
			var allow = false;
			// allow Ctrl+A
			if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
			// allow Ctrl+X (cut)
			if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
			// allow Ctrl+C (copy)
			if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
			// allow Ctrl+Z (undo)
			if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
			// allow or deny Ctrl+V (paste), Shift+Ins
			if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
			|| (e.shiftKey && key == 45)) return true;
			// if a number was not pressed
			if(key < 48 || key > 57)
			{
				/* '-' only allowed at start */
				if(key == 45 && this.value.length == 0 && negative) return true;
				/* only one decimal separator allowed */
				if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1)
				{
					allow = false;
				}
				// check for other keys that have special purposes
				if(
					key != 8 /* backspace */ &&
					key != 9 /* tab */ &&
					key != 13 /* enter */ &&
					key != 35 /* end */ &&
					key != 36 /* home */ &&
					key != 37 /* left */ &&
					key != 39 /* right */ &&
					key != 46 /* del */
				)
				{
					allow = false;
				}
				else
				{
					// for detecting special keys (listed above)
					// IE does not support 'charCode' and ignores them in keypress anyway
					if(typeof e.charCode != "undefined")
					{
						// special keys have 'keyCode' and 'which' the same (e.g. backspace)
						if(e.keyCode == e.which && e.which != 0)
						{
							allow = true;
						}
						// or keyCode != 0 and 'charCode'/'which' = 0
						else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0)
						{
							allow = true;
						}
					}
				}
				// if key pressed is the decimal and it is not already in the field
				if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1)
				{
					allow = true;
				}
			}
			else
			{
				allow = true;
			}
			return allow;
		}
	)
	.blur(
		function()
		{
			var val = jQuery(this).val();
			if(val != "")
			{
				var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");
				if(!re.exec(val))
				{
					callback.apply(this);
				}
			}
		}
	);
	return this;
}

	$.fn.alphanumeric = function(p) { 

		p = $.extend({
			//ichars: "!@#$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",
                        ichars: "!$%^&*()+=[]\\\';,/{}|\":<>?~`·",
			nchars: "",
			allow: ""
		  }, p);	

		return this.each
			(
				function() 
				{

					if (p.nocaps) p.nchars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
					if (p.allcaps) p.nchars += "abcdefghijklmnopqrstuvwxyz";
					
					s = p.allow.split('');
					for ( i=0;i<s.length;i++) if (p.ichars.indexOf(s[i]) != -1) s[i] = "\\" + s[i];
					p.allow = s.join('|');
					
					var reg = new RegExp(p.allow,'gi');
					var ch = p.ichars + p.nchars;
					ch = ch.replace(reg,'');

					$(this).keypress
						(
							function (e)
								{
									if (!e.charCode) k = String.fromCharCode(e.which);
										else k = String.fromCharCode(e.charCode);
										
									if (ch.indexOf(k) != -1) e.preventDefault();
									if (e.ctrlKey&&k=='v') e.preventDefault();
									
								}
								
						);
						
					$(this).bind('contextmenu',function () {return false});
									
				}
			);

	};
        
        
        
        $.fn.readonly = function(e) {
            $(this).keypress( function(e) {return false;} );
        };
        
        jQuery.fn.soloNumerosLetras = function(params) {

        if($(this).length!=1)
            return;
        
        var pressNotAllow = false; //para shift y ctrl    
        var pressSpecialChar = false;// acento
    
        jQuery(this).keydown(function(e){
  
            var key   = e.charCode || e.keyCode || 0;
            //alert(key);
            if(key == 16 || key == 17 || key == 18){
                pressNotAllow = true;
            }    
            if(pressNotAllow) {
                return false;
            } 
        
            if(key == 222 || key == 191 || key == 107 || key == 59 || key == 219|| key == 221){
                //alert(key);
                pressSpecialChar = true;
            }    
            if(pressSpecialChar) {
                return false;
            }     
        
            if ($(this).val().match(/[^a-zA-Z0-9 ]/g)) {
                    $(this).val( $(this).val().replace(/[^a-zA-Z0-9 ]/g, '') );
            }  
        
            return (!pressSpecialChar && !pressNotAllow && (65<=key && key<=90) || (48<=key && key<=57) || (96<=key && key<=105) || key==8 || key==9 || key==46)
    
        });
    
        jQuery(this).keyup(function(e){
                
            var key   = e.charCode || e.keyCode || 0;

            if(key != 16 && key != 17 && key != 18){
                pressNotAllow = false;
            }        

            if(key != 222 && key != 191 && key != 107 && key != 59 && key != 219&& key != 221 && pressSpecialChar){
                pressSpecialChar = false;
            } 
        
            if ($(this).val().match(/[^a-zA-Z0-9 ]/g)) {
                    $(this).val( $(this).val().replace(/[^a-zA-Z0-9 ]/g, '') );
            }        
            // return false;
        });
    };




(function($) {        
    jQuery.fn.numerosLetras = function(params) {
        var GOBAL_PARAMS="";
        params = jQuery.extend({
                    tipoMoneda:"CLP",
                    aceptaNegativo:false,
                    permitidos:"",
                    shiftPressed:false
        },params);
        GOBAL_PARAMS = params;
        
        jQuery(this).blur(function(){
            var allow1 = (jQuery(this).val()).split("");
            for(var i in allow1){
                    var allowChar1 = allow1[i].split("");
                    if(!(allowChar1[0].charCodeAt(0) >= 97 && allowChar1[0].charCodeAt(0) <= 122) &&
                       !(allowChar1[0].charCodeAt(0) >= 65 && allowChar1[0].charCodeAt(0) <= 90) &&
                       !(allowChar1[0].charCodeAt(0) >= 48 && allowChar1[0].charCodeAt(0) <= 57) &&
                       !(allowChar1[0].charCodeAt(0) >= 45 && allowChar1[0].charCodeAt(0) <= 46)){
                        alert("Solo se debe ingresar caracteres alfanumericos");
                        $(this).focus();
                        return false;
                    }       
            }
        });
        jQuery(this).keyup(function(e){
            
            if(e.keyCode==16 ||  e.keyCode==17){
                GOBAL_PARAMS.shiftPressed = false;    
            }
        });

        jQuery(this).keydown(function(e){
            var valor = jQuery.trim(jQuery(this).val());
            var allow = (GOBAL_PARAMS.permitidos).split("$");
            var key   = e.charCode || e.keyCode || 0;
            var char  = String.fromCharCode(e.keyCode);
            var count = 0;
            char = char=="¼"?",":char;
            char = char=="¾"?".":char;
            char = char=="m"?"-":char;
            
            //alert(e.keyCode);
            
            if(e.keyCode==16 ||  e.keyCode==17){
                GOBAL_PARAMS.shiftPressed = true;    
            }

                
            var isAllow = false;            
            if(allow.length>0){
                for(var i in allow){
                    var allowChar = allow[i].split("");
                    if(allowChar.length==2){
                        count=0;
                        for(var x=0 ; x<valor.length;x++){
                            if(valor.charAt(x).toUpperCase()==allowChar[1].toUpperCase())
                                count++;
                        }
                    }
                    if(allowChar[1]==char && count<allowChar[0]){
                        isAllow = true;
                        break;
                    }
                } 
            }

            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return ( 
                !(GOBAL_PARAMS.shiftPressed && key != 86) && (
                isAllow ||
                key == 8 || 
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 65 && key <= 90) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105)
                )
                );            

        });
        
    }
})(jQuery);


