var loaded = [];

(function($){
	$.fn.dynamicSelectSearch = function (options) {
		var sEl = $(this);
		var id = $(sEl).parents(".chosen-container").attr("id").replace("_chosen", "");
		var data = {};
		data["action"] = "update_dynamic_select";
		var e = $("#" + id+"-args");
		data[$(e).data("key")] = options.search;
		data["val"] = $(e).data("val");
		data["table"] = $(e).data("table");
		$.extend(true, data, $(e).data("args"));
		$.ajax({
			type: 'POST',
		    url: 'app/includes/ajax.php',
		    data: data,
		}).done(function(data){
			try{
				data = JSON.parse(data);
				
				if(data.error == 0) {
					$("#"+id).append('<option value="'+data.val+'" selected>'+options.search+'</option>').trigger("chosen:updated");
				} else {
					let val = $("#"+id).val();
					val.push(data.val);
					$("#"+id).val(val).trigger("chosen:updated");
				}
				
			}
			catch(err) {
				console.log(err);
				console.log(data);
			}
			finally {
				// console.log(data);
				$(sEl).attr({"disabled": false});
				return $(sEl);
			}
		})
	},

	$.fn.dynamicSelectLoad = function () {
		var sEl = $(this);
		var id = $(sEl).parents(".chosen-container").attr("id").replace("_chosen", "");
		var e = $("#" + id+"-args");
		$.ajax({
			type: 'POST',
		    url: 'app/includes/ajax.php',
		    data: {action: "get_dynamic_select_options", "table": $(e).data("table"), "val": $(e).data("val"), "key": $(e).data("key"), "args": $(e).data("args")},
		}).done(function(data){
			try{
				data = JSON.parse(data);
				$("#"+id).html("");
				for(var option in data.options) {
					$("#"+id).append('<option value="'+data.options[option]+'">'+option+'</option>').trigger("chosen:updated");
				}
				loaded.push(id);
			}
			catch(err) {
				console.log(err);
				console.log(data);
			}
			finally {
				$(sEl).attr({"disabled": false});
				return $(sEl);
			}
		})
	}
})(jQuery);

jQuery(document).ready(function($){
	$(document).on("keyup", ".dynamicSelect + .chosen-container .chosen-search-input", function(){
		var search = $(this).val();
		var sEl = $(this);
		var id = $(sEl).parents(".chosen-container").attr("id").replace("_chosen", "");
		var e = $("#" + id+"-args");
		if(search.search($(e).data("seperator")) != -1) {
			search = search.replace(new RegExp($(e).data("seperator")), '');
			$(this).val("").attr({"disabled": true});
			$(this).dynamicSelectSearch({search: search});
		}
	}).on("focusin", ".dynamicSelect + .chosen-container .chosen-search-input", function(){
		var sEl = $(this);
		var id = $(sEl).parents(".chosen-container").attr("id").replace("_chosen", "");
		var e = $("#" + id+"-args");

		if(loaded.indexOf(id) == -1) {
			if(e.length > 0) {
				$(this).dynamicSelectLoad();
			} else return;
		}
	});
})

