/*
********************************************************
Copyright @ WebOnWebOff.com, by D. Miller
You may reuse this script, on condition that this copyright text is kept
www.WebOnWebOff.com
********************************************************

y_LinkedSelection vs. 1.0.1
*/

ylib.namespace('ylib.widget');

ylib.widget.LinkedSelection=function(sourceTag, targetTag, 
						 OptionsArray, StartOptionsArray,
						 targetSelectedValue,
						 NoDataOptionsArray){				  
	this.ready = false;
	this.s = xGetElementById(sourceTag);
	this.t = xGetElementById(targetTag); 		
	this.tSel = targetSelectedValue;	
	this.tOptCount = this.t.options.length ? (this.t.options.length-1) : -1;
	this.optsStart = StartOptionsArray;
	this.opts = OptionsArray;
	this.optsNoData = NoDataOptionsArray;
	//validate
	if(this.s && this.t && this.opts) this.ready=true;
	if(!this.ready) return;
	//event
	this.s.objLinkedSelects = this;
	this.s.onchange=this.updateOptions;
	this.s.onchange.call(this.s);	

}
ylib.widget.LinkedSelection.prototype.updateOptions=function(){
	var obj = this.objLinkedSelects;	
	if(!obj) return;
	var io;
	var newOpt; 
	var sVal = this.options[this.selectedIndex].value;
	//clear options
	obj.clearOptions();
	//add start options
	if(obj.optsStart){	
		obj.addSimpleOptions(obj.optsStart);	
	}	
	//add data options
	if(obj.opts){		
		for (io=0; io<obj.opts.length; io++) { 
			if(obj.opts[io].sValue == sVal){
				newOpt = new Option(obj.opts[io].text); 
				if(ylib.util.FindValueInList(obj.opts[io].value, obj.tSel)){
					ylib.util.SetOptionSelected(newOpt,true);
				}
				newOpt.value = obj.opts[io].value; 
				obj.t.options[++obj.tOptCount] = newOpt;
			}
		}
	}
	//apply "no data" options?
	if((obj.tOptCount+1)==obj.optsStart.length && obj.optsNoData){
		//clear start options
		obj.clearOptions();
		//add "no data" options
		obj.addSimpleOptions(obj.optsNoData);
	}
}
ylib.widget.LinkedSelection.prototype.addSimpleOptions=function(optArray){
	if(!optArray) return;
	var io, newOpt;
	for (io=0; io<optArray.length; io++) { 
		newOpt = new Option(optArray[io].text); 
		if(ylib.util.FindValueInList(optArray[io].value, this.tSel)){
			newOpt.selected=true;
		}
		newOpt.value = optArray[io].value; 
		this.t.options[++this.tOptCount] = newOpt;
	}
}
ylib.widget.LinkedSelection.prototype.clearOptions=function(){
	var i;
	
	while(this.t.options.length>0){
		for (i=0; i<this.t.options.length; i++) { 
			this.t.options[i] = null; 
		}
	}
	this.tOptCount = -1; 
}