function CateCode(cate){
this.cate = cate;
this.sub_cate = function(level){
var arr = [];
for(var i=0;i<this.cate.length;i++){
if(this.cate[i]['parent'] == level){
arr.push({code:this.cate[i]['code'],name:this.cate[i]['name'],parent:this.cate[i]['parent']})
}
}
return arr;
}
this.getParent = function (catecode){
var nav = [];
nav.push({code:"0"});
var code_len = catecode.length;
for (var i = 1; i < 4; i++) {
//测试这个位置是否为00
var catecode_level_test = catecode.substring((i - 1) * 2, 2);
if (catecode_level_test == '00') {
break;
}
var catecode_level = catecode.substring( 0, i * 2)+this._strrepeat('0', code_len - i * 2);
nav.push({code:catecode_level});
}
return nav;
}
this._strrepeat = function (str,count){
var goodstr = "";
for(var i=0;i<count;i++){
goodstr+=str.toString();
}
return goodstr;
}
}
function CateSelect(cate){
var _id=new Date().getTime() % 10000;
var _this=this;
this.id=_id;
this.catecode='';
this.set=function(val){
this.catecode=val;
}
this.div_obj=null;
this.call_back=function(){}
this.setCallback=function(fun){
this.call_back=fun;
}
this.change=function(){
var level=parseInt($(this).attr('level'));
for(var i =level+1;i<4;i++){
var sel='#cate_'+(i)+'_'+_this.id;
$(sel).css('display','none');
}
if(level<4){
var arr=cate_obj.sub_cate($(this).val());
var sel='#cate_'+(level+1)+'_'+_this.id;
if(level>0){
$(sel).html('');
}
$(arr).each(function(i,row){
$(sel).append($('<option value="'+row['code']+'">'+row['name']+'</option>'));
})
if(arr.length){
var sel='#cate_'+(level+1)+'_'+_this.id;
$(sel).css('display','');
}else{
$(sel).css('display','none');
_this.call_back($(this).val())
}
}
}
this.show=function(div_obj){
this.div_obj=div_obj;
if(! $('#cate_0_'+this.id).length ){
var html=[];
for(var i=0;i<4;i++){
html.push('<select level="'+i+'" id="cate_'+i+'_'+this.id+'" style="display:none"></select>');
}
$(div_obj).html(html.join("\n"));
$('#cate_0_'+this.id).change(_this.change)
$('#cate_1_'+this.id).change(_this.change)
$('#cate_2_'+this.id).change(_this.change)
$('#cate_3_'+this.id).change(_this.change)
}
var arr=cate_obj.sub_cate('0');
$(arr).each(function(i,row){
$('#cate_0_'+_id).append($('<option value="'+row['code']+'">'+row['name']+'</option>'));
})
$('#cate_0_'+_id).css('display','');
if(this.catecode!="0"){
var arr = cate_obj.getParent(this.catecode);
arr=arr.slice(1);
if(arr.length){
$(arr).each(function(i,row){
$('#cate_'+i+'_'+_id).val(row['code']);
$('#cate_'+i+'_'+_id).trigger('change');
});
}
}
}
}
cate_obj = new CateCode(cate);
show_obj = new CateSelect(cate);
show_obj.set($("#hiddcate").val());
show_obj.setCallback(function(val){
alert('select :'+val);
})
show_obj.show($('#div_show_select')[0]);