var $ = jQuery.noConflict();
formwizard_url = '';

function retrieveCurrentFieldOrder() {
	output = '';
	var jt = $('#formwizard_target').find('div.formwizard_item').each( function() {
		if (output != '') output += ';';
		output += this.dataset.name;
	});
	return output;
}

function getState() {
	let $form = $('#formwizard_preview').closest('form');
	let $title = $form.find('input[name="title"]');
	let $fields = $form.find('input[name="fields"]');
	return {
		url			: $form.attr('action'),
		present_general : $title.length > 0 ? 1 : 0,
		present_fields  : $fields.length > 0 ? 1 : 0,
		title			: $title.val(),
		fields			: retrieveCurrentFieldOrder(),
		auth			: $form.find('input[name="auth"]').val(),
	}
	
}

function update_live_preview() {
	let param = getState();
	let href = param.url;
	delete param.url;
	param.action = 'get-default',
	$.ajax({
		type     : 'POST',
		dataType : 'html',
		data     : param,
		url      : href,
	}).done(function(response) {
		$('#formwizard_preview').html(response);
	});
}

// return the name of the div this item should be added after
function getInsertAfter(droptarget, y, abs_y, ht) {
	output = '*';
	droptarget.find('div').each( function() {
		var e = $(this);
		var q = Math.floor(e.offset().top - abs_y);	// this is the top of the current div
		if (y + ht < q + ht / 2) {
			output = e.attr('id');
			return false;
		}
	});
	return output;	// no divs added, add to end
}

// pick up the list of selected fields
function formwizard_preparesubmit() {
	var fieldlist = retrieveCurrentFieldOrder();
	$('input[name="fields"]').val(fieldlist);
	return true;
}

// move item back to available column
function formwizard_remove(menuitem) {
	var item = $(`.formwizard_item[data-name="${menuitem}"`);
	var home = $('#formwizard_available');
	item.detach().appendTo(home);
}

function SetDefaults(frm, md_id) {
	var items = frm.find('.formwiz_fielditem').serializeArray();
	items = JSON.stringify(items);
	$.ajax({
		type : 'post',
		dataType : 'html',
		data : {items:items, formid:md_id},
		url : formwizard_url,
		success: function(response) {
			$("#response").html(response).show().delay(4000).fadeOut();
		}
	})
}

function confirmDelete(isfield, name) {
	if (isfield) {
		return confirm('Are you sure you wish to completely delete the field "' + name + '" ?');
	} else {
		return confirm('Are you sure you wish to completely delete the form "' + name + '" ? This action cannot be undone!');
	}
}

$(document).on('loaded.template', function(e, data, $container) {
	$('.formwizard_item').each(function() {
		if (typeof this.x_draggable == 'undefined') {
			this.x_draggable = $(this).draggable(
				{containment: $('.formwizpage-fields'), helper: 'clone'}
			);
		}
	});
	
	$('#formwizard_target').droppable({
		drop: function( event, ui ) {
			var target = $(this);
			var offset0 = target.offset();
			var newPosY = Math.floor(ui.offset.top - offset0.top);
			var insertbefore = getInsertAfter(target, newPosY, offset0.top, ui.draggable.height());
			var draggable = ui.draggable;
			if (insertbefore == draggable.attr('id')) return;	// nothing to do
			draggable.detach().css({top: 0,left: 0});
			if (insertbefore == '*') {
				draggable.appendTo(this);
			} else {
				$('#' + insertbefore).before(draggable);
			}
		}
	});
	$('.component-tabs', $container).each(function() {
		$(this).on('tabactive', function(e, data, newPanel, fragment) {
			if (fragment == 'preview') update_live_preview();
		});
	});
});
