﻿// ==UserScript==
// @name                input内容格式判断
// @description	        这个框架用于各个input输入内容格式的判断
// @created date        2009/01/01
// @created author      Tiger(tigershi0507@gmail.com)
// @version             2.0.2
// @version owner       Copyright © 2009-2010 keerr.com All rights reserved.
// ==/UserScript==

/********************************************************************
verified time 	:	2009/8/13   09:49
verified author	:	Tiger
verified purpose:	添加原来在keerr.validate.js中的Email判断（格式和ajax判断是否被注册，以传入的Options的键值对来控制）
*********************************************************************/
/********************************************************************
verified time 	:	2009/8/13   16:49
verified author	:	Tiger
verified purpose:	添加在页面初始化如果input有值时也需判断和样式切换的功能
*********************************************************************/
/********************************************************************
verified time   :   2009/8/21   9:27
verified author :   Martin
verified purpose:   输入的验证码转化为小写（if (_reg_checkCode == this.value.toLower() && this.value != "") ）
*********************************************************************/
/*************************************************
verified time 	:	2009/8/21   9:53
verified author	:	Tiger
verified purpose:	修正了当Input是password的类型是的empty判断
**************************************************/
/*************************************************
verified time 	:	2009/8/25   9:31
verified author	:	Tiger
verified purpose:	修改验证码自动刷新的bug，这个bug会造成自动focus到验证码的input上，无法进行别的input输入了
**************************************************/
/*************************************************
verified time 	:	2009/8/25   9:51
verified author	:	Tiger
verified purpose:	修改了之前focus，blur时input框的width会变化的不好样式变化
**************************************************/
/*************************************************
verified time 	:	2009/11/17   11:11
verified author	:	Tiger
verified purpose:	添加了注释，移动了_reg_checkCode到全局变量js中去了
**************************************************/
/*************************************************
verified time 	:	2009/11/17   16:22
verified author	:	Tiger
verified purpose:	以bylou的思考完成了这个插件的改进，使用了跳出层的样式
**************************************************/
/*************************************************
verified time 	:	2009/11/20   11:17
verified author	:	Tiger
verified purpose:	再次同意修改了这个js插件，使用了很多对象操作
**************************************************/
(function($) {
    // static options
    // s.msgBoxOptions
    var d = defaults = {
        ErrCls: "tooltipinputerr",
        OkCls: "tooltipinputok",
        //BGC_blur_err: "#FFFF99",
        //BGC_blur_ok: "#6DC360",
        BGC_focus: "#CCFF99",
        numberOfOk: 4,
        mustCheck: true,
        isLocal: false,
        msgBoxOptions: { errmsg: "", cssOptions: { top: "190px", left: "280px", opacity: "0.8" }, top: 30, left: 50, delay: 5000, clsName: "pswErrMsg" }
    };
    // helper
    $.judgeHelper = {
        classToggle_blur_err: function($this) {
            $this.removeClass(d.OkCls).addClass(d.ErrCls);
        },
        classToggle_blur_ok: function($this) {
            $this.removeClass(d.ErrCls).addClass(d.OkCls);
        },
        classToggle_focus: function($this, thisID, preValue) {       // 这里可以添加focus时是否清空input
            if ($this.hasClass(d.ErrCls)) {
                $this.val(preValue);
            }
            if ($this.hasClass(d.OkCls)) {
            }
            $.judgeHelper.classToggle_clean($this);
        },
        classToggle_clean: function($this) {
            $this.css("background-color", "").css("border-color", "");
            $this.removeClass(d.OkCls).removeClass(d.ErrCls);
        },
        autoDisplayErrMsg: function(s) {
            $(s.objSer).each(function() {
                if (!$(this).hasClass(d.OkCls) && !$(this).hasClass(d.ErrCls)) {
                    $.judgeHelper.classToggle_blur_err($(this));
                }
            });
        },
        localRight: function($_this) {
            $_this.nextAll(".box-error").hide();
            $_this.nextAll(".box-right").show();
            $_this.addClass("judgeOk");
        },
        localError: function($_this) {
            $_this.nextAll(".box-error").addClass("box-error-error").show();
            $_this.nextAll(".box-right").hide();
            $_this.removeClass("judgeOk");
            $_this.keyup(function() {
                $_this.nextAll(".box-error").removeClass("box-error-error");
            });
        },
        isKeyup: function($_this) {
            $_this.keyup(function() {
                if ($_this.val() !== "" || $_this.val() !== null) {
                    $_this.addClass("_k");
                }
            }); ;
        },
        /// <summary>
        /// 统一的blur后的处理函数
        /// </summary>
        /// <param name="$_this">jQuery对象</param>
        /// <param name="v">input中的value</param>
        /// <param name="myreg">正则表达式</param>
        /// <param name="s">setting参数</param>
        blurRegCheck: function($_this, v, myreg, s) {
            if (s.mustCheck || v) {
                if (v !== "") {
                    if ($_this.hasClass("_k")) {
                        var matchArr = (v.match(myreg) != null) ? ((v.match(myreg).length != 0) ? v.match(myreg) : []) : [],
                        flag = false;
                        for (var x = 0; x < matchArr.length; x++) {
                            if (matchArr[x] === v) {
                                flag = true;
                            }
                        }

                        if (s.isLocal) {    // 是否采用本地样式
                            if (!flag && v !== "") {
                                $.judgeHelper.localError($_this);
                            }
                            else {
                                $.judgeHelper.localRight($_this);
                            }
                        }
                        else {
                            if (!flag && $.trim(v) !== "") {
                                s.msgBoxOptions.errmsg = "请正确填写...";
                                ShowMsgbox(s.msgBoxOptions, $_this);
                            }
                            else {
                                if ($.trim(v) !== "") {
                                    $_this.css("border-color", "#62DB1A").addClass("tooltipinputok");
                                }

                            }
                        }
                    }

                }
                else {
                    if (s.isLocal) {
                        $.judgeHelper.localError($_this);

                    } else {
                        ShowMsgbox(s.msgBoxOptions, $_this);
                    }
                }
            }
            else {
                if (s.isLocal) {
                    $_this.focus().nextAll(".box-error").removeClass("box-error-error");
                }
            }
        },
        /// <summary>
        /// 通过AJAX判断Email是否已被注册
        /// </summary>
        /// <param name=""></param>
        /// <param name=""></param>
        checkEmail: function($_this, v, myreg, s) {
            if (myreg.exec(v)) {
                $.post("/ajax/GetJson.aspx", { type: "regEmail", regEmail: v }, function(data, statut) {
                    if (data === "true") {
                        $.judgeHelper.localRight($_this);
                    }
                    else {
                        $.judgeHelper.localError($_this);
                    }
                });
            }
            else {
                $.judgeHelper.classToggle_blur_err($_this);
                $("#" + $_this.attr("id") + "_tishi").hide();
                $("#" + $_this.attr("id") + "_msg").show().text("请确认输入正确的Email格式！");
            }
        }
    };
    /// <summary>
    /// judgeItem插件的主体
    /// </summary>
    $.fn.extend({
        isEmpty: function(options) {
            var s = options ? $.extend(true, {}, defaults, options) : defaults;
            return this.each(function() {
                var $_this = $(this),
                    myreg = /(\d*\D+\d*)+/g,
                    preValue = "",
                    flagKeyup = false;
                /*$_this.keyup(function() {
                flagKeyup = true;
                });
                if (flagKeyup) {
                $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                }*/

                // 判断是否有键盘输入
                $.judgeHelper.isKeyup($_this);

                if ($_this.val() && $_this.hasClass("_k")) {
                    $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                }

                $_this
                .blur(function() {
                    preValue = $.trim(this.value);
                    if ($(this).is("input:password")) {
                        if (this.value === "") {
                            if (s.isLocal) {
                                $.judgeHelper.localError($_this);
                            } else {
                                ShowMsgbox(s.msgBoxOptions, $_this);
                            }
                        }
                        else {
                            $.judgeHelper.localRight($_this);
                            //myreg = /.{6,}/;
                            //$.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                        }
                    }
                    else {
                        if (preValue === "" || preValue === "我来说两句") {
                            if (s.isLocal) {
                                $.judgeHelper.localError($_this);
                            } else {
                                ShowMsgbox(s.msgBoxOptions, $_this);
                            }
                        }
                        else {
                            $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                        }
                    }

                })
                .focus(function() {
                    $_this.select();
                    $.judgeHelper.classToggle_focus($_this, this.id, preValue);
                })
            });
        },
        isInteger: function(options) {
            var s = options ? $.extend(true, {}, defaults, options) : defaults;
            return this.each(function() {
                var $_this = $(this),
                    myreg = /\d{1,}/g,
                    preValue = "";
                if ($(this).val()) {
                    $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                }
                $_this
                .blur(function() {
                    preValue = this.value;
                    $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                })
                .focus(function() {
                    $.judgeHelper.classToggle_focus($_this, this.id, preValue);
                });

            });
        },
        isFloat: function(options) {
            var s = options ? $.extend(true, {}, defaults, options) : defaults;
            return this.each(function() {
                var $_this = $(this),
                    myreg = /\d+(.\d+)?/g,
                    preValue = "";
                if ($(this).val()) {
                    $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                }
                $_this
                .blur(function() {
                    preValue = this.value;
                    $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                })
                .focus(function() {
                    $.judgeHelper.classToggle_focus($_this, this.id, preValue);
                });
            });
        },
        isEmail: function(options) {
            var s = options ? $.extend(true, {}, defaults, options) : defaults;
            return this.each(function() {
                var $_this = $(this),
                    myreg = /^[-_a-zA-Z0-9]{2,}@([_a-zA-Z0-9]+\.)+[a-zA-Z0-9]{2,3}$/g,
                    preValue = "";
                if ($(this).val()) {
                    $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                }
                $_this
                .blur(function() {
                    preValue = this.value;
                    if (s.isUsed === true) {
                        $.judgeHelper.checkEmail($_this, this.value, myreg, s);
                    }
                    //else {
                    $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                    //}

                })
                .focus(function(e) {
                    var x = e.clientX;
                    $.judgeHelper.classToggle_focus($_this, this.id, preValue);
                });
            });
        },
        isPhone: function(options) {
            var s = options ? $.extend(true, {}, defaults, options) : defaults;
            return this.each(function() {
                var $_this = $(this),
                    myreg = /^(13|15|18)[0-9]\d{8}$/g,
                    preValue = "";
                if ($(this).val()) {
                    $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                }
                $_this
                .blur(function() {
                    preValue = this.value;
                    $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                })
                .focus(function() {
                    $.judgeHelper.classToggle_focus($_this, this.id, preValue);
                });
            });
        },
        isValidate: function(options) {
            var s = options ? $.extend(true, {}, defaults, options) : defaults;
            return this.each(function() {
                var $_this = $(this),
                    preValue = "";
                if ($(this).val()) {
                    this.value = "";
                }
                $_this
                .blur(function() {
                    if (_reg_checkCode === this.value.toLowerCase() && this.value !== "") {
                        if (s.isLocal) {
                            $.judgeHelper.localRight($_this);
                        }
                        else {
                            $_this.css("border-color", "#62DB1A").addClass("tooltipinputok");
                        }
                    }
                    else {
                        if (s.isLocal) {
                            $.judgeHelper.localError($_this);
                        }
                        else {
                            ShowMsgbox(s.msgBoxOptions, $_this);
                        }
                        $_this.next("img.yzm").click();

                    }
                })
                .focus(function() {
                    $.judgeHelper.classToggle_focus($_this, this.id, preValue);
                });
            });
        },
        isReady: function(options) {
            var s = options ? $.extend(true, {}, defaults, options) : defaults;
            return this.each(function() {
                var $_this = $(this);
                $_this.click(function() {
                    $_this.attr("disabled", "disabled");
                    if ($.isFunction(s.readyFunction)) {
                        s.readyFunction(s);
                        $_this.attr("disabled", false);

                    }
                    else {
                        alert("type into a judge ready's function");
                        return false;
                    }
                });
            });
        },
        isFunc: function(options) {
            var s = options ? $.extend(true, {}, defaults, options) : defaults;
            return this.each(function() {
                var $_this = $(this),
                    preValue = "";
                if ($(this).val()) {
                    $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                }
                $_this
                .blur(function() {
                    preValue = this.value;
                    $.judgeHelper.blurRegCheck($_this, this.value, myreg, s);
                })
                .focus(function() {
                    $.judgeHelper.classToggle_focus($_this, this.id, preValue);
                });

            });
        }
    });
})(jQuery);

//$(function() {
//    // 基本判断
//    $(".judgeEmpty").isEmpty({isLocal:true});
//    $(".judgeInteger").isInteger();
//    $(".judgeFloat").isFloat();
//    $(".judgeEmail").isEmail({ isUsed: false });
//    $(".judgePhone").isPhone();
//    // 不是必须判断
//    $(".judgeEmptyNotMust").isEmpty({ mustCheck: false });
//    $(".judgeIntegerNotMust").isInteger({ mustCheck: false });
//    $(".judgeFloatNotMust").isInteger({ mustCheck: false });
//    $(".judgeEmailNotMust").isEmail({ mustCheck: false, isUsed: false });
//    $(".judgePhoneNotMust").isPhone({ mustCheck: false });
//    // 判断Email是否已经被使用，主要是用在注册页面
//    $(".judgeEmailIsUsed").isEmail({ isUsed: true });
//    // 判断验证码
//    $(".judgeValidate").isValidate();
//    // 判断能否上传数据到DB
//    $(".judgeValidateNotMust").isValidate({ mustCheck: false });
//    $(window).unload(function() {
//        $(".tooltipinputerr").val("");
//    });

//    $("#txtU").isEmail({ isUsed: false, isFloatOut: true, msgBoxOptions: { errmsg: "请输入账号", cssOptions: { top: "130px", left: "280px", opacity: "0.8" }, delay: 5000, clsName: "userNameErrMsg"} });

//});


function filterStr(str) {
    str = str.replace(/<\/?[^>]*>/g, '');
    str = str.replace(/[ | ]*\n/g, '\n');
    str = str.replace(/\n[\s| | ]*\r/g, '\n');
    return str;
}

var _reg_checkCode; // 没有添加到了全局变量的js中去了
/// <summary>
/// 获取验证码
/// </summary>
/// <param name=""></param>
/// <param name=""></param>
function getCode_reg() {
    $.ajax({
        url: '/ajax/GetJson.aspx',
        type: 'POST',
        dataType: 'text',
        timeout: 3000,
        data: { type: "getImgSession" },
        cache: false,
        error: function() {
        },
        success: function(str) {
            if (str != '0')
                _reg_checkCode = str;
        }
    });
}

/// <summary>
/// 更改验证码
/// </summary>
/// <param name=""></param>
/// <param name=""></param>
function changeCode_reg(imgId) {
    var obj = $(imgId);
    if (obj) {
        obj.attr("src", "/codeImager.aspx?d=" + Math.random());
        getCode_reg();
    }
}

/// <summary>
/// 获取login错误次数并填写入_LoginErrNumber这个全局变量
/// </summary>
/// <param name=""></param>
/// <param name=""></param>
function getLoginErrNumber() {
    $.ajax({
        url: '/ajax/GetJson.aspx',
        type: 'POST',
        dataType: 'text',
        timeout: 3000,
        data: { type: "getLgErrNumSession" },
        cache: false,
        error: function() {
        },
        success: function(str) {
            if (str != '0') {
                _LoginErrNumber = str;
            }
        }
    });
}

/// <summary>
/// 显示错误并提示错误信息
/// </summary>
/// <param name="msgOpt">只接受关于这个msgbox的options</param>
/// <param name="$_this">input对象</param>
function ShowMsgbox(msgOpt, $_this) {
    if ($("." + msgOpt.clsName).length === 0) {
        $("body").append('<div id="errmsg" class="formError ' + msgOpt.clsName + '" style="display: none;">' +
                            '<div class="formErrorContent">' +
                               ' * This user is available</div>' +
                            '<div class="formErrorArrow">' +
                                '<div class="line10">' +
                                    '<!-- -->' +
                                '</div>' +
                                '<div class="line9">' +
                                    '<!-- -->' +
                                '</div>' +
                                '<div class="line8">' +
                                    '<!-- -->' +
                                '</div>' +
                                '<div class="line7">' +
                                    '<!-- -->' +
                                '</div>' +
                                '<div class="line6">' +
                                    '<!-- -->' +
                                '</div>' +
                                '<div class="line5">' +
                                    '<!-- -->' +
                                '</div>' +
                                '<div class="line4">' +
                                    '<!-- -->' +
                                '</div>' +
                                '<div class="line3">' +
                                    '<!-- -->' +
                                '</div>' +
                                '<div class="line2">' +
                                    '<!-- -->' +
                                '</div>' +
                                '<div class="line1">' +
                                    '<!-- -->' +
                                '</div>' +
                            '</div>' +
                        '</div>');
    };

    msgOpt.cssOptions.top = $_this.offset().top - msgOpt.top;
    msgOpt.cssOptions.left = $_this.offset().left + $_this.innerWidth() - msgOpt.left;
    $("." + msgOpt.clsName).css(msgOpt.cssOptions).fadeIn().find(".formErrorContent").text(msgOpt.errmsg);
    setTimeout(function() {
        $("." + msgOpt.clsName).fadeOut().remove();
    }, msgOpt.delay);
    $_this.addClass("tooltipinputerr").keyup(function() {
        $("." + msgOpt.clsName).fadeOut().remove();
    });
}


