/*
 * Extended helper methods for select-input-fields
 * 
 * Author D. Hampton
 * 
 */
/*
 * Returns the hidden value field of the current selection
 */
jQuery.fn.selectedVal = function() {
	return $(this).selectedOption().val();
};

/*
 * For check boxes. 
 */ 
jQuery.fn.isChecked = function() {
	return $(this).attr('checked');
};

/*
 * Returns the entire selected option
 */
jQuery.fn.selectedOption = function() {
	return $("#"+$(this).attr("id")+" :selected");
};

/*
 * Returns the visible value field of the current selection
 */
jQuery.fn.selectedText = function() {
	return $(this).selectedOption().text();
};

/*
 * Returns an array of all available options
 */
jQuery.fn.getOptions = function() {
	return $("#"+$(this).attr("id")+" option");
};

/*
 * Will set the option who's value is passed in to this function as
 * selected. All other options are not selected.
 */
jQuery.fn.setSelected = function(value) {
	options = $(this).getOptions();
	$.each(options, function() {
		if ($(this).val()==value) {$(this).attr("selected", "selected");}
		else {$(this).attr("selected", false);}
	});
};
jQuery.fn.setMultipleSelected = function(value) {
	options = $(this).getOptions();
	$.each(options, function() {
		if ($(this).val()==value) {$(this).attr("selected", "selected");}
	});
};	

/*
 * Add a new option to the end of a select box
 */
jQuery.fn.addOption = function(value, text) {
	id = "#"+$(this).attr("id");
	var option = document.createElement("option");
	option.value = value;
	option.text = text; 
	$(id).get(0)[$(id+' option').length] = option;
};

/*
 * As it says on the tin...
 */
jQuery.fn.selectAll = function() {
	$("#"+$(this).attr("id")+" *").attr("selected","selected");
};

/*
 * Give this a URL, as long as the URL returns <name>:<value> pairs
 * in JSON format the these values will be added to the select box
 */
jQuery.fn.loadJsonOptions = function(url) {
	id = "#"+$(this).attr("id");
	$.getJSON(url,
    function(data){
    	$.each(data, function(i, item){
			$(id).addOption(item.value, item.name);
      	});
    });
};

/*
 * Empties the select box
 */
jQuery.fn.clear = function() {
	$("#"+$(this).attr("id")).children().remove();
};

/*
 * Will move the selected item to the receiver, removing it from the initial
 * select box.
 */
jQuery.fn.moveSelectedTo = function(receiver) {
	id = "#"+$(this).attr("id");
	o = $(id).selectedOption();
	$(o).remove();
	o.appendTo(receiver);
};

jQuery.fn.removeSelected = function() {
	id = "#"+$(this).attr("id");
	o = $(id).selectedOption();
	$(o).remove();
};
