/**
	 * Form inline fields
	 * this one is going to be tough!
 */
IGDATAPOOLFE.plugins.add('formInlineField', {
    form: null,
    initFields: function(form) {
	this.init(form);
    },
    init: function(form) {
	let $form = $(form);
	this.form = $form;
		//for each field of this type...
		$('.dp-form-inline-field', $form).each(function() {
			//safe a reference to the container
			var $fieldWrap = $(this);
			var $hiddenFields = $fieldWrap.children('div.hiddenfields');

			//define these funcitons in their own context
			var deleteRecord = function() {
				if (!confirm('Field-Möchten Sie diesen Eintrag wirklich löschen?'))
					return;

				//remove it
				var $deleteElement = $(this).closest('div.dp-record-container');
				var deleteId = $deleteElement.data('rel');
				//might not have an id in case of temporary records that have just been cretaed.
			    // delete Element can be outside of record container
			    $deleteElement.remove();
				if (deleteId != null) {
					//enable the hidden field if the recored is persistent
					//$hiddenFields.children('input.record' + deleteId).prop('disabled', false);
					$('.' + deleteId, $form.children('form')).remove();
				}


				// enable the hidden field if no records
				// why one? because of the dummy!
				if ($fieldWrap.children('.dp-record-container').length == 1) {
					$hiddenFields.children('input.isEmpty').prop('disabled', false);
				}

			};






			var copyItself = function() {
				//remove keybinding
				var $this = $(this).off('keydown');
				//clone and append and add keybinding
				$this.clone().on('keydown', copyItself).appendTo($fieldWrap);
				$this.removeClass('dp-record-container-dummy');

				//generate a temp  name. this is basically a random value. by counting the elements it is guaranteed to be unique
				var tempName = $('.dp-record-container', $fieldWrap).length + 99;
				// -1 to get to index 0, -1 for the dummy field
				//change all name tags!
				$('[name]', $this).each(function() {
					//change tha name, remove dummy stuff
					var name = $(this).attr('name');
					name = name.replace('dummy-', '');
					name = name.replace('TEMP', tempName);
					$(this).attr('name', name);
				});

				//enable delete button
				$this.children('.dp-sprite.dp-delete').show().on('click', deleteRecord);

				//disable empty input field, since there is at least one row
			    //$fieldWrap.children('input.isEmpty').prop('disabled', true);
			};
		    //bind existing
		    $('.dp-record-container:not(.dp-record-container-dummy) .dp-sprite.dp-delete', $fieldWrap).on('click', deleteRecord);
		    $('div.dp-record-container-dummy', $fieldWrap).on('keydown', copyItself);
		});
    }
});