(function (exports) {
'use strict';

/**
 * Module : Sparrow touch event
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-07-28 14:41:17
 */

var on = function(element, eventName, child, listener) {
	if(!element)
		return;
	if(arguments.length < 4) {
		listener = child;
		child = undefined;
	} else {
		var childlistener = function(e) {
			if(!e) {
				return;
			}
			var tmpchildren = element.querySelectorAll(child);
			tmpchildren.forEach(function(node) {
				if(node == e.target) {
					listener.call(e.target, e);
				}
			});
		};
	}
	//capture = capture || false;

	if(!element["uEvent"]) {
		//在dom上添加记录区
		element["uEvent"] = {};
	}
	//判断是否元素上是否用通过on方法填加进去的事件
	if(!element["uEvent"][eventName]) {
		element["uEvent"][eventName] = [child ? childlistener : listener];
		if(u.event && u.event[eventName] && u.event[eventName].setup) {
			u.event[eventName].setup.call(element);
		}
		element["uEvent"][eventName + 'fn'] = function(e) {
			//火狐下有问题修改判断
			if(!e)
				e = typeof event != 'undefined' && event ? event : window.event;
			element["uEvent"][eventName].forEach(function(fn) {
				try {
					e.target = e.target || e.srcElement; //兼容IE8
				} catch(ee) {}
				if(fn)
					fn.call(element, e);
			});
		};
		if(element.addEventListener) { // 用于支持DOM的浏览器
			element.addEventListener(eventName, element["uEvent"][eventName + 'fn']);
		} else if(element.attachEvent) { // 用于IE浏览器
			element.attachEvent("on" + eventName, element["uEvent"][eventName + 'fn']);
		} else { // 用于其它浏览器
			element["on" + eventName] = element["uEvent"][eventName + 'fn'];
		}
	} else {
		//如果有就直接往元素的记录区添加事件
		var lis = child ? childlistener : listener;
		var hasLis = false;
		element["uEvent"][eventName].forEach(function(fn) {
			if(fn == lis) {
				hasLis = true;
			}
		});
		if(!hasLis) {
			element["uEvent"][eventName].push(child ? childlistener : listener);
		}
	}

};

/**
 * 阻止冒泡
 */
var stopEvent = function(e) {
	if(typeof(e) != "undefined") {
		if(e.stopPropagation)
			e.stopPropagation();
		else {
			e.cancelBubble = true;
		}
		//阻止默认浏览器动作(W3C)
		if(e && e.preventDefault)
			e.preventDefault();
		//IE中阻止函数器默认动作的方式
		else
			window.event.returnValue = false;
	}
};

/**
 * Module : Sparrow dom
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-08-16 13:59:17
 */
/**
 * 元素增加指定样式
 * @param value
 * @returns {*}
 */
var addClass = function(element, value) {
	if(element){
		if(typeof element.classList === 'undefined') {
			if(u._addClass){
				u._addClass(element, value);
			}else{
				$(element).addClass(value);
			}

		} else {
			element.classList.add(value);
		}
	}

	return this;
};
/**
 * 删除元素上指定样式
 * @param {Object} element
 * @param {Object} value
 */
var removeClass = function(element, value) {
	if(element){
		if(typeof element.classList === 'undefined') {
			if(u._removeClass){
				u._removeClass(element, value);
			}else{
				$(element).removeClass(value);
			}

		} else {
			element.classList.remove(value);
		}
	}
	return this;
};
var makeDOM = function(htmlString) {
	var tempDiv = document.createElement("div");
	tempDiv.innerHTML = htmlString;
	var _dom = tempDiv.children[0];
	return _dom;
};

/**
 * Module : Sparrow extend enum
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-07-27 21:46:50
 */

var enumerables = true;
var enumerablesTest = {
		toString: 1
	};
for(var i in enumerablesTest) {
	enumerables = null;
}
if(enumerables) {
	enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable',
		'toLocaleString', 'toString', 'constructor'
	];
}

/**
 * Module : Sparrow extend
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-07-27 21:46:50
 */

/**
 * 复制对象属性
 *
 * @param {Object}  目标对象
 * @param {config} 源对象
 */
var extend = function(object, config) {
	var args = arguments,
		options;
	if(args.length > 1) {
		for(var len = 1; len < args.length; len++) {
			options = args[len];
			if(object && options && typeof options === 'object') {
				var i, j, k;
				for(i in options) {
					object[i] = options[i];
				}
				if(enumerables) {
					for(j = enumerables.length; j--;) {
						k = enumerables[j];
						if(options.hasOwnProperty && options.hasOwnProperty(k)) {
							object[k] = options[k];
						}
					}
				}
			}
		}
	}
	return object;
};

if(!Object.assign){
	Object.assign = extend;
}

/**
 * Module : Sparrow browser environment
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-07-27 21:46:50
 */

var u$1 = {};


extend(u$1, {
	isIE:  false,
	isFF: false,
	isOpera: false,
	isChrome: false,
	isSafari: false,
	isWebkit: false,
	isIE8_BEFORE: false,
	isIE8: false,
	isIE8_CORE: false,
	isIE9: false,
	isIE9_CORE: false,
	isIE10: false,
	isIE10_ABOVE: false,
	isIE11: false,
	isEdge: false,
	isIOS: false,
	isIphone: false,
	isIPAD: false,
	isStandard: false,
	version: 0,
	isWin: false,
	isUnix: false,
	isLinux: false,
	isAndroid: false,
	isAndroidPAD:false,
	isAndroidPhone:false,
	isMac: false,
	hasTouch: false,
	isMobile: false
});

(function() {
	var userAgent = navigator.userAgent,
		rMsie = /(msie\s|trident.*rv:)([\w.]+)/,
		rFirefox = /(firefox)\/([\w.]+)/,
		rOpera = /(opera).+version\/([\w.]+)/,
		rChrome = /(chrome)\/([\w.]+)/,
		rSafari = /version\/([\w.]+).*(safari)/,
		version,
		ua = userAgent.toLowerCase(),
		s,
		browserMatch = {
			browser: "",
			version: ''
		},
		match = rMsie.exec(ua);

	if(match != null) {
		browserMatch = {
			browser: "IE",
			version: match[2] || "0"
		};
	}
	match = rFirefox.exec(ua);
	if(match != null) {
		browserMatch = {
			browser: match[1] || "",
			version: match[2] || "0"
		};
	}
	match = rOpera.exec(ua);
	if(match != null) {
		browserMatch = {
			browser: match[1] || "",
			version: match[2] || "0"
		};
	}
	match = rChrome.exec(ua);
	if(match != null) {
		browserMatch = {
			browser: match[1] || "",
			version: match[2] || "0"
		};
	}
	match = rSafari.exec(ua);
	if(match != null) {
		browserMatch = {
			browser: match[2] || "",
			version: match[1] || "0"
		};
	}

	if(userAgent.indexOf("Edge") > -1){
		u$1.isEdge = true;
	}
	if(s = ua.match(/opera.([\d.]+)/)) {
		u$1.isOpera = true;
	} else if(browserMatch.browser == "IE" && browserMatch.version == 11) {
		u$1.isIE11 = true;
		u$1.isIE = true;
	} else if(s = ua.match(/chrome\/([\d.]+)/)) {
		u$1.isChrome = true;
		u$1.isStandard = true;
	} else if(s = ua.match(/version\/([\d.]+).*safari/)) {
		u$1.isSafari = true;
		u$1.isStandard = true;
	} else if(s = ua.match(/gecko/)) {
		//add by licza : support XULRunner
		u$1.isFF = true;
		u$1.isStandard = true;
	} else if(s = ua.match(/msie ([\d.]+)/)) {
		u$1.isIE = true;
	} else if(s = ua.match(/firefox\/([\d.]+)/)) {
		u$1.isFF = true;
		u$1.isStandard = true;
	}
	if(ua.match(/webkit\/([\d.]+)/)) {
		u$1.isWebkit = true;
	}
	if(ua.match(/ipad/i)) {
		u$1.isIOS = true;
		u$1.isIPAD = true;
		u$1.isStandard = true;
	}

	if(ua.match(/iphone/i)) {
		u$1.isIOS = true;
		u$1.isIphone = true;
	}

	if((navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel")) {
		//u.isIOS = true;
		u$1.isMac = true;
	}

	if((navigator.platform == "Win32") || (navigator.platform == "Windows") || (navigator.platform == "Win64")) {
		u$1.isWin = true;
	}

	if((navigator.platform == "X11") && !u$1.isWin && !u$1.isMac) {
		u$1.isUnix = true;
	}
	if((String(navigator.platform).indexOf("Linux") > -1)) {
		u$1.isLinux = true;
	}

	if(ua.indexOf('Android') > -1 || ua.indexOf('android') > -1 || ua.indexOf('Adr') > -1 || ua.indexOf('adr') > -1) {
		u$1.isAndroid = true;
	}

	u$1.version = version ? (browserMatch.version ? browserMatch.version : 0) : 0;
	if(u$1.isAndroid){
		if(window.screen.width>=768&&window.screen.width<1024){
			u$1.isAndroidPAD=true;
		}
		if(window.screen.width<=768) {
			u$1.isAndroidPhone = true;
		}
	}
	if(u$1.isIE) {
		var intVersion = parseInt(u$1.version);
		var mode = document.documentMode;
		if(mode == null) {
			if(intVersion == 6 || intVersion == 7) {
				u$1.isIE8_BEFORE = true;
			}
		} else {
			if(mode == 7) {
				u$1.isIE8_BEFORE = true;
			} else if(mode == 8) {
				u$1.isIE8 = true;
			} else if(mode == 9) {
				u$1.isIE9 = true;
				u$1.isSTANDARD = true;
			} else if(mode == 10) {
				u$1.isIE10 = true;
				u$1.isSTANDARD = true;
				u$1.isIE10_ABOVE = true;
			} else {
				u$1.isSTANDARD = true;
			}
			if(intVersion == 8) {
				u$1.isIE8_CORE = true;
			} else if(intVersion == 9) {
				u$1.isIE9_CORE = true;
			} else if(browserMatch.version == 11) {
				u$1.isIE11 = true;
			}
		}
	}
	if("ontouchend" in document) {
		u$1.hasTouch = true;
	}
	if(u$1.isIphone || u$1.isAndroidPhone)
		u$1.isMobile = true;

})();

var env = u$1;

/**
 * Module : Sparrow util tools
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-07-27 21:46:50
 */

/**
 * 创建一个带壳的对象,防止外部修改
 * @param {Object} proto
 */
var isArray = Array.isArray || function(val) {
	return Object.prototype.toString.call(val) === '[object Array]';
};
try{
	NodeList.prototype.forEach = Array.prototype.forEach;
}catch(e){
	
}


/**
 * 获得字符串的字节长度
 */
String.prototype.lengthb = function() {
	//	var str = this.replace(/[^\x800-\x10000]/g, "***");
	var str = this.replace(/[^\x00-\xff]/g, "**");
	return str.length;
};

/**
 * 将AFindText全部替换为ARepText
 */
String.prototype.replaceAll = function(AFindText, ARepText) {
	//自定义String对象的方法
	var raRegExp = new RegExp(AFindText, "g");
	return this.replace(raRegExp, ARepText);
};

/**
 * Module : Sparrow ajax
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-07-28 19:06:36
 */

var XmlHttp = {
	get: "get",
	post: "post",
	reqCount: 4,
	createXhr: function() {
		var xmlhttp = null;
		/*if (window.XMLHttpRequest) {
		  xmlhttp = new XMLHttpRequest();
		} else {
		  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}*/
		if(env.isIE8) {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE低版本创建XMLHTTP
		} else if(env.isIE) {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); //IE高版本创建XMLHTTP
		} else if(window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest();
		}
		return xmlhttp;
	},
	ajax: function(_json) {
		var url = _json["url"];
		var callback = _json["success"];
		var async = (_json["async"] == undefined ? true : _json["async"]);
		var error = _json["error"];
		var params = _json["data"] || {};
		var method = (_json["type"] == undefined ? XmlHttp.post : _json["type"]).toLowerCase();
		var gzipFlag = params.compressType;
		url = XmlHttp.serializeUrl(url);
		params = XmlHttp.serializeParams(params);
		if(method == XmlHttp.get && params != null) {
			url += ("&" + params);
			params = null; //如果是get请求,保证最终会执行send(null)
		}

		var xmlhttp = XmlHttp.createXhr();
		//xmlhttp.open(method, url+ escape(new Date()), async);
		xmlhttp.open(method, url, async);

		if(method == XmlHttp.post) {
			xmlhttp.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded;charset=UTF-8");
		}

		var execount = 0;
		// 异步
		if(async) {
			// readyState 从 1~4发生4次变化
			xmlhttp.onreadystatechange = function() {
				execount++;
				// 等待readyState状态不再变化之后,再执行回调函数
				//if (execount == XmlHttp.reqCount) {// 火狐下存在问题，修改判断方式
				if(xmlhttp.readyState == XmlHttp.reqCount) {
					XmlHttp.execBack(xmlhttp, callback, error);
				}
			};
			// send方法要在在回调函数之后执行
			xmlhttp.send(params);
		} else {
			// 同步 readyState 直接变为 4
			// 并且 send 方法要在回调函数之前执行
			xmlhttp.send(params);
			XmlHttp.execBack(xmlhttp, callback, error);
		}
	},
	execBack: function(xmlhttp, callback, error) {
		//if (xmlhttp.readyState == 4
		if(xmlhttp.status == 200 || xmlhttp.status == 304 || xmlhttp.readyState == 4) {
			callback(xmlhttp.responseText, xmlhttp.status, xmlhttp);
		} else {
			if(error) {
				error(xmlhttp.responseText, xmlhttp.status, xmlhttp);
			} else {
				var errorMsg = "no error callback function!";
				if(xmlhttp.responseText) {
					errorMsg = xmlhttp.responseText;
				}
				alert(errorMsg);
				// throw errorMsg;
			}
		}
	},
	serializeUrl: function(url) {
		var cache = "cache=" + Math.random();
		if(url.indexOf("?") > 0) {
			url += ("&" + cache);
		} else {
			url += ("?" + cache);
		}
		return url;
	},
	serializeParams: function(params) {
		var ud = undefined;
		if(ud == params || params == null || params == "") {
			return null;
		}
		if(params.constructor == Object) {
			var result = "";
			for(var p in params) {
				result += (p + "=" + encodeURIComponent(params[p]) + "&");
			}
			return result.substring(0, result.length - 1);
		}
		return params;
	}
};


var ajax = XmlHttp.ajax;

/**
 * Module : neoui-autocompete
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-08-02 15:14:43
 */

var Autocomplete = u.BaseComponent.extend({
    defaults: {
        inputClass: "ac_input",
        resultsClass: "ac_results",
        lineSeparator: "\n",
        cellSeparator: "|",
        minChars: 1,
        delay: 400,
        matchCase: 0,
        matchSubset: 1,
        matchContains: 0,
        cacheLength: 1,
        mustMatch: 0,
        extraParams: {},
        loadingClass: "ac_loading",
        selectFirst: false,
        selectOnly: false,
        maxItemsToShow: -1,
        autoFill: false,
        width: 0,
        source: null,
        select: null,
        multiSelect: false,
        //moreClick:function(){},
    },
    init: function() {
        var self = this;
        this.options = extend({}, this.defaults, this.options);
        this.requestIndex = 0;
        this.pending = 0;
        if (this.options.inputClass) {
            addClass(this.element, this.options.inputClass);
        }
        this._results = document.querySelector('#autocompdiv');
        if (!this._results) {
            this._results = makeDOM('<div id="autocompdiv"></div>');
            document.body.appendChild(this._results);
        }
        this._results.style.display = 'none';
        this._results.style.position = 'absolute';
        addClass(this._results, this.options.resultsClass);
        if (this.options.width) {
            this._results.style.width = this.options.width;
        }
        this.timeout = null;
        this.prev = "";
        this.active = -1;
        this.cache = {};
        this.keyb = false;
        this.hasFocus = false;
        this.lastKeyPressCode = null;
        this._initSource();
        on(this.element, 'keydown', function(e) {
            self.lastKeyPressCode = e.keyCode;
            switch (e.keyCode) {
                case 38: // up
                    stopEvent(e);
                    self.moveSelect(-1);
                    break;
                case 40: // down
                    stopEvent(e);
                    self.moveSelect(1);
                    break;
                case 9: // tab
                case 13: // return
                    if (self.selectCurrent()) {
                        // make sure to blur off the current field
                        // self.element.blur();
                        stopEvent(e);
                    }
                    break;
                default:
                    self.active = -1;
                    if (self.timeout) clearTimeout(self.timeout);
                    self.timeout = setTimeout(function() {
                        self.onChange();
                    }, self.options.delay);
                    break;
            }
        });
        on(this.element, 'focus', function() {
            self.hasFocus = true;
        });
        on(this.element, 'blur', function() {
            self.hasFocus = false;
            self.hideResults();
        });
        this.hideResultsNow();
    },
    flushCache: function() {
        this.cache = {};
        this.cache.data = {};
        this.cache.length = 0;
    },
    _initSource: function() {
        var array, url, self = this;
        if (isArray(this.options.source)) {
            array = this.options.source;
            this.source = function(request, response) {
                //				response( $.ui.autocomplete.filter( array, request.term ) );
                response(self.filterData(request.term, array));
            };
        } else if (typeof this.options.source === "string") {
            url = this.options.source;
            this.source = function(request, response) {
                if (self.xhr) {
                    self.xhr.abort();
                }
                self.xhr = ajax({
                    url: url,
                    data: request,
                    dataType: "json",
                    success: function(data) {
                        response(data);
                    },
                    error: function() {
                        response([]);
                    }
                });
            };
        } else {
            this.source = this.options.source;
        }
    },
    _response: function() {
        var self = this;
        var index = ++this.requestIndex;

        return function(content) {
            if (index === self.requestIndex) {
                self.__response(content);
            }

            self.pending--;
            if (!self.pending) {}
        };
    },
    __response: function(content) {
        if (content)
            this.receiveData2(content);
        this.showResults();
    },
    onChange: function() {
        // ignore if the following keys are pressed: [del] [shift] [capslock]
        if (this.lastKeyPressCode == 46 || (this.lastKeyPressCode > 8 && this.lastKeyPressCode < 32))
            return this._results.style.disply = 'none';
        if (!this.element.value) return;
        var vs = this.element.value.split(','),
            v = vs[vs.length - 1].trim();
        if (v == this.prev) return;
        this.prev = v;
        if (v.length >= this.options.minChars) {
            addClass(this.element, this.options.loadingClass);
            this.pending++;
            this.source({
                term: v
            }, this._response());
        } else {
            removeClass(this.element, this.options.loadingClass);
            this._results.style.display = 'none';
        }
    },
    moveSelect: function(step) {
        var lis = this._results.querySelectorAll('li');
        if (!lis) return;

        this.active += step;

        if (this.active < 0) {
            this.active = 0;
        } else if (this.active >= lis.length) {
            this.active = lis.length - 1;
        }
        lis.forEach(function(li) {
            removeClass(li, 'ac_over');
        });
        addClass(lis[this.active], 'ac_over');
    },
    selectCurrent: function() {
        var li = this._results.querySelector('li.ac_over'); //$("li.ac_over", this.$results[0])[0];
        if (!li) {
            var _li = this._results.querySelectorAll('li'); //$("li", this.$results[0]);
            if (this.options.selectOnly) {
                if (_li.length == 1) li = _li[0];
            } else if (this.options.selectFirst) {
                li = _li[0];
            }
        }
        if (li) {
            this.selectItem(li);
            return true;
        } else {
            return false;
        }
    },
    selectItem: function(li) {
        var self = this;
        if (!li) {
            li = document.createElement("li");
            li.selectValue = "";
        }
        var v = li.selectValue ? li.selectValue : li.innerHTML;
        this.lastSelected = v;
        this.prev = v;
        this._results.innerHTML = '';
        if (this.options.multiSelect) {

            if ((this.element.value + ',').indexOf(v + ',') != -1)
                return;
            var vs = this.element.value.split(',');
            var lastValue = this.element.value.substring(0, this.element.value.lastIndexOf(','));

            this.element.value = (lastValue ? lastValue + ', ' : lastValue) + v + ', ';
        } else {
            this.element.value = v;
        }

        this.hideResultsNow();

        this.element.focus();

        if (this.options.select) setTimeout(function() {
            self.options.select(li._item, self);
        }, 1);
    },
    createSelection: function(start, end) {
        // get a reference to the input element
        var field = this.element;
        if (field.createTextRange) {
            var selRange = field.createTextRange();
            selRange.collapse(true);
            selRange.moveStart("character", start);
            selRange.moveEnd("character", end);
            selRange.select();
        } else if (field.setSelectionRange) {
            field.setSelectionRange(start, end);
        } else {
            if (field.selectionStart) {
                field.selectionStart = start;
                field.selectionEnd = end;
            }
        }
        field.focus();
    },
    // fills in the input box w/the first match (assumed to be the best match)
    autoFill: function(sValue) {
        // if the last user key pressed was backspace, don't autofill
        if (this.lastKeyPressCode != 8) {
            // fill in the value (keep the case the user has typed)
            this.element.value = this.element.value + sValue.substring(this.prev.length);
            // select the portion of the value not typed by the user (so the next character will erase)
            this.createSelection(this.prev.length, sValue.length);
        }
    },
    showResults: function() {
        // get the position of the input field right now (in case the DOM is shifted)
        var pos = findPos(this.element);
        // either use the specified width, or autocalculate based on form element
        var iWidth = (this.options.width > 0) ? this.options.width : this.element.offsetWidth;
        // reposition
        if ('100%' === this.options.width) {
            this._results.style.top = (pos.y + this.element.offsetHeight) + "px";
            this._results.style.left = pos.x + "px";
            this._results.style.display = 'block';
        } else {
            this._results.style.width = parseInt(iWidth) + "px";
            this._results.style.top = (pos.y + this.element.offsetHeight) + "px";
            this._results.style.left = pos.x + "px";
            this._results.style.display = 'block';
        }
    },
    hideResults: function() {
        var self = this;
        if (this.timeout) clearTimeout(this.timeout);
        this.timeout = setTimeout(function() {
            self.hideResultsNow();
        }, 200);
    },
    hideResultsNow: function() {
        if (this.timeout) clearTimeout(this.timeout);
        removeClass(this.element, this.options.loadingClass);
        //if (this.$results.is(":visible")) {
        this._results.style.display = 'none';
        //}
        if (this.options.mustMatch) {
            var v = this.element.value;
            if (v != this.lastSelected) {
                this.selectItem(null);
            }
        }
    },
    receiveData: function(q, data) {
        if (data) {
            removeClass(this.element, this.options.loadingClass);
            this._results.innerHTML = '';

            if (!this.hasFocus || data.length == 0) return this.hideResultsNow();

            this._results.appendChild(this.dataToDom(data));
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            if (this.options.autoFill && (this.element.value.toLowerCase() == q.toLowerCase())) this.autoFill(data[0][0]);
            this.showResults();
        } else {
            this.hideResultsNow();
        }
    },
    filterData: function(v, items) {
        if (!v) return items;
        var _items = [];
        for (var i = 0, count = items.length; i < count; i++) {
            var label = items[i].label;
            if (label.indexOf(v) > -1)
                _items.push(items[i]);
        }
        return _items;
    },
    receiveData2: function(items) {
        if (items) {
            removeClass(this.element, this.options.loadingClass);
            this._results.innerHTML = '';

            // if the field no longer has focus or if there are no matches, do not display the drop down
            if (!this.hasFocus || items.length == 0) return this.hideResultsNow();

            this._results.appendChild(this.dataToDom2(items));
            this.showResults();
        } else {
            this.hideResultsNow();
        }
    },
    dataToDom2: function(items) {
        var ul = document.createElement("ul");
        var num = items.length;
        var me = this;
        var showMoreMenu = false;

        // limited results to a max number
        if ((this.options.maxItemsToShow > 0) && (this.options.maxItemsToShow < num)) {
            num = this.options.maxItemsToShow;
            if (this.options.moreMenuClick) {
                showMoreMenu = true;
            }
        }

        for (var i = 0; i < num; i++) {
            var item = items[i];
            if (!item) continue;
            var li = document.createElement("li");
            if (this.options.formatItem)
                li.innerHTML = this.options.formatItem(item, i, num);
            else
                li.innerHTML = item.label;
            li.selectValue = item.label;
            li._item = item;
            ul.appendChild(li);
            on(li, 'mouseenter', function() {
                var _li = ul.querySelector('li.ac_over');
                if (_li)
                    removeClass(_li, 'ac_over');
                addClass(this, "ac_over");
                me.active = indexOf(ul.querySelectorAll('li'), this);
            });
            on(li, 'mouseleave', function() {
                removeClass(this, "ac_over");
            });
            on(li, 'mousedown', function(e) {
                stopEvent(e);
                me.selectItem(this);
            });
        }
        if (showMoreMenu) {
            var li = document.createElement("li");
            li.innerHTML = '更多';
            ul.appendChild(li);
            on(li, 'mouseenter', function() {
                var _li = ul.querySelector('li.ac_over');
                if (_li)
                    removeClass(_li, 'ac_over');
                addClass(this, "ac_over");
            });
            on(li, 'mouseleave', function() {
                removeClass(this, "ac_over");
            });
            on(li, 'mousedown', function(e) {
                stopEvent(e);
                me.options.moreMenuClick.call(me);
            });
        }
        return ul;
    },
    parseData: function() {
        if (!data) return null;
        var parsed = [];
        var rows = data.split(this.options.lineSeparator);
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            if (row) {
                parsed[parsed.length] = row.split(this.options.cellSeparator);
            }
        }
        return parsed;
    },
    dataToDom: function(data) {
        var ul = document.createElement("ul");
        var num = data.length;
        var self = this;
        var showMoreMenu = false;

        // limited results to a max number
        if ((this.options.maxItemsToShow > 0) && (this.options.maxItemsToShow < num)) {
            num = this.options.maxItemsToShow;
            if (this.options.moreMenuClick) {
                showMoreMenu = true;
            }
        }

        for (var i = 0; i < num; i++) {
            var row = data[i];
            if (!row) continue;
            var li = document.createElement("li");
            if (this.options.formatItem) {
                li.innerHTML = this.options.formatItem(row, i, num);
                li.selectValue = row[0];
            } else {
                li.innerHTML = row[0];
                li.selectValue = row[0];
            }
            var extra = null;
            if (row.length > 1) {
                extra = [];
                for (var j = 1; j < row.length; j++) {
                    extra[extra.length] = row[j];
                }
            }
            li.extra = extra;
            ul.appendChild(li);
            on(li, 'mouseenter', function() {
                var _li = ul.querySelector('li.ac_over');
                if (_li)
                    removeClass(_li, 'ac_over');
                addClass(this, "ac_over");
                self.active = indexOf(ul.querySelectorAll('li'), this);
            });
            on(li, 'mouseleave', function() {
                removeClass(this, "ac_over");
            });
            on(li, 'mousedown', function() {
                stopEvent(e);
                self.selectItem(this);
            });
        }
        if (showMoreMenu) {
            var li = document.createElement("li");
            li.innerHTML = '更多';
            ul.appendChild(li);
            on(li, 'mouseenter', function() {
                var _li = ul.querySelector('li.ac_over');
                if (_li)
                    removeClass(_li, 'ac_over');
                addClass(this, "ac_over");
            });
            on(li, 'mouseleave', function() {
                removeClass(this, "ac_over");
            });
            on(li, 'mousedown', function(e) {
                stopEvent(e);
                self.options.moreMenuClick.call(self);
            });
        }
        return ul;
    },
    requestData: function() {
        var self = this;
        if (!this.options.matchCase) q = q.toLowerCase();
        var data = this.options.cacheLength ? this.loadFromCache(q) : null;
        // recieve the cached data
        if (data) {
            this.receiveData(q, data);
            // if an AJAX url has been supplied, try loading the data now
        } else if ((typeof this.options.url == "string") && (this.options.url.length > 0)) {
            ajax({
                url: this.makeUrl(q),
                success: function(data) {
                    data = self.parseData(data);
                    self.addToCache(q, data);
                    self.receiveData(q, data);
                }
            });
            // if there's been no data found, remove the loading class
        } else {
            removeClass(this.element, this.options.loadingClass);
        }
    },
    makeUrl: function(q) {
        var url = this.options.url + "?q=" + encodeURI(q);
        for (var i in this.options.extraParams) {
            url += "&" + i + "=" + encodeURI(this.options.extraParams[i]);
        }
        return url;
    },
    loadFromCache: function() {
        if (!q) return null;
        if (this.cache.data[q]) return this.cache.data[q];
        if (this.options.matchSubset) {
            for (var i = q.length - 1; i >= this.options.minChars; i--) {
                var qs = q.substr(0, i);
                var c = this.cache.data[qs];
                if (c) {
                    var csub = [];
                    for (var j = 0; j < c.length; j++) {
                        var x = c[j];
                        var x0 = x[0];
                        if (this.matchSubset(x0, q)) {
                            csub[csub.length] = x;
                        }
                    }
                    return csub;
                }
            }
        }
        return null;
    },
    matchSubset: function(s, sub) {
        if (!this.options.matchCase) s = s.toLowerCase();
        var i = s.indexOf(sub);
        if (i == -1) return false;
        return i == 0 || this.options.matchContains;
    },
    addToCache: function(q, data) {
        if (!data || !q || !this.options.cacheLength) return;
        if (!this.cache.length || this.cache.length > this.options.cacheLength) {
            this.flushCache();
            this.cache.length++;
        } else if (!this.cache[q]) {
            this.cache.length++;
        }
        this.cache.data[q] = data;
    }
});

function findPos(obj) {
    var curleft = obj.offsetLeft || 0;
    var curtop = obj.offsetTop || 0;
    while (obj = obj.offsetParent) {
        curleft += obj.offsetLeft;
        curtop += obj.offsetTop;
    }
    return {
        x: curleft,
        y: curtop
    };
}

function indexOf(element, e) {
    for (var i = 0; i < element.length; i++) {
        if (element[i] == e) return i;
    }
    return -1;
}

if (u.compMgr)
    u.compMgr.regComp({
        comp: Autocomplete,
        compAsString: 'u.Autocomplete',
        css: 'u-autocomplete'
    });

exports.Autocomplete = Autocomplete;

}((this.bar = this.bar || {})));
