(function($) {
    $.fn.DhoverClass = function(className) {
        return $(this).hover(function() { $(this).addClass(className); }, function() { $(this).removeClass(className); });
    }
    function getDulyOffset(target, w, h) {
        var pos = target.offset();
        var height = target.outerHeight();
        var newpos = { left: pos.left, top: pos.top + height - 1 }
        var bw = $(document).width();
        var bh = $(document).height();
        if ((newpos.left + w) >= bw) {
            newpos.left = bw - w - 2;
        }
        if ((newpos.top + h) >= bh && bw > newpos.top) {
            newpos.top = pos.top - h - 2;
        }
        return newpos;
    }
    //namespace
    $.ui = $.ui || {};
    $.fn.combobox = function(opts) {
        var combobox = false;
        if (this[0]) combobox = new $.ui.combobox(opts, this[0]);
        return combobox;
    };
    $.ui.combobox = function(o, elem) {
        var options = $.extend({
            vinputid: false,
            cssClass: "t-form-dropdown",
            containerCssClass: "dropdowncontainer",
            dropwidth: 216,
            dropheight: 200,
            autoheight: true,
            initalValue: 1,
            usepager: true,
            selectedchange: false,
            page: 1,
            TextFiled: 'text',
            ValueFiled: 'value',
            rp: 5,
            query: '',
            customFunction: false,
            pageIndexText:'',
            totalPagerText:''
        }, o);
        var me = $(elem).css("width", options.dropwidth);
        this.wrapper = $(elem).wrap("<div/>").parent().addClass("myui-form-div-dropdown");
        var hidden = false;
        if (options.vinputid) { hidden = $("<input type='hidden' />").attr("id", options.vinputid).appendTo(this.wrapper); }
        var picker = $("<div />").appendTo(this.wrapper).addClass("dropicon").css("left", me.width());
        var g = {
            populate: function(flag) {
                if(flag==undefined)
                {
                    flag=true;
                }
                if (!options.newp) options.newp = 1;
                if (options.page > options.pages) options.page = options.pages;
                //搜索关键字
                options.query = me.val();
                var extp = "";
                if(flag==false)
                {
                    options.query="";
                }
                var queryString = "&pageIndex=" + options.page + "&pageSize=" + options.rp + "&searchStr=" + options.query + "&sortname=" + options.sortname + "&sortorder=" + options.sortorder
                //执行自定义函数
                if (options.customFunction && $.isFunction(options.customFunction)) {
                    var data = options.customFunction.call(this, options.rp, options.newp, options.query, options.extParam, options.sortname + " " + options.sortorder);
                    switch (data.result) {
                        case "0":
                        case "1":
                            {
                                g.addData(data);
                                break;
                            }
                        default:
                            {
                                alert("获取数据发生异常;");
                                break;
                            }

                    }

                }
            },
            changePage: function(ctype) { //change page
                switch (ctype) {
                    case 'first': options.newp = 1; break;
                    case 'prev': if (options.page > 1) options.newp = parseInt(options.page) - 1; break;
                    case 'next': if (options.page < options.pages) options.newp = parseInt(options.page) + 1; break;
                    case 'last': options.newp = options.pages; break;
                }
                $('.pageIndex', this.pDiv).text(options.newp);
                $('.totalPages', this.pDiv).html(options.pages);
                if (options.newp == options.page) return false;
                this.populate();

            },
            buildpager: function() {
                $('.pcontrol .pageIndex', this.pDiv).val(options.page);
                $('.pcontrol .totalpages', this.pDiv).html(options.pages);
                var r1 = (options.page - 1) * options.rp + 1;
                var r2 = r1 + options.rp - 1;
                if (options.total < r2) r2 = options.total;
                //控制按键样式
                var btnNext = $(".pNext", this.pDiv); 																//下一页按钮
                var btnPrev = $(".pPrev", this.pDiv); 																//上一页按钮
                var btnFirst = $(".pFirst", this.pDiv); 														    //首页按钮
                var btnLast = $(".pLast", this.pDiv);
                var currentPageIndex = options.page;
                var totalPage = options.pages;
                if (currentPageIndex == 1 && totalPage == 1) {
                    btnNext.removeClass("pNextdisabled").addClass("pNextdisabled");
                    btnPrev.removeClass("pPrevdisabled").addClass("pPrevdisabled");
                    btnFirst.removeClass("pFirstdisabled").addClass("pFirstdisabled");
                    btnLast.removeClass("pLastdisabled").addClass("pLastdisabled");
                }
                else if (currentPageIndex == totalPage) {
                    btnNext.removeClass("pNextdisabled").addClass("pNextdisabled");
                    btnPrev.removeClass("pPrevdisabled");
                    btnFirst.removeClass("pFirstdisabled");
                    btnLast.removeClass("pLastdisabled").addClass("pLastdisabled");
                } else if (currentPageIndex == 1) {

                    btnNext.removeClass("pNextdisabled");
                    btnPrev.removeClass("pPrevdisabled").addClass("pPrevdisabled");
                    btnFirst.removeClass("pFirstdisabled").addClass("pFirstdisabled");
                    btnLast.removeClass("pLastdisabled");

                } else {
                    btnNext.removeClass("pNextdisabled");
                    btnPrev.removeClass("pPrevdisabled");
                    btnFirst.removeClass("pFirstdisabled");
                    btnLast.removeClass("pLastdisabled");
                }

            },
            SelectedChanged: function(t) {
                var b = true;
                me.val(t[options.TextFiled]);
                if (hidden && t[options.ValueFiled]) {
                    hidden.val(t[options.ValueFiled]);
                    options.initalValue = t[options.ValueFiled];
                }
                if (options.selectedchange && $.isFunction(options.selectedchange)) {

                    options.selectedchange.apply(me, [t]);
                }
                g.gDiv.hide();
            },
            processKey: function(e) {
                if (
					(/27$|38$|40$|^9$/.test(e.keyCode) && g.gDiv.is(':visible')) ||
					(/^37$|39$|13$|^9$/.test(e.keyCode)) || /40$/.test(e.keyCode)
				) {
                    if (e.preventDefault) e.preventDefault();
                    if (e.stopPropagation) e.stopPropagation();
                    e.cancelBubble = true;
                    e.returnValue = false;
                    switch (e.keyCode) {
                        case 37: // left

                            break;

                        case 38: // up

                            break;

                        case 39: // right

                            break;

                        case 40: // down

                            break;

                        case 9:  // tab

                            break;

                        case 13: // return

                            break;

                        case 27: //	escape

                            break;
                    }

                }
                else {
                    options.newp = 1;
                    g.populate();
                    var pos = getDulyOffset(me, options.dropwidth, options.dropheight);
                    g.gDiv.css(pos);
                    g.gDiv.show();
                    if ($.browser.msie) {
                        if (parseFloat($.browser.version) <= 6) {
                            var h = g.gDiv.height();
                            if (h > options.dropheight) {
                                g.gDiv.height(options.dropheight);
                            }
                        }
                    }

                    $(document).one("click", function(event) { g.gDiv.hide(); });
                    return false;
                }
            },

            addData: function(data) {
                if (!data) {
                    return false;
                }
                var temp = options.total;
                if (data.result == "0") {
                    options.total = 0;
                }
                else {
                    options.total = data.table[0].AllCount;
                    
                }
                if (options.total < 0) {
                    options.total = temp;
                }
                if (options.total == 0) {
                    options.pages = 1;
                    options.page = 1;
                    this.buildpager();
                    g.bDiv.empty();
                    return false;
                }
                options.pages = Math.ceil(options.total / options.rp);
              
                options.page = data.pageIndex;
                this.buildpager();
                var p = this.target;
                var ul = $("<ul/>");
                if (data.table && data.table.length > 0) {
                    $.each(data.table, function() {
                        var item = this
                        var li = $("<li/>").hover(function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); }).html(item[options.TextFiled])
                            .click(function() { g.SelectedChanged(item); });
                        ul.append(li);

                        if (options.initalValue && options.initalValue == item[options.ValueFiled]) {
                            li.addClass("selected");
                        }
                    });
                }

                $("li:last", ul).css("border", "0px");
                g.bDiv.empty().append(ul);
            }


        };
        if (options.dropwidth) {
            options.dropwidth = (me.outerWidth() > 2 ? me.outerWidth() - 2 : me.outerWidth());
        }

        g.gDiv = $("<div/>"); //create global container
        g.bDiv = $("<div/>"); //create body container
        g.pDiv = $("<div/>"); //create pager
        g.gDiv.addClass("myui-form-dropdown-container")
                           .css({ position: "absolute", "z-index": "999", width: options.dropwidth + 9, display: "none", "border": "solid 1px #B5B8C8" }).append(g.bDiv).append(g.pDiv)
                           .click(function(event) { event.stopPropagation(); })
                           .appendTo($("body"));
        if (options.autoheight) {

            g.gDiv.css("max-height", options.dropheight);
        }
        else {
            g.gDiv.css("height", options.dropheight);
        }
        ///////////pager///////////////////
        if (options.usepager) {
            g.pDiv.addClass("pDiv").html("<div class=\"pDiv2\"></div>");
            var html = '<div class="pGroup"><div class="pFirst pButton" title="转到第一页"></div><div class="pPrev pButton" title="转到上一页"></div> </div><div class="pGroup"><span class="pcontrol">' + options.pageIndexText + '<span class="pageIndex">1</span>/' + options.totalPagerText + '<span class="totalpages"> 1 </span></span></div><div class="pGroup"> <div class="pNext pButton" title="转到下一页"><span></span></div><div class="pLast pButton" title="转到最后一页"><span></span></div></div>';
            $('div', g.pDiv).html(html);
            $('.pFirst', g.pDiv).click(function() { g.changePage('first'); });
            $('.pPrev', g.pDiv).click(function() { g.changePage('prev'); });
            $('.pNext', g.pDiv).click(function() { g.changePage('next'); });
            $('.pLast', g.pDiv).click(function() { g.changePage('last'); });
            if ($.browser.msie && $.browser.version < 7) $('.pButton', g.pDiv).hover(function() { $(this).addClass('pBtnOver'); }, function() { $(this).removeClass('pBtnOver'); });
        }
        $(g.pDiv).append("<div style='clear:both'></div>");
        /////////////end pager/////////////////////

        if ($.browser.msie) {
            if (parseFloat($.browser.version) <= 6) {
                g.gDiv.bgiframe();
            }
        }
        $(picker).click(function() {
            options.query="";
            options.newp = 1;
            g.populate(false);
            var pos = getDulyOffset(me, options.dropwidth, options.dropheight);
            g.gDiv.css(pos);
            g.gDiv.show();
            if ($.browser.msie) {
                if (parseFloat($.browser.version) <= 6) {
                    var h = g.gDiv.height();
                    if (h > options.dropheight) {
                        g.gDiv.height(options.dropheight);
                    }
                }
            }

            $(document).one("click", function(event) { g.gDiv.hide(); });
            return false;
        });
        $(me).mousedown(function(ev) { ev.stopPropagation(); }).mouseup(function(ev) {
            this.focus();
            ev.stopPropagation();
        }).keyup(g.processKey);


    }

})(jQuery);