jQuery(document).ready(function ($) {

	$('input[name="fullsyncbtn"]').on('click', function (e) {
		e.preventDefault();

		var $btn = $(this);

		$btn.prop('disabled', true);
		$('.gcalbtn-message').html('Synchronising, please wait...');

		$.ajax({
			type: 'POST',
			url: mdjm_gcal_vars.ajax_url,
			dataType: 'json',
			data: {
				action: 'gcal_full_sync'
				// If you add a nonce in PHP, include it here too.
				// nonce: mdjm_gcal_vars.nonce
			}
		})
		.done(function (resp) {
			if (resp && resp.success) {
				var synced = resp.data && resp.data.synced ? resp.data.synced : 0;
				var failed = resp.data && resp.data.failed ? resp.data.failed : 0;

				$('.gcalbtn-message').html(
					'Finished. Synced: ' + synced + ' | Failed: ' + failed
				);
			} else {
				var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Sync failed (unknown error).';
				$('.gcalbtn-message').html(msg);
			}
		})
		.fail(function (xhr) {
			var msg = 'Sync failed. ';
			if (xhr && xhr.responseText) {
				msg += xhr.responseText;
			}
			$('.gcalbtn-message').html(msg);
		})
		.always(function () {
			// Always re-enable the button after the request completes.
			$btn.prop('disabled', false);
		});
	});

	$("input[name='mdjm_settings[gcal_client_id]'],input[name='mdjm_settings[gcal_client_secret]']").on(
		'input',
		function () {
			$('.changemsg').html('Please save your settings to use your updated oAuth credentials.');
		}
	);

});