(function($) {
	//If the UI scope is not availalable, add it
	$.ui = $.ui || {};
	
	$.fn.dropdown = function(options) {
		var defaults = {
					url:null,
					selected:null,
					params:null,
					data:null,
					firstoption:null,
					refresh:false,					
					errormsg: 'Failed to populate dropdown.<br />Please check that the url is valid and your have not lost connection.',
					retries:3,
					timeout:5000,
					onError:null,
					onSuccess:null
				};

		options = $.extend({},defaults, options);

		return this.each(function() 
						{
							new $.ui.dropdown(this,options);
						});
	}
	
	$.ui.dropdown = function(el,objOptions)
	{
					if(!objOptions) var objOptions = {};
					this.element = el;
					this.options = {};
					$.extend(this.options, objOptions);
					this.init();
	}


	$.extend($.ui.dropdown.prototype, {
		init: function(){
					this.element.length = 0; //reset options
					if(typeof(this.options.firstoption) == 'object' && this.options.firstoption!=null)
					{
						this.element.length++;
						this.element.options[0].value= this.options.firstoption.id;
						this.element.options[0].text = this.options.firstoption.name;						
					}
					this.options.retriesLeft = this.options.retries;
					
					var ajaxSuccess =  function(response)
										{													
												if(this.dropdown.urlretry != null)
												{
													clearTimeout(this.dropdown.urlretry);
													this.dropdown.urlretry = null;									
												}	
												if(response.success){													
													this.dropdown.populate(response.data);													
													if(typeof(this.dropdown.options.onSuccess) == 'function')
													{														
														this.dropdown.options.onSuccess(this.dropdown.element);
													}
												}
										};					
					
					var ajaxError = function(request)
									{
											
											clearInterval(this.dropdown.urlretry);								
											if(this.dropdown.options.retriesLeft > 0)
											{
												this.dropdown.options.retriesLeft--;
												ajaxOptions = this;	
												this.dropdown.urlretry = setTimeout('$.ajax(ajaxOptions);',this.dropdown.options.timeout);										
												
											}			
											
											if(typeof(this.dropdown.options.onError) == 'function'){
												this.dropdown.options.onError({
													message : this.dropdown.options.errormsg,
													retries :this.dropdown.options.retries,
													retryAttempt   : (this.dropdown.options.retries - this.dropdown.options.retriesLeft),
													url		: this.url,
													statusText: request.statusText,
													status : request.status,
													timeout: this.dropdown.options.timeout
												});	
											}						
									};					
					$.ajax({ url: this.options.url,
							   data: this.options.params,
							   type: "POST",						   
							   dataType: "json",
							   success: ajaxSuccess,
							   error: ajaxError,
							   global: false,
							   dropdown: this
						   });	
					
		      },
		populate: function(json){
			
			var selected = new Array();
			
			if(this.options.selected!=null)
			{				
				if(typeof this.options.selected == 'string')
				{
					selected = this.options.selected.split(',');
				}else
				{
					selected.push(this.options.selected);
				}				
			}
			
			if(json!=null || json!=undefined)
			{
								
				var idField = null;
				var nameField = null;
		
				for(field in json[0]){
		
					if(idField == null){
						idField = field;
					}else{
						nameField = field;
						break;
					}
				}
		
				for(var i = 0; i < json.length; i++){
					this.element.length++;
					this.element.options[this.element.length-1].value= json[i][idField];
					this.element.options[this.element.length-1].text = json[i][nameField];
					for(var j=0; j < selected.length; j++){
						if(selected[j] == this.element.options[this.element.length-1].value) this.element.options[this.element.length-1].selected=true;
					}
				}
			}
		}
	 });

})(jQuery);