(function($) {
	'use strict';

	var cfg = window.wppsChangePostType || {};
	var busy = false;

	function boxConfig($box) {
		return {
			ajaxUrl: $box.attr('data-ajax-url') || '',
			action: $box.attr('data-action') || 'wpps_change_post_type',
			nonce: $box.attr('data-nonce') || '',
			postId: parseInt($box.attr('data-post-id'), 10) || 0,
			currentType: String($box.attr('data-current-type') || '')
		};
	}

	function selectedType($box) {
		return String($box.find('.wpps-change-post-type__select').val() || '');
	}

	function typeChanged($box, boxCfg) {
		var next = selectedType($box);
		return next && boxCfg.currentType && next !== boxCfg.currentType;
	}

	function transfer($box) {
		if (busy) {
			return;
		}

		var boxCfg = boxConfig($box);
		var $button = $box.find('.wpps-change-post-type__apply');

		if (!typeChanged($box, boxCfg) || !boxCfg.ajaxUrl || !boxCfg.nonce || !boxCfg.postId) {
			return;
		}

		busy = true;
		$button.prop('disabled', true).text((cfg.i18n && cfg.i18n.working) || 'Changing…');

		$.post(boxCfg.ajaxUrl, {
			action: boxCfg.action,
			nonce: boxCfg.nonce,
			post_id: boxCfg.postId,
			post_type: selectedType($box)
		})
			.done(function(response) {
				if (response && response.success && response.data && response.data.redirect) {
					window.location.assign(response.data.redirect);
					return;
				}
				window.alert((cfg.i18n && cfg.i18n.error) || 'Could not change post type.');
			})
			.fail(function(xhr) {
				var message = (cfg.i18n && cfg.i18n.error) || 'Could not change post type.';
				if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
					message = xhr.responseJSON.data.message;
				}
				window.alert(message);
			})
			.always(function() {
				busy = false;
				$button.prop('disabled', false).text((cfg.i18n && cfg.i18n.apply) || 'Change post type');
			});
	}

	$(document).on('click', '.wpps-change-post-type__apply', function(event) {
		event.preventDefault();
		transfer($(this).closest('.wpps-change-post-type'));
	});
})(jQuery);
