/**
*    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 : true, before:function() {}, after: function() {}, parameters : { parameter1 : 'value1', parameter2 : 'value2'} }	
*   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
*   You can specify additional parameters to be sent to the the server in settings.parameters.
*
*/
jQuery.fn.chainSelect = function( target, url, settings ) 
{
  return this.each( function()
  {
	var chainSelf = this;
	$(chainSelf)
		.unbind('change')
		.bind('change', function() 
	{
		settings = jQuery.extend(
		{
			after : null,
			before : null,
			usePost : false,
			parameters : { '_id' :  $(chainSelf).attr('id'), '_name' : $(chainSelf).attr('name') },
        } , settings);
		settings.parameters._value =  $(chainSelf).val();

		if ( settings.before != null ) 
		{
			settings.before( target, chainSelf );
		}

  		ajaxCallback = function ( data, textStatus ) 
		{
			//if (data=='[]' && $(target).is('select')) {$(target).replaceWith('<input type="text"></input>');}
			//if (data!='[]' && !$(target).is('select')) {$(target).replaceWith('<select><option value="0">Select One</option></select>');}
			
			if (settings.before_data != null  ) 
			{
				settings.before_data( target, chainSelf, data );
			}
			
			if ($(target).is('select'))
			{
				$(target).html("");//clear old options
				data = eval(data);//get json array
				for (i = 0; i < data.length; i++)//iterate over all options
				{
	               $(target).get(0).add(new Option(data[i].value,data[i].key), document.all ? i : null);
				}
			}

			if (settings.after != null  ) 
			{
				settings.after( target, chainSelf, data );
			}

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

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

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