/**********************************************
 * @author Gabriel Felipe Soare - gabrielfs7@gmail.com
 * @param method 'post' or 'get'
 * @param url 'url to request'
 * @param data 'Data will be sent on request'  
 * @param loadingText 'Text of option displayed while load the data'
 * @param loadingValue 'Value of option displayed while load the data'
 * @param initialText 'Text of option displayed first' 
 * @param initialValue 'Value of option displayed first' 
 * @param selectedIndex 'Value of the index must be selected'
 * @param responseType 'html' or 'json' => Json Format must be '[[value:text],[value:text],etc...]
 *********************************************/
jQuery.fn.updateSelect = function($options)
{	
	// Retrieve the default values 
	var settings = jQuery.extend({}, jQuery.fn.updateSelect.defaults, $options);
		
	return this.each( function(){
		
		var $this = $(this);
		
		$.ajax(
		{
			type: settings.method, 
			url : settings.url, 
			data: settings.data,
			beforeSend: function(){$this.html('<option value="'+settings.loadingValue+'" >'+settings.loadingText+'</option>')}, 
			success: function($request)
			{
				var $tx_slc = '';
				
				if(settings.initialText)
				{
					$tx_slc = '<option value="'+settings.initialValue+'" selected="selected" >'+settings.initialText+'</option>';										
				}
				
				// if the resposnse text is JSON
				if(settings.reponseType == 'json')
				{
					$data = eval('('+$request+')');
					
					for($i=0; $i< $data.length; $i++)
					{
						$index = Number($i);
						$selected = settings.selectedIndex == $data[$index][0] && (!settings.initialText) ? ' selected="selected" ' : '';
						$tx_slc+='<option value="'+$data[$index][0]+'" '+$selected+'>'+$data[$index][1]+'</option>';
					}
				}
				// if the resposnse text is HTML
				else
				{
					$tx_slc = $request;
				}
				$this.html($tx_slc);
				
				//alert($('#slc2:value$=2').text());
			}
		});
	});
};

/*****************************************
 * Define the default values of function
 *****************************************/
jQuery.fn.updateSelect.defaults = {

	method: 'post',
	loadingText: 'Carregando...',
	loadingValue: '',
	initialText: '',
	reponseType: 'json'
		
};


