﻿//microboat@gmail.com
//by 令狐葱
// 扩展Function对象
Function.prototype.bind = function(scope, args){
    var method = this;
    if(args === undefined){
        args = [];
    }
    return function() {
        return method.apply(scope, args.concat(arguments));
    }
}

//联动下拉框
//config: {url:xml路径,el:父容器ID,root:根节点名,field:子节点名,text:显示文本,value:值}
//xml文件格式：<root><list id='' text=''></list></root>
linkSelect = function(config){
    this.conf = config;
    this.el = $('#' + config.el);
    this.init();
}

linkSelect.prototype = {
    init: function(){
        this.el.append('加载中...');
        $.get(this.conf.url, this.callback.bind(this));
    },
    
    callback: function(result){       
        this.data = $(result).find(this.conf.root);
        this.el.empty();
        this.create(this.data.children());
    },
    
    create: function(data){
        if(data.length == 0){return false;}
        
        var select = $('<select style="width:100px" name="'+this.conf.el+'"></select>').appendTo(this.el).change(this.change.bind(this));
        var text = this.conf.text;
        var value = this.conf.value;
        var option = $('<option value="">---请选择---</option>').appendTo(select);
        data.each(function(){
            var option = $('<option value='+$(this).attr(value)+'>'+$(this).attr(text)+'</option>').appendTo(select);
        });
        
        select.change();
    },
    
    change: function(e){
        var select = $(e[0].target);
        var value = select.val();
        var data = this.data.find(this.conf.field+'['+this.conf.value+'='+value+']').children();
        
        this.remove(select);
        this.create(data);
    },
    
    remove: function(el){
        var next = el.nextAll('select');
        next.remove();       
    }
};
