/**
*    Chained Selects for JQuery 
*    Copyright (C) 2007 Ziadin Givan www.CodeAssembly.com  
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see http://www.gnu.org/licenses/
*
*    
*   settings = { usePost : false, before:function() {}, after: function() {} }	
*   if usePost is true, then the form will use POST to pass the parameters to the target, otherwise will use GET
*   "before" function is called before the ajax request and "after" function is called after the ajax request
*
*/

jQuery.fn.chainSelect = function( target, url, settings ) 
{
  return this.each( function()
  {
	$(this).change( function( ) 
	{

		if ( settings != undefined && settings.before != undefined ) 
		{
			settings.before( target );
		}
		
		parameters = { '_id' : $(this).attr('id'), '_name' : $(this).attr('name'), '_value' : $(this).val() };

       		ajaxCallback = function ( data, textStatus ) 
		{
			$(target).html("");//clear old options
			data = eval(data);//get json array
			og = false;
			for (i = 0; i < data.length; i++)//iterate over all options
			{
			  for ( key in data[i] )//get key => value
			  {
				  if (key == 'lo')
				  {
					  og = true;
					  $(target).append('<optgroup label="' + data[i][key] + '">');
				  }
				  else if (key == 'lr')
				  {
					   $(target).append('<optgroup label="' + data[i][key] + '">');
				  }
				  else
				  {
					  $(target).append('<option value="' + key + '">' + data[i][key] + '</option>');
				  //option = document.createElement("option");//create a new option
			      //option.value = key;//set option value	
			      //option.text = data[i][key];
                  //$(target).append(option);//insert the option into the select
				  }
               }
			}
		   if (og == true)
		   {
				$(target).append('</optgroup>');
		   }
			//alert($(target).html());

		if (settings != undefined && settings.after != undefined  ) 
		{
			settings.after( target );
		}

		$(target).change();//call next chain
		};

		if ( settings != undefined && settings.usePost == true )
		{
			$.post( url, parameters, ajaxCallback );
		} else
		{
			$.get( url, parameters, ajaxCallback );
		}

		$("option:first", target).attr( "selected", "selected" );//select first option
	});
    
  });
};
