/**
 * Multi Select Boxes
 */
IGDATAPOOLFE.plugins.add('selectBox', {
    form: null,
    initFields: function(form) {
	this.init(form);
    },
    init: function(form) {
	let $form = $(form);
	this.form = $form;
	$('.dp-multiSelectBox', $form).each(function() {
	    var $field = $(this);
	    var $left = $('select.left', $field);
	    var $right = $('select.right', $field);
	    var name = $field.data('nametemplate');
	    var $filter = $('input.filter', $field);
	    
	    var activate = function($opt) {
		$left.append($opt.prop('selected', false));
		//add checkboxes
		$opt.each(function() {
		    $('<input type="hidden">').attr('name', name).val($(this).val()).appendTo($field);
		});
	    };
	    var deactivate = function($opt) {
		$right.append($opt.prop('selected', false));

		$opt.each(function() {
		    $('input[value=' + $(this).val() + ']', $field).remove();
		});
	    };

	    var filterRef;
	    var doFilter = function() {
		if( $filter.data('ajaxUrl')) {
		    var delay = $filter.data('delay');
		    window.clearTimeout(filterRef);
		    filterRef = window.setTimeout( function() {
			//var url = $filter.data('ajaxUrl') + '&term=intern&_type=query&q=' + $filter.val();
			$right.empty();
			$.ajax({
			    cache: false,
			    type: "get",
			    url: $filter.data('ajaxUrl'),
			    data: 'term=intern&_type=query&q=' + $filter.val(),
			    success: function (data) {
				var selectedValues = [];
				$('option', $left).each(function(i) {
				    selectedValues[i] = parseInt($(this).val());
				});
				// search keyword from result == keyword in input field
				if (data['debug']==$filter.val()) {
				    $.each(data['results'], function(nr,item){
					//console.log(data,nr,item['id'], item['text']);
					// only items not yet selected
					if ($.inArray(item['id'], selectedValues)==-1) {
					    $right.append(new Option(item['text'],item['id']));
					}
					//$right.append('<option value="'+item['id']+'">'+item['text']+'</option>');
				    });
				}
			    },
			    error: function (xhr, ajaxOptions, thrownError) {
			    }
			});
		    }, delay);

		} else {
		    var str = $filter.val().toUpperCase();
		    if (str == '') {
			$('option', $right).show();
			return;
		    }

		    $('option', $right).show().each(function() {
			var $this = $(this);
			var pos = $this.text().toUpperCase().indexOf(str);
			if (pos == -1) {
			    $this.hide();
			}
		    });
		}
	    };

	    //activate all selected
	    activate($('option:selected', $right));

	    $right.on('click', function() {
		activate($(this).children(':selected'));

                $('option', $left).on('click', function() {
                    if($('option:selected', $left).length) {
                        $('.dp-sprite', $field).addClass('dp-sprite-show');
                    }
                });
	    });

	    //delete
	    $('.dp-sprite.dp-delete', $field).click(function() {
		var $all = $('option:selected', $left);
		deactivate($all);
		doFilter();

                if(!$('option:selected', $left).length) {
                    $('.dp-sprite', $field).removeClass('dp-sprite-show');
                }
	    });

	    // move up
	    $('.dp-sprite.up', $field).click(function() {
		var $first = $('option:selected', $left).first();
		$('option:selected', $left).each(function() {
		    $(this).insertBefore($first.prev()); // move Option-Tag
		    var $thisHidden = $('input:hidden[value=' + $(this).val() + ']',$field);
		    $thisHidden.insertBefore($thisHidden.prev()); // move hidden-input
		});
	    });

	    //move down
	    $('.dp-sprite.down', $field).click(function() {
		//Xvar $hidden = $(this).parent().parent();
		var $last = $('option:selected', $left).last();
		var $main_value='';
		$('option:selected', $left).each(function() {
		    $(this).insertAfter($last.next());// move Option-Tag
		    var $thisHidden = $('input:hidden[value=' + $(this).val() + ']',$field);
		    $thisHidden.insertAfter($thisHidden.next()); // move hidden-input

		});
	    });

	    //filter list on keyup
	    $('input.filter').on('keyup', function() {
		doFilter();
	    });
	});
    }
});

