/*
expected format of output stream from ajax request

{"subCategories":[
{"optionValue":"dk","optionText":"Denmark"},
{"optionValue":"no","optionText":"Norway"},
{"optionValue":"us","optionText":"United States"},
{"optionValue":"ca","optionText":"Canada"}
]}
*/

var moochained = new Class({
	initialize: function(primaryDDLID, secondaryDDLID, AjaxURL, GroupID) {

		var addSubCats = function(subCats){
			var cats = $(secondaryDDLID);
			var emptyIt = 0;
			cats.disabled = false;
			cats.options.length = 0;
			subCats.each(function(subCat){
				var option = new Element("option");
				option.setProperty("value", subCat.optionValue);
				option.setHTML(subCat.optionText); 
				cats.adopt(option);
				emptyIt++;
			});
			if (emptyIt < 2) 
			{
				cats.disabled = true;
			}
		}
		
		$(primaryDDLID).addEvent('change', function(e) {
			e = new Event(e).stop();
			var url = AjaxURL;
			if (this.options[this.selectedIndex].value != "0") 
			{
				if (GroupID != null )
				{
					url = url +'?tid='+this.options[this.selectedIndex].value + '&group_id=' + GroupID;
				}
				else
					url = url +'?tid='+this.options[this.selectedIndex].value ;
				
			}
			var request = new Json.Remote(url, {
				onComplete: function(jsonObj) {
					addSubCats(jsonObj.subCategories);
				}
			}).send();
		});
	}
});
