/* 

=head1 NAME 

Cascading Select

=head1 SYNOPSIS 
   
Cascading select:

Changes the list of options in another select list, dependent on the current select list.

passed a hash, 

thisEle - Select list where next list is dependent on

nextEle - Select list where the vaules will be populated.

listfunc - a function object, if present, this is used to lookup the values to be used in the secondary list.
	  passed the same argument object as updateSelects

noBlank- optional.  if present and set to true, the first element will not be blank

values - a nested structure of hashes or strings, 
the keys must map to values in thisEle.  keys in the sublist (be they arrays or hashes)
will be the 'values' in the generated list. 

data can be in two forms: 

The first way sorts by displaytitles

 { value-in-first-list: { value-in-second-list: displaytitle, value2-in-second-list: displaytitle2 },
   value2-in-first-list: ... }
 }

The second form allows you to manually set a display order.

{ value-in-first-list: { value-in-second-list: {id: value-in-second-list, Title: displaytitle: DisplayOrder: order}},
  value-in-first-list: { value2-in-second-list: {id: value2-in-second-list, Title: displaytitle2: DisplayOrder: order2}},
 
 }

   
=cut
	
 */

//loathe ie.
function addOption(select,opt){
	if(document.all) { //ie
		return select.add(opt,-1);
	} else {
		//correct browsers
		return select.add(opt,null);
	}
}

function updateSelects(args) {
	
	var lst;
	if (args.listfunc){
		lst = args.listfunc(args);
	} else {
	 	lst = args.values[args.thisEle.value]; 
	}
	
	args.nextEle.selectedIndex = 0;
	while(args.nextEle.options.length > 0) {
		args.nextEle.remove(0);
	}
	
	if(!args.noBlank) { 
		addOption(args.nextEle, new Option('',''));
	}

	// convert the contents of the list
	// to the same format
	var newlist = new Array();
	for(var i in lst) { 
		if(typeof lst[i] == 'object') { 
			newlist.push(lst[i]);
		} else { 	
			newlist.push({id:i, Title:lst[i]});
		}
	}
	
	newlist.sort(compareTitles);
	var selectedindex = 0;

	for(i=0;i<newlist.length;i++) { 
		addOption(args.nextEle,new Option(newlist[i].Title,newlist[i].id));
		if (args.selectValue == newlist[i].id) {
			selectedindex = i;
		}
	}
	
	args.nextEle.selectedIndex = selectedindex;
			
}

/* Used in updateSelects to sort themes by Title*/
function compareTitles(a, b) {
	var x;
	var y;
	if(a['DisplayOrder']) { 
		x = a.DisplayOrder;
		y = b.DisplayOrder;
	} else if(a.Title.toLowerCase) { 
		x = a.Title.toLowerCase();
		y = b.Title.toLowerCase();
	}
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));

}

