/**
 * selectCombo for jQuery
 * 
 * Copyright (c) 2007 Shelane Enos
 * Dual licensed under the MIT (MIT-LICENSE.txt) 
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Initial base logic from Remy Sharp's blog: http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/
 *   
 * @example  $('#myselect').selectCombo('myurltoprocess.lasso?additionalparamtoserverifnecessary=myparam', '#mytargetselect', {hidetarget: false});
 * 
 * Option: hidetarget - Allows you to override the default hide behavior if set to false.  Default true will hide your target select and its label until and option from your source select is selected.  Use this if your target select is not empty when the page loads and its values correspond to your default selected of your source select.
 *
 * Parameter sent to server is q
 *
 * Expected server response is JSON in this format: [{oV: 'myfirstvalue', oT: 'myfirsttext'}, {oV: 'mysecondvalue', oT: 'mysecondtext'}]
 *
 * May 24, 2007 - Added option for indicator display during ajax call (initially hides the indicator and displays onchange - hides again on callback of JSON request)
 *				use: $('#myselect').selectCombo('myurltoprocess.lasso', '#mytargetselect', {indicator: '#loading'});//where #loading would be the id of the indicator div, img, or whatever
 *				  Added check that if target ID is the same as the original source, it will override hidetarget setting and not hide target
 */
 (function($){
$.fn.selectCombo = function(url, target, settings){

var defaults = {hidetarget: true, indicator: false};
$.extend(defaults, settings);
return this.each(function(){
if(defaults.indicator != false)
	$(defaults.indicator).hide();

if($(this).val() == '0' && defaults.hidetarget && $(this).attr('id') != $(target).attr('id')){
	var targetlabel = target.replace(/#/, '');
	targetlabel = "label[@for='" + targetlabel + "']";
	$(targetlabel).hide();
	$(target).hide();
}

$(this).change(function(){
	if(defaults.indicator != false)
		$(defaults.indicator).show();
	$.getJSON(url,{q: $(this).val()}, function(j){
		var options = '';
		for (var i = 0; i < j.length; i++) {
  			options += '<option value="' + j[i].oV + '">' + j[i].oT + '</option>';
		}
		$(target).html(options);
		$("option:first", target).attr("selected","selected");
		if(defaults.indicator != false)
			$(defaults.indicator).hide();
		$(targetlabel).show();
		$(target).show();
	});//end JSON
});//end change fn
});//end return for each
}
})(jQuery);