﻿$(function() {
    var ui_dropdownlist = $(".ui-dropdownlist");
    $(document.body).click(function() {
        ui_dropdownlist.each(function(i) {
            $("#" + $(this).attr("name")).css("visibility", "hidden");
        });
    });

    ui_dropdownlist.each(function(i) {
        var e1 = $(this);
        var e2 = $("#" + e1.attr("name"));
        var e3 = $("input[name=" + e1.attr("name") + "]");

        e1.mouseover(function() {
            e1.addClass("ui-dropdownlist_hover");
            window.event.cancelBubble = true;
        });

        e1.mouseout(function() {
            e1.removeClass("ui-dropdownlist_hover");
            window.event.cancelBubble = true;
        });

        e1.children("img").click(function() {
            var close = e2.css("visibility") == "visible";
            ui_dropdownlist.each(function(i) {
                $("#" + $(this).attr("name")).css("visibility", "hidden");
            });
            if (close) return;

            var pos = e1.offset();
            if (e2.children("p").length <= 0)
                return;

            if (e2.attr("first") != "false") {
                var width = e2.attr("offsetWidth") > e1.attr("offsetWidth") ? e2.attr("offsetWidth") : e1.attr("offsetWidth");
                e2.css("width", width - 12 + "px");

                e2.css("left", pos.left + e1.attr("offsetWidth") - e2.attr("offsetWidth"));
                e2.css("top", pos.top + e1.attr("offsetHeight") - 23);
                e2.children("p").each(function(i) {
                    if ($(this).attr("offsetWidth") < width - 16)
                        $(this).css("width", width - 16 + "px");
                });
                e2.attr("first" ,"false");
            }
            e2.css("visibility", "visible");
            window.event.cancelBubble = true;

            e2.children("p").each(function(i, ui) {
                var e4 = $(this);
                if (!ui.onmouseover) {
                    ui.onmouseover = function() {
                        e4.addClass("ui-dropdownlist-item-p_hover");
                        window.event.cancelBubble = true;
                    };
                }
                if (!ui.onmouseout) {
                    ui.onmouseout = function() {
                        e4.removeClass("ui-dropdownlist-item-p_hover");
                        window.event.cancelBubble = true;
                    };
                }

                e4.one("click", function() {
                    $($(this).prevAll("input[type=hidden]")).val($(this).val());
                    e1.children("p").html($(this).html());
                    e2.css("visibility", "hidden");
                    window.event.cancelBubble = true;
                });
            });
        });
    });
});

