/*
 * Copyright (c) 2009 C. F., Wong (<a href="http://cloudgen.w0ng.hk">Cloudgen Examplet Store</a>)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * See details in: <a href="http://cloudgen.w0ng.hk/javascript/javascript.php">Javascript Examplet</a>
 *
 * version 1.02
 * fix the problem when precision has been set and the input start with decimal dot or comma ,e.g. precision set to 3 and input with ".1234"
 *
 * @ VERSIONE 1.1 MODIFICATA DA FILIPPO BRAZZO
 * Se un numero ha decimali allora accetto anche i caratteri ., poi la formatN sistsema il valore
 * 
 */
var email={tldn:new RegExp("^[^\@]+\@[^\@]+\.(A[C-GL-OQ-UWXZ]|B[ABD-JM-OR-TVWYZ]|C[ACDF-IK-ORUVX-Z]|D[EJKMOZ]|E[CEGR-U]|F[I-KMOR]|G[ABD-IL-NP-UWY]|H[KMNRTU]|I[DEL-OQ-T]|J[EMOP]|K[EG-IMNPRWYZ]|L[A-CIKR-VY]|M[AC-EGHK-Z]|N[ACE-GILOPRUZ]|OM|P[AE-HKL-NR-TWY]|QA|R[EOSUW]|S[A-EG-ORT-VYZ]|T[CDF-HJ-PRTVWZ]|U[AGKMSYZ]|V[ACEGINU]|W[FS]|XN|Y[ETU]|Z[AMW]|AERO|ARPA|ASIA|BIZ|CAT|COM|COOP|EDU|GOV|INFO|INT|JOBS|MIL|MOBI|MUSEUM|NAME|NET|ORG|PRO|TEL|TRAVEL)$","i")};
var data={tldn:new RegExp("(0[1-9]|[12][0-9|3[01]+)/(0[1-9]|1[012]+)/(19|20|)\d\d","i")};
(function($){
	$.extend($.expr[":"],{
		regex:function(d,a,c){
			var e=new RegExp(c[3],"g");
			var b=("text"===d.type)?d.value:d.innerHTML;
			return(b=="")?true:(e.exec(b))
		}
	});
	$.fn.output=function(d){
		return(this.is(":text"))?this.val(d):this.html(d)
	};
	formatter={
		getRegex:function(settings){
			var settings    = $.extend({type:"decimal",precision:5,decimal:'.',allow_negative:true,extra:"none"},settings);
			var result      = "";
            var tipo        = settings.type.toUpperCase();
            switch (tipo){
                case 'DATE':
                    result ="^\\d{2}[-\\./]\\d{2}[-\\./]\\d{4}$";
                break;

                case 'DECIMAL':
                    var e=(settings.allow_negative)?"-?":"";
                    if(settings.precision>0)
                    //    result="^"+e+"\\d+$|^"+e+"\\d*"+settings.decimal+"\\d{1,"+settings.precision+"}$";
                        result="^"+e+"\\d+$|^"+e+"\\d*[\\.\\,]\\d{1,"+settings.precision+"}$";
                    else
                        result="^"+e+"\\d+$";
                break;

                case 'PHONE-NUMBER':
                    result="^\\d[\\d\\-]*\\d$";
                break;

                case 'ALPHABET':
                    result="^[A-Za-z]+$";
                break;
            }
	    	return result
		},
		isEmail:function(d){
			var a=$(d).output();
			var c=false;
			var e=true;
			var e=new RegExp("[\s\~\!\#\$\%\^\&\*\+\=\(\)\[\]\{\}\<\>\\\/\;\:\,\?\|]+");
			if(a.match(e)!=null)    return c
			if(a.match(/((\.\.)|(\.\-)|(\.\@)|(\-\.)|(\-\-)|(\-\@)|(\@\.)|(\@\-)|(\@\@))+/)!=null) return c
			if(a.indexOf("\'")!=-1)	return c
			if(a.indexOf("\"")!=-1)	return c
			if(email.tldn&&a.match(email.tldn)==null)   return c
			return e
		},
        isURL:function(d){
            var a=$(d).output();
            var c=false;
            var e=true;
            var e=new RegExp("[\<\>\ \'\!\,\$\;\@\=\à\á\â\ã\ä\å\è\é\ê\ë\ì\í\î\ï\ò\ð\ó\ô\õ\ö\ù\ú\û\ü\ñ\ý\ÿ\|\?\_]+");
            if(a.match(e)!=null)    return c
            if(a.indexOf("\'")!=-1) return c
            if(a.indexOf("\"")!=-1) return c
            return e
        },
		formatString:function(target,settings){
			var settings    = $.extend({type:"decimal",precision:5,decimal:'.',allow_negative:true,extra:"none"},settings);
			var oldText     = $(target).output();
			var newText     = oldText;
            var tipo_input  = target.name.substr(0,1);
            if(String(tipo_input) == "D")  settings.type="date";
            var tipo        = settings.type.toUpperCase();
            switch (tipo){
                case 'DECIMAL':
                    if(newText!=""){
                        var g;
                        var h=(settings.allow_negative)?"\\-":"";
                        // var i="\\"+settings.decimal;
                        var i="\\.\\,";
                            g=new RegExp("[^\\d"+h+i+"]+","g");
                        newText=newText.replace(g,"");

                        var h=(settings.allow_negative)?"\\-?":"";
                        if(settings.precision>0)
                            g=new RegExp("^("+h+"\\d*"+i+"\\d{1,"+settings.precision+"}).*");
                        else
                            g=new RegExp("^("+h+"\\d+).*");
                        newText=newText.replace(g,"$1")
                    }
                break;

                case 'DATE':
                    newText=newText.replace(/[^\-\d\/\.\:]+/g,"");
                break;

                case 'PHONE-NUMBER':
                    newText=newText.replace(/[^\-\d]+/g,"").replace(/^\-+/,"").replace(/\-+/,"-");
                break;

                case 'ALPHABET':
                    newText=newText.replace(/[^A-Za-z]+/g,"");
                break;
            }
			if(newText!=oldText)
				$(target).output(newText);
		}
	};
	$.fn.format=function(settings,wrongFormatHandler){
        /*
            CANC = 46, / = 47,   : = 58,  \ = 124,  ~ = 126,  SPACE = 32,  - = 45
            BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,
            ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,
            NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,
            RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38
        */
        var range="", retVal="", nrDec=0, fFormat="", sepT=':', sepMigl = "N", idx = "";
		var settings        = $.extend({type:"decimal",precision:5,decimal:".",allow_negative:true,autofix:false,extra:"none"},settings);
		var decimal         = settings.decimal;
		wrongFormatHandler  = typeof wrongFormatHandler=="function"?wrongFormatHandler:function(){};
		this.keypress(function(d){
			$(this).data("old-value",$(this).val());
	        var a=d.charCode?d.charCode:d.keyCode?d.keyCode:0;
			if(a==13&&this.nodeName.toLowerCase()!="input"){return false}
			if(d.ctrlKey&&(a==97||a==65||a==120||a==88||a==99||a==67||a==122||a==90||a==118||a==86||a==45))
				return true;

       //     alert(a);
            // Aggiunto controllo per non bloccare il tasto CANC = 46
            var tipo_input  = this.name.substr(0,1);
            var tipo        = settings.type.toUpperCase();
            if(a==46&&tipo!="DECIMAL"||a==8||a==9)  return true;
			if(a<48||a>57){
                switch (tipo){
                    case 'DECIMAL':
                        if(settings.allow_negative&&a==45&&this.value.length==0) return true;
//                        if(a==decimal.charCodeAt(0)){
                        if(a==44||a==46&&String(tipo_input) != "D"){
                            if(settings.precision>0&&this.value.indexOf(decimal)==-1) return true
                            else return false;
                        }
                        if(String(tipo_input) == "D"){
                            settings.type="date";
                            if(a==47||a==32||a==45||a==46)  return true;
                        }
                        if(a!=13&&a!=35&&a!=36&&a!=37&&a!=39) return false;
                        return true;
                    break;

                    case 'EMAIL':
                        if(a==13||(a>34&&a<38)||a==39||a==45||(a>64&&a<91)||(a>96&&a<123)) return true;
                        if(a==64&&this.value.indexOf("@")==-1) return true;
                        return false;
                    break;

                    case 'URL':
                        if(a==13||(a>34&&a<38)||a==39||a==45||a==47||a==58||a==126||(a>64&&a<91)||(a>96&&a<123)) return true;
                        return false;
                    break;

                    case 'PHONE-NUMBER':
                        if(a==45&&this.value.length==0) return false;
                        if(a==13||(a>34&&a<38)||a==39||a==45) return true;
                        return false;
                    break;

                    case 'ALPHABET':
                        if(a==13||(a>34&&a<38)||a==39||(a>64&&a<91)||(a>96&&a<123)) return true;
                    break;

                    case 'ALFA':
                        if(a<48||a<65||(a>90&&a<97)||a>122&&a!=45) return false;
                        return true;
                    break;

                    default:
                        if(a==96) return false;
                        return true;
                    break;
                }
            }else{
                switch (tipo){
                    case 'ALPHABET':
                        return false;
                    break;

                    default:
                        return true;
                    break;
                }
            }
		})
		.blur(function(){
            var tipo_input  = this.name.substr(0,1); 
            if(String(tipo_input) == "D")  settings.type="date";
            var tipo        = String(settings.type).toUpperCase();
            switch (tipo){
                case 'URL':
                    retVal  =   SistemaURL(this.value);
                    if(!formatter.isURL(this)){
                        wrongFormatHandler.apply(this);
                    }
                break;

                case 'EMAIL':
                    if(!formatter.isEmail(this)){
                        wrongFormatHandler.apply(this);
                    }
                    if(this.value.length>0)
                        retVal = isEmail(this);
                break;

//                 case 'DATE':
//                 break;

                case 'DECIMAL':
                case 'PHONE-NUMBER':
                case 'ALPHABET':
                    if(!$(this).is(":regex("+formatter.getRegex(settings)+")")){
                        wrongFormatHandler.apply(this);
                    }
                break;

                default:
                break;
            }
            // Extra controlli
            var sParametri  = settings.extra.split(/\s|,/);
            //  Interpretazione parametri di formattazione
            for(var ii=0; ii<sParametri.length; ii++){
                var sData       =   sParametri[ii].split(/=/);
                var sParametro  =   sData[0].toUpperCase();
                if (sData.length == 1) sData[1] = "";
                switch (sParametro){
                    case 'UPPER':
                    case 'UPP':
                        this.value  = this.value.toUpperCase();
                    break;

                    case 'LOWER':
                    case 'LOW':
                        this.value  = this.value.toLowerCase();
                    break;

                    case 'CODFISC':
                    case 'CF':
                        fFormat = 'CF';
                    break;

                    case 'PARTIVA':
                    case 'PIVA':
                        fFormat = 'PI';
                    break;

                    case 'VALUTA':
                    case 'VAL':
                        nrDec=2;
                        sepMigl = "S";
                    break;

                    case 'DATEMON':
                        fFormat = 'DM';
                    break;

                    case 'DATESHORT':
                        fFormat = 'DS';
                    break;

                    case 'MY':
                        fFormat = 'MY';
                    break;

                    case 'TIME':
                        fFormat = 'T';
                        if (sData[1] != '') sepT=sData[1];
                    break;

                    case 'DATETIME':
                        fFormat = 'H24';
                    break;

                    case 'NRDEC':
                        nrDec       = sData[1];
                    break;

                    case 'RANGE':
                        fFormat     = "RG";
                        range       = sData[1];
                    break;
                }
            }
            retVal = this.value;
  
/*
            switch(tipo_input){
                case 'N':
                    retVal = formatN(this.value, parseInt(settings.precision), sepMigl);
                break;

                case 'D':
                    retVal = formatD(this.value, fFormat);
                break;

                case 'C':
                    switch(fFormat){
                        case 'CF':
                            retVal  =   ctrlCodFisc(this.value.toUpperCase());
                        break;

                        case 'PI':
                            retVal  =   ctrlPartIVA(this.value.toUpperCase());
                        break;

                        case 'T':
                            retVal  =   formatH(this.value,sepT);
                        break;

                        case 'MY':
                            retVal  =   formatD(this.value,'MY');
                        break;
                    }
                break;
            }

            if(fFormat == "RG"){
                retVal = chkRange(this.name.substr(0,1), this.value, range, idx);
            }

            if(retVal == 'ERR')
                this.value="";
            else{
                if(retVal != "")
                    this.value = retVal;
            }

            // chiamata dopo la formattazione. se non è presente nella pagina interessata, non fa nulla.
            try{
                eval('v_lookup'+this.name.toUpperCase()+'(this)');
            }catch(e){};*/

		})
        .change(function(){
            // onchange faccio onblur
         //   $(this).blur();
        })
		.focus(function(){
			$(this).select()
		});
		if(settings.autofix){
			this.keyup(function(d){
				if($(this).data("old-value")!=$(this).val())
					formatter.formatString(this,settings)
				}
			)
		}
		return this
	}
})(jQuery);
