/**
 * JSON to dropdown plugin
 *
 * @author Andrew Hart
 * @version 1.1
 */
(function($) {
	
	$.fn.json_to_dropdown = function(options) {
		// Build main options
		$.fn.json_to_dropdown.options = $.extend({}, $.fn.json_to_dropdown.defaults, options);
		
		var $this = $(this);
		
		$this.unbind("reload").bind("reload", function() {
			$this.empty();
			
			switch (typeof options.before)
			{
				case "string":
					$this.append(options.before);
					break;
			}
			
			$.get(options.json_data, {selected: options.selected_value}, function(json) {
				if (json) {
					$.each(json, function() {
						var selected = (this.selected) ? ' selected="selected"' : '';
						$this.append('<option value="' + this.value + '"' + selected + '>' + this.text + '</option>');
						$this.addClass("is_reloadable");
					});
				}
			}, "json");
			
			switch (typeof options.after)
			{
				case "string":
					$this.append(options.after);
					break;
			}
		}).trigger("reload");
		
		return $(this);
	};

	$.fn.json_to_dropdown.defaults = {
		json_data: "",
		selected_value: ""
	};
	
	$.fn.json_to_dropdown.options = {
		before: false,
		json_data: "",
		after: false
	};

})(jQuery);
