/**
 * 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'}]
 *
 */
 (function($){
$.fn.selectCombo = function(url, target, settings){//, options

var defaults = {hidetarget: true};
$.extend(defaults, settings);
return this.each(function(){
//console.log($(this).val());
var targetlabel = target.replace(/#/, '');
targetlabel = "label[@for='" + targetlabel + "']";

if($(this).val() == '' && defaults.hidetarget){
	$(targetlabel).hide();
	$(target).hide();
	var targetOption = $("option:first", target);
}

$(this).change(function(){

	var targetlabel = target.replace(/#/, '');
	targetlabel = "label[@for='" + targetlabel + "']";

	id = parseInt(target.charAt(2));
	if (id)
	for (var i = (id+1); i < 13; i++) {
		str = "#q"+i;

		$("#q"+i).hide();
		$("label[@for='q"+i+"']").hide();
	}

	//alert ();

	query = $(this).val();

	$.getJSON(url,{q: query}, function(j){
		if (j[0].oU == ''){
			var options = '';
			var labelhtml = '';
			labelhtml = j[0].oQ;
			for (var i = 0; i < j.length; i++) {
				if (j[i].oV == '-1'){
					//options += '<optgroup disabled="disabled"><option value="' + j[i].oV + '">' + j[i].oT + '</option></optgroup>';
					options += '<option disabled="disabled" value="' + j[i].oV + '">' + j[i].oT + '</option>';
				}else{
					options += '<option value="' + j[i].oV + '">' + j[i].oT + '</option>';
				}
			}
			$(target).html(options);
			$(targetlabel).html(labelhtml);
			$("option:first", target).attr("selected","selected");
			$(targetlabel).fadeIn(500);
			$(target).fadeIn(500);
		}else{
			location.href = j[0].oU + '&pageid=' + pageid;
		}
	});//end JSON
});//end change fn

});//end return for each
}
})(jQuery);
