jQuery(document).ready(function ($) {
	var cfg = window.moSfSyncDeactivationFeedback || {};
	var basename = cfg.pluginBasename || '';
	var openClass = 'mo_sf_sync_feedback_modal_is_open';

	function mo_sf_sync_feedback_find_deactivate_link() {
		if (!basename) {
			return document.querySelector('a[aria-label="Deactivate Object Data Sync for Salesforce"]');
		}
		var encoded = encodeURIComponent(basename);
		var anchors = document.querySelectorAll('tr[data-plugin] a[href*="action=deactivate"], .plugins a[href*="action=deactivate"]');
		for (var i = 0; i < anchors.length; i++) {
			var href = anchors[i].getAttribute('href') || '';
			if (href.indexOf(basename) !== -1 || href.indexOf(encoded) !== -1) {
				return anchors[i];
			}
		}
		return document.querySelector('a[aria-label="Deactivate Object Data Sync for Salesforce"]');
	}

	function mo_sf_sync_feedback_modal_open(modal) {
		modal.classList.add(openClass);
		modal.setAttribute('aria-hidden', 'false');
		document.documentElement.classList.add('mo_sf_sync_feedback_modal_body_lock');
	}

	function mo_sf_sync_feedback_modal_close(modal) {
		modal.classList.remove(openClass);
		modal.setAttribute('aria-hidden', 'true');
		document.documentElement.classList.remove('mo_sf_sync_feedback_modal_body_lock');
	}

	var feedbackModal = document.getElementById('mo_sf_sync_feedback_modal');
	if (feedbackModal) {
		feedbackModal.addEventListener('click', function (event) {
			if (event.target === feedbackModal) {
				mo_sf_sync_feedback_modal_close(feedbackModal);
			}
		});
	}

	var deactivateLink = mo_sf_sync_feedback_find_deactivate_link();
	if (!deactivateLink) {
		return;
	}

	deactivateLink.addEventListener('click', function (event) {
		event.preventDefault();
		var modal = document.getElementById('mo_sf_sync_feedback_modal');
		if (!modal) {
			return false;
		}
		mo_sf_sync_feedback_modal_open(modal);
		var ta = document.getElementById('query_feedback');
		if (ta) {
			ta.focus();
		}
		return false;
	});

	$(document).on('click', '#mo_sf_sync_feedback_modal .mo_sf_sync_close', function () {
		var modal = document.getElementById('mo_sf_sync_feedback_modal');
		if (modal) {
			mo_sf_sync_feedback_modal_close(modal);
		}
	});

	$(document).on('click', '.mo_sf_sync_feedback_edit_mail', function (e) {
		e.preventDefault();
		var mail = document.querySelector('#mo_sf_sync_query_mail');
		if (mail) {
			mail.removeAttribute('readonly');
			mail.focus();
		}
		return false;
	});
});
