/**
*combotree控件
*
*/

(function ($) {

    function init(target) {

        var options = $.data(target, "cihoComboTree").options;
        if (options.disabled == true) {
            $("#" + target.id).attr("readonly", true);
        }
        else {
            $("#" + target.id).attr("readonly", false);
        }
        $("#" + target.id).width(options.width);

        //生成层
        //$(".ciho_Tree").remove();
        var div = $('<div class="ciho-Tree"></div>');

        $("body").append(div);

        if (options.showBox == true) {
            var box = $('<span id="' + target.id + 'ciho-combo-arrow" class="ciho-combo-arrow" z-index="' + options.index + '"></span>');
            $(target).after(box);
        }

        //添加样式
        //        if (options.showBox == true) {
        //            div.css("width", options.width + 5 + options.boxWidth)
        //        }
        //        else {
        //            div.css("width", options.width);
        //        }
        div.css("height", options.height);
        div.css("z-index", options.index);
        return {
            cihoComboTree: div
        }
    }

    function getValue(target) {
        var div = $.data(target, 'cihoComboTree').cihoComboTree;

        var value = div.find("div.ciho-tree-node-selected").eq(0).attr("node-id");
        if (value == undefined) {
            return "";
        }
        else {
            return value;
        }
    }

    function getText(target) {
        var text = $("#" + target.id).val();
        if (text == undefined) {
            return "";
        }
        else {
            return text;
        }
    }

    function getBH(target) {
        var div = $.data(target, 'cihoComboTree').cihoComboTree;
        var strBH = "";
        div.find("div").each(function () {
            if ($(this).is(".ciho-tree-node-selected") == true) {
                strBH = $(this).attr("node-bh") + "";
            }
        });
        return strBH == "undefined" ? "" : strBH;
    }

    function setValue(target, param) {
        var div = $.data(target, 'cihoComboTree').cihoComboTree;
        div.find("div").each(function () {
            if ($(this).attr("node-id") == param) {
                div.find("div").removeClass("ciho-tree-node-selected");
                $(this).addClass("ciho-tree-node-selected");
                $("#" + target.id).val($(this).text());
                return false;
            }
        });
    }

    function setText(target, param) {
        var div = $.data(target, 'cihoComboTree').cihoComboTree;
        var options = $.data(target, 'cihoComboTree').options;
        $("#" + target.id).val("");

        if (options.showMode == "normal") {
            $("#" + target.id).val(param);
        }
        else {
            var strKmmc = "";
            $("div.ciho-tree-node-selected", div).parent().parent().parentsUntil(".ciho-Tree").filter("li").each(function () {
                if (strKmmc != "") {
                    strKmmc = $(this).children("div:first").text() + "-" + strKmmc;
                }
                else {
                    strKmmc = $(this).children("div:first").text();
                }
            });
            if (strKmmc != "") {
                strKmmc = strKmmc + "-" + $(".ciho-tree-node-selected:eq(0)", div).text();
            }
            else {
                strKmmc = param;
            }
            //去掉最顶级的节点
            if (options.showMode == "noTop") {
                strKmmc = strKmmc.substr(strKmmc.indexOf("-") + 1, strKmmc.length);
            }
            $("#" + target.id).val(strKmmc);
        }
        //隐藏层
        hidePanel(div);
    }

    function showPanel(target) {

        //关闭所有panel
        $(".layoutpanel").css("display", "none");
        //$(".combo-panel").css("display", "none");
        $(".ciho-Tree").css("display", "none");
        $(".ui-datepicker").css("display", "none");

        var div = $.data(target, 'cihoComboTree').cihoComboTree;
        var offset = $(target).offset();
        offset.top += $("#" + target.id).outerHeight();
        div.css("left", offset.left);
        div.css("top", offset.top);
        div.show();

        $(document).bind("mousedown.cihoComboTree", function (event) {
            if (event.target.className != undefined && event.target.className.indexOf("tree") == '-1' && event.target.className != "ciho-Tree") {
                hidePanel(div);
            }
        });
    }

    function hidePanel(target) {
        target.hide();
        $(document).unbind("mousedown.cihoComboTree");
    }

    function orgData(target, param, level) {
        var strHtml = '';
        for (var i = 0; i < param.length; i++) {
            strHtml += "<li>";
            strHtml += "<div  class=\"ciho-tree-node ";

            if (param[i].selected == true) {
                strHtml += "ciho-tree-node-selected";
                $("#" + target.id).val(param[i].text);
            }
            strHtml += " \" ";
            if (param[i].children) {
                strHtml += "  parent =true ";
            }
            strHtml += " node-id=\"" + param[i].id + "\" ";
            strHtml += " node-bh='" + param[i].bh + "' >";
            //加缩进
            for (var j = 0; j < level; j++) {
                strHtml += "<span class=\"ciho-tree-indent\">";
                strHtml += "</span>";
            }
            //加Icon
            if (param[i].children) {
                strHtml += "<span class=\"ciho-tree-expanded\">";
                strHtml += "</span>";
            }
            else {
                strHtml += "<span class=\"ciho-tree-indent\">";
                strHtml += "</span>";
            }
            strHtml += "<span class=\"ciho-tree-title\">";
            strHtml += param[i].text;
            strHtml += "</span>";
            strHtml += "</div>";
            if (param[i].children) {
                strHtml += "<ul>";
                strHtml += orgData(target, param[i].children, (level + 1));
                strHtml += "</ul>";
            }
            strHtml += "</li>";
        }
        return strHtml;
    }

    function loadData(target, param) {
        var div = $.data(target, 'cihoComboTree').cihoComboTree;
        var options = $.data(target, 'cihoComboTree').options;

        //清空里面的数据
        div.empty();

        var strUL = "<ul>";
        strUL += orgData(target, param, 0);
        strUL += "</ul>";
        div.append(strUL);
        if (div.find("div").is(".ciho-tree-node-selected") == false) {
            div.find("div").eq(0).addClass("ciho-tree-node-selected");
            $("#" + target.id).val(div.find("div").eq(0).text());
        }

        //绑定事件
        div.find("div").mouseover(function () {
            div.children("div").removeClass("ciho-tree-node-hover");
            $(this).addClass("ciho-tree-node-hover");
        });
        div.find("div").mouseout(function () {
            $(this).removeClass("ciho-tree-node-hover");
        });
        div.find("div").click(function (event) {
            //选中节点

            if ($(this).next().css("display") == "none") {
                $(this).next().show();
                if ($(this).attr("parent") == "true") {
                    $(this).find("span.ciho-tree-collapsed").addClass("ciho-tree-expanded");
                    $(this).find("span.ciho-tree-collapsed").removeClass("ciho-tree-collapsed");
                }
            }
            else {
                $(this).next().hide();
                if ($(this).attr("parent") == "true") {
                    $(this).find("span.ciho-tree-expanded").addClass("ciho-tree-collapsed");
                    $(this).find("span.ciho-tree-expanded").removeClass("ciho-tree-expanded");
                }
            }

            //是否能够选中父节点
            if (options.mode == "child") {
                if ($(this).attr("parent") == "true") {
                    event.stopPropagation();
                    $(document).trigger("mousedown.hasDatepicker");
                }
                else {
                    div.find("div").removeClass("ciho-tree-node-selected");
                    $(this).addClass("ciho-tree-node-selected");
                    setText(target, $(this).text());
                }
            }
            else if (options.mode == "all") {
                div.find("div").removeClass("ciho-tree-node-selected");
                $(this).addClass("ciho-tree-node-selected");
                setText(target, $(this).text());
            }

            //事件
            options.onSelect.call(target, { dm: $(this).attr("node-id"), mc: $(this).text(), bh: $(this).attr("node-bh") });
        });

        //调整下拉列表层的宽度，比文本框宽度小时，设定其跨度与文本框宽度相同
        var iItemWidth = 0;
        if (options.showBox == true) {//有下拉箭头
            if (div.width() < options.width + 5 + options.boxWidth) {
                iItemWidth = options.width + 5 + options.boxWidth;
            }
            else {
                iItemWidth = div.width();
                div.find('div').each(function () {
                    $(this).width();
                });
            }
        }
        else {
            if (div.width() < options.width) {
                iItemWidth = options.width;
            }
            else {
                div.find('div').each(function () {
                    iItemWidth = div.width();
                });
            }
        }
        //设定所有选项的宽度。
        div.find('div').each(function () {
            $(this).width(iItemWidth);
        });
        //隐藏下拉列表层
        hidePanel(div);
    }

    function focus(target) {
        showPanel(target);
        $.data(target, "cihoComboTree").options.onfocus.call(target);
    }

    function bindEvent(target) {
        var div = $.data(target, 'cihoComboTree').cihoComboTree;
        var options = $.data(target, "cihoComboTree").options;

        $("#" + target.id).unbind("click");
        $(document).unbind("mousedown.cihoComboTree");
        $("#" + target.id).unbind("keydown.cihoComboTree");
        $("#" + target.id).unbind("focus");

        $("#" + target.id).bind("click", function (event) {
            $(document).triggerHandler("mousedown");
            showPanel(target);
            event.stopPropagation();
        }).bind("keydown.cihoComboTree", function (e) {
            if (e.keyCode == 9 || e.keyCode == 27 || e.keyCode == 13) { //tab键
                hidePanel(div);
            }
        });

        $("#" + target.id).bind("focus", function () {
            focus(this);
        });

        $(document).bind("mousedown.cihoComboTree", function (event) {
            if (event.target.className != undefined && event.target.className.indexOf("tree") == '-1' && event.target.className != "ciho-Tree") {
                hidePanel(div);
            }
        });

        //下拉箭头的绑定
        if (options.showBox == true) {
            $("#" + target.id + "ciho-combo-arrow").unbind();
            $("#" + target.id + "ciho-combo-arrow").bind("click", function () {
                showPanel(target);
            });
        }
    }

    $.fn.cihoComboTree = function (options, param) {
        if (typeof options == "string") {
            switch (options) {
                case "setValue":
                    return this.each(function () {
                        setValue(this, param);
                    });
                case "getValue":
                    return getValue(this[0]);
                case "getText":
                    return getText(this[0]);
                case "getBH":
                    return getBH(this[0]);
                case "setText":
                    return this.each(function () {
                        setText(this, param);
                    });
                case "loadData":
                    return this.each(function () {
                        loadData(this, param);
                    });
                case "focus":
                    return focus(this[0]);

            }
        }
        options = options || {};
        return this.each(function () {
            var state = $.data(this, 'cihoComboTree');
            if (state) {
                $.extend(state.options, options);
            }
            else {
                state = $.data(this, 'cihoComboTree', {
                    options: $.extend({}, $.fn.cihoComboTree.defaults, options)
                });
                var r = init(this);
                $.data(this, 'cihoComboTree', {
                    options: state.options,
                    cihoComboTree: r.cihoComboTree
                });
            }
            //绑定事件
            bindEvent(this);
        });

    };

    $.fn.cihoComboTree.defaults = {
        width: 150,
        height: 200,
        disabled: true,
        index: 9999999,
        showBox: true,
        boxWidth: 24,
        mode: "child", //all:都能选中，child:只有子节点能选中
        showMode: "noTop", // all:显示顶级到该节点所有的文本，noTop:不显示顶级, normal:只显示当前节点
        onSelect: function (record) { },
        //onChange: function (newValue, oldValue) { },
        onfocus: function () { }
        //onblur: function () { }
    };

})(jQuery);