/*
#
# Select级联对象，依赖于jquery
# 
# author: zhuwei
# create at 2011-05-08
#
////////////////////////////////////////////
使用例子：
<select id="s1"></select>
<br />
<select id="s11"></select>
<br />
<select id="s12"></select>
<br />
<select id="s111"></select>
<script>
var s1=new SelectObject("s1");
var s11=new SelectObject("s11");
var s111=new SelectObject("s111");
var s12=new SelectObject("s12");

s1.addOption(1,'AAA');
s1.addOption(2,'BBB');
s1.addOption(3,'CCC');
s1.needHeader=false;

s11.addOption(110,'AAA0',1);
s11.addOption(111,'AAA1',1);
s11.addOption(112,'AAA2',1);
//s11.needHeader=false;
s11.emptyDisable=true;
s11.emptyHide=true;

s111.addOption(1110,'AAA00',110);
s111.addOption(1111,'AAA01',110);
s111.addOption(1112,'AAA20',112);
//s111.needHeader=false;
s111.emptyDisable=true;
s111.emptyHide=true;

s12.addOption(120,'BBB0',2);
s12.addOption(121,'BBB1',2);
s12.addOption(122,'BBB2',2);
//s12.needHeader=false;
s12.emptyDisable=true;
s12.emptyHide=true;

s1.addSubSelectObject(s11);
s1.addSubSelectObject(s12);
s11.addSubSelectObject(s111);
s1.renderer();
</script>
*/
function SelectObject(selectID){
	//控件的ID
	this.targetId=selectID;
	//属性：初始值
	this.initValue=null;
	//属性：是否需要空白的头部行
	this.needHeader=true;
	//属性：当没有选项时，是否disable掉
	this.emptyDisable=false;
	//属性：当没有选项时，是否隐藏掉
	this.emptyHide=false;
	//选项集合
	this.optionArray=new Array();
	this.addOption=function(id,name,pid){
		var optObj=new Object();
		optObj.id=id;
		optObj.name=name;
		optObj.pid=pid;
		this.optionArray[this.optionArray.length]=optObj;
	}
	//子对象集合	
	this.subObjectArray=new Array();
	this.addSubSelectObject=function(subObj){
		this.subObjectArray[this.subObjectArray.length]=subObj;
	};
	//渲染方法
	this.renderer=function(pid){
		var str=this._generateOpertionString(pid);
		var $me=$("#"+this.targetId);
		var isOptEmpty=str.length<1;
		if(isOptEmpty){
			if(this.emptyDisable) $me.attr("disabled",true);
			if(this.emptyHide) $me.hide();
		}else{
			$me.attr("disabled",false);
			$me.show();	
		}
		$me.html(this._getHeaderString()+str);
		//渲染子对象集合
		this._rendererSubObjectArray($me.val());
		//保存引用，添加事件
		$("#"+this.targetId).data("SelectObject",this); 
		$("#"+this.targetId).bind('change', function() {
			var theVal=$(this).val();
			$(this).data("SelectObject")._rendererSubObjectArray(theVal);
		});
	}
	/////// 以下为私有方法 ///////
	//渲染子对象集合
	this._rendererSubObjectArray=function(pid){
		if(this.subObjectArray==null) return;
		for(var i=0;i<this.subObjectArray.length;i++){
			this.subObjectArray[i].renderer(pid);
		}
	}
	//生成option字符串
	this._generateOpertionString=function(pid){
		var res="";
		for(var i=0;i<this.optionArray.length;i++){
			if(this.optionArray[i].pid!=pid)continue;
			var selFlag=this.optionArray[i].id==this.initValue?"selected":"";
			res=res+"<option "+selFlag+" value=\""+this.optionArray[i].id+"\">"+this.optionArray[i].name+"</option>";
		}
		return res;
	}
	this._getHeaderString=function(){
		return this.needHeader?"<option value=\"\"></option>":"";
	}
}