var undo = window.undo || {};

var getOrder = function(el) {
	el = $(el);
	var sectionId = el.data('section-id');
	var items = [];
	_.each(el.children('div.js-field-row'), function(row) {
		row = $(row);
		items.push({
			field_id : row.data('field-id'),
			position : row.data('field-position')
		});
	});
	return {
		sectionId : sectionId,
		items : items
	};
};
/**
 * Called by xajax, updates the data attributes after a database has been updated.
 * @param {Object} sectionId
 * @param {Object} fields
 */
var updateDOM = function(sectionId, fields) {
	fields = JSON.parse(fields);
	var section = $('#form_details_tab').find('div[data-section-id="' + sectionId + '"]');
	_.each(fields, function(field) {
		section.find('div[data-field-id="' + field.field_id + '"]').attr('data-field-position', field.position);
	});
};

$(document).ready(function() {

	// drag form rows
	$('.ic-section-fields').sortable({
		// handle : 'label',
		axis : 'y',
		delay : 300,
		opacity : '.75',
		placeholder : 'sortable-placeholder',
		start : function(event, ui) {
			var originalOrder = getOrder(event.currentTarget);
			ui.placeholder.height(ui.item.height());
			$(ui.item).data("originalOrder", originalOrder);
		},
		stop : function(event, ui) {
			var newOrder = getOrder(event.target);
			var originalOrder = $(ui.item).data("originalOrder");
			xajax_update_position(originalOrder, newOrder);
			window.undo.originalOrder = originalOrder;
			window.undo.newOrder = newOrder;
			$('#undo_reorder').show();
		}
	});
	$('.ic-section-fields').find('label').disableSelection();
	$('#undo_reorder').on('click', function() {
		xajax_update_position(window.undo.newOrder, window.undo.originalOrder);
		$('.ic-section-fields').sortable('cancel');
		$('#undo_reorder').hide();
	});

    $(":checkbox[name='no_default']").change(function(){
        hideOrShowDropdownCheck();
    });

    $("a[name='wysiwyg_edit']").click(function(){
        hideOrShowDropdownCheck();
    });

    var navbar = document.querySelector('.claro-navbar')
    var navbarOffsetHeight = navbar ? navbar.offsetHeight : 0;

    window.addEventListener('navbarHeightChanged', function(event){
        navbarOffsetHeight = navbar ? navbar.offsetHeight : 0;
        setToolbarOffset();
    });

    //Calculate overall height of broadcast messages and set value for toolbar offset
    function setToolbarOffset() {
        var affixedToolbar = document.querySelector('.form-toolbar-inner-top');

        if (affixedToolbar && window.innerWidth >= 768) {
            affixedToolbar.style.top = navbarOffsetHeight - 2 + 'px';
        } else if(affixedToolbar && window.innerWidth < 768) {
            affixedToolbar.style.top = navbarOffsetHeight - 3 + 'px';
        }
    }

    // Callback function to handle intersection changes
    var intersectionCallback = function(entries, observer) {
        entries.forEach(function(entry) {
            var toolbarInnerChild = entry.target.querySelector('.form-toolbar-inner');

            if (toolbarInnerChild) {
                if (entry.isIntersecting) {
                    // If the parent element is in view, remove the CSS class from the child
                    toolbarInnerChild.classList.remove('affix');
                } else {
                    // If the parent element is outside of view, add the CSS class to the child
                    toolbarInnerChild.classList.add('affix');
                    setToolbarOffset();
                }
            }
        });
    };


    //Hide the sticky toolbar when switching between mobile and desktop
    // then re-set the offset
    let wasAbove768 = window.innerWidth > 768;

    window.addEventListener('resize', () => {
        const isAbove768 = window.innerWidth > 768;
        const toolbarInnerTop = document.querySelector('.form-toolbar-inner-top');

        // Only act when the threshold is crossed
        if (isAbove768 !== wasAbove768) {
            if (isAbove768) {
                toolbarInnerTop.classList.add('affix');
            } else {
                toolbarInnerTop.classList.remove('affix');
            }
            wasAbove768 = isAbove768;
        }
    });

    // Select all elements with data attribute 'data-spy="affix"'
    var spyElements = document.querySelectorAll('[data-spy="affix"]');
    var options = {
        rootMargin: '-' + navbarOffsetHeight + 'px 0px 0px 0px' // adjust root margin to account for navbar height
    }

    // Create a new IntersectionObserver
    var intersectionObserver = new IntersectionObserver(intersectionCallback, options);

    // Observe each spy element
    spyElements.forEach(function(element) {
        intersectionObserver.observe(element);
    });

    function hideOrShowDropdownCheck()
    {
        if($(":checkbox[name='no_default']").length == 0)
            return false;

        if($(":checkbox[name='no_default']").attr('checked')) {
            $("select[name='default_value']").hide();
        }
        else {
            $("select[name='default_value']").show();
        }
    }
});
