/**
	 * Form inline fields
	 * this one is going to be tough!
 */
IGDATAPOOLFE.plugins.add('formInlineRecord', {
    form: null,
    initFields: function(form) {
	this.init(form);
    },
    init: function(form) {
	let $form = $(form);
	this.form = $form;

	// called on insert/delete records - hide/show add button
	var onUpdate =  function($fieldWrap) {
	    var $addButton = $('.dp-form-inline-record-add', $fieldWrap);
	    var maxitems = $fieldWrap.data('maxitems');
	    var currentItems = $fieldWrap.children('div.dp-record-container-show').length;

	    if (maxitems > 0 && currentItems >= maxitems) {
		$addButton.parent().hide();
	    } else {
		$addButton.parent().show();
	    }
	};
	
        //define these funcitons in their own context
	var deleteRecord = function() {
            if (!confirm('Record-Möchten Sie diesen Eintrag wirklich löschen?'))
                return;

            //remove it
            var $fieldWrap = $(this).closest('div.dp-form-inline-record');;
            var $deleteElement = $(this).closest('div.dp-record-container'); //dp-delete
            var deleteId = $deleteElement.data('rel');
            var $rte = $deleteElement.find('.dp-rte textarea');
            if($rte.length > 0) {
                var rteId = $rte.attr('id');
                //if(tinymce.get(rteId))
                //    tinymce.remove('#' + rteId);
            }

            //might not have an id in case of temporary records that have just been cretaed.
            $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) {// nur noch dummy
		var $hiddenFields = $fieldWrap.children('div.hiddenfields');
                $hiddenFields.children('input.isEmpty').prop('disabled', false);
            }
	    onUpdate($fieldWrap);

        };
        $('.dp-form-inline-record .dp-record', $form).children('.dp-panel').children('.dp-sprite.dp-delete').each(function(){
	    var events = $._data(this, "events");
	    var hasEvents = (events != null);
	    //console.log(hasEvents);
	    $(this).show().on('click', deleteRecord);
	});

        $('.dp-sorting-up', $form).each(function() {
            $(this).on('click', function() {
                // if ($el.not(':first-child'))
                //var $el = $(this).parent().parent().parent();
                var $el = $(this).parents('.dp-record-container');
                //'.dp-generalinline-record');

                var $el_cur_sort = $('input.dp-file-upload-sort', $el).val();
                var $el_prev_sort = $('input.dp-file-upload-sort', $el.prev()).val();
                $('input.dp-file-upload-sort', $el).val($el_prev_sort);
                $('input.dp-file-upload-sort', $el.prev()).val($el_cur_sort);
		//console.log($el_cur_sort, $el_prev_sort);
                $el.prev().before($el);
		console.log($el_cur_sort, $el_prev_sort, $el);
                //tinymce.remove();
                //$form.initFields($el.get());
            });
        });


        $('.dp-sorting-down', $form).each(function() {
            $(this).on('click', function() {
                // if ($el.not(':last-child'))
                var $el = $(this).parent().parent().parent();
                //'.dp-generalinline-record');
                var $el_cur_sort = $('input.dp-file-upload-sort', $el).val();
                var $el_next_sort = $('input.dp-file-upload-sort', $el.next()).val();
                $('input.dp-file-upload-sort', $el).val($el_next_sort);
                $('input.dp-file-upload-sort', $el.next()).val($el_cur_sort);

                $el.next().after($el);
                //tinymce.remove();
                //$form.initFields($el.get());
            });
        });
        //for each field of this type...
        $('.dp-form-inline-record .dp-form-inline-record-add', $form).each(function() {
            var $addButton = $(this);
	    var $fieldWrap = $(this).closest('div.dp-form-inline-record');;
	    onUpdate($fieldWrap);
            $addButton.click(function() {
                var $containerNew = $('.dp-record-container',$addButton.next());
                var $containerEntries = $addButton.prev().parent().parent();
                var $contanerClone = $containerNew.clone();
                // Falls sortierfeld existiert
                if( $('input.dp-file-upload-sort', $contanerClone).length ) {
                var maxVal=0;
                $('.dp-record-show', $containerEntries.parent()).each( function() {
                    if(parseInt($('input.dp-file-upload-sort', this).val())>maxVal)
                    maxVal=parseInt($('input.dp-file-upload-sort', this).val());
                });
                maxVal++;
                $('input.dp-file-upload-sort', $contanerClone).val(maxVal);
                }
                $containerEntries.before($contanerClone); //html()
		
		onUpdate($fieldWrap);
		
                //generate a temp  name. this is basically a random value. by counting the elements it is guaranteed to be unique
                var tempName = $containerEntries.parent().find('div.dp-record-container').length+99;
                //alert('add'+ tempName);
                // -1 to get to index 0, -1 for the dummy field

                //change all name tags!
                $('[name]', $contanerClone).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);
                });
                $('[id]', $contanerClone).each(function() {
                    var id = $(this).attr('id');
                    id = id.replace('dummy-', '');
                    id = id.replace('TEMP', tempName);
                    $(this).attr('id', id);
                });
		var $deleteButton = $contanerClone.children('.dp-record-container .dp-record').children('.dp-panel').children('.dp-sprite.dp-delete');
		$deleteButton.show().on('click', deleteRecord);
		this.form.initFields($addButton.prev().parent().parent().prev().get());
            });
        });
    }
});