/**
 * 分类读取
 */
// fix createOption 前的注释会造成 ie6 无法识别 toSelect，去掉注释或加空格。
if (typeof(String.prototype.repeat) == "undefined"){
    String.prototype.repeat = function(l){
        return new Array(l*2+1).join(this);
    };
}
if (typeof(labelLoader) == "undefined"){
    var labelLoader = function(){
        /* 读取 */
        this.loadCount = 0;
        this.loader = function(){
            try{
                var _params = this.params;
                var _url = _params.url;
                var _mapping = _params.mapping;
                var _toEl = _params.toEl;
                var selfObj = this;
                /**
                 * 读取条
                 */
                _params.waiter = (typeof(_params["waiter"]) =="undefined")?"._waiter":_params["waiter"];
                var isOnlyFirstChildren = !!_params.isOnlyFirstChildren;
                var _waiter =jQuery(_params.waiter);
                _waiter.show();//
                //
                this.loadCount++;
                jQuery.getJSON(_url,
                    function(json){
                        if (!json){
                            _waiter.fadeOut("slow");
                            return;
                        }
                        this.loadCount = -1;
                        var _labelInfo;
                        var _labelInfo_result;
                        var _labelInfoList = [];
                        /**
                         * 完成不同来源的转换 articleLabelId -> sId
                         **/
                        for(var _Key in json){
                            _labelInfo_result = {};
                            _labelInfo = json[_Key];
                            for(var _mkey in _mapping)
                            {
                                _labelInfo_result[_mkey] = _labelInfo[_mapping[_mkey]];
                            }
                            if (isOnlyFirstChildren ){

                                if (_labelInfo_result['pid'] != _params.cId){
                                    continue;
                                }
                                _labelInfo_result['pid'] = 0;
                            }
                            _labelInfoList.push(_labelInfo_result);
                        }
                        selfObj.labelInfoList = _labelInfoList;
                        selfObj.labelInfoList = selfObj.getLabelInfoList();
                        selfObj._caculateDeep();

                        //			alert(selfObj.labelInfoList.toSource());
                        //			alert(selfObj.getLabelByPid(0));
                        var _cEl ; // 当前
                        var _cTagName ; // 当前
                        var _cElList ; // 当前
                        var _cTemplete ; // 当前
                        var _cStyle ; // 当前
                        var _cEvent ; // 当前
                        for(var _eKey in _toEl)
                        {
                            _cEl = _toEl[_eKey];
                            _cTagName = _cEl.tagName;
                            _cElList = _cEl.elList;
                            switch(_cTagName)
                            {
                                case "select":
                                    selfObj.toSelect(_cElList);
                                    break;
                                case "div":
                                    _cTemplete = _cEl.templete;
                                    _cStyle = _cEl.style;
                                    _cEvent = _cEl.event;
                                    selfObj.toDiv(_cElList,_cTemplete,_cStyle,_cEvent);
                                    break;
                                case "crumb":
                                    _cTemplete = _cEl.templete;
                                    var _cPosition = _cEl.position;
                                    selfObj.toCrumb(_cElList,_cTemplete,_cPosition);
                                    break;
                            }
                        //				if (_cTagName == "select"){
                        //				}else if(_cTagName == "div"){
                        //				}
                        }
                        //                			}catch(e){
                        //				return false;
                        //                			};
                        _waiter.fadeOut("slow");
                    });
            }catch(e){
                if (this.loadCount != -1 && this.loadCount < 3){
                    this.loader();
                }
            }
        };
        this.params = null;
        this.cId = null;
        this.init = function(_params){
            this.params = _params;
            this.cId = _params.cId;
            this.loader();
        };
        /* 分类列表 */
        this.labelInfoList = [];
        /* 样式集合 */
        this.style = {
            _pEl :"", // 父元素 样式
            _cEl :"" // 子元素 样式
        };
        /*  创立一个option对象 */

        this.createOption = function(_value,_name,_selected,_id){
            //		var _option = jQuery(document.createElement("option"));
            var _option = document.createElement("option");
            if (typeof(_value) == "string")
            {
                _option.value = _value;
                if (_id)
                {
                    _option.id = _id;
                }
                _option.text = _name;
                _option.selected = _selected;
            }
            return _option;
        };
        /* 追加入select 中 以option列出  */
        this.toSelect = function(_selectList){
            var _selectList_Len = _selectList.length;
            var _optionList ;
            var _optionList_Len ;
            var _cSelecter ;
            var _option;
            for(var _i=0;_i<_selectList_Len;_i++){
                _cSelecter = document.getElementById(_selectList[_i]);
                //			_cSelecter = jQuery("#"+_selectList[_i]);
                if(!_cSelecter){
                    continue;
                }
                _optionList = this.createOptionList();
                _optionList_Len = _optionList.length;
                for(var _oKey =0;_oKey<_optionList_Len;_oKey++)
                {
                    _option = _optionList[_oKey];
                    if(_option){
                        _cSelecter.options.add(_option);
                    }
                }
            }
        };
        this._getParentDeep = function(id){
            var label;
            for(var i in this.labelInfoList){
                label= this.labelInfoList[i];
                if (label['sid'] == id){
                    return label['deep'];
                }
            }
            return 0;
        };
        this._caculateDeep = function(){
            var label;
            for(var i in this.labelInfoList){
                label= this.labelInfoList[i];
                if (label['pid'] == 0){
                    label['deep'] = 0;
                }else{
                    label['deep'] = this._getParentDeep(label['pid'])+1;
                }
                this.labelInfoList[i] = label;
            }
        };
        /**
         * 创建Option列表
         **/
        this.createOptionList = function(){
            var _optionList = new Array();
            var _labelInfo;
            var _option;
            var _value,_name,_selected,_id,_deep;
            var _cId = this.cId;
            var _labelInfoList = this.labelInfoList;
            var _labelInfoList_Len = _labelInfoList.length;
            for(var _lKey=0;_lKey<_labelInfoList_Len;_lKey++)
            {
                _labelInfo = _labelInfoList[_lKey];
                _value = _labelInfo["sid"];
                _deep = _labelInfo["deep"]; // parseInt
                _name = _labelInfo["name"];
                if(jQuery.browser.msie)
                {
                    _deep  = " ".repeat(_deep*2);
                    _name = _deep+_name;
                }else{
                    _deep = _deep*10+"px";
                }
                _selected = (_value==_cId)?true:false;
                _id = null;
                _option = this.createOption(_value,_name,_selected,_id);
                if(!jQuery.browser.msie)
                {
                    _option.style.paddingLeft = _deep;
                }
                _optionList.push(_option);
                preParent = _labelInfo['pid'];
            }
            return _optionList;
        };
        this.replacer = function(labelInfo,filler,style){
            var _result = "";
            var cid = this.cId; // 当前分类
            try{
                labelInfo["title"] = labelInfo["name"];
                if (typeof(filler) == "string"){
                    if (labelInfo["sid"] == cid){
                        if (style && typeof(style['ael']) == 'string'){
                            filler = filler.replace(new RegExp("\\{aClass\\}","ig"),style['ael']);
                        }else{
                            filler = filler.replace(new RegExp("\\{aClass\\}","ig"),"");
                        }
                    }
                    filler = filler.replace(new RegExp("\\{name\\}","ig"),labelInfo["name"]);
                    filler = filler.replace(new RegExp("\\{title\\}","ig"),labelInfo["title"]);
                    filler = filler.replace(new RegExp("\\{pid\\}","ig"),labelInfo["pid"]);
                    filler = filler.replace(new RegExp("\\{sid\\}","ig"),labelInfo["sid"]);
                    filler = filler.replace(new RegExp("\\{order\\}","ig"),labelInfo["order"]);
                    //
                    filler = filler.replace(new RegExp("\\{pic}","ig"),labelInfo["pic"]);
                    filler = filler.replace(new RegExp("\\{url\\}","ig"),labelInfo["url"]);
                    filler = filler.replace(new RegExp("\\{brief}","ig"),labelInfo["brief"]);

                    _result = filler;
                    delete filler;
                }else if(typeof(filler) == "function") {
                    _result = filler(labelInfo);
                }
            }catch(e){
//                if (console && console['log']){
//                    console.log(e);
//                }
            }
            return _result;
        };
        /**
         * 制取一个行对象 作为子集元素
         **/
        this.__line_object_ = "__line_object_";
        this.__line_bindable_ = "__line_bindable_";
        this.getCLine = function(labelInfo,templete,style){
            try{
                /**
                 * 制取填充物！
                 **/
                var _filler = templete.filler;
                var _cEl = templete.cel; // 子集元素
                var _fEl = (typeof(templete["fel"]) == "undefined") ? "div" : templete['fel']; // 总父级元素
                var _prefixEl = null;
                if (typeof(_filler) == 'object' && _filler['inner'] != null && _filler['outter'] != null){

                    var url = jQuery.trim(labelInfo['url']) ;
                    if (url != null && url.length > 0   ){
                        _filler = this.replacer(labelInfo,_filler['outter'],style);
                    }else{
                        _filler = this.replacer(labelInfo,_filler['inner'],style);
                    }
                }else{
                    _filler = this.replacer(labelInfo,_filler);
                }
 
                if(_filler != null)
                {
                    var _parentEL = jQuery(document.createElement(_cEl));
                    var _fillEL = jQuery(document.createElement(_fEl));
                    if (typeof(templete["felClass"]) != "undefined"){
                        _fillEL.attr("className",templete["felClass"]);
                    }
                    _fillEL.addClass(this.__line_object_);
                    _fillEL.html(_filler);

                    if (templete["prefix"])
                    {
                        _prefixEl = (typeof(templete["prefix"]["el"]) == "undefined") ? "div" : templete["prefix"]["el"];
                        _prefixEl = jQuery(document.createElement(_prefixEl));
                        var _cClass = (typeof(templete["prefix"]["cClass"]) == "undefined") ? null: templete["prefix"]["cClass"];
                        if (_cClass != null)
                        {
                            _prefixEl.addClass(_cClass);
                        }
                    }
                    if (_prefixEl)
                    {
                        _parentEL.append(_prefixEl);
                    }
                    _parentEL.addClass(style["cel"]);
                    _parentEL.append(_fillEL);
                    return _parentEL;
                }else{
                    return null;
                }
            }catch(e){
                //									alert(e)
                return null;
            }
        };
        this.blindLineEvents = function(area,event){
            if (event && event["cel"])
            {
                jQuery("."+this.__line_object_,area).each(function(e){
                    var events = event["cel"];
                    var selfObj = jQuery(this);

                    //                    var eName;
                    //					for(eName in events)
                    //					{
                    //						_fillEL.bind(eName, function(){
                    //							events[eName](this);
                    //						});
                    //					}
                    events(selfObj.parent(),selfObj);
                //                selfObj.removeClass(this.__line_object_);
                });
            }
        };
        /**
         * 填充子集元素
         **/
        this.appendChildren = function(pNode,cNode,templete,style){
            try{
                var pel = (typeof(templete["pel"]) == "undefined") ? "ul" : templete["pel"];
                var _isExistPel = jQuery(pel+":first",pNode); // 当前需要载入子集元素的元素内是否包含父级html元素
                if (_isExistPel.html() != null)
                {
                    _isExistPel.append(cNode);
                }else{
                    var _cpNode = jQuery(document.createElement(pel));
                    _cpNode.addClass(style["pel"]);
                    _cpNode.append(cNode);
                    pNode.append(_cpNode);
                //				var _cpNode = document.createElement(pel);
                //				cNode.appendTo(_cpNode);
                //				pNode.append(_cpNode);
                }
                var _prefixEl = null;
                if (templete["prefix"])
                {
                    _prefixEl = (typeof(templete["prefix"]["el"]) == "undefined") ? "div" : templete["prefix"]["el"];
                    _prefixEl = jQuery(_prefixEl+":first",pNode);
                    var _pClass = (typeof(templete["prefix"]["pClass"]) == "undefined") ? null: templete["prefix"]["pClass"];
                    if (_pClass != null)
                    {
                        _prefixEl.removeClass();
                        _prefixEl.addClass(_pClass);
                    }
                }
                return pNode;
            }
            catch(e){
                return null;
            }
        };
        /* 追加在 div 中以 ul + li 显示 */
        this.toDiv = function(_divList,templete,style,event){
            var _sId,_name,_selected,_deep; // 各项属性
            var _cId = this.cId;
            var _labelInfoList = this.labelInfoList; // 处理过的数据集
            var _labelInfoList_Len = _labelInfoList.length;
            var _nodeInfo = null;// 节点信息
            var _labelInfo = null;// 分类信息
            var _nodeStack= new Object();
            var _sid = null;
            var _pid = null;
            var _area = null; // 放置区域
            var _pel = templete.pel; // 父集元素
            var _cel = templete.cel; // 子集元素
            //        var _cel = templete.cel; // 子集元素
            var prefix = templete.prefix; // 子集元素
            for(var i=0;i<_labelInfoList_Len ;i++)
            {
                _labelInfo = _labelInfoList[i];
                _sid = _labelInfo['sid'];
                _pid = _labelInfo['pid'];
                _nodeInfo = this.getCLine(_labelInfo,templete,style,event);
                if (typeof(_nodeInfo) == "undefined"){
                    continue;
                }
                _nodeStack[_sid] = _nodeInfo;
            }
            _area = jQuery("#"+_divList.pop());
            for(var _id in _nodeStack)
            {
                _area.append(_nodeStack[_id]) ;
            }
            var _selfNod = null;
            for(i=0;i<_labelInfoList_Len ;i++)
            {
                _labelInfo = _labelInfoList[i];
                _sid = _labelInfo['sid'];
                _pid = _labelInfo['pid'];
                if (_pid != 0)
                {
                    if (typeof(_nodeStack[_pid]) != "undefined")
                    {
                        //					_nodeStack[_pid].append(_nodeStack[_sid]);
                        this.appendChildren(_nodeStack[_pid],_nodeStack[_sid],templete,style);
                    }
                }
            // root
            }
            for(i=0;i<_labelInfoList_Len ;i++)
            {
                _labelInfo = _labelInfoList[i];
                _sid = _labelInfo['sid'];
                _pid = _labelInfo['pid'];
                if (_pid == 0)
                {
                    _selfNod = _nodeStack[_sid];
                    if (_selfNod.children(_pel).html() == null){
                        if (prefix){
                            _selfNod.children(prefix.el+":first").attr("className",prefix.pClass);
                        }
                    }
                }
            // root
            }
            var _pNode = jQuery(document.createElement(_pel));
            _pNode.addClass(style['fpel']); // 最上端父级class
            //		_pNode.append(_area.html());
            //		_area.html(_pNode);
            _area.wrapInner(_pNode);
            //		_area.find(_pel).each(function(){
            //			jQuery(this).children(_cel+":first").children(prefix.el).attr("className","pPrefix_first");
            //			jQuery(this).children(_cel+":last").children(prefix.el).attr("className","pPrefix_last");
            //		});
            if (typeof(templete['treeview']) != "undefined")
            {
                if (templete['treeview'] == true)
                {
                    _area.treeview();
                }
            }else{
                _area.treeview();
            }
            if (!_divList || _divList.length == 0){
            //            return;
            }
            var _cKey = null;
            var _carea = null;
            this.blindLineEvents(_area,event);
            for(i= _divList.length;i>0;i--)
            {

                _cKey = _divList[i-1];
                //			if (_cKey != 0)
                //			{
                _carea = jQuery("#"+_cKey);
                _carea.append(_area.children().clone(true));
                this.blindLineEvents(_carea,event);
            //			}
            }
            //		document.write("<textarea rows=18 cols=60>" + _labelInfoList.toSource() + "</textarea>");
            return ;
        };
        this.getLabelInfoList = function(){
            var _labelInfoList = new Array();
            var _labelList = this.getLabelByPid(0,"desc");
            var _cNode;
            var _subNodes;
            var _iS;
            while(_labelList.length>0)
            {
                _cNode = _labelList.pop();
                _labelInfoList.push(_cNode);
                _subNodes = this.getLabelByPid(_cNode["sid"],"desc");
                for(_iS=0;_iS<_subNodes.length;_iS++)
                {
                    _labelList.push(_subNodes[_iS]);
                }
            }
            return _labelInfoList;
        };
        /* 面包屑 crumb */
        this.toCrumb = function(_crumbList,templete,_cPosition){
            var _crumbList_Len = _crumbList.length;
            var _optionList ;
            var _optionList_Len ;
            var _cSelecter ;
            var _option;
            var _crumbContent = this.createCrumb(templete);
            for(var _i=0;_i<_crumbList_Len;_i++){
                //			_cCrumb = document.getElementById(_crumbList[_i]);
                _cCrumb = jQuery("#"+_crumbList[_i]);
                if(!_cCrumb){
                    continue;
                }
                if (_cPosition == "replace"){
                    _cCrumb.html(_crumbContent);
                }else{
                    _cCrumb.append(_crumbContent);
                }
            }
        };
        /* 建立 crumb */
        this.createCrumb = function(templete){
            var _labelInfoList = this.labelInfoList; // 处理过的数据集
            var _labelInfoList_Len = _labelInfoList.length;
            var _cId = this.cId;
            var _pTree = new Array();
            var _labelInfo;
            for(var i=0;i<_labelInfoList_Len;i++)
            {
                _labelInfo = _labelInfoList[_labelInfoList_Len-i-1]; // 当前
                if (_labelInfo['sid'] == _cId){
                    _cId = _labelInfo['pid'];
                    _pTree.push(_labelInfo);
                }
            }
            var _returnHtml = "";
            while(_pTree.length > 0)
            {
                _labelInfo = _pTree.pop();
                _returnHtml += this.replacer(_labelInfo,templete);
            }
            return _returnHtml;
        };
        /* 获取 父级编号 为 _pid的所有信息 */
        this.getLabelByPid = function(_pid,_order){
            var _returnInfo = new Array();
            var _labelInfoList = this.labelInfoList;
            if (!_labelInfoList){
                return _returnInfo;
            }
            var _labelInfoList_len = _labelInfoList.length;
            var _labelInfo;
            for(var i=0;i<_labelInfoList_len;i++)
            {
                _labelInfo = _labelInfoList[i]; // 当前
                if (_labelInfo['pid'] == _pid){
                    _returnInfo.push(_labelInfo);
                }
            }
            if (_order == "desc"){
                _returnInfo.sort(this._desc);
            }else{
                _returnInfo.sort(this._asc);
            }
            //		}
            return _returnInfo;
        };
        /* 数组排序 */
        this._desc = function(x,y)
        {
            x.order = parseInt(x.order,"10");
            y.order = parseInt(y.order,"10");
            if (x.order > y.order)
            {
                return -1;
            }
            if (x.order < y.order)
            {
                return 1;
            }
            return 0;
        };
        this._asc = function(x,y)
        {
            x.order = parseInt(x.order,"10");
            y.order = parseInt(y.order,"10");
            if (x.order > y.order)
            {
                return 1;
            }
            if (x.order < y.order)
            {
                return -1;
            }
            return 0;
        };
    };
}
//[
//{sid:"2", pid:"0", name:"\u653F\u6CBB", order:"0", deep:"0"},
//{sid:"11", pid:"2", name:"\u653F\u6CBB\u7B2C\u4E00\u5B50\u96C6", order:"0", deep:"1"},
//{sid:"12", pid:"11", name:"\u653F\u6CBB\u7B2C\u4E8C\u5B50\u96C6", order:"0", deep:"2"},
//{sid:"1", pid:"0", name:"\u519B\u4E8B", order:"0", deep:"0"},
//{sid:"8", pid:"1", name:"\u519B\u4E8B\u7B2C\u4E00\u5B50\u96C6", order:"0", deep:"1"},
//{sid:"9", pid:"8", name:"\u519B\u4E8B\u7B2C\u4E8C\u5B50\u96C6", order:"0", deep:"2"},
//{sid:"10", pid:"9", name:"\u519B\u4E8B\u7B2C\u4E09\u5B50\u96C6", order:"0", deep:"3"}
//]