function sortOptions(selectId){
	// get the select
	var $dd = $(selectId);
	if ($dd.length > 0) { // make sure we found the select we were looking for
	
	    // save the selected value
	    var selectedVal = $dd.val();
	
	    // get the options and loop through them
	    var $options = $('option', $dd);
	    var arrVals = [];
	    $options.each(function(){
		// push each option value and text into an array
		arrVals.push({
		    val: $(this).val(),
		    text: $(this).text()
		});
	    });
	
	    // sort the array by the value (change val to text to sort by text instead)
	arrVals.sort(function(a, b){
	    if(a.text>b.text){
		return 1;
	    }
	    else if (a.text==b.text){
		return 0;
	    }
	    else {
		return -1;
	    }
	});
	
	    // loop through the sorted array and set the text/values to the options
	    for (var i = 0, l = arrVals.length; i < l; i++) {
		$($options[i]).val(arrVals[i].val).text(arrVals[i].text);
	    }
	
	    // set the selected value back
	    $dd.val(selectedVal);
	}
}

function selectAll(id){
	$(id + ' option').each(function(i) {
		$(this).attr("selected", "selected");
	});	
}

function deselect(id){
	$(id + ' option').each(function(i) {
		$(this).attr("selected", false);
	});	
}

$().ready(function() {
	$('.jsReqired').show();
	
	if(typeof(requestLimit) == 'undefined'){
		requestLimit = 10;
	}	

	selectAll('#select2');

	$('#select1').click(function() {
		if($('#select2').children().size() + $(this).children('option:selected').size()<= requestLimit){
			$(this).children('option:selected').remove().appendTo('#select2');
			sortOptions('#select2');
			selectAll('#select2');
			
			return true;
		}else {
			alert('You can only select ' + requestLimit + ' programs. Please remove one or more programs by clicking on them in the box to the right.');
			return true;
		}
		
	});

	$('#select2').click(function() {
		$(this).children('option:selected').remove().appendTo('#select1');
		sortOptions('#select1');
		deselect('#select1');
		selectAll('#select2');
		
		return false;
	});
	
	$('form').submit(function() {
		selectAll('#select2');
	});
});