jQuery( document ).ready( function( $ ) {
	var wizardConfig = window.cardOracleWizard || {};
	var endpoint = wizardConfig.endpoint || window.location.href;
	var nonce = wizardConfig.nonce || '';

	$( '.card_oracle_wizard_table.sortable tbody' ).sortable({
		items: 'tr',
		cursor: 'move',
		axis: 'y',
		scrollSensitivity: 40,
		forcePlaceholderSize: true,
		helper: 'clone',
		opacity: 0.65,
		placeholder: 'card-oracle-sortable-placeholder',
		stop: function() {
			var selectedData = [];

			$( '.row_position tr' ).each( function() {
				selectedData.push( $( this ).attr( 'id' ) );
			} );

			updateOrder( selectedData );
		}
	});

	function updateOrder( data ) {
		if ( ! nonce ) {
			return;
		}

		$.ajax({
			url: endpoint,
			type: 'post',
			data: {
				position: data,
				card_oracle_sort_nonce: nonce
			},
			success: function() {
				window.location.reload();
			}
		});
	}
});
