/* Note for future improvement. Utilize double clicking for add/remove. */

//The makes select list
ddMake = document.getElementById('makeBucket');
//The models select list
ddModel = document.getElementById('modelBucket');
//The bucket where the selections appear
ddBucket = document.getElementById('bucket');

// multi dimensional array with users selected make, model
// 0=make, 1=model
makeModelArray=new Array(); 

/**
 * Adds the currently selected model in the model list to the bucket
 * Enforces the rule of only allowing up to six models to be selected at
 * any one time.
 */
function addModels(){
	if(ddModel.selectedIndex < 0) {
		return;
	}
	
	if(alreadyInBucket()) {
		alert('You have already selected this model');
		return false;
	}

	if(makeModelArray.length > 5) { // Stop at 6
		alert('You may choose up to 6 makes/models per search');
		return;
	}
	
	//get the currently selected make in the make list
	var makeText=ddMake.options[ddMake.selectedIndex].text;
	
	//Clear the bucket first
	for(i=0; i<6; i++) {
		ddBucket.options[i]=null;
	}
	//Add this new model, but overwrite the oldest model
	//if there are already 6 models in the bucket
	for(i=0; i<ddModel.options.length; i++){
		o=ddModel.options[i];
		if (o.selected){
			makeModelArray[makeModelArray.length]=[makeText, o.text];
		}
	}
	fillBucket();
}  

/**
 * Removes the selected model from the bucket
 */
function removeModels() {

	makeModelArray.splice(ddBucket.selectedIndex,1);
	
	// Clear bucket
	for(i=0; i<6; i++) {
		// This doesn't work in all cases ddBucket.options[i]=null; 
		try {
		  ddBucket.options[i].text='';
		  ddBucket.options[i].selected=false
		  document.getElementById('hmake' + i).value=''
		  document.getElementById('hmodel' + i).value='';
		} catch(e) { 
		}
	}
	fillBucket();
}

/**
 * Fills the bucket with options corresponding to the users
 * make/model selections. It also updates
 * the hidden fields in the form corresponding to the
 * selected makes/models.
 */
function fillBucket(){
	for(i=0; i<makeModelArray.length; i++) {
		num = i + 1;
		var text = num + '. ' + makeModelArray[i][0] + ' - ' + makeModelArray[i][1];
		ddBucket.options[i] = new Option(text);
		
		// Fill the hidden fields.
		document.getElementById('hmake' + i).value = makeModelArray[i][0];
		if(makeModelArray[i][1] == 'All') {
			document.getElementById('hmodel' + i).value = '';
		} else {
			document.getElementById('hmodel' + i).value = makeModelArray[i][1];
		}
	}
} 

/**
 * Returns true if the given item is already in the bucket
 * and false otherwise
 */
function alreadyInBucket() {
	//get the currently selected make and model
	var make = ddMake.options[ddMake.selectedIndex].text;
	var model = ddModel.options[ddModel.selectedIndex].text;
	
	for(i=0; i<ddBucket.options.length; i++){
		if(ddBucket.options[i].text.indexOf(make + ' - ' + model) != -1) {
			return true;
		}
	}
	return false;
}

