/* SPEC 

Create routines to manage a group of 'pseudo' checkboxes that are linked to 'hidden' checkboxes on a page.
Each group will have a 'select all' box that sets all others to 'checked'.

*/

/*  IMPLEMENTAION

Each checkbox will be in two parts - the 'pseudo' will be visible and the 'real' hidden from the user.
The pseudo and the real must be kept synchronized.
Each pseudo and real box will have unique IDs within the page and within the group.
The pseudo and real will have similar IDs in some way so that they are easy to identify & Synch together.

The pseudo will be a CSS styled <a href> with the link set to javascript void and the onclick event handled by the checkbox synchronize routine(s) 

*/

/*    define a group of boxes as a class   */
function optGroup() {
	// properties
	this.options=new Array() ;
	this.pseudoPrefix='pseudo_' ;
	this.realPrefix='real_' ;
	
	// methods
	this.init = function() { // initialiise the boxes so the checked value isn't undefined
		for (i=0; i < this.options.length; i++) {
			this.toggle(this.pseudoPrefix+this.options[i],true) ;
			this.toggle(this.pseudoPrefix+this.options[i],false) ;
			}
		}
	
	// add the IDs to the options array
	this.addOptions = function() {
		for (i=0; i < arguments.length; i++)
			this.options.push(arguments[i]) ;
		}
		
	// add the 'all' button to the start of the array
	this.addAllButton = function(btn) {
		this.options.unshift(btn) ;
		}
		
	// toggle the real checkbox state
	this.toggle = function(id, state) {
		var tmp=id.split('_') ;
		realBox=document.getElementById(this.realPrefix+tmp[1]) ;
		if (!realBox)
			return ;
		if (state != undefined)
			realBox.checked=state ;
		else
			realBox.checked=!realBox.checked ;
		// synch real & pseudo boxes	
		this.synch(id) ;
		}
			
	// synch the pseudo & real
	this.synch = function(id) {
		var tmp=id.split('_') ;
		realBox=document.getElementById(this.realPrefix+tmp[1]) ;
		pseudo=document.getElementById(this.pseudoPrefix+tmp[1]) ;
		if (!(realBox && pseudo))
			return ;
		if (realBox.checked)
			pseudo.style.backgroundImage='url(css/images/checkbox-on.gif)' ;
		else
			pseudo.style.backgroundImage='url(css/images/checkbox-off.gif)' ;
		}
		
	this.toggleAll = function(id) {
		this.toggle(id) ;
		var state = this.stateOf(id) ;
		for (i=1; i < this.options.length; i++)
			this.toggle(this.pseudoPrefix+this.options[i],state) ;
		}
		
	/* -------------------    helper functions ---------------*/
	// find needle in array haystack
	this.indexOf = function(needle,haystack) {
		for (i=0; i < haystack.length; i++) {
			if (needle == haystack[i])
				return i ;
				}
		return -1 ;
		}
		
	// return the state of a checkbox
	this.stateOf = function(id) {
		var tmp=id.split('_') ;
		realBox=document.getElementById(this.realPrefix+tmp[1]) ;
		if (!realBox)
			return ;
		return realBox.checked ;
		}
	} // end class
