
if (typeof jQuery !== "undefined" && jQuery && (typeof jquery_autocomplete_check_is_gyb === "undefined" || !jquery_autocomplete_check_is_gyb)) {
    jquery_autocomplete_check_is_gyb = true;


    (function() {
        var style = ".autocompleter_frame{font-size: 12px;padding: 0px; margin: 0px;width:270px;border:1px solid #7f9db9;position:absolute;background-color:#fff;}";
        style += ".autocompleter_frame .autocompleter_tip{width:260px;overflow:hidden;color:rgb(128,128,128);border-bottom:1px dashed;margin:5px;line-height:20px;}";
        style += ".autocompleter_frame .autocompleter_tip span{margin-left:5px;}";
        style += ".autocompleter_frame .autocompleter_list{width:100%;height:375px;overflow-x:hidden;margin-bottom:0px;margin-top:5px;}";
        style += ".autocompleter_frame .autocompleter_list ol{padding: 0px; margin: 0px;width:260px;background:white;list-style-image: none; list-style-position: outside; list-style-type: none; clear: left; overflow: hidden;}";
        style += ".autocompleter_frame .autocompleter_list ol li{width:100%;margin-bottom:2px;color:#404040;padding:1px 0 2px;font-size:12px;line-height:18px;float:left;width:260px;cursor:pointer;overflow:hidden;}";
        style += ".autocompleter_frame .autocompleter_list ol li .autocompleter_left{text-transform:capitalize;float:left;text-align:left;padding-left:10px;}";
        style += ".autocompleter_frame .autocompleter_list ol li .autocompleter_right{float:right;text-align:right;padding-right:10px;}";
        style += ".autocompleter_frame .autocompleter_list ol li span{color:#385fb1;}";
        style += ".autocompleter_frame .autocompleter_bottom{text-align:center;margin-top:10px;margin-bottom:5px;}";
        style += ".autocompleter_frame .autocompleter_list ol .autocompleter_selected{background-color:#b9ceee;}";
        style += ".autocompleter_frame .autocompleter_list ol .autocompleter_active{background-color:#e7ebf1;}";

        jQuery.createStyle(style);
    })();

    jQuery.autocomplete = function(input, options) {
        input.autocompleter = this;

        this.input = input;
        this.$input = jQuery(input);
        this.container = this.createContainer(options.containerClass);
        this.isContainerInBody = false;
        this.options = options;
        this.currentIndex = -1;
        this.currentRows = 0;
        this.timer = null;
        this.isShowDefault = false;
        this.lastLoadDataTime = "";
        this.loadTimeout = false;
        this.allowShow = true;

        this._init();
        this.$input.attr("autocomplete", "off");
    };

    jQuery.autocomplete.prototype = {
        _init:function() {

            this._initInputEvent();
        },

        _initInputEvent:function() {
            this.$input.keydown(function(e) {

                switch (e.keyCode) {
                    case 9 :
                        break;
                    case 38: // up
                        if (this.autocompleter.isShow()) {
                            e.preventDefault();

                            this.autocompleter.moveSelect(-1);
                        }
                        break;
                    case 40: // down
                        if (this.autocompleter.isShow()) {
                            e.preventDefault();

                            this.autocompleter.moveSelect(1);
                        }
                        break;
                    case 13:
                        break;
                    default:
                      
                        this.autocompleter.start();
                        break;
                }
            });

            this.$input.keyup(function(e) {

                switch (e.keyCode) {
                    case 9 :
                        break;
                    case 13: // return
                        if (this.autocompleter.isShow()) {

                            this.autocompleter.fillValue();
                        }
                        break;
                   case 8: // return
                       if (jQuery.trim(this.autocompleter.$input.val()) == '') {

                            this.autocompleter.showDefault();
                        }
                        break;
                    default:
                         
                        if (jQuery.trim(this.autocompleter.$input.val()) == '') {

                            this.autocompleter.start();
                        } 
                        break;
                }

            });

            this.$input.click(function(e) {

                if (!this.autocompleter.isShow()) {

                    if (jQuery.trim(this.autocompleter.$input.val()) == '') {

                         this.autocompleter.showDefault();
                    } else {
                      
                        this.autocompleter.start();
                    }
                }
            });

            this.$input.focus(function(e) {

                if (!this.autocompleter.isShow()) {

                    if (jQuery.trim(this.autocompleter.$input.val()) == '') {
                         
                         this.autocompleter.showDefault();
                    } else {

                        this.autocompleter.start();
                    }
                }
            });

            this.$input.blur(function(e) {
                  
                if (this.autocompleter.isShow()) {
                    
                    var div = this.autocompleter.container;
                    var x1 = div.offset().left;
                    var y1 = div.offset().top;

                    var x2 = x1 + div.outerWidth();
                    var y2 = y1 + div.outerHeight();

                    if (jQuery.mouseXY.X >= x1 && jQuery.mouseXY.X <= x2 && jQuery.mouseXY.Y >= y1 && jQuery.mouseXY.Y <= y2) {
                        var _me = this;
                        setTimeout(function() {
                            jQuery(_me).focus();
                        }, 0);
                        return;
                    }
                }
                this.autocompleter.fillValue();
            });
        },

        createContainer:function(containerClass) {
            var div = jQuery("<div>");
            div.hide();
            div.addClass(containerClass);

            var tip = jQuery("<div><span></span></div>");
            tip.addClass("autocompleter_tip");

            var list = jQuery("<div>");
            list.addClass("autocompleter_list");

            var bottom = jQuery("<div>");
            bottom.addClass("autocompleter_bottom");

            tip.appendTo(div);
            list.appendTo(div);
            bottom.appendTo(div);

            return div;
        },

        isShow:function() {
            return !this.container.is(":hidden");
        },

        moveSelect:function(i) {



            if (this.currentRows > 0) {

                this.currentIndex = this.currentIndex + i;

                this.currentIndex = this.currentIndex < 0 ? this.currentRows - 1 : this.currentIndex;
                this.currentIndex = this.currentIndex >= this.currentRows ? 0 : this.currentIndex;

                var div = this.container;
                div.find(".autocompleter_list ol li").each(function() {

                    jQuery(this).removeClass("autocompleter_selected");
                });



              jQuery(div.find(".autocompleter_list ol li")[this.currentIndex]).addClass("autocompleter_selected")
            }
        },

        fillValue:function() {
            if (this.currentIndex >= 0) {
                var li = jQuery(this.container.find(".autocompleter_list ol li")[this.currentIndex]);
                var key = "";
                var value = "";
                li.each(function() {
                    key = this._key;
                    value = this._text;
                });

                if (this.options.fillValueFn) {
                    this.options.fillValueFn(key, value);
                } else {
                    if (this.options.keyInput) {
                        jQuery(this.options.keyInput).val(key);
                    }
                    this.$input.val(value);
                }
            } else {
                if (this.options.fillValueFn) {
                    this.options.fillValueFn('', '');
                } else {
                    if (this.options.keyInput) {
                        jQuery(this.options.keyInput).val('');
                    }
                    this.$input.val('');
                }
            }
            this.allowShow = false;
            var __this = this;
            setTimeout(function() {
                __this.allowShow = true
            }, 500);
            this.hide();
        },

        show:function(data, tip, isDefault) {
            if (!this.allowShow) {
                return;
            }
            this.container.floating(this.$input);

            data = data && data.constructor == Array ? data : null;

            if (data && data.length > 0) {
                this.isShowDefault = isDefault;
                if (!this.isContainerInBody) {
                    this.isContainerInBody = true;
                    this.container.appendTo("body");
                }

                this.currentIndex = -1;
                this.currentRows = data.length;

                var list = jQuery('<ol>');

                var defaultIndex = 1;
                var defaultKey = '';

                if (this.options.keyInput) {
                    defaultKey = jQuery(this.options.keyInput).val();
                } else {
                    defaultKey = this.$input.val();
                }

                for (var i = 0; i < data.length; i++) {
                       var li = this.createItem(data[i]);
                          li.each(function() {
                          this._index = i;
                           });
                          li.appendTo(list);
                         //                    if (defaultKey == data[i]["key"]) {
                         //                        defaultIndex = i + 1;
                         //                    }
                }

                if (tip) {
                    this.container.find(".autocompleter_tip span").html(tip);
                    this.container.find(".autocompleter_tip").show();
                } else {
                    this.container.find(".autocompleter_tip").hide();
                }

                this.container.find(".autocompleter_list").html('');
                list.appendTo(this.container.find(".autocompleter_list"));

                this.container.find(".autocompleter_list ol li").mouseover(function() {
                    jQuery(this).addClass("autocompleter_active");
                });
                this.container.find(".autocompleter_list ol li").mouseout(function() {
                    jQuery(this).removeClass("autocompleter_active");
                });

                var _autocompleter = this;
                this.container.find(".autocompleter_list ol li").click(function() {
                    var li = jQuery(this);
                    li.each(function() {
                        _autocompleter.currentIndex = this._index;
                    });
                    _autocompleter.fillValue();
                });

                this.container.find(".autocompleter_bottom").hide();

                this.container.show();
                jQuery.iframeDecorateDiv(this.container);

                this.moveSelect(defaultIndex);
            } else {
                if (!this.isShow) {
                    this.container.find(".autocompleter_list").html("");
                    this.currentIndex = -1;
                    this.currentRows = 0;
                    this.isShowDefault = false;
                }
            }
        },

        hide:function() {
            this.container.hide();
            this.isShowDefault = false;
        },

        showDefault:function() {
            
            this.hide();
            this.lastLoadDataTime = "" + new Date().getTime();
            this.loadTimeout = true;
            this.$input.val("");
            if (this.options.defaultData) {
                if (!this.isShowDefault) {

                    this.show(this.options.defaultData, this.options.defaultTip, true);
                }
            } else {
               
                this.container.find(".autocompleter_list").html("");
                this.currentIndex = -1;
                this.currentRows = 0;
                this.isShowDefault = false;
                this.hide();
            }
        },

        createItem:function(data) {
           var li;

            //周永胜修改  开始

            if(data["key"] != null && data["key"] != ""){

                   li  = jQuery('<li><span class="autocompleter_left" ></span><span class="autocompleter_right"></span></li>');

            }else{
               li  = jQuery('<li style="display:none;"><span class="autocompleter_left" ></span><span class="autocompleter_right"></span></li>');
            }
             //周永胜修改  结束

            var key = '', value = '', leftText = '', rightText = '';


            if (typeof data == "object") {
                    key = data["key"];
                    value = data["value"];
                    leftText = data["leftText"];
                    rightText = data["rightText"];

                    leftText = leftText || value;
                    rightText = rightText || '';

            } else {
                key = data;
                value = data;
                leftText = data;
                rightText = '';
            }

            li.each(function() {
                this._key = key;
                this._text = value;
            });

            jQuery(li.find(".autocompleter_left")).html(leftText);
            jQuery(li.find(".autocompleter_right")).html(rightText);
            return li;
        },

        getQueryUrl:function() {
            if (jQuery.trim(this.$input.val()) == '') {
                this.$input.val('');
                return null;
            } else {
                if (this.options.url) {

                    if (this.options.getParamsFn) {
                        var p = null;
                        var params = this.options.getParamsFn();
                        for (var name in params) {
                            if (p == null) {
                                p = '?' + name + '=' + encodeURIComponent(params[name]);
                            } else {
                                p = p + '&' + name + '=' + encodeURIComponent(params[name]);
                            }
                        }
                        return p == null ? null : this.options.url + p;
                    } else {
                        return this.options.url + '?q=' + encodeURIComponent(this.$input.val());
                    }
                } else {
                    return null;
                }
            }
        },

        requestData:function() {
            if ($.getByteLength($.trim(this.$input.val())) < this.options.minChars) {
                return;
            }

            var _this = this;
            var src = this.getQueryUrl();
            src = src + (src.indexOf('?') > 0 ? '&' : '?') + 'callback=jQuery.autocomplete.jscallback';

            _this.timeFunction = setTimeout(function() {
                var head = document.getElementsByTagName("head")[0];
                var script = document.createElement("script");
                _this.loadTimeout = false;
                _this.lastLoadDataTime = "" + new Date().getTime();
                script._time = this.lastLoadDataTime;
                script.type = "text/javascript";
                script.src = src;
                script.x_onLoad = script.onreadystatechange = function() {
                    if (_this.lastLoadDataTime != this._time) {
                        _this.loadTimeout = true;
                    }
                    if (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") {
                        setTimeout(function() {
                            head.removeChild(script);
                        }, 1);
                    }
                };
                head.appendChild(script);
            }, 200);
        },

        start:function() {
            if (jQuery.autocomplete.focusInstance != null) {
                this.stop();
            }

            jQuery.autocomplete.focusInstance = this;
            var _instance = this;
            _instance.timer = setTimeout(function() {
                if (jQuery.trim(_instance.$input.val()) != "") {
                    _instance.requestData();
                }
            }, this.options.delay);
        },

        stop:function() {
            jQuery.autocomplete.focusInstance = null;
            clearTimeout(this.timer);
        },

        version:"1.0"
    };

    jQuery.fn.autocomplete = function(url, options) {
        options = options || {};
        options.url = url;
        options.containerClass = options.containerClass || "autocompleter_frame";
        options.getParamsFn = jQuery.isFunction(options.getParamsFn) ? options.getParamsFn : null;
        options.fillValueFn = jQuery.isFunction(options.fillValueFn) ? options.fillValueFn : null;
        options.keyInput = jQuery.isInputText(options.keyInput) ? options.keyInput : null;
        options.minChars = (!options.minChars || options.minChars < 1) ? 1 : options.minChars;
        options.tip = options.tip || null;
        options.defaultTip = options.defaultTip || null;
        options.defaultData = jQuery.isArray(options.defaultData) ? options.defaultData : null;
        options.delay = 10;

        this.each(function() {
            var input = this;
            new jQuery.autocomplete(input, options);
        });

        return this;
    };

    jQuery.autocomplete.focusInstance = null;
    jQuery.autocomplete.jscallback = function(data) {
        if (jQuery.autocomplete.focusInstance) {
            setTimeout(function() {
                if ($.trim(jQuery.autocomplete.focusInstance.$input.val()) !== "") {
                    jQuery.autocomplete.focusInstance.show(data, jQuery.autocomplete.focusInstance.options.tip, false);
                }
            }, 0);
        }
    };
}

/*
 * 作者：顾燕兵
 * 版本：0.1.0
 *
 * 使用方法：

 $("#countryName").autocomplete("${CONTEXT_PATH}/common/listCountry.action", {
 keyInput:$("#countryCode"),
 getParamsFn:function() {
 return {"countryName":$("#countryName").val()};
 },
 tip:"拼音排序，使用 ↑↓ 选择",
 defaultTip:"输入中文或拼音，使用 ↑↓ 选择"
 });

 ${CONTEXT_PATH}/common/listCountry.action 返回的JSP页面内容：
 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 <%@ taglib uri="/struts-tags" prefix="s" %>
 <%
 String callback = request.getParameter("callback");
 %>

 (function(){
 var countrys_ = [];
 <s:iterator value="countrys">
 countrys_.push({key:"<s:property value="code"/>",value:"<s:property value="chsName" escape="false"/>",leftText:"<s:property
 value="enuName"/>",rightText:"<s:property value="chsName" escape="false"/>"});
 </s:iterator>

 <%=callback%>(countrys_);

 })();
 * */
