(function($) { // Hide scope, no $ conflict

var PROP_NAME = 'co_Filebrowser';

/* co_Filebrowser. */
function autofill() {
	this._defaults = {
		location: null, //get location
		data: {}, //get data
		success: function(){} //success callback
	};
}

$.extend(autofill.prototype, {
	setDefaults: function(settings) {
		$.extend(this._defaults, settings || {});
		return this;
	},
	autofill: function(form, options) {
		var d = this._defaults;
		var field, json, id, img, form_id;
		this.setDefaults(options);
		if(form.tagName != "FORM"){
			return;
		}	
		form = $(form);
		form_id = form.attr("id");
		if(form.hasClass("edit_table")){
			form_id = form.attr("id").substr(0, form.attr("id").lastIndexOf("_"));
		}
		$.getJSON(d.location, d.data, function(data){
			$.each(data, function(i, v){
				field = form.find("[name=" + i + "]")
				img = form.find("img."+i);
				if(field.length > 0){
					if(field.hasClass("autocomplete_val")){
						json = window[form_id + "_" + i];
						field.siblings("input").val(json_arr_return_val(json, "value", v, "label"));
					}
					if(field.prop("type")=="checkbox"){
						if(v && v != "0" && v.length != 0){
							field.prop("checked", "checked");
						} else field.prop("checked", false);
					}
					if(field.hasClass(form.attr("id") + "_" + i + "_cascade")){
						json = window[form_id + "_" + i];
						if(!json){
							if(console.log) console.log("can't find cascade refresh json");
						}
						else{
							id = field.attr("class").match(/cascade_requires_\w+/);
							id = id[0].substring(17);		
							field.empty().append(force_cascade(data[id], json));
						}
					}
					if(v == null){
						v = '';
					}
					
					if(field.prop("type")!="checkbox" && field.prop("type")!="radio") field.val(v);
					
					if(field.hasClass("elrte")){
						field.elrte('val', v)
					}
				}
				if(img.length > 0){
					var d = new Date();
					img.attr("src", v  + "?" + d.getTime());
				}
			});
			d.success(form, data);
		});
	}
});

/* Attach the co_Filebrowser functionality to a jQuery selection.
   This is intended to be applied to a button or file input.
   @param  command  (string) the command to run (optional, default 'attach')
   @param  options  (object) the new settings to use for these instances (optional)
   @return  (jQuery) for chaining further calls */
$.fn.autofill = function(options) {
	return this.each(function() {
		$.autofill.autofill(this, options || {});
	});
};

$.autofill = new autofill(); // singleton instance

})(jQuery);
