$.fn.regionSelect = function(options){
	return new RegionSelectTag(this.get(0), options);
};

function RegionSelectTag(options){

	this.id =options.ids;
	this.val=options.vals;
	this.level=options.level;
	this.setOptions(options);
	this.init();
}

RegionSelectTag.prototype = {
	init:function(){
		for(var i=0;i< this.id.length;i++){	
		 	var select =$("#"+this.id[i]);
			if(select!=undefined){
				if(i==0){
					this.createFirstRegion(this.val[i]);
				}
				this.eventListener(i);//绑定事件
			}
		}
		
	},createFirstRegion:function(val){
		//首次加载
		var data = this.loadRegion(1);	
		this.createSelect(0,data,val,true);
		 
	},initRegion:function(selIndex,val){
		//初始选择
	 	var next=selIndex+1;
		if(next<4){
		   select=$("#"+this.id[next]);
		   dfval=this.val[next];
		   this.createChildRegion(next,val,dfval);
		 }
	}
	,createChildRegion:function(index,val,dfval){
		var data;
		if(index==0){
			data=this.loadRegion(1);	
		}else if(val!=null && val!=''){
			data=this.loadChildren(val);
		}
		this.createSelect(index,data,dfval);
	},
	createSelect:function(selIndex,data,val){
		select=$("#"+this.id[selIndex]);
		var option=select.find("option").eq(0);
		select.find("option").remove();	 
		select.append(option);
		if(data!=undefined && data!=null && data.length>0){
			for(var i=0;i<data.length;i++){
				select.append("<option value='"+data[i].regId+"'>"+data[i].regNm+"</option>");//.options.add(new Option(data[i].regNm,data[i].regId));	
			}
			if(val!=null &&val!=''){
				$(select).val(val);
			}
			this.initRegion(selIndex,val);
		}else{
			this.initRegion(selIndex,'');
		}
		
	},
	loadRegion:function(level){
		var result;
		$.ajax({
			url:'?index-region-t-1.htm',
			data:{'level':level},
			dataType:'json',
			async:false,
			success:function(data){
				result = data;
			},
		});
		return result;
	},
	loadChildren:function(regId){
		var result;
		$.ajax({
			url:'?index-region-t-2.htm',
			data:{'regId':regId},
			dataType:'json',
			async:false,
			success:function(data){
				result = data;
			}
		});
		return result;
	},
	eventListener:function(index){
		var obj = this;
		$("#"+obj.id[index]).change(function(){
			var nextindex=index+1;
			obj.createChildRegion(nextindex,$(this).val(),'');//
		});
	},changeSelect:function(val1,val2,val3,val4){//所在级别四个级别的值
		 	this.val=[val1,val2,val3,val4];
			this.createFirstRegion(val1);
		
	},selectVal:function(){
		//获取所选值
		var val="";
		for(var i=this.id.length-1;i>=0;i--){
			  val=$("#"+this.id[i]).val();
			  if(val!="" &&val!=null && val!="-1"){
				  return val;
			  }
		}
		return val;
	},setOptions:function(options){
		var o = this.options;
		$.extend(o, options);
	}
};