/**
 * @author Julián Solanas
 * Canarias7 Digital
 */

(function($){
	$.fn.selects = function(options) {
		
		var defaults = {
			firstSelect: false,
			secondSelect: false,
			thirdSelect: false,
			firstQuery: false,
			secondQuery: false,
			file: 'helpers/selects.php'
		};
	
		var options = $.extend(defaults, options);
	
		return this.each(function() {
		
	  		$(options.firstSelect).change(function() {
				
				$.post(options.file, { value: $(options.firstSelect + " option:selected").val(), query: options.firstQuery },
					function(data){
						$(options.secondSelect).html(data);
					} 
				);
				
				// Cuando cambio el uno vacio el tres
				if (options.thirdSelect != false) {
					$(options.thirdSelect).html("<option value = ''>-</option>");
				}
				
	        });
			
			if ($(options.secondSelect).html() == '') {
				$(options.firstSelect).ready(function(){
				
					$.post(options.file, {
						value: $(options.firstSelect + " option:selected").val(),
						query: options.firstQuery
					}, function(data){
						$(options.secondSelect).html(data);
					});
					
				});
			}
			
			if (options.thirdSelect != false) {
				
		  		$(options.secondSelect).change(function() {
					
					$.post(options.file, { value: $(options.secondSelect + " option:selected").val(), query: options.secondQuery },
						function(data){
							$(options.thirdSelect).html(data);
						} 
					);
					
		        });
				
				if ($(options.thirdSelect).html() == '') {
					$(options.firstSelect).ready(function(){
					
						$.post(options.file, {
							value: $(options.secondSelect + " option:selected").val(),
							query: options.secondQuery
						}, function(data){
							$(options.thirdSelect).html(data);
						});
						
					});
				}
				
			}
		
		});
	};  
})(jQuery);  
