;(function ($) {
    //这里放入插件代码
    var RemoteSearchPerformance = function (element, options) {
        this.$element = $(element);
        this.options = $.extend(true, {}, $.fn.remoteSearchPerformance.defaults, options);
        this.id = $(element).attr('id');
        this.ulID = '#' + this.id + '_ul';
        this.ulFoucus = false;

        // Method overrides
        this.render = this.options.render || this.render;
        this.select = this.options.select || this.select;

        this.ajax = $.extend({}, $.fn.remoteSearchPerformance.defaults.ajax, this.options.ajax);

        this.listen();
    }
    
    RemoteSearchPerformance.prototype = {
    	listen: function () {
            this.$element.on('blur', $.proxy(this.blur, this))
                .on('keyup', $.proxy(this.keyup, this));
			
			this.$element.parent('div.remote_wrapper').on('click',this.ulID, $.proxy(this.click, this));
        },
        blur: function (e) {
            var that = this;
            e.stopPropagation();
            e.preventDefault();
            setTimeout(function () {
                if (!that.ulFoucus) {
                    that.$element.val(that.$element.attr('data-name'));
                    that.hide();
                }
            }, 150)
        },
        keyup: function (e) {
            e.stopPropagation();
            e.preventDefault();
            switch (e.keyCode) {
                case 40:
                	// down arrow
                case 38:
                    // up arrow
                    break;
                case 9:
                	// tab
                case 13:
                    // enter
                    this.ajaxer();
                case 27:
                    // escape
                    break;
                default:
                    this.ajaxer();
            }
        },
        hide: function () {
            $(this.ulID).remove();
            return this;
        },
        ajaxer: function () {
            var that = this,
                keyword = that.$element.val();
                busiType = window.typeRadio;
                couType = window.typeCoupe;
            // Query changed
            that.keyword = keyword;
            // Cancel last timer if set
            if (that.ajax.timerId) {
                clearTimeout(that.ajax.timerId);
                that.ajax.timerId = null;
            }

            // Query is good to send, set a timer
            that.ajax.timerId = setTimeout(function() {
                var params = {
                    keyword : keyword,
                    busiType: busiType,
                    couType: couType,
                    bindType: '1,4'
                };
                var jAjax =  $.get;
                // var jAjax = (that.ajax.method === "post") ? $.post : $.get;
                jAjax(that.ajax.url, params, function(data){
                	return that.render(data.rows);
                });
                that.ajax.timerId = null;
            }, that.ajax.timeout);

            return that;
        },
        render: function (data) {
        	this.ulFoucus = false;
            var liList = data || [];
			var num = this._getNum();
			//添加 ul
			if($(this.ulID).length == 0) {
				this.$element.after("<ul id='" + this.id + "_ul' class='remote_search remote_search_top'></ul>");
			};
			//添加li
			var str = "";
			if(num) {
				if(liList.length) {
					for(var i = 0; i < liList.length; i++) {
						str += "<li data-id='"+liList[i].couponId+"' data-name='"+liList[i].title+"' title='"+liList[i].title+"' value='"+liList[i].couponId+"'>" + liList[i].title + "</li>";
					}
				} else {
					str = "<li data-id='' data-name=''>搜索无数据</li>"
				}
			} else {
				this.$element.attr('data-name',"");
				this.$element.attr('data-id',"");
			}
			$(this.ulID).html(str);
			var bodyHeight = $(document.body).height();
			var offsetTop = this.$element.offset().top;
			var height = $(this.ulID).outerHeight(true);
			if(offsetTop + height > bodyHeight){
				$(this.ulID).addClass('remote_search_bottom').removeClass('remote_search_top');
			}else{
				$(this.ulID).addClass('remote_search_top').removeClass('remote_search_bottom');
			}
            return this;
       },
       	click: function (e) {
            e.stopPropagation();
            e.preventDefault();
            var dataName = $(e.target).attr('data-name');
			var dataID = $(e.target).attr('data-id');
			this.$element.val(dataName);
			this.$element.attr('data-name',dataName);
			this.$element.attr('data-id',dataID);
            this.options.chose(dataName,dataID);
            this.ulFoucus = true;
            return this.hide();
       	},
       	_getNum: function(){

       		return this.$element.val().length;
       }
    }
    
    
    $.fn.remoteSearchPerformance = function (option) {
        return this.each(function () {
            var $this = $(this),
                data = $this.data('remoteSearchPerformance'),
                options = typeof option === 'object' && option;

            if (!data) {
                $this.data('remoteSearchPerformance', (data = new RemoteSearchPerformance(this, options)));
            }

            if (typeof option === 'string') {
                data[option]();
            }
        });
    }
    
    $.fn.remoteSearchPerformance.defaults = {
        hiddenVal: '',
        chose: function () { },

        ajax: {
            url: null,
            timeout: 300,
            method: 'get',
            timerId: null
        },
        success: function(res){
        }
    }
    
    $.fn.remoteSearchPerformance.Constructor = RemoteSearchPerformance;
    
})(jQuery);