﻿function PopupControl(namePrefix) {
    var _this = this;
    _this.Id = namePrefix + "divPopup";
    _this.IsInit = false;
    _this.DefaultText = "请选择";
    _this.Level = 2; //默认为显示2层的数据。
    _this.SelectedCount = 5; //最多选择几项，默认为5个。
    _this.ColumnNum = 3;
    _this.SelectedColumnNum = 2;
    _this.Prefix = "";
    _this.RootDataUrl = "";
    _this.ChildDataUrl = "";
    _this.SelectedValueUrl = "";
    _this.PopWindow = null;
    _this.TitleDiv = null; //窗口标题。
    _this.RootDataDiv = null;
    _this.ChildTitleDiv = null;
    _this.ChildDataDiv = null;
    _this.SelectedTitleDiv = null;
    _this.SelectedDataDiv = null;
    _this.OperationDiv = null;
    _this.SelectedTitleContainer = null;
    _this.SelectedTitle = "您选择的是：";
    _this.BtnOK = null;
    _this.BtnCancel = null;
    _this.BtnReset = null;
    _this.DisplayContainer = null; //显示选中框。    
    _this.RootControl = null;
    _this.RootControlTagName = "select";
    _this.ChildControlTagName = "";
    _this.SelectedValue = "";
    _this.SelectedName = "";
    _this.showTimer = null;
    _this.hideTimer = null;
    
    {
        _this.Prefix = namePrefix;

        _this.DisplayContainer = document.getElementById(namePrefix + "divSelected");
        
        _this.PopWindow = document.createElement("div");
        _this.PopWindow.setAttribute("id", namePrefix + "divPopup");
        _this.PopWindow.className = "popWindow";
        _this.PopWindow.style.display = "none";
        _this.PopWindow.style.top = 0;
        _this.PopWindow.style.left = 0;

        _this.TitleDiv = document.createElement("div");
        _this.TitleDiv.setAttribute("id", namePrefix + "divTitle");
        _this.TitleDiv.className = "Title";
        _this.TitleDiv.appendChild(document.createTextNode(_this.DefaultText));

        _this.BtnCancel = document.createElement("a");
        _this.BtnCancel.setAttribute("id", namePrefix + "btnCancel");
        _this.BtnCancel.setAttribute("href", "javascript:void(0);");
        _this.BtnCancel.setAttribute("onclick", "javascript:Close();");
        //_this.BtnCancel.appendChild(document.createTextNode("×"));
        _this.TitleDiv.appendChild(_this.BtnCancel);
        _this.PopWindow.appendChild(_this.TitleDiv);

        _this.OperationDiv = document.createElement("div");
        _this.SelectedTitleContainer = document.createElement("span");
        _this.SelectedTitleContainer.appendChild(document.createTextNode(_this.SelectedTitle));
        _this.OperationDiv.appendChild(_this.SelectedTitleContainer);
        _this.OperationDiv.className = "Operation";
        _this.BtnReset = document.createElement("input");
        _this.BtnReset.setAttribute("id", namePrefix + "btnReset");
        _this.BtnReset.setAttribute("type", "button");
        _this.BtnReset.setAttribute("value", "清空");
        _this.OperationDiv.appendChild(_this.BtnReset);
        _this.BtnOK = document.createElement("input");
        _this.BtnOK.setAttribute("id", namePrefix + "btnOk");
        _this.BtnOK.setAttribute("type", "button");
        _this.BtnOK.setAttribute("value", "确定");
        _this.OperationDiv.appendChild(_this.BtnOK);

        _this.PopWindow.appendChild(_this.OperationDiv);

        _this.SelectedDataDiv = document.createElement("div");
        _this.SelectedDataDiv.setAttribute("id", namePrefix + "divSelectedData");
        _this.SelectedDataDiv.className = "SelectedDataDiv";
        _this.PopWindow.appendChild(_this.SelectedDataDiv);
        
        _this.RootDataDiv = document.createElement("div");
        _this.RootDataDiv.setAttribute("id", namePrefix + "divRootData");
        _this.RootDataDiv.className = "RootDataDiv";
        _this.PopWindow.appendChild(_this.RootDataDiv);

        _this.DisplayContainer.onclick = function() {
            Show();
        }

        _this.BtnOK.onclick = function() {
            SelectOk();
        }

        _this.BtnCancel.onclick = function() {
            Close();
        }

        _this.BtnReset.onclick = function() {
            RemoveSelectedAll();
        }
        
        document.forms[0].appendChild(_this.PopWindow); //必须在初始化时执行，不然获取不到SelectedValue
    }

    _this.InitRootData = function() {
        var ul = document.createElement("ul");
        var li = null;
        var rootControl;
        var rootLabel;
        var rootDataArray = GetJsonData(_this.RootDataUrl);
        if (rootDataArray == null) return;
        for (var index = 0; index < rootDataArray.length; index++) {
            li = document.createElement("li");

            li.style.width = 100 / _this.ColumnNum + "%";
            rootControl = document.createElement("input");
            rootControl.setAttribute("id", _this.Prefix + "rootData");
            rootControl.setAttribute("name", _this.Prefix + "rootData");
            rootControl.setAttribute("type", "checkbox");
            rootControl.setAttribute("value", rootDataArray[index].Value);
            rootControl.className = "RootData";
            rootControl.defaultChecked = IsSelected(rootDataArray[index].Value);

            rootControl.onclick = function() {
                Select(this);
            }

            li.onmouseover = function() {
                this.style.backgroundColor = "#E4ECF3";
                ShowChild(this);
            }

            li.onmouseout = function() {
                this.style.backgroundColor = "#FFFFFF";
                HideChild(this);
            }

            rootLabel = document.createTextNode(rootDataArray[index].Name);
            li.appendChild(rootControl);
            li.appendChild(rootLabel);
            ul.appendChild(li);
        }
        _this.RootDataDiv.appendChild(ul);
        _this.IsInit = true;
    }
    
    _this.GetDisplayText = function() {
        var str = "";
        switch (_this.DisplayContainer.nodeName.toLowerCase()) {
            case "input":
                str = _this.DisplayContainer.value;
                break;
            default:
                str = _this.DisplayContainer.innerHTML;
        }
        return str;
    }
    
    _this.SetDisplayText = function(strValue) {
        switch (_this.DisplayContainer.nodeName.toLowerCase()) {
            case "input":
                _this.DisplayContainer.value = strValue;
                break;
            default:
                _this.DisplayContainer.innerHTML = strValue;
        }
        _this.DisplayContainer.title = _this.DisplayContainer.innerHTML;
    }

    _this.SetSelectedValue = function(selectedValue) {
        _this.SelectedValue = selectedValue;
        var list = GetJsonData(_this.SelectedValueUrl + selectedValue);
        if (list == null) return;

        _this.SelectedName = "";
        _this.SelectedDataDiv.innerHTML = "";
        for (var i = 0; i < list.length; i++) {
            if (_this.SelectedName.length == 0) {
                _this.SelectedName = list[i].Name;
            } else {
                _this.SelectedName += "," + list[i].Name;
            }

            //初始化已选择数据
            var selectedData = document.createElement("input");
            selectedData.setAttribute("id", _this.Prefix + "selectedData");
            selectedData.setAttribute("name", _this.Prefix + "selectedData");
            selectedData.setAttribute("type", "checkbox");
            selectedData.setAttribute("value", list[i].Value);
            selectedData.className = "SelectedData";
            selectedData.defaultChecked = true;

            selectedData.onclick = function() {
                RemoveSelected(this);
            }

            var _label = document.createElement("label");
            _label.style.cursor = "pointer";
            _label.className = "SelectedDataLabel";
            _label.appendChild(selectedData);
            _label.appendChild(document.createTextNode(list[i].Name));

            _this.SelectedDataDiv.appendChild(_label);
        }
        _this.SetDisplayText(_this.SelectedName);
        //        _this.DisplayContainer.innerHTML = "";
        //        _this.DisplayContainer.appendChild(document.createTextNode(_this.SelectedName));
        //        _this.DisplayContainer.title = _this.SelectedName;
    }
    
    var GetChildDataList = function() {
        var selectedDataList = _this.ChildDataDiv.getElementsByTagName("input");
        return selectedDataList;
    },

    GetSelectedDataList = function() {
        var selectedDataList = _this.SelectedDataDiv.getElementsByTagName("input");
        return selectedDataList;
    },

    GetJsonData = function(url) {
        var xmlhttp;
        if (document.all)
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        else
            xmlhttp = new XMLHttpRequest();

        xmlhttp.open("GET", url, false);
        xmlhttp.send("");
        var jsonStr = xmlhttp.responseText;
        var data;
        try {
            data = JSON.parse(jsonStr);
        } catch (e) {
            data = null;
        }
        return data;
    },
    
    ShowChild = function(parentControl) {
        var childDataLayer,
        childControl,
        childLabel,
        childWidth;
        if (parentControl.lastChild.nodeType === 1) {
            childDataLayer = parentControl.lastChild;
            childDataLayer.style.display = "block";
            var childDataList = childDataLayer.getElementsByTagName("input");
            for (var i = 0; i < childDataList.length; i++) {
                childDataList[i].checked = IsSelected(childDataList[i].value)
            }
            return;
        }

        var childDataArray = GetJsonData(_this.ChildDataUrl + parentControl.firstChild.value);
        if (childDataArray == null || childDataArray.length == 0) return;

        var ul = document.createElement("ul");
        var li = null;
        for (var index = 0; index < childDataArray.length; index++) {
            li = document.createElement("li");
            childControl = document.createElement("input");
            childControl.setAttribute("id", _this.Prefix + "childData");
            childControl.setAttribute("name", _this.Prefix + "childData");
            childControl.setAttribute("type", "checkbox");
            childControl.setAttribute("value", childDataArray[index].Value);
            childControl.className = "ChildData";
            //childControl.disabled = parentControl.firstChild.checked;
            childControl.defaultChecked = IsSelected(childDataArray[index].Value);
            
            childControl.onclick = function() {
                Select(this);
            }

            childLabel = document.createTextNode(childDataArray[index].Name);
            li.appendChild(childControl);
            li.appendChild(childLabel);
            ul.appendChild(li);
        }

        childDataLayer = document.createElement("div");
        childDataLayer.className = "ChildDataDiv";
        childDataLayer.appendChild(ul);

        if (childDataArray.length < 3) {
            childDataLayer.style.width = childDataArray.length * 95 + "px";
        }

        parentControl.appendChild(childDataLayer);
        childDataLayer.style.display = "block";        
        if (!IsIE6()) {
            childDataLayer.style.top = parentControl.offsetTop + "px";
            childDataLayer.style.left = parentControl.offsetLeft + parentControl.offsetWidth / 2 + "px";
        } else {
            childDataLayer.style.top = parentControl.offsetTop + "px";
            childDataLayer.style.left = parentControl.offsetLeft + (_this.PopWindow.offsetWidth/_this.ColumnNum/2) + "px";
        }
    },

    HideChild = function(parentControl) {
        if(parentControl.lastChild.style!=undefined&&parentControl.lastChild.style!=null)
            parentControl.lastChild.style.display = "none";
    },

    IsSelected = function(dataValue) {
        //用于同步已经选中的项。
        var selectedDataList = GetSelectedDataList();
        var isSelected = false;
        for (var i = 0; i < selectedDataList.length; i++) {
            if (selectedDataList[i].value == dataValue) {
                isSelected = true;
                break;
            }
        }
        return isSelected;
    },

    GetRootName = function(rootValue) {
        for (var i = 0; i < _this.RootControl.options.length; i++) {
            if (_this.RootControl.options[i].value == rootValue) {
                return _this.RootControl.options[i].text;
                break;
            }
        }
        return "";
    },

    Select = function(obj) {
        var selectedDataList = GetSelectedDataList();
        var needAdd = true;
        for (var i = 0; i < selectedDataList.length; i++) {

            if (selectedDataList[i].value == obj.value) {
                if (obj.checked) {
                    needAdd = false;
                    break;
                } else {
                    needAdd = false;
                    //_this.SelectedDataDiv.removeChild(selectedDataList[i].nextSibling);
                    _this.SelectedDataDiv.removeChild(selectedDataList[i].parentNode);
                }
            }
        }
        
        if (needAdd) {
            ValidateSelected(obj);
            
            if (selectedDataList.length >= _this.SelectedCount) {
                obj.checked = false;
                alert("最多选择" + _this.SelectedCount + "项。");
            }
            else {
                AddToSelected(obj);
            }
        }
    },
    
    //选择父类则取消全部子类
    ValidateSelected = function(obj) {
        if(obj.parentNode.childNodes.length == 3) {
            var childDataList = obj.parentNode.lastChild.getElementsByTagName("input");
            for (var i = 0; i < childDataList.length; i++) {
                if(childDataList[i].checked = true) {
                    childDataList[i].checked = false;
                    RemoveSelected(childDataList[i]);
                }
            }
        } else if(obj.className == "ChildData") { 
            RemoveSelected(obj.parentNode.parentNode.parentNode.parentNode.firstChild);
        }
    },       
    
    AddToSelected = function(obj) {
        var selectedData = document.createElement("input");
        selectedData.setAttribute("id", _this.Prefix + "selectedData");
        selectedData.setAttribute("name", _this.Prefix + "selectedData");
        selectedData.setAttribute("type", "checkbox");
        selectedData.setAttribute("value", obj.value);
        selectedData.className = "SelectedData";
        selectedData.defaultChecked = obj.checked;

        selectedData.onclick = function() {
            RemoveSelected(this);
        }
        
        var _label = document.createElement("label");
        _label.style.cursor = "pointer";
        _label.className = "SelectedDataLabel";
        _label.appendChild(selectedData);
        _label.appendChild(document.createTextNode(obj.nextSibling.nodeValue));
        
//        _label.onmouseover = function() {
//            this.style.backgroundColor = "#3D62A6";
//            this.style.color = "#ffffff";
//        }
//        _label.onmouseout = function() {
//            this.style.backgroundColor = "#E4ECF3";
//            this.style.color = "#000000";
//        }
            
        _this.SelectedDataDiv.appendChild(_label);
    },

    RemoveSelected = function(obj) {
        var selectedDataList = GetSelectedDataList();
        for (var i = 0; i < selectedDataList.length; i++) {
            if (selectedDataList[i].value == obj.value) {
                _this.SelectedDataDiv.removeChild(selectedDataList[i].parentNode);

                var rootDataList = _this.RootDataDiv.getElementsByTagName("input");
                for (var j = 0; j < rootDataList.length; j++) {
                    //rootDataList[j].disabled = false;
                    if (rootDataList[j].value == obj.value) {
                        rootDataList[j].checked = false;
                    }
                }
            }
        }
    },

    RemoveSelectedAll = function() {
        var selectedDataList = GetSelectedDataList();
        for (var i = selectedDataList.length - 1; i > -1; i--) {
            _this.SelectedDataDiv.removeChild(selectedDataList[i].parentNode);

            var rootDataList = _this.RootDataDiv.getElementsByTagName("input");
            for (var j = 0; j < rootDataList.length; j++) {
                //rootDataList[j].disabled = false;
                rootDataList[j].checked = false;
            }
        }
        _this.SetDisplayText(_this.DefaultText);
        //_this.DisplayContainer.innerHTML = _this.DefaultText;
    },

    SelectOk = function() {
        var SelectedValueName = "";
        _this.SelectedValue = "";
        var tagList = GetSelectedDataList();

        for (var i = 0; i < tagList.length; i++) {
            if (SelectedValueName.length == 0) {
                SelectedValueName = tagList[i].nextSibling.nodeValue;
                _this.SelectedValue = tagList[i].value;
            } else {
                SelectedValueName += "," + tagList[i].nextSibling.nodeValue;
                _this.SelectedValue += "," + tagList[i].value;
            }
        }
        if (SelectedValueName != "")
            _this.SetDisplayText(SelectedValueName);
        else
            _this.SetDisplayText(_this.DefaultText);
        //        _this.DisplayContainer.innerHTML = "";
        //        if(SelectedValueName!="") {
        //            _this.DisplayContainer.appendChild(document.createTextNode(SelectedValueName));
        //        } else {
        //            _this.DisplayContainer.appendChild(document.createTextNode(_this.DefaultText));
        //        }
        //        _this.DisplayContainer.title = SelectedValueName;

        Close();
    },

    GetPopWindowBg = function() {
        var popWindoBg = document.getElementById("popWindoBg");
        if (popWindoBg == null) {
            popWindoBg = document.createElement("div");
            popWindoBg.id = "popWindoBg";
            popWindoBg.className = "popWindowBg";
            popWindoBg.style.display = "none";
            
            if (IsIE6() == true) {
                var bgIframe = null;
                bgIframe = document.createElement("iframe");
                bgIframe.setAttribute("src", "");
                bgIframe.style.cssText = "position:absolute;top:0px;left:0px;width:100%;height:100%; filter: alpha(opacity=0); opacity: 0; z-index:-1;";
                popWindoBg.appendChild(bgIframe);
            }
            document.body.appendChild(popWindoBg);
        }
        return popWindoBg;
    },

    Show = function() {
        if (_this.IsInit == false) {
            _this.InitRootData();
        }
        var popWindoBg = GetPopWindowBg();
        popWindoBg.style.display = 'block';
        _this.PopWindow.style.display = "block";
        SetPosition();
    },

    Close = function() {
        //if(_this.DisplayContainer.innerHTML==_this.DefaultText) {
        if(_this.GetDisplayText() == _this.DefaultText){
            RemoveSelectedAll();
        }   
        _this.PopWindow.style.display = "none";
        var popWindoBg = GetPopWindowBg();
        popWindoBg.style.display = 'none';
    },

    getAbsolutePos = function(el) {
        var SL = 0, ST = 0;
        var is_div = /^div$/i.test(el.tagName);
        if (is_div && el.scrollLeft)
            SL = el.scrollLeft;
        if (is_div && el.scrollTop)
            ST = el.scrollTop;
        var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
        if (el.offsetParent) {
            var tmp = getAbsolutePos(el.offsetParent);
            r.x += tmp.x;
            r.y += tmp.y;
        }
        return r;

//        var offsetLeft = 24, offsetTop = 0, offsetControl = el;
//        while (offsetControl) {
//            offsetLeft += offsetControl.offsetLeft;
//            offsetTop += offsetControl.offsetTop;
//            offsetControl = offsetControl.offsetParent;
//        }

//        if (navigator.userAgent.indexOf("Mac") != -1 &&
//        typeof (document.body.leftMargin) != "undefined") {
//            offsetLeft += document.body.leftMargin;
//            offsetLeft += document.body.leftMargin;
//        }

//        var r = { x: offsetLeft, y: offsetTop };
//        return r;
    },

    SetPosition = function() {
//        var pos = getAbsolutePos(_this.DisplayContainer);
//        var left = pos.x,
//        top = pos.y + _this.DisplayContainer.offsetHeight,
//        popWindowWidth = _this.PopWindow.offsetWidth,
//        popWindowHeight = _this.PopWindow.offsetHeight;
//        if (document.body.offsetHeight < (top + popWindowHeight)) {
//            top = pos.y - popWindowHeight;
//        }
//        if (document.body.offsetWidth < (pos.x + popWindowWidth)) {
//            left = pos.x + _this.DisplayContainer.offsetWidth - popWindowWidth;
//        }
//        _this.PopWindow.style.left = left;
//        _this.PopWindow.style.top = top;
        
        _this.PopWindow.style.left = (document.documentElement.clientWidth - _this.PopWindow.offsetWidth) / 2 + 'px';
        _this.PopWindow.style.top = (document.documentElement.clientHeight - _this.PopWindow.offsetHeight) / 2 + document.documentElement.scrollTop + 'px';
    },

    IsIE6 = function() {
        var b = new Browser();
        if (b.isIE == true && b.version == "6")
            return true;
        else
            return false;
    };
}

function Browser() {

    var ua, s, i;

    this.isIE = false;   // Internet Explorer
    this.isNS = false;   // Netscape
    this.version = null;

    ua = navigator.userAgent;

    s = "MSIE";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isIE = true;
        this.version = parseFloat(ua.substr(i + s.length));
        return;
    }

    s = "Netscape6/";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isNS = true;
        this.version = parseFloat(ua.substr(i + s.length));
        return;
    }

    // Treat any other "Gecko" browser as NS 6.1.

    s = "Gecko";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isNS = true;
        this.version = 6.1;
        return;
    }
}

function AddLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}
    