/*
 * Created by Alan Szlosek
 * http://www.greaterscope.net
 *
 * Usage:
	<select name="a" multiple="multiple" onmousedown="scms_cache(this)" onchange="scms(this)">
	<option value="a" selected="selected">Alan</option>
	<option value="b" selected="selected">Brian</option>
	<option value="c">Carlos</option>
	</select>
 * */
selectedCache = new Array();

/*
 * This function should be run at "onmousedown".
 * It caches all items that were selected before the first click.
 * If you have multiple fields of the same name, pass in a different cacheName parameter to avoid conflicts
 * */
function scms_cache(field, cacheName) {
	var i;

	if(!cacheName)
		cacheName = field.name;

	if(!selectedCache[cacheName]) { // populate with currently selected items
		selectedCache[cacheName] = new Array();
		for(i in field.options) {
			if(field.options[i].selected)
				selectedCache[cacheName].push(i);
		}
	} 
}

/*
 * This is the main function to be run at "onchange"
 * If you have multiple fields of the same name, pass in a different cacheName parameter to avoid conflicts
 * */
function scms(field, cacheName) {
	var i;
	var cache;
	var found = false;

	if(!cacheName)
		cacheName = field.name;
	cache = selectedCache[cacheName];
	for(i in cache) {
		if( cache[i] == field.selectedIndex) {
			selectedCache[cacheName][i] = false;
			found = true;
			break;
		}
	}

	if(!found)
		selectedCache[cacheName].push(field.selectedIndex);

	field.selectedIndex = -1;
	cache = selectedCache[cacheName];
	for(i in cache) {
		if(cache[i] !== false)
			field.options[ cache[i] ].selected = 'selected';
	}
}
